feat: disable convert when uploading

issue #177
This commit is contained in:
C4illin
2024-11-12 22:30:16 +01:00
parent 24bea6e4d2
commit 58e220e82d

View File

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