Skip to content

Commit

Permalink
ui/project_form: Improve file handling in UI
Browse files Browse the repository at this point in the history
- 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: nexB#991
Signed-off-by: Jayanth Kumar <jknani111@gmail.com>
  • Loading branch information
jayanth-kumar-morem committed Dec 20, 2023
1 parent ce4cae0 commit e7bf48a
Showing 1 changed file with 39 additions and 2 deletions.
41 changes: 39 additions & 2 deletions scancodeio/static/add-inputs.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,33 @@
// 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
function updateFiles() {
if (fileInput.files.length > 0) {
const fileName = document.querySelector('#inputs_file_name');
fileName.innerHTML = "";
for (let file of fileInput.files) {
fileName.innerHTML += `<span class="is-block">${file.name}</span>`;

// 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 += `
<span class="is-flex is-justify-content-space-between is-block" id="file-name-${fileNameWithoutSpaces}">
<span class="is-block">${file.name}</span>
<a href="#" onclick="removeFile('${fileNameWithoutSpaces}')" class="model-button" id="file-delete-btn-${fileNameWithoutSpaces}">
<i class="fa-solid fa-trash-can mr-2"></i>
</a>
</span>
`;
document.getElementById("file-delete-btn-"+ fileNameWithoutSpaces).addEventListener("click", function(event){
disableEvent(event);
removeFile(fileNameWithoutSpaces);
});
}
}
}
Expand All @@ -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;
Expand Down

0 comments on commit e7bf48a

Please sign in to comment.