From e7bf48a70c7e05e5063864f869befd58eedc73cb Mon Sep 17 00:00:00 2001 From: Jayanth Kumar Date: Thu, 21 Dec 2023 02:26:41 +0530 Subject: [PATCH] ui/project_form: Improve file handling in UI - Enhance file input handling in the UI to avoid losing selected files when adding new inputs. - Introduce a `selectedFiles` array to store and manage selected files. - Display selected files in the UI with additional features, including a delete button. - Update the `removeFile` function to correctly remove files from both the UI and the `selectedFiles` array. Fixes: #991 Signed-off-by: Jayanth Kumar --- scancodeio/static/add-inputs.js | 41 +++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/scancodeio/static/add-inputs.js b/scancodeio/static/add-inputs.js index 508326ce2..51cd303d3 100644 --- a/scancodeio/static/add-inputs.js +++ b/scancodeio/static/add-inputs.js @@ -21,6 +21,8 @@ // Visit https://github.com/nexB/scancode.io for support and download. const fileInput = document.querySelector('#id_input_files'); +let selectedFiles = []; // Store selected files + fileInput.onchange = updateFiles; // Update the list of files to be uploaded in the UI @@ -28,8 +30,24 @@ function updateFiles() { if (fileInput.files.length > 0) { const fileName = document.querySelector('#inputs_file_name'); fileName.innerHTML = ""; - for (let file of fileInput.files) { - fileName.innerHTML += `${file.name}`; + + // Update the selectedFiles array + selectedFiles = selectedFiles.concat(Array.from(fileInput.files)); + + for (let file of selectedFiles) { + const fileNameWithoutSpaces = file.name.replace(/\s/g, ''); + fileName.innerHTML += ` + + ${file.name} + + + + + `; + document.getElementById("file-delete-btn-"+ fileNameWithoutSpaces).addEventListener("click", function(event){ + disableEvent(event); + removeFile(fileNameWithoutSpaces); + }); } } } @@ -40,6 +58,25 @@ function disableEvent(event) { event.preventDefault(); } +function removeFile(fileName) { + selectedFiles = selectedFiles.filter(file => { + const fileNameWithoutSpaces = file.name.replace(/\s/g, ''); + return fileNameWithoutSpaces !== fileName; + }); + + const fileNameElement = document.getElementById(`file-name-${fileName}`); + if (fileNameElement) { + fileNameElement.remove(); + } + + const dataTransfer = new DataTransfer(); + for (let file of selectedFiles) { + dataTransfer.items.add(file); + } + + fileInput.files = dataTransfer.files; +} + function dropHandler(event) { disableEvent(event); const droppedFiles = event.dataTransfer.files;