Skip to content

Commit

Permalink
Better Drag and drop handling of files to upload
Browse files Browse the repository at this point in the history
  • Loading branch information
jbidoret committed Oct 16, 2024
1 parent a0e055d commit fe4ef90
Showing 1 changed file with 59 additions and 22 deletions.
81 changes: 59 additions & 22 deletions src/media.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,41 +10,78 @@ window.addEventListener('load', () => {
*/
const fileInput = document.getElementById('file');
const fileMenu = fileInput.closest('details');
const droppedFilesSet = new Set(); // Track dropped files

'drag dragstart dragend dragover dragenter dragleave drop'
.split(' ')
.forEach(function(listener) {
document.body.addEventListener(
listener,
function(e) {
e.preventDefault();
e.stopPropagation();
},
false
);
});

'dragover dragenter'.split(' ').forEach(function(listener) {
const allDragAndDropListeners = [
'drag',
'dragstart',
'dragend',
'dragover',
'dragenter',
'dragleave',
'drop',
];
for (const listener of allDragAndDropListeners) {
document.body.addEventListener(
listener,
function(e) {
e.preventDefault();
e.stopPropagation();
},
false
);
}

const dragListeners = ['dragover', 'dragenter'];
for (const listener of dragListeners) {
document.body.addEventListener(
listener,
function(e) {
fileMenu.setAttribute('open', true);
},
false
);
});
}

document.body.addEventListener(
'drop',
function(e) {
const files = e.dataTransfer.files;
const info = document.createElement('p');
info.className = 'dropped-files-info';
for (const f of files) {
info.innerHTML += `<span>${f.name}</span> `;
const droppedFiles = e.dataTransfer.files;
const fileList = new DataTransfer();

// Prepare user feeedback
const info =
document.querySelector('.dropped-files-info') ||
document.createElement('p');

// If feedback element doesn’t exist
if (!document.querySelector('.dropped-files-info')) {
info.className = 'dropped-files-info';
fileInput.insertAdjacentElement('afterend', info);
}

// Loop through the currently existing files in the file input
for (let i = 0; i < fileInput.files.length; i++) {
fileList.items.add(fileInput.files[i]);
// Track already added files
droppedFilesSet.add(
fileInput.files[i].name + fileInput.files[i].size
);
}
fileInput.insertAdjacentElement('afterend', info);
fileInput.files = files;

// append only new files to droppedFiles array
for (const file of droppedFiles) {
const uniqueID = file.name + file.size;

// Check if the file is already added
if (!droppedFilesSet.has(uniqueID)) {
fileList.items.add(file); // Add file if it's not already added
droppedFilesSet.add(uniqueID); // Add to the tracking set
info.innerHTML += `<span>${file.name}</span> `; // Feedback
}
}

fileInput.files = fileList.files;
},
false
);

0 comments on commit fe4ef90

Please sign in to comment.