Merge pull request #233 from Lacni135/feature-progress

Added progress bar for file upload
This commit is contained in:
Emrik Östling 2025-02-28 09:57:39 +01:00 committed by GitHub
commit a8ed60d48f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,236 +1,257 @@
const webroot = document.querySelector("meta[name='webroot']").content; const webroot = document.querySelector("meta[name='webroot']").content;
const fileInput = document.querySelector('input[type="file"]'); const fileInput = document.querySelector('input[type="file"]');
const dropZone = document.getElementById("dropzone"); const dropZone = document.getElementById("dropzone");
const convertButton = document.querySelector("input[type='submit']"); const convertButton = document.querySelector("input[type='submit']");
const fileNames = []; const fileNames = [];
let fileType; let fileType;
let pendingFiles = 0; let pendingFiles = 0;
let formatSelected = false; let formatSelected = false;
dropZone.addEventListener("dragover", () => { dropZone.addEventListener("dragover", () => {
dropZone.classList.add("dragover"); dropZone.classList.add("dragover");
}); });
dropZone.addEventListener("dragleave", () => { dropZone.addEventListener("dragleave", () => {
dropZone.classList.remove("dragover"); dropZone.classList.remove("dragover");
}); });
dropZone.addEventListener("drop", () => { dropZone.addEventListener("drop", () => {
dropZone.classList.remove("dragover"); dropZone.classList.remove("dragover");
}); });
const selectContainer = document.querySelector("form .select_container"); const selectContainer = document.querySelector("form .select_container");
const updateSearchBar = () => { const updateSearchBar = () => {
const convertToInput = document.querySelector( const convertToInput = document.querySelector(
"input[name='convert_to_search']", "input[name='convert_to_search']",
); );
const convertToPopup = document.querySelector(".convert_to_popup"); const convertToPopup = document.querySelector(".convert_to_popup");
const convertToGroupElements = document.querySelectorAll(".convert_to_group"); const convertToGroupElements = document.querySelectorAll(".convert_to_group");
const convertToGroups = {}; const convertToGroups = {};
const convertToElement = document.querySelector("select[name='convert_to']"); const convertToElement = document.querySelector("select[name='convert_to']");
const showMatching = (search) => { const showMatching = (search) => {
for (const [targets, groupElement] of Object.values(convertToGroups)) { for (const [targets, groupElement] of Object.values(convertToGroups)) {
let matchingTargetsFound = 0; let matchingTargetsFound = 0;
for (const target of targets) { for (const target of targets) {
if (target.dataset.target.includes(search)) { if (target.dataset.target.includes(search)) {
matchingTargetsFound++; matchingTargetsFound++;
target.classList.remove("hidden"); target.classList.remove("hidden");
target.classList.add("flex"); target.classList.add("flex");
} else { } else {
target.classList.add("hidden"); target.classList.add("hidden");
target.classList.remove("flex"); target.classList.remove("flex");
} }
} }
if (matchingTargetsFound === 0) { if (matchingTargetsFound === 0) {
groupElement.classList.add("hidden"); groupElement.classList.add("hidden");
groupElement.classList.remove("flex"); groupElement.classList.remove("flex");
} else { } else {
groupElement.classList.remove("hidden"); groupElement.classList.remove("hidden");
groupElement.classList.add("flex"); groupElement.classList.add("flex");
} }
} }
}; };
for (const groupElement of convertToGroupElements) { for (const groupElement of convertToGroupElements) {
const groupName = groupElement.dataset.converter; const groupName = groupElement.dataset.converter;
const targetElements = groupElement.querySelectorAll(".target"); const targetElements = groupElement.querySelectorAll(".target");
const targets = Array.from(targetElements); const targets = Array.from(targetElements);
for (const target of targets) { for (const target of targets) {
target.onmousedown = () => { target.onmousedown = () => {
convertToElement.value = target.dataset.value; convertToElement.value = target.dataset.value;
convertToInput.value = `${target.dataset.target} using ${target.dataset.converter}`; convertToInput.value = `${target.dataset.target} using ${target.dataset.converter}`;
formatSelected = true; formatSelected = true;
if (pendingFiles === 0 && fileNames.length > 0) { if (pendingFiles === 0 && fileNames.length > 0) {
convertButton.disabled = false; convertButton.disabled = false;
} }
showMatching(""); showMatching("");
}; };
} }
convertToGroups[groupName] = [targets, groupElement]; convertToGroups[groupName] = [targets, groupElement];
} }
convertToInput.addEventListener("input", (e) => { convertToInput.addEventListener("input", (e) => {
showMatching(e.target.value.toLowerCase()); showMatching(e.target.value.toLowerCase());
}); });
convertToInput.addEventListener("search", () => { convertToInput.addEventListener("search", () => {
// when the user clears the search bar using the 'x' button // when the user clears the search bar using the 'x' button
convertButton.disabled = true; convertButton.disabled = true;
formatSelected = false; formatSelected = false;
}); });
convertToInput.addEventListener("blur", (e) => { convertToInput.addEventListener("blur", (e) => {
// Keep the popup open even when clicking on a target button // Keep the popup open even when clicking on a target button
// for a split second to allow the click to go through // for a split second to allow the click to go through
if (e?.relatedTarget?.classList?.contains("target")) { if (e?.relatedTarget?.classList?.contains("target")) {
convertToPopup.classList.add("hidden"); convertToPopup.classList.add("hidden");
convertToPopup.classList.remove("flex"); convertToPopup.classList.remove("flex");
return; return;
} }
convertToPopup.classList.add("hidden"); convertToPopup.classList.add("hidden");
convertToPopup.classList.remove("flex"); convertToPopup.classList.remove("flex");
}); });
convertToInput.addEventListener("focus", () => { convertToInput.addEventListener("focus", () => {
convertToPopup.classList.remove("hidden"); convertToPopup.classList.remove("hidden");
convertToPopup.classList.add("flex"); convertToPopup.classList.add("flex");
}); });
}; };
// Add a 'change' event listener to the file input element // Add a 'change' event listener to the file input element
fileInput.addEventListener("change", (e) => { fileInput.addEventListener("change", (e) => {
// Get the selected files from the event target // Get the selected files from the event target
const files = e.target.files; const files = e.target.files;
// Select the file-list table // Select the file-list table
const fileList = document.querySelector("#file-list"); const fileList = document.querySelector("#file-list");
// Loop through the selected files // Loop through the selected files
for (const file of files) { for (const file of files) {
// Create a new table row for each file // Create a new table row for each file
const row = document.createElement("tr"); const row = document.createElement("tr");
row.innerHTML = ` row.innerHTML = `
<td>${file.name}</td> <td>${file.name}</td>
<td>${(file.size / 1024).toFixed(2)} kB</td> <td><progress max="100"></progress></td>
<td><a onclick="deleteRow(this)">Remove</a></td> <td>${(file.size / 1024).toFixed(2)} kB</td>
`; <td><a onclick="deleteRow(this)">Remove</a></td>
`;
if (!fileType) {
fileType = file.name.split(".").pop(); if (!fileType) {
fileInput.setAttribute("accept", `.${fileType}`); fileType = file.name.split(".").pop();
setTitle(); fileInput.setAttribute("accept", `.${fileType}`);
setTitle();
// choose the option that matches the file type
// for (const option of convertFromSelect.children) { // choose the option that matches the file type
// console.log(option.value); // for (const option of convertFromSelect.children) {
// if (option.value === fileType) { // console.log(option.value);
// option.selected = true; // if (option.value === fileType) {
// } // option.selected = true;
// } // }
// }
fetch(`${webroot}/conversions`, {
method: "POST", fetch(`${webroot}/conversions`, {
body: JSON.stringify({ fileType: fileType }), method: "POST",
headers: { body: JSON.stringify({ fileType: fileType }),
"Content-Type": "application/json", headers: {
}, "Content-Type": "application/json",
}) },
.then((res) => res.text()) })
.then((html) => { .then((res) => res.text())
selectContainer.innerHTML = html; .then((html) => {
updateSearchBar(); selectContainer.innerHTML = html;
}) updateSearchBar();
.catch((err) => console.log(err)); })
} .catch((err) => console.log(err));
}
// Append the row to the file-list table
fileList.appendChild(row); // Append the row to the file-list table
fileList.appendChild(row);
// Append the file to the hidden input
fileNames.push(file.name); //Imbed row into the file to reference later
} file.htmlRow = row;
uploadFiles(files);
}); // Append the file to the hidden input
fileNames.push(file.name);
const setTitle = () => {
const title = document.querySelector("h1"); uploadFile(file);
title.textContent = `Convert ${fileType ? `.${fileType}` : ""}`; }
}; });
// Add a onclick for the delete button const setTitle = () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars const title = document.querySelector("h1");
const deleteRow = (target) => { title.textContent = `Convert ${fileType ? `.${fileType}` : ""}`;
const filename = target.parentElement.parentElement.children[0].textContent; };
const row = target.parentElement.parentElement;
row.remove(); // Add a onclick for the delete button
// eslint-disable-next-line @typescript-eslint/no-unused-vars
// remove from fileNames const deleteRow = (target) => {
const index = fileNames.indexOf(filename); const filename = target.parentElement.parentElement.children[0].textContent;
fileNames.splice(index, 1); const row = target.parentElement.parentElement;
row.remove();
// reset fileInput
fileInput.value = ""; // remove from fileNames
const index = fileNames.indexOf(filename);
// if fileNames is empty, reset fileType fileNames.splice(index, 1);
if (fileNames.length === 0) {
fileType = null; // reset fileInput
fileInput.removeAttribute("accept"); fileInput.value = "";
convertButton.disabled = true;
setTitle(); // if fileNames is empty, reset fileType
} if (fileNames.length === 0) {
fileType = null;
fetch(`${webroot}/delete`, { fileInput.removeAttribute("accept");
method: "POST", convertButton.disabled = true;
body: JSON.stringify({ filename: filename }), setTitle();
headers: { }
"Content-Type": "application/json",
}, fetch(`${webroot}/delete`, {
}) method: "POST",
.catch((err) => console.log(err)); body: JSON.stringify({ filename: filename }),
}; headers: {
"Content-Type": "application/json",
const uploadFiles = (files) => { },
convertButton.disabled = true; })
convertButton.textContent = "Uploading..."; .catch((err) => console.log(err));
pendingFiles += 1; };
const formData = new FormData(); const uploadFile = (file) => {
convertButton.disabled = true;
for (const file of files) { convertButton.textContent = "Uploading...";
formData.append("file", file, file.name); pendingFiles += 1;
}
const formData = new FormData();
fetch(`${webroot}/upload`, { formData.append("file", file, file.name);
method: "POST",
body: formData, let xhr = new XMLHttpRequest();
})
.then((res) => res.json()) xhr.open("POST", `${webroot}/upload`, true);
.then((data) => {
pendingFiles -= 1; xhr.onload = (e) => {
if (pendingFiles === 0) { let data = JSON.parse(xhr.responseText);
if (formatSelected) {
convertButton.disabled = false; pendingFiles -= 1;
} if (pendingFiles === 0) {
convertButton.textContent = "Convert"; if (formatSelected) {
} convertButton.disabled = false;
console.log(data); }
}) convertButton.textContent = "Convert";
.catch((err) => console.log(err)); }
};
//Remove the progress bar when upload is done
const formConvert = document.querySelector(`form[action='${webroot}/convert']`); let progressbar = file.htmlRow.getElementsByTagName("progress");
progressbar[0].parentElement.remove();
formConvert.addEventListener("submit", () => { console.log(data);
const hiddenInput = document.querySelector("input[name='file_names']"); };
hiddenInput.value = JSON.stringify(fileNames);
}); xhr.upload.onprogress = (e) => {
let sent = e.loaded;
updateSearchBar(); let total = e.total;
console.log(`upload progress (${file.name}):`, (100 * sent) / total);
let progressbar = file.htmlRow.getElementsByTagName("progress");
progressbar[0].value = ((100 * sent) / total);
};
xhr.onerror = (e) => {
console.log(e);
};
xhr.send(formData);
};
const formConvert = document.querySelector(`form[action='${webroot}/convert']`);
formConvert.addEventListener("submit", () => {
const hiddenInput = document.querySelector("input[name='file_names']");
hiddenInput.value = JSON.stringify(fileNames);
});
updateSearchBar();