From de7f7eef6aac874a3182a4a449def7c15122471f Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sat, 10 Apr 2021 16:00:58 -0400 Subject: [PATCH] Add async uploads with progress --- assets/js/app.js | 2 + assets/js/async_uploads.js | 47 +++++++++++++++++++++++ lib/wiki_web/templates/page/edit.html.eex | 3 +- 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 assets/js/async_uploads.js diff --git a/assets/js/app.js b/assets/js/app.js index af00596..0b9d7cf 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -13,3 +13,5 @@ import "../css/app.scss" // import socket from "./socket" // import "phoenix_html" + +import "./async_uploads" diff --git a/assets/js/async_uploads.js b/assets/js/async_uploads.js new file mode 100644 index 0000000..ec18432 --- /dev/null +++ b/assets/js/async_uploads.js @@ -0,0 +1,47 @@ +document.addEventListener("DOMContentLoaded", () => { + const form = document.querySelector(".edit-upload-form"); + if (!form) return; + + const button = form.querySelector("button[type=submit]"); + button.addEventListener("click", (event) => { + event.preventDefault(); + button.setAttribute("disabled", "true"); + + const file = form.querySelector("input[type=file]").files[0]; + if (!file) return; + + const pageID = /^\/pages\/(\d+)\/edit$/.exec(window.location.pathname)[1]; + const progress = form.querySelector("progress"); + progress.style.visibility = "visible"; + + const fd = new FormData(); + fd.append("_csrf_token", form.querySelector("input[type=hidden]").value); + fd.append("file", file); + + // it's 2021 and fetch doesn't have progress support, smh + const xhr = new XMLHttpRequest(); + xhr.upload.addEventListener("progress", (event) => { + const newVal = event.loaded / event.total; + if (newVal >= 1) { + progress.removeAttribute("value"); + } else { + progress.value = newVal; + } + }); + xhr.addEventListener("load", () => { + window.location.reload(); + }); + xhr.addEventListener("error", (event) => { + console.error(event); + progress.style.visibility = "hidden"; + alert("Upload error"); + }); + xhr.addEventListener("abort", (event) => { + console.error(event); + progress.style.visibility = "hidden"; + alert("Upload aborted"); + }); + xhr.open("POST", `/pages/${pageID}/uploads`); + xhr.send(fd); + }); +}); diff --git a/lib/wiki_web/templates/page/edit.html.eex b/lib/wiki_web/templates/page/edit.html.eex index b3d38bb..9740d52 100644 --- a/lib/wiki_web/templates/page/edit.html.eex +++ b/lib/wiki_web/templates/page/edit.html.eex @@ -28,9 +28,10 @@ <% end %> -<%= form_tag Routes.page_path(@conn, :create_upload, @page.id), method: :post, multipart: true do %> +<%= form_tag Routes.page_path(@conn, :create_upload, @page.id), method: :post, multipart: true, class: "edit-upload-form" do %> <%= submit "Upload" %> + <% end %> <%= link "Back", to: Routes.page_path(@conn, :show, @page.id) %>