// Files in Ask: the paperclip, paste and drop, the chips above the field // while files upload, and the viewer a thumbnail opens. ask.js imports it // (data-attach on the composer) and hooks it in: a send carries the chips' // ids, and the thread draws a message's files (filesRow) as the server // does (chat.html, ask-files). Without scripts none of this exists: the // thread still shows files, and a thumbnail opens the image itself. // // Base keeps no byte: each file goes to POST /ask/attachments, which // relays it to Equipo, and comes back as an id. The server's word is // final: only the size, the count and HEIC are refused here first, in its // words. Files upload two at a time, in order; a busy answer (503) is // tried again after its Retry-After, five times at most. Remove deletes // the upload; the page's unsent uploads are deleted as it goes away // (a beacon), apart from those of a send still on its way. Text is only // ever set with textContent. const MAX_FILES = 5; const MAX_BYTES = 10 << 20; const AT_ONCE = 2; const RETRIES = 5; const ACCEPT = "image/png,image/jpeg,image/webp,image/gif,application/pdf,text/plain,text/markdown,text/csv,application/json,.md,.markdown,.csv,.json,.txt"; // The page of a file, its corner folded (chat.html, ask-file-mark). const FILE_MARK = "M14 3.5H7.5a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2V8zM14 3.5V8h4.5"; const CLIP = "M20.5 11.5l-8.1 8.1a5 5 0 0 1-7.1-7.1l8.5-8.5a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.5a1.7 1.7 0 0 1-2.4-2.4l7.8-7.8"; const CROSS = "M7 7l10 10M17 7L7 17"; const svgNS = "http://www.w3.org/2000/svg"; function icon(d, cls) { const svg = document.createElementNS(svgNS, "svg"); svg.setAttribute("viewBox", "0 0 24 24"); svg.setAttribute("aria-hidden", "true"); if (cls) svg.setAttribute("class", cls); const path = document.createElementNS(svgNS, "path"); path.setAttribute("d", d); svg.append(path); return svg; } function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; } // fill puts values in a sentence's {name}s. function fill(s, values) { return s.replace(/\{(\w+)\}/g, (m, k) => (k in values ? values[k] : m)); } const href = (id, preview) => `/ask/attachments/${encodeURIComponent(id)}${preview ? "/preview" : ""}`; // fileSize is a size as the server writes it (ask_files.go, fileSize): // bytes, whole KB, then MB to one place, half up, 1024 to the K, in the // page's locale. export function fileSize(n) { const lang = document.documentElement.lang || "en"; const whole = new Intl.NumberFormat(lang); if (n < 1024) return whole.format(Math.max(n, 0)) + " B"; if (n < 1048576) return whole.format(Math.floor((n + 512) / 1024)) + " KB"; const tenths = Math.floor((n * 10 + 524288) / 1048576); return new Intl.NumberFormat(lang, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(tenths / 10) + " MB"; } // filesRow is a message's files as chat.html's ask-files draws them: // thumbnails, then a pill per other file. words are the composer's. export function filesRow(list, words) { const row = el("div", "files"); row.setAttribute("role", "group"); row.setAttribute("aria-label", words.files); for (const a of list) { if (a.kind !== "image") continue; const link = el("a", "thumb"); link.href = href(a.id); link.dataset.attachment = a.id; const img = document.createElement("img"); img.loading = "lazy"; img.src = href(a.id, true); img.alt = a.name; if (a.width && a.height) { img.width = a.width; img.height = a.height; } link.append(img); row.append(link); } for (const a of list) { if (a.kind === "image") continue; const link = el("a", "file"); link.href = href(a.id); link.setAttribute("download", ""); const size = fileSize(a.size); link.setAttribute("aria-label", fill(words.pill, { name: a.name, size })); link.append(icon(FILE_MARK, "file-mark"), el("span", "file-name", a.name), el("span", "file-size", size)); row.append(link); } return row; } // wordsOf reads the composer's data-w-* words. export function wordsOf(composer) { const out = {}; for (const [k, v] of Object.entries(composer.dataset)) { if (k.startsWith("w") && k.length > 1 && k[1] === k[1].toUpperCase()) out[k[1].toLowerCase() + k.slice(2)] = v; } return out; } // What Equipo's refusals say, by code. const refusals = { attachment_too_large: "tooLarge", attachment_type: "type", attachment_heic: "heic", attachment_pixels: "pixels", attachment_limit: "limit", busy: "busy", }; // attach wires files into the composer of root. hooks: // changed() the chips changed (Send may show, or go); // lost(state) an upload heard Ask isn't connected (connect, pending, // reconnect): the chat shows that state. // It answers the composer's side of files: // enable(on) can_attach: the paperclip shows, and drop and paste // attach, only while on; // count() chips that would go with a send; // ready() a promise of their ids, in chip order, once every upload // has settled; null when one that was uploading didn't // take (its chip says why, and nothing should go); // sending(ids, on, outcome) a send with ids is on its way (the beacon // leaves them), or has ended: outcome "sent", "refused" // (Base answered no) or "unknown" (no answer came); // sent(ids) they went: their chips go; // refused(why, ids) the send was refused for its files: "unavailable" or // "stale", said on their chips; // paste(e) a paste with files and no words of its own attaches // them (true), else leaves it to the text path (false). export function attach(root, hooks) { const composer = root.querySelector("form.composer"); const field = composer.querySelector("textarea"); const actions = composer.querySelector(".actions"); const thread = root.querySelector(".thread"); const words = wordsOf(composer); let enabled = false; const items = []; // every chip, in order const inflight = new Set(); // ids of a send on its way const removedInflight = new Set(); // of those, ids whose chip was removed meanwhile // ids of a send whose outcome never came (the network failed, or the // page is going): it may have landed, so nothing here deletes them; a // send that is never made leaves them to Equipo's 24-hour drop. const unsure = new Set(); let running = 0; // The paperclip, left of Send; the picker it opens. const picker = document.createElement("input"); picker.type = "file"; picker.multiple = true; picker.accept = ACCEPT; picker.hidden = true; picker.tabIndex = -1; picker.setAttribute("aria-hidden", "true"); const clip = el("button", "attach"); clip.type = "button"; clip.hidden = true; clip.setAttribute("aria-label", words.attach); clip.title = words.attach; clip.append(icon(CLIP)); actions.prepend(clip); composer.append(picker); clip.addEventListener("click", () => picker.click()); picker.addEventListener("change", () => { add([...picker.files]); picker.value = ""; }); // The chips, above the field; a live region for what happens to them. const chips = el("div", "chips"); chips.setAttribute("role", "list"); chips.setAttribute("aria-label", words.files); chips.hidden = true; composer.prepend(chips); const live = el("p", "sr-only"); live.setAttribute("aria-live", "polite"); composer.append(live); function announce(text) { live.textContent = ""; setTimeout(() => { live.textContent = text; }, 50); } function enable(on) { enabled = !!on; clip.hidden = !enabled; if (!enabled) composer.classList.remove("dropping"); } enable(composer.hasAttribute("data-can-attach")); // A chip's state: queued, uploading, done, or one that won't go // (refused: never uploaded; failed: the upload didn't take; stale: an // upload Equipo no longer has). unavailable is a done chip the runner // couldn't take, which a later send tries again. const goes = (it) => ["queued", "uploading", "done", "unavailable"].includes(it.state); function count() { return items.filter(goes).length; } function chipOf(file) { const it = { file, name: file.name || "file", size: file.size, type: file.type, state: "queued", id: "", xhr: null, removed: false, tries: 0 }; const li = el("div", "chip"); li.setAttribute("role", "listitem"); const mark = el("span", "chip-mark"); mark.append(icon(FILE_MARK, "file-mark")); const ring = el("span", "chip-ring"); ring.setAttribute("role", "progressbar"); ring.setAttribute("aria-valuemin", "0"); ring.setAttribute("aria-valuemax", "100"); ring.setAttribute("aria-valuenow", "0"); ring.setAttribute("aria-label", words.uploading); const svg = document.createElementNS(svgNS, "svg"); svg.setAttribute("viewBox", "0 0 24 24"); svg.setAttribute("aria-hidden", "true"); const track = document.createElementNS(svgNS, "circle"); const arc = document.createElementNS(svgNS, "circle"); for (const c of [track, arc]) { c.setAttribute("cx", "12"); c.setAttribute("cy", "12"); c.setAttribute("r", "9"); } track.setAttribute("class", "track"); arc.setAttribute("class", "arc"); arc.setAttribute("pathLength", "100"); svg.append(track, arc); ring.append(svg); mark.append(ring); const text = el("span", "chip-text"); const name = el("span", "chip-name", it.name); const meta = el("span", "chip-meta", fileSize(it.size)); text.append(name, meta); const remove = el("button", "chip-remove"); remove.type = "button"; remove.setAttribute("aria-label", fill(words.remove, { name: it.name })); remove.title = fill(words.remove, { name: it.name }); remove.append(icon(CROSS)); remove.addEventListener("click", () => drop(it, true)); li.append(mark, text, remove); Object.assign(it, { li, mark, ring, arc, meta }); return it; } // show draws a chip's state, with line under its name (its size when // there is nothing to say). function show(it, state, line) { it.state = state; it.li.dataset.state = state; it.ring.hidden = state !== "uploading" && state !== "queued"; it.meta.textContent = line || (state === "uploading" || state === "queued" ? words.uploading : fileSize(it.size)); it.li.classList.toggle("bad", ["refused", "failed", "stale", "unavailable"].includes(state)); hooks.changed(); settle(); } function progress(it, pct) { it.ring.setAttribute("aria-valuenow", String(Math.round(pct))); it.arc.style.strokeDasharray = `${pct} 100`; } const heic = (f) => /^image\/hei[cf]/i.test(f.type) || /\.hei[cf]$/i.test(f.name || ""); const isPDF = (it) => it.type === "application/pdf" || /\.pdf$/i.test(it.name); function add(files) { if (!enabled || !files.length) return; for (const file of files) { const it = chipOf(file); items.push(it); chips.append(it.li); let refuse = ""; if (items.filter(goes).length > MAX_FILES) refuse = words.tooMany; else if (file.size > MAX_BYTES) refuse = words.tooLarge; else if (heic(file)) refuse = words.heic; if (refuse) { show(it, "refused", refuse); announce(fill(words.notAttached, { name: it.name, reason: refuse })); } else show(it, "queued"); } chips.hidden = items.length === 0; chips.lastElementChild?.scrollIntoView?.({ block: "nearest", inline: "end" }); pump(); } // pump starts the next queued uploads, AT_ONCE at a time, in order. function pump() { for (const it of items) { if (running >= AT_ONCE) return; if (it.state === "queued" && !it.waiting) upload(it); } } function upload(it) { running++; show(it, "uploading"); progress(it, 0); const xhr = new XMLHttpRequest(); it.xhr = xhr; xhr.open("POST", "/ask/attachments"); xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", it.type || "application/octet-stream"); xhr.setRequestHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodeURIComponent(it.name).replace(/['()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase())); xhr.upload.onprogress = (e) => { if (!e.lengthComputable) return; it.sending = e.loaded < e.total; progress(it, (e.loaded / e.total) * 100); }; xhr.upload.onload = () => { it.sending = false; }; const finish = () => { running--; it.xhr = null; pump(); }; xhr.onload = () => { finish(); let out = {}; try { out = JSON.parse(xhr.responseText); } catch {} if (it.removed) { // Removed (or the page came back from the cache) as it landed: the // upload goes too. if (xhr.status === 201 && out.id) fetch(href(out.id), { method: "DELETE", headers: { Accept: "application/json" } }).catch(() => {}); return; } if (xhr.status === 201 && out.id) { it.id = out.id; it.kind = out.kind; show(it, "done", isPDF(it) ? words.pdf : ""); if (out.kind === "image") { const img = document.createElement("img"); img.src = href(out.id, true); img.alt = ""; it.mark.replaceChildren(img); } announce(fill(words.attached, { name: it.name })); return; } if (xhr.status === 503 && it.tries < RETRIES) { it.tries++; const after = Math.min(Math.max(Number(xhr.getResponseHeader("Retry-After")) || 2, 1), 10); it.waiting = true; show(it, "queued"); setTimeout(() => { it.waiting = false; pump(); }, after * 1000); return; } if (["connect", "pending", "reconnect"].includes(out.state)) hooks.lost(out.state); const reason = words[refusals[out.code]] || words.failed; show(it, refusals[out.code] ? "refused" : "failed", reason); announce(fill(words.notAttached, { name: it.name, reason })); }; xhr.onerror = () => { finish(); if (it.removed) return; show(it, "failed", words.failed); announce(fill(words.notAttached, { name: it.name, reason: words.failed })); }; xhr.onabort = finish; xhr.send(it.file); } // drop takes a chip away: Remove aborts its upload while its bytes are // seen still going; otherwise the upload is left to land and is deleted // then (onload): a browser that has sent them all may keep the request // open, and Base would never hear it was given up. An upload already made is // deleted (Equipo's own 404 counts as done). Focus moves to the next // chip, or the field. function drop(it, focus) { const at = items.indexOf(it); if (at < 0) return; items.splice(at, 1); it.removed = true; if (it.xhr && it.sending) it.xhr.abort(); else if (it.xhr) { // onload deletes it. } else if (it.id && inflight.has(it.id)) removedInflight.add(it.id); else if (it.id && !unsure.has(it.id)) fetch(href(it.id), { method: "DELETE", headers: { Accept: "application/json" } }).catch(() => {}); it.li.remove(); chips.hidden = items.length === 0; if (focus) { const next = items[at] || items[at - 1]; (next ? next.li.querySelector(".chip-remove") : field).focus(); } hooks.changed(); settle(); pump(); } // ready waits for every upload to settle, and answers the ids that go, // in chip order. let waiters = []; function settle() { if (items.some((it) => it.state === "queued" || it.state === "uploading")) return; const ids = items.filter((it) => it.state === "done" || it.state === "unavailable").map((it) => it.id); for (const w of waiters) w(ids); waiters = []; } function ready() { const pending = items.filter((it) => it.state === "queued" || it.state === "uploading"); return new Promise((resolve) => { waiters.push((ids) => resolve(pending.some((it) => !it.removed && it.state !== "done") ? null : ids)); settle(); }); } function sending(ids, on, outcome) { for (const id of ids) { if (on) { inflight.add(id); continue; } inflight.delete(id); if (outcome === "unknown") unsure.add(id); else unsure.delete(id); // A chip removed while its send was on its way: if Base said the // send didn't take the file, the upload goes now. if (removedInflight.delete(id) && outcome === "refused") fetch(href(id), { method: "DELETE", headers: { Accept: "application/json" } }).catch(() => {}); } } function sent(ids) { for (const it of [...items]) { if (ids.includes(it.id)) { items.splice(items.indexOf(it), 1); it.li.remove(); } } chips.hidden = items.length === 0; hooks.changed(); } // refused: the send's files were refused. unavailable keeps them (a // later send tries them again, and the paperclip goes, can_attach being // false); stale marks them gone: Remove clears them. function refused(why, ids) { for (const it of items) { if (!ids.includes(it.id)) continue; if (why === "unavailable") show(it, "unavailable", words.unavailable); else show(it, "stale", words.stale); } // Said once, as the chips say it (Fable S1). announce(why === "unavailable" ? words.unavailable : words.stale); if (why === "unavailable") enable(false); } // A paste with files attaches them only when it has no words of its // own (D8, Fable B5 and B8): HTML with text, or plain text beyond the // files' own names (a file copied in the Finder may come with its name), // is words, and the text path pastes it. function paste(e) { const d = e.clipboardData; if (!enabled || !d || !d.files || !d.files.length) return false; const files = [...d.files]; const html = d.getData("text/html"); if (html && new DOMParser().parseFromString(html, "text/html").body.textContent.trim()) return false; const names = new Set(files.map((f) => f.name.trim())); // A line is a file's own when it is the name, or a file: URL to it. const own = (line) => { if (names.has(line)) return true; if (!/^file:\/\//i.test(line)) return false; let last = line.split("/").pop(); try { last = decodeURIComponent(last); } catch {} return names.has(last); }; const plain = d.getData("text/plain"); if (plain && plain.split(/\r\n?|\n/).map((l) => l.trim()).some((l) => l && !own(l))) return false; e.preventDefault(); add(files); return true; } // Drop: an outline while files are dragged over the composer. let depth = 0; const dragging = (e) => enabled && e.dataTransfer && [...e.dataTransfer.types].includes("Files"); composer.dataset.drop = words.drop; composer.addEventListener("dragenter", (e) => { if (!dragging(e)) return; e.preventDefault(); depth++; composer.classList.add("dropping"); }); composer.addEventListener("dragover", (e) => { if (!dragging(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = "copy"; }); composer.addEventListener("dragleave", () => { if (depth > 0 && --depth === 0) composer.classList.remove("dropping"); }); composer.addEventListener("drop", (e) => { depth = 0; composer.classList.remove("dropping"); if (!dragging(e)) return; e.preventDefault(); add([...e.dataTransfer.files]); }); // The page goes: its unsent uploads are deleted, as best Base can, // apart from a send's on its way (Fable B7). Kept for Back, it comes back // without its chips, whose uploads are gone; the words stay. addEventListener("pagehide", () => { const ids = items.filter((it) => it.id && !inflight.has(it.id) && !unsure.has(it.id)).map((it) => it.id); if (!ids.length) return; navigator.sendBeacon("/ask/attachments/discard", new URLSearchParams(ids.map((id) => ["id", id]))); }); addEventListener("pageshow", (e) => { if (!e.persisted) return; for (const it of items) { it.removed = true; if (it.xhr) it.xhr.abort(); it.li.remove(); } items.length = 0; chips.hidden = true; hooks.changed(); settle(); }); // The viewer: a thumbnail in the thread opens its image full size, in a // sheet that holds focus until Close (or Escape) gives it back. const viewer = el("dialog", "viewer"); const shut = el("button", "round viewer-close"); shut.type = "button"; shut.setAttribute("aria-label", words.close); shut.append(icon(CROSS)); const full = document.createElement("img"); viewer.append(shut, full); document.body.append(viewer); let back = null; thread.addEventListener("click", (e) => { const thumb = e.target.closest("a.thumb[data-attachment]"); if (!thumb || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return; e.preventDefault(); back = thumb; const img = thumb.querySelector("img"); full.src = href(thumb.dataset.attachment); full.alt = img ? img.alt : ""; viewer.setAttribute("aria-label", full.alt); viewer.showModal(); shut.focus(); }); shut.addEventListener("click", () => viewer.close()); viewer.addEventListener("click", (e) => { if (e.target === viewer) viewer.close(); }); viewer.addEventListener("keydown", (e) => { if (e.key === "Tab") { e.preventDefault(); shut.focus(); } }); viewer.addEventListener("close", () => { full.removeAttribute("src"); if (back && back.isConnected) back.focus({ preventScroll: true }); else field.focus({ preventScroll: true }); back = null; }); return { enable, count, ready, sending, sent, refused, paste, words }; }