Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Github File Upload #41

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/api/file.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getTotalPages, encodeString } from "@/helpers/index.js";
import { Base64 } from "js-base64";
import axios from "axios";

export async function filesListFromSession(
Expand Down Expand Up @@ -136,7 +137,10 @@ export async function updateFile(
sha,
) {
try {
const base64Content = encodeString(content);
const base64Content =
typeof content === "string"
? encodeString(content)
: Base64.fromUint8Array(content.bytes);

await octokit.rest.repos.createOrUpdateFileContents({
owner,
Expand Down
42 changes: 42 additions & 0 deletions src/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,48 @@ export async function createAndUpdateFile(
);
}

export async function createAndUpdateMultipleFiles(session, path, files, sha) {
const { githubConfig, octokit } = useOctokitStore();
const { head } = session;
const errorFiles = [];

for (const file of files) {
const fileName = file.newName || file.name
const fullFilePath = (path + fileName).replace("/", "");

const arrayBuffer = await file.arrayBuffer();
const bytes = new Uint8Array(arrayBuffer);

const result = await updateFile(
octokit,
githubConfig,
head.repo.owner.login,
head.repo.name,
head.ref,
fullFilePath,
fileName,
{ bytes },
sha,
);

if (result.status === "error") {
errorFiles.push(fileName);
}
}

if (errorFiles.length) {
return {
text: `Upload failed for following files: ${errorFiles.join(", ")}`,
status: "error",
};
} else {
return {
text: "Uploaded successfully",
status: "success",
};
}
}

export async function fetchSchemaFromURL(url) {
return schemaFromURL(url);
}
41 changes: 29 additions & 12 deletions src/components/file/CreateFile.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { onMounted, ref, watch, defineProps, inject, h } from "vue";
import {
createAndUpdateFile,
createAndUpdateMultipleFiles,
fetchSchemaFromURL,
getBranchFileStructure,
} from "@/api/index.js";
Expand All @@ -13,9 +14,11 @@ import {
} from "@/helpers/index.js";
import map from "lodash.map";
import { useRouter } from "vue-router";
import FileUploader from "@/components/file/FileUploader.vue";

const router = useRouter();

const files = ref([]);
const filePath = ref(null);
const fileContent = ref("");
const updatedFilePath = ref("/");
Expand Down Expand Up @@ -152,7 +155,7 @@ const close = () => {
};

const createFile = async () => {
if (!filePath.value) {
if (!files.value.length && !filePath.value) {
snackbar.value = {
text: "Please add a filename",
status: "error",
Expand All @@ -161,19 +164,31 @@ const createFile = async () => {
}
const loader = useLoader().show();

const fullFilePath = (updatedFilePath.value + filePath.value).replace(
"/",
"",
);
if (files.value.length) {
snackbar.value = await createAndUpdateMultipleFiles(
props.session,
updatedFilePath.value,
files.value,
);
} else {
const fullFilePath = (updatedFilePath.value + filePath.value).replace(
"/",
"",
);

snackbar.value = await createAndUpdateFile(
props.session,
fullFilePath,
filePath.value,
fileContent.value,
);
}

snackbar.value = await createAndUpdateFile(
props.session,
fullFilePath,
filePath.value,
fileContent.value,
);
if (snackbar.value.status === "success") {
await router.push(`/${props.session.number}/${encodeString(fullFilePath)}`);
if (!files.value.length)
await router.push(
`/${props.session.number}/${encodeString(fullFilePath)}`,
);
close();
props.updateDetails();
}
Expand Down Expand Up @@ -254,6 +269,8 @@ const onSelectFile = (item) => {
</v-row>
</div>
<div class="pa-6">
<FileUploader @changed="(newFiles) => (files = newFiles)" />
<v-divider class="mb-7 mt-8 mx-15"> OR </v-divider>
<v-textarea
v-model="fileContent"
class="bg-white text-mono"
Expand Down
173 changes: 173 additions & 0 deletions src/components/file/FileUploader.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
<script setup>
import { inject, ref, watch } from "vue";
const emit = defineEmits(["changed"]);

const files = ref([]);
const fileInput = ref(null);
const uploadArea = ref(null);
const isDropping = ref(false);
const maxFileSize = 100 * 1024 * 1024; // 100MB

const snackbar = inject("set-snackbar");

const onDragEnter = (e) => {
e.preventDefault();
isDropping.value = true;
};

const onDragLeave = (e) => {
e.preventDefault();
isDropping.value = false;
};

const onDrop = (e) => {
e.preventDefault();
isDropping.value = false;
const droppedFiles = [...e.dataTransfer.files];
validateAndAddFiles(droppedFiles);
};

const onFileInput = (e) => {
const selectedFiles = [...e.target.files];
validateAndAddFiles(selectedFiles);
};

const validateAndAddFiles = (newFiles) => {
newFiles.forEach((file) => {
if (file.size > maxFileSize) {
snackbar.value = {
text: "Some files are too large. Maximum file size is 100 MB.",
status: "error",
};
return;
}

files.value.push(file);
});
};

const removeFile = (index) => {
files.value.splice(index, 1);
if (files.value.length === 0) {
resetFileInput();
}
};

const clearAll = () => {
files.value = [];
resetFileInput();
};

const resetFileInput = () => {
if (fileInput.value) {
fileInput.value.value = ""; // Reset the file input value
}
};

const triggerFileInput = () => {
fileInput.value?.click();
};

watch(files.value, (newFiles) => {
emit("changed", newFiles);
});
</script>

<template>
<v-card variant="flat" color="secondary" class="mx-auto">
<v-card-text>
<v-sheet
ref="uploadArea"
class="upload-area pa-6"
:class="{ dropping: isDropping }"
rounded
border
@dragenter="onDragEnter"
@dragleave="onDragLeave"
@dragover.prevent
@drop="onDrop"
@click="triggerFileInput()"
>
<div class="text-center">
<v-icon size="64" color="primary" icon="mdi-cloud-upload"></v-icon>

<div class="text-h6 mt-4">Drag & Drop / Browse</div>

<div class="text-caption text-grey">Supports: All file format.</div>
</div>

<input
ref="fileInput"
type="file"
hidden
accept="*"
multiple
@change="onFileInput"
/>
</v-sheet>

<!-- File List -->
<v-list v-if="files.length" class="mt-4">
<v-list-item
v-for="(file, index) in files"
:key="index"
:title="file.name"
:subtitle="`${(file.size / (1024 * 1024)).toFixed(2)} MB`"
lines="three"
prepend-icon="mdi-file"
>
<template v-slot:title>
<v-text-field
:model-value="file.newName || file.name"
placeholder="File Name"
density="compact"
variant="underlined"
hide-details
class="w-25 pa-0 mb-2 bg-white"
@update:model-value="(val) => file.newName = val"
></v-text-field>
</template>

<template v-slot:append>
<v-btn
icon="mdi-close"
variant="text"
size="small"
density="comfortable"
@click="removeFile(index)"
></v-btn>
</template>
</v-list-item>
</v-list>

<!-- Actions -->
<v-card-actions v-if="files.length" class="mt-4">
<v-spacer></v-spacer>
<v-btn color="error" @click="clearAll"> Clear All </v-btn>
</v-card-actions>
</v-card-text>
</v-card>
</template>

<style scoped>
.v-card {
background-color: #f6f6f6 !important;
}
.upload-area {
border: 1px dashed rgb(var(--v-theme-primary));
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: center;
}

.upload-area.dropping {
background-color: rgb(var(--v-theme-primary), 0.1);
border-style: solid;
}

.upload-area:hover {
background-color: rgb(var(--v-theme-secondary));
cursor: pointer;
}
</style>
7 changes: 5 additions & 2 deletions src/methods/file-edit-view/init-eox-jsonform.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
function getShadowRoot(jsonFormInstance) {
return (
jsonFormInstance.value.shadowRoot ||
jsonFormInstance.value.attachShadow({ mode: "open" })
jsonFormInstance.value?.shadowRoot ||
jsonFormInstance.value?.attachShadow({ mode: "open" })
);
}

export function hideHiddenFieldsMethod(jsonFormInstance) {
const shadowRoot = getShadowRoot(jsonFormInstance);
if (!shadowRoot) return;

const checkForElements = () => {
const elements = shadowRoot.querySelectorAll(".je-indented-panel .row");
Expand All @@ -32,6 +33,8 @@ export function initEOXJSONFormMethod(
) {
jsonFormInstance.value = document.querySelector("eox-jsonform");
const shadowRoot = getShadowRoot(jsonFormInstance);
if (!shadowRoot) return;

const mainDivClass =
".je-indented-panel > div > div:not(.je-child-editor-holder):not(.je-child-editor-holder *)";

Expand Down
11 changes: 10 additions & 1 deletion src/views/FileEditView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,16 @@ onUnmounted(() => {
v-if="fileContent !== null && schemaMetaDetails.schema"
:class="`bg-white ${!previewURL && 'px-12 py-8 non-preview-height'} d-block file-editor ${schemaMetaDetails.generic && 'file-editor-code'}`"
>
<v-row no-gutters :class="previewURL ? 'd-flex' : ''">
<div
v-if="file.encoding === 'none'"
class="d-flex align-center justify-center flex-column h-50"
>
<router-link target="_blank" :href="file.download_url"
>View Raw</router-link
>
<p>(Sorry about that, but we can’t show files that are big right now.)</p>
</div>
<v-row v-else no-gutters :class="previewURL ? 'd-flex' : ''">
<v-col :cols="previewURL ? 3 : 12" class="overflow-x-auto">
<eox-jsonform
:schema="schemaMetaDetails.schema"
Expand Down