update upload file/folder list

This commit is contained in:
Ryan
2025-03-14 20:40:03 -04:00
committed by GitHub
parent 9a536653a7
commit eee3611da9
2 changed files with 816 additions and 543 deletions

File diff suppressed because it is too large Load Diff

441
upload.js
View File

@@ -2,86 +2,144 @@ import { loadFileList, displayFilePreview, initFileActions } from './fileManager
import { showToast, escapeHTML } from './domUtils.js';
import { loadFolderTree } from './folderManager.js';
export function initUpload() {
const fileInput = document.getElementById("file");
// Enhancement: Allow folder upload with subfolders by setting directory attributes.
if (fileInput) {
fileInput.setAttribute("webkitdirectory", "");
fileInput.setAttribute("mozdirectory", "");
fileInput.setAttribute("directory", "");
// Helper: Recursively traverse a dropped folder.
function traverseFileTreePromise(item, path = "") {
return new Promise((resolve, reject) => {
if (item.isFile) {
item.file(file => {
// Instead of modifying file.webkitRelativePath (read-only),
// define a new property called "customRelativePath"
Object.defineProperty(file, 'customRelativePath', {
value: path + file.name,
writable: true,
configurable: true
});
resolve([file]);
});
} else if (item.isDirectory) {
const dirReader = item.createReader();
dirReader.readEntries(entries => {
const promises = [];
for (let i = 0; i < entries.length; i++) {
promises.push(traverseFileTreePromise(entries[i], path + item.name + "/"));
}
Promise.all(promises).then(results => {
resolve(results.flat());
});
});
} else {
resolve([]);
}
});
}
const progressContainer = document.getElementById("uploadProgressContainer");
const uploadForm = document.getElementById("uploadFileForm");
const dropArea = document.getElementById("uploadDropArea");
// Helper: Given DataTransfer items, recursively retrieve files.
function getFilesFromDataTransferItems(items) {
const promises = [];
for (let i = 0; i < items.length; i++) {
const entry = items[i].webkitGetAsEntry();
if (entry) {
promises.push(traverseFileTreePromise(entry));
}
}
return Promise.all(promises).then(results => results.flat());
}
// Helper function: set the drop area's default layout using CSS classes.
function setDropAreaDefault() {
if (dropArea) {
dropArea.innerHTML = `
<div id="uploadInstruction" class="upload-instruction">
Drop files here or click 'Choose files'
</div>
<div id="uploadFileRow" class="upload-file-row">
<button id="customChooseBtn" type="button">
Choose files
</button>
</div>
<!-- New wrapper below the upload row -->
<div id="fileInfoWrapper" class="file-info-wrapper">
<div id="fileInfoContainer" class="file-info-container">
<span id="fileInfoDefault">No files selected</span>
</div>
</div>
// Helper: Update file info container count/preview.
function updateFileInfoCount() {
const fileInfoContainer = document.getElementById("fileInfoContainer");
if (fileInfoContainer && window.selectedFiles) {
if (window.selectedFiles.length === 0) {
fileInfoContainer.innerHTML = `<span id="fileInfoDefault">No files selected</span>`;
} else if (window.selectedFiles.length === 1) {
fileInfoContainer.innerHTML = `
<div id="filePreviewContainer" class="file-preview-container" style="display:inline-block;"></div>
<span id="fileNameDisplay" class="file-name-display">${escapeHTML(window.selectedFiles[0].name)}</span>
`;
} else {
fileInfoContainer.innerHTML = `
<div id="filePreviewContainer" class="file-preview-container" style="display:inline-block;"></div>
<span id="fileCountDisplay" class="file-name-display">${window.selectedFiles.length} files selected</span>
`;
}
// Show preview of first file.
const previewContainer = document.getElementById("filePreviewContainer");
if (previewContainer && window.selectedFiles.length > 0) {
previewContainer.innerHTML = "";
displayFilePreview(window.selectedFiles[0], previewContainer);
}
// Initialize drop area.
if (dropArea) {
dropArea.classList.add("upload-drop-area");
setDropAreaDefault();
dropArea.addEventListener("dragover", function (e) {
e.preventDefault();
dropArea.style.backgroundColor = "#f8f8f8";
});
dropArea.addEventListener("dragleave", function (e) {
e.preventDefault();
dropArea.style.backgroundColor = "";
});
dropArea.addEventListener("drop", function (e) {
e.preventDefault();
dropArea.style.backgroundColor = "";
const dt = e.dataTransfer;
if (dt && dt.files && dt.files.length > 0) {
fileInput.files = dt.files;
fileInput.dispatchEvent(new Event("change"));
}
});
dropArea.addEventListener("click", function () {
fileInput.click();
});
}
}
// When files are selected, update file info container and build progress list.
if (fileInput) {
fileInput.addEventListener("change", function () {
const files = fileInput.files;
// Helper: Create a file entry element with a remove button.
function createFileEntry(file) {
const li = document.createElement("li");
li.classList.add("upload-progress-item");
li.style.display = "flex";
li.dataset.uploadIndex = file.uploadIndex;
// Create remove button positioned to the left of the preview.
const removeBtn = document.createElement("button");
removeBtn.classList.add("remove-file-btn");
removeBtn.textContent = "×";
removeBtn.addEventListener("click", function (e) {
e.stopPropagation();
// Remove file from global selected files array.
const uploadIndex = file.uploadIndex;
window.selectedFiles = window.selectedFiles.filter(f => f.uploadIndex !== uploadIndex);
li.remove();
updateFileInfoCount();
});
// Store the button so we can hide it later when upload completes.
li.removeBtn = removeBtn;
const preview = document.createElement("div");
preview.className = "file-preview";
displayFilePreview(file, preview);
const nameDiv = document.createElement("div");
nameDiv.classList.add("upload-file-name");
nameDiv.textContent = file.name;
const progDiv = document.createElement("div");
progDiv.classList.add("progress", "upload-progress-div");
progDiv.style.flex = "0 0 250px";
progDiv.style.marginLeft = "5px";
const progBar = document.createElement("div");
progBar.classList.add("progress-bar");
progBar.style.width = "0%";
progBar.innerText = "0%";
progDiv.appendChild(progBar);
// Append in order: remove button, preview, name, progress.
li.appendChild(removeBtn);
li.appendChild(preview);
li.appendChild(nameDiv);
li.appendChild(progDiv);
li.progressBar = progBar;
li.startTime = Date.now();
return li;
}
// Process selected files: Build preview/progress list and store files for later submission.
function processFiles(filesInput) {
const fileInfoContainer = document.getElementById("fileInfoContainer");
const files = Array.from(filesInput);
// Update file info container with preview and file count.
if (fileInfoContainer) {
if (files.length > 0) {
if (files.length === 1) {
fileInfoContainer.innerHTML = `
<div id="filePreviewContainer" class="file-preview-container"></div>
<div id="filePreviewContainer" class="file-preview-container" style="display:inline-block;"></div>
<span id="fileNameDisplay" class="file-name-display">${escapeHTML(files[0].name)}</span>
`;
} else {
fileInfoContainer.innerHTML = `
<div id="filePreviewContainer" class="file-preview-container"></div>
<div id="filePreviewContainer" class="file-preview-container" style="display:inline-block;"></div>
<span id="fileCountDisplay" class="file-name-display">${files.length} files selected</span>
`;
}
@@ -95,28 +153,34 @@ export function initUpload() {
}
}
// Convert FileList to an array and assign a unique uploadIndex to each file.
const allFiles = Array.from(files);
allFiles.forEach((file, index) => {
// Assign unique uploadIndex to each file.
files.forEach((file, index) => {
file.uploadIndex = index;
});
// Build progress list.
const progressContainer = document.getElementById("uploadProgressContainer");
progressContainer.innerHTML = "";
if (allFiles.length > 0) {
if (files.length > 0) {
const maxDisplay = 10;
const list = document.createElement("ul");
list.classList.add("upload-progress-list");
// Check if any file has a relative path (i.e. folder upload).
const hasRelativePaths = allFiles.some(file => file.webkitRelativePath && file.webkitRelativePath.trim() !== "");
// Determine grouping using relative path.
const hasRelativePaths = files.some(file => {
const rel = file.webkitRelativePath || file.customRelativePath || "";
return rel.trim() !== "";
});
if (hasRelativePaths) {
// Group files by folder.
const fileGroups = {};
allFiles.forEach(file => {
files.forEach(file => {
let folderName = "Root";
if (file.webkitRelativePath && file.webkitRelativePath.trim() !== "") {
const parts = file.webkitRelativePath.split("/");
const relativePath = file.webkitRelativePath || file.customRelativePath || "";
if (relativePath.trim() !== "") {
const parts = relativePath.split("/");
if (parts.length > 1) {
folderName = parts.slice(0, parts.length - 1).join("/");
}
@@ -127,137 +191,74 @@ export function initUpload() {
fileGroups[folderName].push(file);
});
// Create a list element for each folder group.
// Create list elements for each folder group.
Object.keys(fileGroups).forEach(folderName => {
// Folder header with Material Icon.
const folderLi = document.createElement("li");
folderLi.classList.add("upload-folder-group");
folderLi.innerHTML = `<i class="material-icons folder-icon" style="vertical-align:middle;">folder</i> ${folderName}:`;
folderLi.innerHTML = `<i class="material-icons folder-icon" style="vertical-align:middle; margin-right:8px;">folder</i> ${folderName}:`;
list.appendChild(folderLi);
// Nested list for files in this folder.
// Nested list for files.
const nestedUl = document.createElement("ul");
nestedUl.classList.add("upload-folder-group-list");
fileGroups[folderName]
.sort((a, b) => a.uploadIndex - b.uploadIndex)
.forEach(file => {
const li = document.createElement("li");
li.classList.add("upload-progress-item");
li.style.display = "flex";
li.dataset.uploadIndex = file.uploadIndex;
const preview = document.createElement("div");
preview.className = "file-preview";
displayFilePreview(file, preview);
const nameDiv = document.createElement("div");
nameDiv.classList.add("upload-file-name");
// Only show the file's basename.
nameDiv.textContent = file.name;
const progDiv = document.createElement("div");
progDiv.classList.add("progress", "upload-progress-div");
progDiv.style.flex = "0 0 250px";
progDiv.style.marginLeft = "5px";
const progBar = document.createElement("div");
progBar.classList.add("progress-bar");
progBar.style.width = "0%";
progBar.innerText = "0%";
progDiv.appendChild(progBar);
li.appendChild(preview);
li.appendChild(nameDiv);
li.appendChild(progDiv);
li.progressBar = progBar;
li.startTime = Date.now();
const li = createFileEntry(file);
nestedUl.appendChild(li);
});
list.appendChild(nestedUl);
});
} else {
// Normal flat list (no grouping)
allFiles.forEach((file, index) => {
const li = document.createElement("li");
li.classList.add("upload-progress-item");
// Flat list.
files.forEach((file, index) => {
const li = createFileEntry(file);
li.style.display = (index < maxDisplay) ? "flex" : "none";
li.dataset.uploadIndex = index;
const preview = document.createElement("div");
preview.className = "file-preview";
displayFilePreview(file, preview);
const nameDiv = document.createElement("div");
nameDiv.classList.add("upload-file-name");
nameDiv.textContent = file.name;
const progDiv = document.createElement("div");
progDiv.classList.add("progress", "upload-progress-div");
progDiv.style.flex = "0 0 250px";
progDiv.style.marginLeft = "5px";
const progBar = document.createElement("div");
progBar.classList.add("progress-bar");
progBar.style.width = "0%";
progBar.innerText = "0%";
progDiv.appendChild(progBar);
li.appendChild(preview);
li.appendChild(nameDiv);
li.appendChild(progDiv);
li.progressBar = progBar;
li.startTime = Date.now();
list.appendChild(li);
});
if (allFiles.length > maxDisplay) {
if (files.length > maxDisplay) {
const extra = document.createElement("li");
extra.classList.add("upload-progress-extra");
extra.textContent = `Uploading additional ${allFiles.length - maxDisplay} file(s)...`;
extra.textContent = `Uploading additional ${files.length - maxDisplay} file(s)...`;
extra.style.display = "flex";
list.appendChild(extra);
}
}
progressContainer.appendChild(list);
}
});
}
// Submit handler.
if (uploadForm) {
uploadForm.addEventListener("submit", function (e) {
e.preventDefault();
const files = fileInput.files;
if (files.length === 0) {
showToast("No files selected.");
return;
}
const allFiles = Array.from(files);
// Make sure each file has an uploadIndex (if not already assigned).
allFiles.forEach((file, index) => {
if (typeof file.uploadIndex === "undefined") file.uploadIndex = index;
});
const maxDisplay = 10;
// Store files globally for submission.
window.selectedFiles = files;
updateFileInfoCount();
}
// Function to handle file uploads; triggered when the user clicks the "Upload" button.
function submitFiles(allFiles) {
const folderToUse = window.currentFolder || "root";
// Build a mapping of uploadIndex => progress element.
const progressContainer = document.getElementById("uploadProgressContainer");
const fileInput = document.getElementById("file");
// Map uploadIndex to progress element.
const progressElements = {};
// Query all file list items (they have the class "upload-progress-item")
const listItems = progressContainer.querySelectorAll("li.upload-progress-item");
listItems.forEach(item => {
progressElements[item.dataset.uploadIndex] = item;
});
let finishedCount = 0;
let allSucceeded = true;
const uploadResults = new Array(allFiles.length).fill(false);
allFiles.forEach((file, index) => {
allFiles.forEach(file => {
const formData = new FormData();
formData.append("file[]", file);
formData.append("folder", folderToUse);
// If a relative path is available, send it.
if (file.webkitRelativePath && file.webkitRelativePath !== "") {
formData.append("relativePath", file.webkitRelativePath);
const relativePath = file.webkitRelativePath || file.customRelativePath || "";
if (relativePath.trim() !== "") {
formData.append("relativePath", relativePath);
}
const xhr = new XMLHttpRequest();
let currentPercent = 0;
@@ -292,6 +293,10 @@ export function initUpload() {
if (li) {
li.progressBar.style.width = "100%";
li.progressBar.innerText = "Done";
// Hide the remove button now that upload is done.
if (li.removeBtn) {
li.removeBtn.style.display = "none";
}
}
uploadResults[file.uploadIndex] = true;
} else {
@@ -301,9 +306,8 @@ export function initUpload() {
allSucceeded = false;
}
finishedCount++;
console.log("Upload response for file", file.name, xhr.responseText);
if (finishedCount === allFiles.length) {
refreshFileList();
refreshFileList(allFiles, uploadResults, progressElements);
}
});
@@ -315,9 +319,8 @@ export function initUpload() {
uploadResults[file.uploadIndex] = false;
allSucceeded = false;
finishedCount++;
console.error("Error uploading file:", file.name);
if (finishedCount === allFiles.length) {
refreshFileList();
refreshFileList(allFiles, uploadResults, progressElements);
}
});
@@ -329,9 +332,8 @@ export function initUpload() {
uploadResults[file.uploadIndex] = false;
allSucceeded = false;
finishedCount++;
console.error("Upload aborted for file:", file.name);
if (finishedCount === allFiles.length) {
refreshFileList();
refreshFileList(allFiles, uploadResults, progressElements);
}
});
@@ -339,14 +341,14 @@ export function initUpload() {
xhr.send(formData);
});
function refreshFileList() {
function refreshFileList(allFiles, uploadResults, progressElements) {
loadFileList(folderToUse)
.then(serverFiles => {
initFileActions();
serverFiles = (serverFiles || []).map(item => item.name.trim().toLowerCase());
allFiles.forEach((file, index) => {
allFiles.forEach(file => {
// Skip verification for folder-uploaded files.
if (file.webkitRelativePath && file.webkitRelativePath.trim() !== "") {
if ((file.webkitRelativePath || file.customRelativePath || "").trim() !== "") {
return;
}
const clientFileName = file.name.trim().toLowerCase();
@@ -359,10 +361,19 @@ export function initUpload() {
}
});
setTimeout(() => {
if (fileInput) fileInput.value = "";
// Hide remove buttons in progress container.
const removeBtns = progressContainer.querySelectorAll("button.remove-file-btn");
removeBtns.forEach(btn => btn.style.display = "none");
progressContainer.innerHTML = "";
fileInput.value = "";
window.selectedFiles = [];
const fileInfoContainer = document.getElementById("fileInfoContainer");
if (fileInfoContainer) {
fileInfoContainer.innerHTML = `<span id="fileInfoDefault">No files selected</span>`;
}
const dropArea = document.getElementById("uploadDropArea");
if (dropArea) setDropAreaDefault();
}, 10000);
}, 5000);
if (!allSucceeded) {
showToast("Some files failed to upload. Please check the list.");
}
@@ -375,6 +386,94 @@ export function initUpload() {
loadFolderTree(window.currentFolder);
});
}
}
// Main initUpload: sets up file input, drop area, and form submission.
function initUpload() {
const fileInput = document.getElementById("file");
const dropArea = document.getElementById("uploadDropArea");
const uploadForm = document.getElementById("uploadFileForm");
// Set folder upload attributes.
if (fileInput) {
fileInput.setAttribute("webkitdirectory", "");
fileInput.setAttribute("mozdirectory", "");
fileInput.setAttribute("directory", "");
}
// Helper: Set default drop area content.
function setDropAreaDefault() {
if (dropArea) {
dropArea.innerHTML = `
<div id="uploadInstruction" class="upload-instruction">
Drop files/folders here or click 'Choose files'
</div>
<div id="uploadFileRow" class="upload-file-row">
<button id="customChooseBtn" type="button">
Choose files
</button>
</div>
<div id="fileInfoWrapper" class="file-info-wrapper">
<div id="fileInfoContainer" class="file-info-container">
<span id="fileInfoDefault">No files selected</span>
</div>
</div>
`;
}
}
if (dropArea) {
dropArea.classList.add("upload-drop-area");
setDropAreaDefault();
dropArea.addEventListener("dragover", function (e) {
e.preventDefault();
// Use a darker color if dark mode is active.
if (document.body.classList.contains("dark-mode")) {
dropArea.style.backgroundColor = "#333";
} else {
dropArea.style.backgroundColor = "#f8f8f8";
}
});
dropArea.addEventListener("dragleave", function (e) {
e.preventDefault();
dropArea.style.backgroundColor = "";
});
dropArea.addEventListener("drop", function (e) {
e.preventDefault();
dropArea.style.backgroundColor = "";
const dt = e.dataTransfer;
if (dt.items && dt.items.length > 0) {
getFilesFromDataTransferItems(dt.items).then(files => {
if (files.length > 0) {
processFiles(files);
}
});
} else if (dt.files && dt.files.length > 0) {
processFiles(dt.files);
}
});
dropArea.addEventListener("click", function () {
if (fileInput) fileInput.click();
});
}
if (fileInput) {
fileInput.addEventListener("change", function () {
processFiles(fileInput.files);
});
}
if (uploadForm) {
uploadForm.addEventListener("submit", function (e) {
e.preventDefault();
const files = window.selectedFiles || (fileInput ? fileInput.files : []);
if (!files || files.length === 0) {
showToast("No files selected.");
return;
}
submitFiles(files);
});
}
}
export { initUpload };