From 1e8bc3e14ce0a3fed832d415c6ff86f57a1ac83e Mon Sep 17 00:00:00 2001 From: Paul Chavard Date: Tue, 12 Feb 2019 17:56:06 +0100 Subject: [PATCH] Refactor upload progress bar --- .../shared/activestorage/progress.js | 61 ++++++++++++------- 1 file changed, 38 insertions(+), 23 deletions(-) diff --git a/app/javascript/shared/activestorage/progress.js b/app/javascript/shared/activestorage/progress.js index aa428a4ac..996fb8c11 100644 --- a/app/javascript/shared/activestorage/progress.js +++ b/app/javascript/shared/activestorage/progress.js @@ -1,49 +1,64 @@ addEventListener('direct-upload:initialize', event => { - const target = event.target, - detail = event.detail, - id = detail.id, - file = detail.file; + const { + target, + detail: { + id, + file: { name: filename } + } + } = event; - target.insertAdjacentHTML( - 'beforebegin', - '\n
\n
\n' + - file.name + - '\n
\n' + const errorElements = target.parentElement.querySelectorAll( + '.direct-upload--error' ); + for (let element of errorElements) { + element.remove(); + } + target.insertAdjacentHTML('beforebegin', template(id, filename)); }); addEventListener('direct-upload:start', event => { const id = event.detail.id, - element = document.getElementById('direct-upload-' + id); + element = getDirectUploadElement(id); element.classList.remove('direct-upload--pending'); + return false; }); addEventListener('direct-upload:progress', event => { - const id = event.detail.id, - progress = event.detail.progress, - progressElement = document.getElementById('direct-upload-progress-' + id); + const { id, progress } = event.detail, + progressElement = getDirectUploadProgressElement(id); progressElement.style.width = `${progress}%`; }); addEventListener('direct-upload:error', event => { - event.preventDefault(); - const id = event.detail.id, - error = event.detail.error, - element = document.getElementById('direct-upload-' + id); + const { id, error } = event.detail, + element = getDirectUploadElement(id); element.classList.add('direct-upload--error'); element.setAttribute('title', error); }); addEventListener('direct-upload:end', event => { - const id = event.detail.id, - element = document.getElementById('direct-upload-' + id); + const { id } = event.detail, + element = getDirectUploadElement(id); element.classList.add('direct-upload--complete'); }); + +function template(id, filename) { + return `
+
+ ${filename} +
`; +} + +function getDirectUploadElement(id) { + return document.getElementById(`direct-upload-${id}`); +} + +function getDirectUploadProgressElement(id) { + return document.querySelector( + `#direct-upload-${id} .direct-upload__progress` + ); +}