From 6262891b5669716db7c46dcdcec685d2f55903b5 Mon Sep 17 00:00:00 2001 From: Javan Makhmali Date: Thu, 27 Jul 2017 19:47:03 -0400 Subject: Add JavaScript direct upload support (#81) --- app/javascript/activestorage/ujs.js | 74 +++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 app/javascript/activestorage/ujs.js (limited to 'app/javascript/activestorage/ujs.js') diff --git a/app/javascript/activestorage/ujs.js b/app/javascript/activestorage/ujs.js new file mode 100644 index 0000000000..a2ce2cfc58 --- /dev/null +++ b/app/javascript/activestorage/ujs.js @@ -0,0 +1,74 @@ +import { DirectUploadsController } from "./direct_uploads_controller" +import { findElement } from "./helpers" + +const processingAttribute = "data-direct-uploads-processing" +let started = false + +export function start() { + if (!started) { + started = true + document.addEventListener("submit", didSubmitForm) + document.addEventListener("ajax:before", didSubmitRemoteElement) + } +} + +function didSubmitForm(event) { + handleFormSubmissionEvent(event) +} + +function didSubmitRemoteElement(event) { + if (event.target.tagName == "FORM") { + handleFormSubmissionEvent(event) + } +} + +function handleFormSubmissionEvent(event) { + const form = event.target + + if (form.hasAttribute(processingAttribute)) { + event.preventDefault() + return + } + + const controller = new DirectUploadsController(form) + const { inputs } = controller + + if (inputs.length) { + event.preventDefault() + form.setAttribute(processingAttribute, "") + inputs.forEach(disable) + controller.start(error => { + form.removeAttribute(processingAttribute) + if (error) { + inputs.forEach(enable) + } else { + submitForm(form) + } + }) + } +} + +function submitForm(form) { + let button = findElement(form, "input[type=submit]") + if (button) { + const { disabled } = button + button.disabled = false + button.click() + button.disabled = disabled + } else { + button = document.createElement("input") + button.type = "submit" + button.style = "display:none" + form.appendChild(button) + button.click() + form.removeChild(button) + } +} + +function disable(input) { + input.disabled = true +} + +function enable(input) { + input.disabled = false +} -- cgit v1.2.3