| 1 | // Attachments in the conversation's composer: the + and its menu (a photo |
| 2 | // or image, which on a phone offers the library and the camera, or a |
| 3 | // file), paste and drop on a desktop, and a chip per file above the words |
| 4 | // with its upload's progress, Remove, and what went wrong in words. Each |
| 5 | // file uploads at once (POST /conversation/attachments, the bytes as the |
| 6 | // body); a send takes the chips that uploaded. The server decides what is |
| 7 | // allowed; here only the size and HEIC are refused early, in its words. |
| 8 | // Thumbnails in the feed open full size in the page. |
| 9 | (function () { |
| 10 | "use strict"; |
| 11 | var form = document.querySelector("#composer[equipo-composer][data-upload]"); |
| 12 | if (!form || !window.XMLHttpRequest) return; |
| 13 | var box = form.querySelector("[equipo-adder]"); |
| 14 | var plus = box.querySelector("[equipo-plus]"); |
| 15 | var menu = box.querySelector("[equipo-add-menu]"); |
| 16 | var chips = form.querySelector("[equipo-chips]"); |
| 17 | var note = form.querySelector("[equipo-add-note]"); |
| 18 | var input = form.querySelector("textarea"); |
| 19 | var template = document.querySelector("template[equipo-chip-template]"); |
| 20 | var max = Number(form.dataset.maxFiles) || 5; |
| 21 | var maxBytes = Number(form.dataset.maxBytes) || 10 << 20; |
| 22 | var items = []; |
| 23 | box.hidden = false; |
| 24 | |
| 25 | // ── The + menu ─────────────────────────────────────────────────── |
| 26 | function show(open, focus) { |
| 27 | menu.hidden = !open; |
| 28 | plus.setAttribute("aria-expanded", String(open)); |
| 29 | if (open && focus) menu.querySelector("[role=menuitem]").focus(); |
| 30 | } |
| 31 | plus.addEventListener("click", function (event) { |
| 32 | // A keyboard press (detail 0) moves focus into the menu. |
| 33 | show(menu.hidden, event.detail === 0); |
| 34 | }); |
| 35 | menu.addEventListener("click", function (event) { |
| 36 | var pick = event.target.closest("[data-pick]"); |
| 37 | if (!pick) return; |
| 38 | show(false); |
| 39 | box.querySelector('[data-picker="' + pick.dataset.pick + '"]').click(); |
| 40 | }); |
| 41 | menu.addEventListener("keydown", function (event) { |
| 42 | var all = Array.from(menu.querySelectorAll("[role=menuitem]")); |
| 43 | var at = all.indexOf(document.activeElement); |
| 44 | if (event.key === "ArrowDown" || event.key === "ArrowUp") { |
| 45 | event.preventDefault(); |
| 46 | all[(at + (event.key === "ArrowDown" ? 1 : all.length - 1)) % all.length].focus(); |
| 47 | } else if (event.key === "Escape") { |
| 48 | event.preventDefault(); |
| 49 | show(false); |
| 50 | plus.focus(); |
| 51 | } else if (event.key === "Tab") { |
| 52 | show(false); |
| 53 | } |
| 54 | }); |
| 55 | document.addEventListener("click", function (event) { |
| 56 | if (!menu.hidden && !box.contains(event.target)) show(false); |
| 57 | }); |
| 58 | box.querySelectorAll("[data-picker]").forEach(function (picker) { |
| 59 | picker.addEventListener("change", function () { |
| 60 | add(picker.files); |
| 61 | picker.value = ""; |
| 62 | input.focus({ preventScroll: true }); |
| 63 | }); |
| 64 | }); |
| 65 | |
| 66 | // ── Chips ──────────────────────────────────────────────────────── |
| 67 | function say(text) { |
| 68 | note.textContent = text || ""; |
| 69 | note.hidden = !text; |
| 70 | } |
| 71 | function size(n) { |
| 72 | if (n < 1024) return n + " B"; |
| 73 | if (n < 1048576) return Math.round(n / 1024) + " KB"; |
| 74 | return (n / 1048576).toFixed(1) + " MB"; |
| 75 | } |
| 76 | function changed() { |
| 77 | chips.hidden = items.length === 0; |
| 78 | form.dispatchEvent(new CustomEvent("equipo:changed")); |
| 79 | } |
| 80 | function add(list) { |
| 81 | say(""); |
| 82 | Array.from(list || []).forEach(function (file) { |
| 83 | if (items.length >= max) { |
| 84 | say(form.dataset.tooMany); |
| 85 | return; |
| 86 | } |
| 87 | items.push(chip(file)); |
| 88 | }); |
| 89 | changed(); |
| 90 | } |
| 91 | function heic(file) { |
| 92 | return /hei[cf]/i.test(file.type) || /\.(heic|heif|hif)$/i.test(file.name || ""); |
| 93 | } |
| 94 | function imageLike(file) { |
| 95 | return /^image\//.test(file.type) || heic(file); |
| 96 | } |
| 97 | // ── Images, prepared here ──────────────────────────────────────── |
| 98 | // The page's policy allows data: images only (no blob:), so a preview |
| 99 | // is drawn on a canvas and kept as a data: URL. Safari decodes HEIC, so |
| 100 | // a HEIC photo goes up as a JPEG (0.85); so does anything over LONG px |
| 101 | // on its longer side. A GIF goes as it is (it may move). |
| 102 | var LONG = 2560, PREVIEW = 320; |
| 103 | function decode(file) { |
| 104 | function viaImage() { |
| 105 | return new Promise(function (resolve, reject) { |
| 106 | var reader = new FileReader(); |
| 107 | reader.onload = function () { |
| 108 | var img = new Image(); |
| 109 | img.onload = function () { resolve(img); }; |
| 110 | img.onerror = reject; |
| 111 | img.src = reader.result; |
| 112 | }; |
| 113 | reader.onerror = reject; |
| 114 | reader.readAsDataURL(file); |
| 115 | }); |
| 116 | } |
| 117 | if (window.createImageBitmap) return createImageBitmap(file).catch(viaImage); |
| 118 | return viaImage(); |
| 119 | } |
| 120 | function canvasOf(img, edge) { |
| 121 | var w = img.naturalWidth || img.width, h = img.naturalHeight || img.height; |
| 122 | var scale = Math.min(1, edge / Math.max(w, h)); |
| 123 | var c = document.createElement("canvas"); |
| 124 | c.width = Math.max(1, Math.round(w * scale)); |
| 125 | c.height = Math.max(1, Math.round(h * scale)); |
| 126 | var g = c.getContext("2d"); |
| 127 | g.fillStyle = "#fff"; |
| 128 | g.fillRect(0, 0, c.width, c.height); |
| 129 | g.drawImage(img, 0, 0, c.width, c.height); |
| 130 | return c; |
| 131 | } |
| 132 | function prepare(item) { |
| 133 | if (item.kind !== "image") return Promise.resolve(); |
| 134 | return decode(item.file).then(function (img) { |
| 135 | item.preview = canvasOf(img, PREVIEW).toDataURL("image/jpeg", 0.8); |
| 136 | var thumb = document.createElement("img"); |
| 137 | thumb.src = item.preview; |
| 138 | thumb.alt = ""; |
| 139 | item.el.querySelector("[equipo-chip-thumb]").replaceChildren(thumb); |
| 140 | var w = img.naturalWidth || img.width, h = img.naturalHeight || img.height; |
| 141 | if (!heic(item.file) && (item.file.type === "image/gif" || Math.max(w, h) <= LONG)) return; |
| 142 | return new Promise(function (resolve) { |
| 143 | canvasOf(img, LONG).toBlob(function (blob) { |
| 144 | if (blob) { |
| 145 | item.file = blob; |
| 146 | item.name = item.name.replace(/\.[^.]*$/, "") + ".jpg"; |
| 147 | } |
| 148 | if (img.close) img.close(); |
| 149 | resolve(); |
| 150 | }, "image/jpeg", 0.85); |
| 151 | }); |
| 152 | }, function () { |
| 153 | // Not decodable here: the server decides (HEIC elsewhere is refused). |
| 154 | item.kind = item.el.dataset.kind = "file"; |
| 155 | }); |
| 156 | } |
| 157 | function chip(file) { |
| 158 | var el = template.content.firstElementChild.cloneNode(true); |
| 159 | var name = file.name || "image"; |
| 160 | var item = { el: el, file: file, name: name, kind: imageLike(file) ? "image" : "file", state: "uploading", done: Promise.resolve() }; |
| 161 | el.dataset.kind = item.kind; |
| 162 | el.dataset.state = "uploading"; |
| 163 | el.querySelector("[equipo-chip-name]").textContent = name; |
| 164 | el.querySelector("[equipo-chip-note]").textContent = form.dataset.uploading || ""; |
| 165 | el.querySelector("[equipo-chip-progress]").setAttribute("aria-label", (form.dataset.uploading || "") + " " + name); |
| 166 | var remove = el.querySelector("[equipo-chip-remove]"); |
| 167 | remove.setAttribute("aria-label", (form.dataset.remove || "%s").replace("%s", name)); |
| 168 | remove.title = remove.getAttribute("aria-label"); |
| 169 | remove.addEventListener("click", function () { drop(item); }); |
| 170 | chips.append(el); |
| 171 | chips.hidden = false; |
| 172 | item.done = prepare(item).then(function () { |
| 173 | if (item.state === "removed") return; |
| 174 | if (item.file.size > maxBytes) fail(item, form.dataset.tooLarge); |
| 175 | else if (heic(item.file) || (item.kind === "file" && heic(file))) fail(item, form.dataset.heic); |
| 176 | else return upload(item); |
| 177 | }).then(changed); |
| 178 | return item; |
| 179 | } |
| 180 | function fail(item, words) { |
| 181 | item.state = item.el.dataset.state = "error"; |
| 182 | item.el.querySelector("[equipo-chip-note]").textContent = words || form.dataset.uploadFailed; |
| 183 | item.el.title = words || form.dataset.uploadFailed; |
| 184 | } |
| 185 | function progress(item, share) { |
| 186 | var pct = Math.round(Math.max(0, Math.min(1, share)) * 100); |
| 187 | var bar = item.el.querySelector("[equipo-chip-progress]"); |
| 188 | bar.setAttribute("aria-valuenow", String(pct)); |
| 189 | bar.style.setProperty("--p", pct + "%"); |
| 190 | } |
| 191 | function upload(item) { |
| 192 | return new Promise(function (resolve) { |
| 193 | var x = new XMLHttpRequest(); |
| 194 | item.xhr = x; |
| 195 | x.open("POST", form.dataset.upload); |
| 196 | x.setRequestHeader("Accept", "application/json"); |
| 197 | x.setRequestHeader("Content-Type", item.file.type || "application/octet-stream"); |
| 198 | x.setRequestHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodeURIComponent(item.name)); |
| 199 | x.upload.onprogress = function (e) { if (e.lengthComputable) progress(item, e.loaded / e.total); }; |
| 200 | x.onload = function () { |
| 201 | var body = {}; |
| 202 | try { body = JSON.parse(x.responseText); } catch (_) { body = {}; } |
| 203 | if (x.status === 201 && body.id) { |
| 204 | item.meta = body; |
| 205 | item.state = item.el.dataset.state = "ready"; |
| 206 | item.el.querySelector("[equipo-chip-note]").textContent = size(body.size); |
| 207 | } else { |
| 208 | fail(item, body.message); |
| 209 | } |
| 210 | changed(); |
| 211 | resolve(); |
| 212 | }; |
| 213 | x.onerror = function () { fail(item); changed(); resolve(); }; |
| 214 | x.onabort = function () { resolve(); }; |
| 215 | x.send(item.file); |
| 216 | }); |
| 217 | } |
| 218 | function drop(item) { |
| 219 | // An upload already made is deleted, so it stops counting against |
| 220 | // the unsent limit; nothing waits on it. |
| 221 | if (item.state === "ready" && item.meta && item.meta.id) { |
| 222 | fetch(form.dataset.upload + "/" + encodeURIComponent(item.meta.id), { method: "DELETE", credentials: "same-origin" }).catch(function () {}); |
| 223 | } |
| 224 | if (item.xhr && item.state === "uploading") item.xhr.abort(); |
| 225 | if (item.state === "uploading") item.state = "removed"; |
| 226 | item.el.remove(); |
| 227 | items = items.filter(function (i) { return i !== item; }); |
| 228 | say(""); |
| 229 | changed(); |
| 230 | input.focus({ preventScroll: true }); |
| 231 | } |
| 232 | |
| 233 | // ── Paste and drop ─────────────────────────────────────────────── |
| 234 | // A pasted image or file (a long-press paste on iOS gives it as an item). |
| 235 | input.addEventListener("paste", function (event) { |
| 236 | var data = event.clipboardData, files = []; |
| 237 | if (data && data.files && data.files.length) files = Array.from(data.files); |
| 238 | else if (data && data.items) { |
| 239 | Array.from(data.items).forEach(function (it) { |
| 240 | var f = it.kind === "file" && it.getAsFile(); |
| 241 | if (f) files.push(f); |
| 242 | }); |
| 243 | } |
| 244 | if (files.length) { |
| 245 | event.preventDefault(); |
| 246 | add(files); |
| 247 | } |
| 248 | }); |
| 249 | var area = document.querySelector("[equipo-conversation]") || form; |
| 250 | function carriesFiles(event) { |
| 251 | return event.dataTransfer && Array.from(event.dataTransfer.types || []).indexOf("Files") >= 0; |
| 252 | } |
| 253 | area.addEventListener("dragover", function (event) { |
| 254 | if (!carriesFiles(event)) return; |
| 255 | event.preventDefault(); |
| 256 | event.dataTransfer.dropEffect = "copy"; |
| 257 | form.setAttribute("data-dropping", ""); |
| 258 | }); |
| 259 | area.addEventListener("dragleave", function (event) { |
| 260 | if (!event.relatedTarget || !area.contains(event.relatedTarget)) form.removeAttribute("data-dropping"); |
| 261 | }); |
| 262 | area.addEventListener("drop", function (event) { |
| 263 | if (!carriesFiles(event)) return; |
| 264 | event.preventDefault(); |
| 265 | form.removeAttribute("data-dropping"); |
| 266 | add(event.dataTransfer.files); |
| 267 | input.focus({ preventScroll: true }); |
| 268 | }); |
| 269 | |
| 270 | // ── For a send ─────────────────────────────────────────────────── |
| 271 | window.EquipoAttach = { |
| 272 | // count is the attachments a send would carry (refused ones stay out). |
| 273 | count: function () { |
| 274 | return items.filter(function (i) { return i.state !== "error"; }).length; |
| 275 | }, |
| 276 | // take hands the waiting attachments to a send and clears the chips: |
| 277 | // items (with a data: preview for images) and ready, the uploaded |
| 278 | // ones' records once every upload has settled. |
| 279 | take: function () { |
| 280 | var mine = items.filter(function (i) { return i.state !== "error"; }); |
| 281 | items = []; |
| 282 | chips.replaceChildren(); |
| 283 | say(""); |
| 284 | changed(); |
| 285 | var ready = Promise.all(mine.map(function (i) { return i.done; })).then(function () { |
| 286 | var out = mine.filter(function (i) { return i.state === "ready"; }).map(function (i) { return i.meta; }); |
| 287 | if (out.length < mine.length) say(form.dataset.uploadFailed); |
| 288 | return out; |
| 289 | }); |
| 290 | return { items: mine, ready: ready }; |
| 291 | } |
| 292 | }; |
| 293 | |
| 294 | // ── Full size, in the page ─────────────────────────────────────── |
| 295 | var viewer = null; |
| 296 | document.addEventListener("click", function (event) { |
| 297 | var link = event.target.closest && event.target.closest("[equipo-file-thumb]"); |
| 298 | if (!link || event.metaKey || event.ctrlKey || event.shiftKey || !window.HTMLDialogElement) return; |
| 299 | event.preventDefault(); |
| 300 | if (!viewer) { |
| 301 | viewer = document.createElement("dialog"); |
| 302 | viewer.setAttribute("equipo-lightbox", ""); |
| 303 | viewer.addEventListener("click", function () { viewer.close(); }); |
| 304 | document.body.append(viewer); |
| 305 | } |
| 306 | var img = document.createElement("img"); |
| 307 | var thumb = link.querySelector("img"); |
| 308 | img.src = link.href; |
| 309 | img.alt = thumb ? thumb.alt : ""; |
| 310 | viewer.replaceChildren(img); |
| 311 | viewer.showModal(); |
| 312 | }); |
| 313 | })(); |
| 314 | |