oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1// Files in Ask: the paperclip, paste and drop, the chips above the field
2// while files upload, and the viewer a thumbnail opens. ask.js imports it
3// (data-attach on the composer) and hooks it in: a send carries the chips'
4// ids, and the thread draws a message's files (filesRow) as the server
5// does (chat.html, ask-files). Without scripts none of this exists: the
6// thread still shows files, and a thumbnail opens the image itself.
7//
8// Base keeps no byte: each file goes to POST /ask/attachments, which
9// relays it to Equipo, and comes back as an id. The server's word is
10// final: only the size, the count and HEIC are refused here first, in its
11// words. Files upload two at a time, in order; a busy answer (503) is
12// tried again after its Retry-After, five times at most. Remove deletes
13// the upload; the page's unsent uploads are deleted as it goes away
14// (a beacon), apart from those of a send still on its way. Text is only
15// ever set with textContent.
16
17const MAX_FILES = 5;
18const MAX_BYTES = 10 << 20;
19const AT_ONCE = 2;
20const RETRIES = 5;
21const ACCEPT = "image/png,image/jpeg,image/webp,image/gif,application/pdf,text/plain,text/markdown,text/csv,application/json,.md,.markdown,.csv,.json,.txt";
22// The page of a file, its corner folded (chat.html, ask-file-mark).
23const 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";
24const 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";
25const CROSS = "M7 7l10 10M17 7L7 17";
26
27const svgNS = "http://www.w3.org/2000/svg";
28function icon(d, cls) {
29 const svg = document.createElementNS(svgNS, "svg");
30 svg.setAttribute("viewBox", "0 0 24 24");
31 svg.setAttribute("aria-hidden", "true");
32 if (cls) svg.setAttribute("class", cls);
33 const path = document.createElementNS(svgNS, "path");
34 path.setAttribute("d", d);
35 svg.append(path);
36 return svg;
37}
38function el(tag, cls, text) {
39 const e = document.createElement(tag);
40 if (cls) e.className = cls;
41 if (text !== undefined) e.textContent = text;
42 return e;
43}
44// fill puts values in a sentence's {name}s.
45function fill(s, values) {
46 return s.replace(/\{(\w+)\}/g, (m, k) => (k in values ? values[k] : m));
47}
48const href = (id, preview) => `/ask/attachments/${encodeURIComponent(id)}${preview ? "/preview" : ""}`;
49
50// fileSize is a size as the server writes it (ask_files.go, fileSize):
51// bytes, whole KB, then MB to one place, half up, 1024 to the K, in the
52// page's locale.
53export function fileSize(n) {
54 const lang = document.documentElement.lang || "en";
55 const whole = new Intl.NumberFormat(lang);
56 if (n < 1024) return whole.format(Math.max(n, 0)) + " B";
57 if (n < 1048576) return whole.format(Math.floor((n + 512) / 1024)) + " KB";
58 const tenths = Math.floor((n * 10 + 524288) / 1048576);
59 return new Intl.NumberFormat(lang, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(tenths / 10) + " MB";
60}
61
62// filesRow is a message's files as chat.html's ask-files draws them:
63// thumbnails, then a pill per other file. words are the composer's.
64export function filesRow(list, words) {
65 const row = el("div", "files");
66 row.setAttribute("role", "group");
67 row.setAttribute("aria-label", words.files);
68 for (const a of list) {
69 if (a.kind !== "image") continue;
70 const link = el("a", "thumb");
71 link.href = href(a.id);
72 link.dataset.attachment = a.id;
73 const img = document.createElement("img");
74 img.loading = "lazy";
75 img.src = href(a.id, true);
76 img.alt = a.name;
77 if (a.width && a.height) {
78 img.width = a.width;
79 img.height = a.height;
80 }
81 link.append(img);
82 row.append(link);
83 }
84 for (const a of list) {
85 if (a.kind === "image") continue;
86 const link = el("a", "file");
87 link.href = href(a.id);
88 link.setAttribute("download", "");
89 const size = fileSize(a.size);
90 link.setAttribute("aria-label", fill(words.pill, { name: a.name, size }));
91 link.append(icon(FILE_MARK, "file-mark"), el("span", "file-name", a.name), el("span", "file-size", size));
92 row.append(link);
93 }
94 return row;
95}
96
97// wordsOf reads the composer's data-w-* words.
98export function wordsOf(composer) {
99 const out = {};
100 for (const [k, v] of Object.entries(composer.dataset)) {
101 if (k.startsWith("w") && k.length > 1 && k[1] === k[1].toUpperCase()) out[k[1].toLowerCase() + k.slice(2)] = v;
102 }
103 return out;
104}
105
106// What Equipo's refusals say, by code.
107const refusals = {
108 attachment_too_large: "tooLarge", attachment_type: "type", attachment_heic: "heic",
109 attachment_pixels: "pixels", attachment_limit: "limit", busy: "busy",
110};
111
112// attach wires files into the composer of root. hooks:
113// changed() the chips changed (Send may show, or go);
114// lost(state) an upload heard Ask isn't connected (connect, pending,
115// reconnect): the chat shows that state.
116// It answers the composer's side of files:
117// enable(on) can_attach: the paperclip shows, and drop and paste
118// attach, only while on;
119// count() chips that would go with a send;
120// ready() a promise of their ids, in chip order, once every upload
121// has settled; null when one that was uploading didn't
122// take (its chip says why, and nothing should go);
123// sending(ids, on, outcome) a send with ids is on its way (the beacon
124// leaves them), or has ended: outcome "sent", "refused"
125// (Base answered no) or "unknown" (no answer came);
126// sent(ids) they went: their chips go;
127// refused(why, ids) the send was refused for its files: "unavailable" or
128// "stale", said on their chips;
129// paste(e) a paste with files and no words of its own attaches
130// them (true), else leaves it to the text path (false).
131export function attach(root, hooks) {
132 const composer = root.querySelector("form.composer");
133 const field = composer.querySelector("textarea");
134 const actions = composer.querySelector(".actions");
135 const thread = root.querySelector(".thread");
136 const words = wordsOf(composer);
137 let enabled = false;
138 const items = []; // every chip, in order
139 const inflight = new Set(); // ids of a send on its way
140 const removedInflight = new Set(); // of those, ids whose chip was removed meanwhile
141 // ids of a send whose outcome never came (the network failed, or the
142 // page is going): it may have landed, so nothing here deletes them; a
143 // send that is never made leaves them to Equipo's 24-hour drop.
144 const unsure = new Set();
145 let running = 0;
146
147 // The paperclip, left of Send; the picker it opens.
148 const picker = document.createElement("input");
149 picker.type = "file";
150 picker.multiple = true;
151 picker.accept = ACCEPT;
152 picker.hidden = true;
153 picker.tabIndex = -1;
154 picker.setAttribute("aria-hidden", "true");
155 const clip = el("button", "attach");
156 clip.type = "button";
157 clip.hidden = true;
158 clip.setAttribute("aria-label", words.attach);
159 clip.title = words.attach;
160 clip.append(icon(CLIP));
161 actions.prepend(clip);
162 composer.append(picker);
163 clip.addEventListener("click", () => picker.click());
164 picker.addEventListener("change", () => {
165 add([...picker.files]);
166 picker.value = "";
167 });
168
169 // The chips, above the field; a live region for what happens to them.
170 const chips = el("div", "chips");
171 chips.setAttribute("role", "list");
172 chips.setAttribute("aria-label", words.files);
173 chips.hidden = true;
174 composer.prepend(chips);
175 const live = el("p", "sr-only");
176 live.setAttribute("aria-live", "polite");
177 composer.append(live);
178 function announce(text) {
179 live.textContent = "";
180 setTimeout(() => { live.textContent = text; }, 50);
181 }
182
183 function enable(on) {
184 enabled = !!on;
185 clip.hidden = !enabled;
186 if (!enabled) composer.classList.remove("dropping");
187 }
188 enable(composer.hasAttribute("data-can-attach"));
189
190 // A chip's state: queued, uploading, done, or one that won't go
191 // (refused: never uploaded; failed: the upload didn't take; stale: an
192 // upload Equipo no longer has). unavailable is a done chip the runner
193 // couldn't take, which a later send tries again.
194 const goes = (it) => ["queued", "uploading", "done", "unavailable"].includes(it.state);
195 function count() {
196 return items.filter(goes).length;
197 }
198
199 function chipOf(file) {
200 const it = { file, name: file.name || "file", size: file.size, type: file.type, state: "queued", id: "", xhr: null, removed: false, tries: 0 };
201 const li = el("div", "chip");
202 li.setAttribute("role", "listitem");
203 const mark = el("span", "chip-mark");
204 mark.append(icon(FILE_MARK, "file-mark"));
205 const ring = el("span", "chip-ring");
206 ring.setAttribute("role", "progressbar");
207 ring.setAttribute("aria-valuemin", "0");
208 ring.setAttribute("aria-valuemax", "100");
209 ring.setAttribute("aria-valuenow", "0");
210 ring.setAttribute("aria-label", words.uploading);
211 const svg = document.createElementNS(svgNS, "svg");
212 svg.setAttribute("viewBox", "0 0 24 24");
213 svg.setAttribute("aria-hidden", "true");
214 const track = document.createElementNS(svgNS, "circle");
215 const arc = document.createElementNS(svgNS, "circle");
216 for (const c of [track, arc]) {
217 c.setAttribute("cx", "12");
218 c.setAttribute("cy", "12");
219 c.setAttribute("r", "9");
220 }
221 track.setAttribute("class", "track");
222 arc.setAttribute("class", "arc");
223 arc.setAttribute("pathLength", "100");
224 svg.append(track, arc);
225 ring.append(svg);
226 mark.append(ring);
227 const text = el("span", "chip-text");
228 const name = el("span", "chip-name", it.name);
229 const meta = el("span", "chip-meta", fileSize(it.size));
230 text.append(name, meta);
231 const remove = el("button", "chip-remove");
232 remove.type = "button";
233 remove.setAttribute("aria-label", fill(words.remove, { name: it.name }));
234 remove.title = fill(words.remove, { name: it.name });
235 remove.append(icon(CROSS));
236 remove.addEventListener("click", () => drop(it, true));
237 li.append(mark, text, remove);
238 Object.assign(it, { li, mark, ring, arc, meta });
239 return it;
240 }
241
242 // show draws a chip's state, with line under its name (its size when
243 // there is nothing to say).
244 function show(it, state, line) {
245 it.state = state;
246 it.li.dataset.state = state;
247 it.ring.hidden = state !== "uploading" && state !== "queued";
248 it.meta.textContent = line || (state === "uploading" || state === "queued" ? words.uploading : fileSize(it.size));
249 it.li.classList.toggle("bad", ["refused", "failed", "stale", "unavailable"].includes(state));
250 hooks.changed();
251 settle();
252 }
253 function progress(it, pct) {
254 it.ring.setAttribute("aria-valuenow", String(Math.round(pct)));
255 it.arc.style.strokeDasharray = `${pct} 100`;
256 }
257
258 const heic = (f) => /^image\/hei[cf]/i.test(f.type) || /\.hei[cf]$/i.test(f.name || "");
259 const isPDF = (it) => it.type === "application/pdf" || /\.pdf$/i.test(it.name);
260
261 function add(files) {
262 if (!enabled || !files.length) return;
263 for (const file of files) {
264 const it = chipOf(file);
265 items.push(it);
266 chips.append(it.li);
267 let refuse = "";
268 if (items.filter(goes).length > MAX_FILES) refuse = words.tooMany;
269 else if (file.size > MAX_BYTES) refuse = words.tooLarge;
270 else if (heic(file)) refuse = words.heic;
271 if (refuse) {
272 show(it, "refused", refuse);
273 announce(fill(words.notAttached, { name: it.name, reason: refuse }));
274 } else show(it, "queued");
275 }
276 chips.hidden = items.length === 0;
277 chips.lastElementChild?.scrollIntoView?.({ block: "nearest", inline: "end" });
278 pump();
279 }
280
281 // pump starts the next queued uploads, AT_ONCE at a time, in order.
282 function pump() {
283 for (const it of items) {
284 if (running >= AT_ONCE) return;
285 if (it.state === "queued" && !it.waiting) upload(it);
286 }
287 }
288
289 function upload(it) {
290 running++;
291 show(it, "uploading");
292 progress(it, 0);
293 const xhr = new XMLHttpRequest();
294 it.xhr = xhr;
295 xhr.open("POST", "/ask/attachments");
296 xhr.setRequestHeader("Accept", "application/json");
297 xhr.setRequestHeader("Content-Type", it.type || "application/octet-stream");
298 xhr.setRequestHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodeURIComponent(it.name).replace(/['()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()));
299 xhr.upload.onprogress = (e) => {
300 if (!e.lengthComputable) return;
301 it.sending = e.loaded < e.total;
302 progress(it, (e.loaded / e.total) * 100);
303 };
304 xhr.upload.onload = () => { it.sending = false; };
305 const finish = () => {
306 running--;
307 it.xhr = null;
308 pump();
309 };
310 xhr.onload = () => {
311 finish();
312 let out = {};
313 try { out = JSON.parse(xhr.responseText); } catch {}
314 if (it.removed) {
315 // Removed (or the page came back from the cache) as it landed: the
316 // upload goes too.
317 if (xhr.status === 201 && out.id) fetch(href(out.id), { method: "DELETE", headers: { Accept: "application/json" } }).catch(() => {});
318 return;
319 }
320 if (xhr.status === 201 && out.id) {
321 it.id = out.id;
322 it.kind = out.kind;
323 show(it, "done", isPDF(it) ? words.pdf : "");
324 if (out.kind === "image") {
325 const img = document.createElement("img");
326 img.src = href(out.id, true);
327 img.alt = "";
328 it.mark.replaceChildren(img);
329 }
330 announce(fill(words.attached, { name: it.name }));
331 return;
332 }
333 if (xhr.status === 503 && it.tries < RETRIES) {
334 it.tries++;
335 const after = Math.min(Math.max(Number(xhr.getResponseHeader("Retry-After")) || 2, 1), 10);
336 it.waiting = true;
337 show(it, "queued");
338 setTimeout(() => { it.waiting = false; pump(); }, after * 1000);
339 return;
340 }
341 if (["connect", "pending", "reconnect"].includes(out.state)) hooks.lost(out.state);
342 const reason = words[refusals[out.code]] || words.failed;
343 show(it, refusals[out.code] ? "refused" : "failed", reason);
344 announce(fill(words.notAttached, { name: it.name, reason }));
345 };
346 xhr.onerror = () => {
347 finish();
348 if (it.removed) return;
349 show(it, "failed", words.failed);
350 announce(fill(words.notAttached, { name: it.name, reason: words.failed }));
351 };
352 xhr.onabort = finish;
353 xhr.send(it.file);
354 }
355
356 // drop takes a chip away: Remove aborts its upload while its bytes are
357 // seen still going; otherwise the upload is left to land and is deleted
358 // then (onload): a browser that has sent them all may keep the request
359 // open, and Base would never hear it was given up. An upload already made is
360 // deleted (Equipo's own 404 counts as done). Focus moves to the next
361 // chip, or the field.
362 function drop(it, focus) {
363 const at = items.indexOf(it);
364 if (at < 0) return;
365 items.splice(at, 1);
366 it.removed = true;
367 if (it.xhr && it.sending) it.xhr.abort();
368 else if (it.xhr) {
369 // onload deletes it.
370 } else if (it.id && inflight.has(it.id)) removedInflight.add(it.id);
371 else if (it.id && !unsure.has(it.id)) fetch(href(it.id), { method: "DELETE", headers: { Accept: "application/json" } }).catch(() => {});
372 it.li.remove();
373 chips.hidden = items.length === 0;
374 if (focus) {
375 const next = items[at] || items[at - 1];
376 (next ? next.li.querySelector(".chip-remove") : field).focus();
377 }
378 hooks.changed();
379 settle();
380 pump();
381 }
382
383 // ready waits for every upload to settle, and answers the ids that go,
384 // in chip order.
385 let waiters = [];
386 function settle() {
387 if (items.some((it) => it.state === "queued" || it.state === "uploading")) return;
388 const ids = items.filter((it) => it.state === "done" || it.state === "unavailable").map((it) => it.id);
389 for (const w of waiters) w(ids);
390 waiters = [];
391 }
392 function ready() {
393 const pending = items.filter((it) => it.state === "queued" || it.state === "uploading");
394 return new Promise((resolve) => {
395 waiters.push((ids) => resolve(pending.some((it) => !it.removed && it.state !== "done") ? null : ids));
396 settle();
397 });
398 }
399 function sending(ids, on, outcome) {
400 for (const id of ids) {
401 if (on) {
402 inflight.add(id);
403 continue;
404 }
405 inflight.delete(id);
406 if (outcome === "unknown") unsure.add(id);
407 else unsure.delete(id);
408 // A chip removed while its send was on its way: if Base said the
409 // send didn't take the file, the upload goes now.
410 if (removedInflight.delete(id) && outcome === "refused") fetch(href(id), { method: "DELETE", headers: { Accept: "application/json" } }).catch(() => {});
411 }
412 }
413 function sent(ids) {
414 for (const it of [...items]) {
415 if (ids.includes(it.id)) {
416 items.splice(items.indexOf(it), 1);
417 it.li.remove();
418 }
419 }
420 chips.hidden = items.length === 0;
421 hooks.changed();
422 }
423 // refused: the send's files were refused. unavailable keeps them (a
424 // later send tries them again, and the paperclip goes, can_attach being
425 // false); stale marks them gone: Remove clears them.
426 function refused(why, ids) {
427 for (const it of items) {
428 if (!ids.includes(it.id)) continue;
429 if (why === "unavailable") show(it, "unavailable", words.unavailable);
430 else show(it, "stale", words.stale);
431 }
432 // Said once, as the chips say it (Fable S1).
433 announce(why === "unavailable" ? words.unavailable : words.stale);
434 if (why === "unavailable") enable(false);
435 }
436
437 // A paste with files attaches them only when it has no words of its
438 // own (D8, Fable B5 and B8): HTML with text, or plain text beyond the
439 // files' own names (a file copied in the Finder may come with its name),
440 // is words, and the text path pastes it.
441 function paste(e) {
442 const d = e.clipboardData;
443 if (!enabled || !d || !d.files || !d.files.length) return false;
444 const files = [...d.files];
445 const html = d.getData("text/html");
446 if (html && new DOMParser().parseFromString(html, "text/html").body.textContent.trim()) return false;
447 const names = new Set(files.map((f) => f.name.trim()));
448 // A line is a file's own when it is the name, or a file: URL to it.
449 const own = (line) => {
450 if (names.has(line)) return true;
451 if (!/^file:\/\//i.test(line)) return false;
452 let last = line.split("/").pop();
453 try { last = decodeURIComponent(last); } catch {}
454 return names.has(last);
455 };
456 const plain = d.getData("text/plain");
457 if (plain && plain.split(/\r\n?|\n/).map((l) => l.trim()).some((l) => l && !own(l))) return false;
458 e.preventDefault();
459 add(files);
460 return true;
461 }
462
463 // Drop: an outline while files are dragged over the composer.
464 let depth = 0;
465 const dragging = (e) => enabled && e.dataTransfer && [...e.dataTransfer.types].includes("Files");
466 composer.dataset.drop = words.drop;
467 composer.addEventListener("dragenter", (e) => {
468 if (!dragging(e)) return;
469 e.preventDefault();
470 depth++;
471 composer.classList.add("dropping");
472 });
473 composer.addEventListener("dragover", (e) => {
474 if (!dragging(e)) return;
475 e.preventDefault();
476 e.dataTransfer.dropEffect = "copy";
477 });
478 composer.addEventListener("dragleave", () => {
479 if (depth > 0 && --depth === 0) composer.classList.remove("dropping");
480 });
481 composer.addEventListener("drop", (e) => {
482 depth = 0;
483 composer.classList.remove("dropping");
484 if (!dragging(e)) return;
485 e.preventDefault();
486 add([...e.dataTransfer.files]);
487 });
488
489 // The page goes: its unsent uploads are deleted, as best Base can,
490 // apart from a send's on its way (Fable B7). Kept for Back, it comes back
491 // without its chips, whose uploads are gone; the words stay.
492 addEventListener("pagehide", () => {
493 const ids = items.filter((it) => it.id && !inflight.has(it.id) && !unsure.has(it.id)).map((it) => it.id);
494 if (!ids.length) return;
495 navigator.sendBeacon("/ask/attachments/discard", new URLSearchParams(ids.map((id) => ["id", id])));
496 });
497 addEventListener("pageshow", (e) => {
498 if (!e.persisted) return;
499 for (const it of items) {
500 it.removed = true;
501 if (it.xhr) it.xhr.abort();
502 it.li.remove();
503 }
504 items.length = 0;
505 chips.hidden = true;
506 hooks.changed();
507 settle();
508 });
509
510 // The viewer: a thumbnail in the thread opens its image full size, in a
511 // sheet that holds focus until Close (or Escape) gives it back.
512 const viewer = el("dialog", "viewer");
513 const shut = el("button", "round viewer-close");
514 shut.type = "button";
515 shut.setAttribute("aria-label", words.close);
516 shut.append(icon(CROSS));
517 const full = document.createElement("img");
518 viewer.append(shut, full);
519 document.body.append(viewer);
520 let back = null;
521 thread.addEventListener("click", (e) => {
522 const thumb = e.target.closest("a.thumb[data-attachment]");
523 if (!thumb || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
524 e.preventDefault();
525 back = thumb;
526 const img = thumb.querySelector("img");
527 full.src = href(thumb.dataset.attachment);
528 full.alt = img ? img.alt : "";
529 viewer.setAttribute("aria-label", full.alt);
530 viewer.showModal();
531 shut.focus();
532 });
533 shut.addEventListener("click", () => viewer.close());
534 viewer.addEventListener("click", (e) => { if (e.target === viewer) viewer.close(); });
535 viewer.addEventListener("keydown", (e) => {
536 if (e.key === "Tab") {
537 e.preventDefault();
538 shut.focus();
539 }
540 });
541 viewer.addEventListener("close", () => {
542 full.removeAttribute("src");
543 if (back && back.isConnected) back.focus({ preventScroll: true });
544 else field.focus({ preventScroll: true });
545 back = null;
546 });
547
548 return { enable, count, ready, sending, sent, refused, paste, words };
549}
550