aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/app/javascript/activestorage/ujs.js
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2017-08-04 18:05:13 -0500
committerGitHub <noreply@github.com>2017-08-04 18:05:13 -0500
commit552840660389e39f3ba8e47dcf35ab817c01cb48 (patch)
tree5013b2d5a1691ac1f675935eea38848639ac54bc /activestorage/app/javascript/activestorage/ujs.js
parent978b3d604ab082ac0be071245646b0803b8ff382 (diff)
parent3179f089be4f631b9c0f8b431567992164f2bdb4 (diff)
downloadrails-552840660389e39f3ba8e47dcf35ab817c01cb48.tar.gz
rails-552840660389e39f3ba8e47dcf35ab817c01cb48.tar.bz2
rails-552840660389e39f3ba8e47dcf35ab817c01cb48.zip
Merge pull request #30020 from rails/active-storage-import
Add Active Storage to Rails
Diffstat (limited to 'activestorage/app/javascript/activestorage/ujs.js')
-rw-r--r--activestorage/app/javascript/activestorage/ujs.js74
1 files changed, 74 insertions, 0 deletions
diff --git a/activestorage/app/javascript/activestorage/ujs.js b/activestorage/app/javascript/activestorage/ujs.js
new file mode 100644
index 0000000000..a2ce2cfc58
--- /dev/null
+++ b/activestorage/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
+}