@monster-orange/den-ui 0.0.0-stage → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +408 -2
  3. package/bin/den-ui-parity.mjs +365 -0
  4. package/inventory/nav-inventory.d.ts +89 -0
  5. package/inventory/nav-inventory.js +590 -0
  6. package/inventory/reference/den-chromium-1280.json +5137 -0
  7. package/inventory/reference/den-chromium-390.json +3653 -0
  8. package/inventory/reference/den-webkit-1280.json +5137 -0
  9. package/inventory/reference/den-webkit-390.json +3653 -0
  10. package/package.json +51 -4
  11. package/src/base.css +80 -0
  12. package/src/busy-words.d.ts +2 -0
  13. package/src/busy-words.js +71 -0
  14. package/src/busy.css +155 -0
  15. package/src/busy.d.ts +80 -0
  16. package/src/busy.js +662 -0
  17. package/src/dialog.css +103 -0
  18. package/src/dialog.d.ts +44 -0
  19. package/src/dialog.js +282 -0
  20. package/src/fonts/OFL.txt +97 -0
  21. package/src/fonts/rubik-latin-400-normal.woff2 +0 -0
  22. package/src/fonts/rubik-latin-500-normal.woff2 +0 -0
  23. package/src/fonts/rubik-latin-ext-400-normal.woff2 +0 -0
  24. package/src/fonts/rubik-latin-ext-500-normal.woff2 +0 -0
  25. package/src/fonts/space-mono-latin-400-normal.woff2 +0 -0
  26. package/src/fonts/space-mono-latin-ext-400-normal.woff2 +0 -0
  27. package/src/fonts.css +71 -0
  28. package/src/icons.d.ts +4 -0
  29. package/src/icons.js +43 -0
  30. package/src/kit.d.ts +146 -0
  31. package/src/kit.js +224 -0
  32. package/src/report-shot.d.ts +47 -0
  33. package/src/report-shot.js +255 -0
  34. package/src/report.css +387 -0
  35. package/src/report.d.ts +61 -0
  36. package/src/report.js +909 -0
  37. package/src/shell-client.d.ts +31 -0
  38. package/src/shell-client.js +240 -0
  39. package/src/shell-html.d.ts +91 -0
  40. package/src/shell-html.js +289 -0
  41. package/src/shell.css +558 -0
  42. package/src/strings.d.ts +18 -0
  43. package/src/strings.js +514 -0
  44. package/src/time.d.ts +18 -0
  45. package/src/time.js +254 -0
  46. package/src/tokens.css +158 -0
  47. package/src/update-pill.css +32 -0
  48. package/src/update-pill.d.ts +17 -0
  49. package/src/update-pill.js +95 -0
  50. package/src/version.d.ts +7 -0
  51. package/src/version.js +31 -0
  52. package/src/whatsnew.css +235 -0
  53. package/src/whatsnew.d.ts +36 -0
  54. package/src/whatsnew.js +411 -0
package/src/busy.js ADDED
@@ -0,0 +1,662 @@
1
+ /**
2
+ * UK-2: the working pop-up, <den-busy>, and busyAction.
3
+ *
4
+ * A slow click never looks dead: the button is held at once; after OPEN_MS
5
+ * with no answer the pop-up names what is happening; it stays until the
6
+ * server answers, then says what happened. Framework-free; the product
7
+ * plugs in its words, its Report, its toast and its routes:
8
+ *
9
+ * configureBusy({
10
+ * lang: () => "en", the page's language (en, es, ja)
11
+ * words: { en: {...}, ... }, extra or replaced shared words
12
+ * idHeader: "X-Request-Id", the header the request id rides in
13
+ * statusUrl: (id) => url, Check again's GET (never resends)
14
+ * request: (id) => Promise<state> Check again through the product's
15
+ * adapter instead ({ state, result?,
16
+ * error? }); statusUrl is then unused
17
+ * report: (info) => void, Report: { title, details, requestId }
18
+ * toast: (text) => void, a fast success, said without a pop-up
19
+ * open: (url) => void, a held answer's page (default: go)
20
+ * logUrl: "/logs", Open the log (reconnect mode)
21
+ * reconnect: { reconnect mode (a product restarting)
22
+ * url, polled until the product is back
23
+ * back: (now, before) => bool, is this a new run of the product?
24
+ * waitMs: (before) => number, how long before "not back" (60 s)
25
+ * version: (now) => string,
26
+ * done: (now) => void, after "back" (default: reload)
27
+ * },
28
+ * })
29
+ *
30
+ * registerActions({ name: {
31
+ * who: "Hub", whose answer it waits for (a name)
32
+ * autoClose: true, (kept for older callers: every success
33
+ * now closes at once, with the toast)
34
+ * inline: true, its place shows a quick failure itself
35
+ * mode: "reconnect",
36
+ * words: { en: { working, success, failure, ... }, es: {...}, ja: {...} },
37
+ * } })
38
+ *
39
+ * busyAction(name, run, opts) → Promise<data | null>
40
+ * run(headers) the request; it must send `headers` (the id).
41
+ * opts.button held (disabled, aria-busy) and focused again.
42
+ * opts.vars words' {placeholders}.
43
+ * opts.success(data) the success line, worked out from the answer.
44
+ * opts.onDone(data), opts.onFail(err)
45
+ * opts.toastFast a fast success says so in a toast (default true).
46
+ * opts.quietFail a refusal under OPEN_MS goes back to the caller
47
+ * (the promise rejects with it).
48
+ * opts.inlineError a network error before the pop-up opens goes back
49
+ * to the caller.
50
+ * opts.skipDone(res) true: no success line (closes quietly).
51
+ * opts.extra(res) a node under the success line; waits for Close.
52
+ * opts.before reconnect: the product's answer from before (else
53
+ * the kit asks reconnect.url first).
54
+ * opts.next a failure trying again won't fix: { label, href },
55
+ * or (err) => { label, href } | null. The Failure
56
+ * pop-up then offers that link (the primary) in
57
+ * place of Try again. With no href ({ label }: who
58
+ * to ask, say), it says the words instead and
59
+ * Close is the primary.
60
+ *
61
+ * run(headers, progress) progress(text) adds a line under the working
62
+ * title (in order; the newest is the brightest),
63
+ * shown when the pop-up opens and as it works.
64
+ *
65
+ * Its look is busy.css (linked from beside this file).
66
+ *
67
+ * Reconnect mode: the request may get no answer (the product stopped
68
+ * first); that counts as going down, and the pop-up waits for it to come
69
+ * back. busyAction then resolves with the new answer from reconnect.url.
70
+ *
71
+ * The request contract (Settled in v2): Try again sends the same id only
72
+ * when no answer came back; after the server answered with an error it
73
+ * sends a new one. Check again asks statusUrl(id) and never resends:
74
+ * done, failed, running ("still running") or unknown ("no record").
75
+ * An answer { held: { id, url } } closes the pop-up with no success line
76
+ * and opens url.
77
+ */
78
+ import { BUSY_WORDS } from "./busy-words.js";
79
+
80
+ export const OPEN_MS = 300;
81
+ export const MIN_MS = 600;
82
+ export const STILL_MS = 10_000;
83
+ export const NO_ANSWER_MS = 60_000;
84
+ export const SUCCESS_CLOSE_MS = 1200;
85
+ export const POLL_MS = 1000;
86
+ export const POLL_MAX_MS = 3000;
87
+
88
+ const hook = {
89
+ lang: () =>
90
+ (typeof document !== "undefined" &&
91
+ document.documentElement.lang?.slice(0, 2)) ||
92
+ "en",
93
+ words: {},
94
+ idHeader: "X-Request-Id",
95
+ statusUrl: (id) => `/requests/${encodeURIComponent(id)}`,
96
+ report: null,
97
+ toast: null,
98
+ open: (url) => window.location.assign(url),
99
+ logUrl: null,
100
+ reconnect: null,
101
+ };
102
+ const actions = new Map();
103
+
104
+ /** The product's words, routes and services (see the top of this file). */
105
+ export function configureBusy(h) {
106
+ Object.assign(hook, h ?? {});
107
+ }
108
+
109
+ /** Each action's words and rules, by name. */
110
+ export function registerActions(map) {
111
+ for (const [name, a] of Object.entries(map ?? {})) actions.set(name, a);
112
+ }
113
+
114
+ /** The registered action, for a product's own checks. */
115
+ export function busyActionOf(name) {
116
+ return actions.get(name) ?? null;
117
+ }
118
+
119
+ const fill = (s, vars) =>
120
+ String(s ?? "").replace(/\{(\w+)\}/g, (m, k) =>
121
+ vars && vars[k] !== undefined ? String(vars[k]) : m,
122
+ );
123
+
124
+ /** A shared word, in the page's language, with the product's own on top. */
125
+ function word(key, vars) {
126
+ const l = hook.lang();
127
+ const s =
128
+ hook.words?.[l]?.[key] ??
129
+ BUSY_WORDS[l]?.[key] ??
130
+ hook.words?.en?.[key] ??
131
+ BUSY_WORDS.en[key] ??
132
+ key;
133
+ return fill(s, vars);
134
+ }
135
+
136
+ /** One of the action's own words (working, success, failure, …). */
137
+ function actionWord(a, key, vars) {
138
+ const l = hook.lang();
139
+ return fill(a.words?.[l]?.[key] ?? a.words?.en?.[key] ?? "", vars);
140
+ }
141
+
142
+ const esc = (s) =>
143
+ String(s ?? "").replace(
144
+ /[&<>"']/g,
145
+ (c) =>
146
+ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
147
+ c
148
+ ],
149
+ );
150
+
151
+ const ICONS = {
152
+ clock:
153
+ '<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 7v5l3 2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',
154
+ ok: '<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M8 12.5l3 3 5-6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>',
155
+ bad: '<path d="M12 4l9 16H3z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><path d="M12 10v4.5M12 17.5v.01" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',
156
+ };
157
+ const icon = (k) =>
158
+ `<svg class="bz-ico bz-${k}" viewBox="0 0 24 24" aria-hidden="true">${ICONS[k]}</svg>`;
159
+
160
+ /**
161
+ * The look is busy.css, beside this file: linked once, never injected, so
162
+ * a page under style-src 'self' takes it. A page that links it itself (in
163
+ * its <head>, say) keeps its own link.
164
+ */
165
+ const CSS_URL = new URL("./busy.css", import.meta.url).href;
166
+
167
+ function ensureCss() {
168
+ if (document.getElementById("bz-css")) return;
169
+ for (const l of document.querySelectorAll('link[rel="stylesheet"]'))
170
+ if (/(^|\/)busy\.css(\?|$)/.test(new URL(l.href, location.href).pathname))
171
+ return;
172
+ const l = document.createElement("link");
173
+ l.id = "bz-css";
174
+ l.rel = "stylesheet";
175
+ l.href = CSS_URL;
176
+ document.head.append(l);
177
+ }
178
+
179
+ /** <den-busy>: the pop-up's element, defined on first use (a browser only). */
180
+ function defineElement() {
181
+ if (typeof customElements === "undefined" || customElements.get("den-busy"))
182
+ return;
183
+ customElements.define("den-busy", class extends HTMLElement {});
184
+ }
185
+
186
+ function makeDialog(host) {
187
+ const d = document.createElement("dialog");
188
+ d.className = "bz-dlg";
189
+ d.setAttribute("aria-labelledby", "bz-h");
190
+ d.setAttribute("aria-modal", "true");
191
+ host.append(d);
192
+ return d;
193
+ }
194
+
195
+ function newId() {
196
+ try {
197
+ return crypto.randomUUID();
198
+ } catch {
199
+ return (
200
+ Date.now().toString(16) +
201
+ "-" +
202
+ Math.random().toString(16).slice(2, 12).padEnd(10, "0")
203
+ );
204
+ }
205
+ }
206
+
207
+ const later = (ms) => new Promise((r) => setTimeout(r, ms));
208
+
209
+ /** The first message with words: the error's own, its answer's, nothing. */
210
+ export function messageOf(err) {
211
+ const tries = [
212
+ err?.message,
213
+ err?.error?.message,
214
+ err?.error,
215
+ err?.body?.message,
216
+ err?.body?.error?.message,
217
+ err?.body?.error,
218
+ ];
219
+ for (const m of tries)
220
+ if (typeof m === "string" && m.trim() !== "") return m.trim();
221
+ return "";
222
+ }
223
+
224
+ /** The server answered (with an error), as opposed to no answer at all. */
225
+ const answeredWithError = (err) =>
226
+ !!err && !err.network && typeof err.status === "number";
227
+
228
+ /** Details: status code · request id · time (never the API path). */
229
+ function detailsText(err, id, at) {
230
+ const bits = [];
231
+ if (err?.status) bits.push(`status ${err.status}`);
232
+ bits.push(`request ${id}`);
233
+ bits.push(at.toLocaleTimeString([], { hour12: false }));
234
+ const said = messageOf(err);
235
+ return said ? `${bits.join(" · ")}\n${said}` : bits.join(" · ");
236
+ }
237
+
238
+ export function busyAction(name, run, opts = {}) {
239
+ const a = actions.get(name);
240
+ if (!a) throw new Error(`busyAction: no action named "${name}"`);
241
+ const { button } = opts;
242
+ const who = a.who ?? "";
243
+ const vars = { ...(opts.vars ?? {}), who };
244
+ const reconnect = a.mode === "reconnect";
245
+ let id = newId();
246
+ let el = null;
247
+ let d = null;
248
+ let openedAt = 0;
249
+ let state = "working";
250
+ let ticker = 0;
251
+ let settled = false;
252
+ let lastErr = null;
253
+ let okData = null;
254
+ let lastAt = new Date();
255
+ /** progress(text)'s lines, this attempt. */
256
+ let lines = [];
257
+ let finish;
258
+ let fail;
259
+ const result = new Promise((res, rej) => {
260
+ finish = res;
261
+ fail = rej;
262
+ });
263
+
264
+ const hold = (on) => {
265
+ if (!button) return;
266
+ button.disabled = on;
267
+ if (on) button.setAttribute("aria-busy", "true");
268
+ else button.removeAttribute("aria-busy");
269
+ };
270
+
271
+ function ensureDialog() {
272
+ if (d) return d;
273
+ ensureCss();
274
+ defineElement();
275
+ el = document.createElement("den-busy");
276
+ document.body.append(el);
277
+ d = makeDialog(el);
278
+ // Working: Esc does nothing. Otherwise Esc is Close.
279
+ d.addEventListener("cancel", (e) => {
280
+ e.preventDefault();
281
+ if (state !== "working") close(null);
282
+ });
283
+ // The backdrop: a press on the dialog itself, outside its body.
284
+ d.addEventListener("click", (e) => {
285
+ if (e.target === d && state !== "working") close(null);
286
+ });
287
+ return d;
288
+ }
289
+
290
+ function paint(html, focusSel) {
291
+ const dl = ensureDialog();
292
+ dl.dataset.state = state;
293
+ dl.setAttribute("aria-busy", String(state === "working"));
294
+ dl.innerHTML = `<div class="bz-b">${html}</div>`;
295
+ if (!dl.open) {
296
+ if (typeof dl.showModal === "function") dl.showModal();
297
+ else dl.setAttribute("open", "");
298
+ openedAt = Date.now();
299
+ }
300
+ dl.querySelector(focusSel ?? "#bz-h")?.focus?.();
301
+ }
302
+
303
+ const title = (ic, text) =>
304
+ `<h2 id="bz-h" tabindex="-1">${icon(ic)}${esc(text)}</h2>`;
305
+ const btn = (key, primary) =>
306
+ `<button type="button" class="bz-btn${primary ? " bz-primary" : ""}" data-bz="${key}">${esc(word(key))}</button>`;
307
+
308
+ /**
309
+ * Report · Close · [Open the log] · the primary, last. `next`: the
310
+ * caller's link ({ label, href }) is the primary.
311
+ */
312
+ const footer = (primary, withLog, next) =>
313
+ `<div class="bz-ft">` +
314
+ (hook.report ? btn("report") : "") +
315
+ // A next step with no link: its words are in the body; Close leads.
316
+ btn("close", !!next && !next.href) +
317
+ (withLog && hook.logUrl ? btn("log") : "") +
318
+ (next
319
+ ? next.href
320
+ ? `<a class="bz-btn bz-primary" href="${esc(next.href)}">${esc(next.label)}</a>`
321
+ : ""
322
+ : btn(primary, true)) +
323
+ `</div>`;
324
+
325
+ /** The caller's next step for this failure, or null (then Try again). */
326
+ function nextStep(err) {
327
+ let n = opts.next;
328
+ if (typeof n === "function") {
329
+ try {
330
+ n = n(err);
331
+ } catch {
332
+ n = null;
333
+ }
334
+ }
335
+ return n && n.label ? n : null;
336
+ }
337
+
338
+ function paintWorking(secs, note) {
339
+ state = "working";
340
+ const line = note
341
+ ? note
342
+ : secs >= STILL_MS / 1000
343
+ ? word("still", { s: secs })
344
+ : reconnect && actionWord(a, "working_body", vars)
345
+ ? actionWord(a, "working_body", vars)
346
+ : word("wait", { who });
347
+ paint(
348
+ title("clock", actionWord(a, "working", vars)) +
349
+ `<p aria-live="polite" class="bz-live">${esc(line)}</p>` +
350
+ progressHtml() +
351
+ `<div class="bz-bar" role="progressbar" aria-label="${esc(word("wait", { who }))}"><i></i></div>`,
352
+ );
353
+ }
354
+
355
+ /** The progress lines so far ("" with none). */
356
+ function progressHtml() {
357
+ if (!lines.length) return "";
358
+ return (
359
+ `<ol class="bz-prog" aria-label="${esc(word("progress"))}" aria-live="polite">` +
360
+ lines.map((l) => `<li>${esc(l)}</li>`).join("") +
361
+ `</ol>`
362
+ );
363
+ }
364
+
365
+ /** run's progress(text): a new line, in the open pop-up too. */
366
+ function progress(text) {
367
+ if (settled || text == null || text === "") return;
368
+ lines.push(String(text));
369
+ if (state !== "working" || !d?.open) return;
370
+ const ol = d.querySelector(".bz-prog");
371
+ if (ol) {
372
+ const li = document.createElement("li");
373
+ li.textContent = String(text);
374
+ ol.append(li);
375
+ } else {
376
+ d.querySelector(".bz-live")?.insertAdjacentHTML(
377
+ "afterend",
378
+ progressHtml(),
379
+ );
380
+ }
381
+ }
382
+
383
+ function tick(startedAt) {
384
+ clearInterval(ticker);
385
+ ticker = setInterval(() => {
386
+ if (state !== "working") return clearInterval(ticker);
387
+ const ms = Date.now() - startedAt;
388
+ if (ms >= NO_ANSWER_MS) {
389
+ clearInterval(ticker);
390
+ return paintNoAnswer();
391
+ }
392
+ if (ms >= STILL_MS && !reconnect) {
393
+ const live = d?.querySelector(".bz-live");
394
+ if (live)
395
+ live.textContent = word("still", { s: Math.floor(ms / 1000) });
396
+ }
397
+ }, 1000);
398
+ }
399
+
400
+ function wire() {
401
+ const on = (k, fn) =>
402
+ d.querySelector(`[data-bz="${k}"]`)?.addEventListener("click", fn);
403
+ on("close", () => close(state === "success" ? okData : null));
404
+ on("done", () => close(okData));
405
+ on("retry", () => attempt());
406
+ on("check", () => (reconnect ? waitBack(Date.now()) : checkAgain()));
407
+ on("log", () => hook.open(hook.logUrl));
408
+ on("report", () =>
409
+ hook.report?.({
410
+ title: actionWord(a, "failure", vars),
411
+ details: detailsText(lastErr, id, lastAt),
412
+ requestId: id,
413
+ }),
414
+ );
415
+ }
416
+
417
+ function paintFailure(err) {
418
+ state = "failure";
419
+ lastErr = err;
420
+ lastAt = new Date();
421
+ // The server's own words, only when it answered (a network error's
422
+ // message is the client's, not the server's).
423
+ const said = answeredWithError(err) ? messageOf(err) : "";
424
+ const why = err?.network
425
+ ? word("network", { who })
426
+ : err?.status
427
+ ? word("err_code", { who, code: err.status })
428
+ : messageOf(err) || word("network", { who });
429
+ opts.onFail?.(err);
430
+ const next = nextStep(err);
431
+ paint(
432
+ title("bad", actionWord(a, "failure", vars)) +
433
+ `<p>${esc(why)}</p>` +
434
+ (said && said !== why ? `<p class="bz-said">${esc(said)}</p>` : "") +
435
+ (next ? `<p class="bz-next">${esc(word("next"))}</p>` : "") +
436
+ (next && !next.href
437
+ ? `<p class="bz-step">${esc(next.label)}</p>`
438
+ : "") +
439
+ `<details><summary>${esc(word("details"))}</summary><pre>${esc(detailsText(err, id, lastAt))}</pre></details>` +
440
+ footer("retry", false, next),
441
+ next
442
+ ? next.href
443
+ ? ".bz-ft a.bz-primary"
444
+ : '[data-bz="close"]'
445
+ : '[data-bz="retry"]',
446
+ );
447
+ wire();
448
+ }
449
+
450
+ function paintNoAnswer(note) {
451
+ state = "noanswer";
452
+ const t = reconnect
453
+ ? actionWord(a, "failure", vars)
454
+ : word("noans_t", { who });
455
+ const b = reconnect ? actionWord(a, "failure_body", vars) : word("noans_b");
456
+ paint(
457
+ title("clock", t) +
458
+ `<p>${esc(b)}</p>` +
459
+ (note ? `<p class="bz-note">${esc(note)}</p>` : "") +
460
+ footer("check", reconnect),
461
+ '[data-bz="check"]',
462
+ );
463
+ wire();
464
+ }
465
+
466
+ function paintSuccess(data, node) {
467
+ state = "success";
468
+ const text = opts.success
469
+ ? opts.success(data)
470
+ : actionWord(a, "success", vars);
471
+ paint(
472
+ title("ok", text) +
473
+ (reconnect && data?.version
474
+ ? `<p>${esc(actionWord(a, "success_body", { ...vars, v: data.version }))}</p>`
475
+ : "") +
476
+ `<div class="bz-extra"></div>` +
477
+ `<div class="bz-ft">${btn(node ? "close" : "done", true)}</div>`,
478
+ node ? '[data-bz="close"]' : '[data-bz="done"]',
479
+ );
480
+ if (node) d.querySelector(".bz-extra")?.append(node);
481
+ else d.querySelector(".bz-extra")?.remove();
482
+ wire();
483
+ if (a.autoClose && !node)
484
+ setTimeout(() => {
485
+ if (state === "success") close(data);
486
+ }, SUCCESS_CLOSE_MS);
487
+ }
488
+
489
+ function close(data) {
490
+ if (settled) return;
491
+ settled = true;
492
+ clearInterval(ticker);
493
+ if (d?.open && typeof d.close === "function") d.close();
494
+ el?.remove();
495
+ hold(false);
496
+ button?.focus?.();
497
+ finish(data);
498
+ }
499
+
500
+ /** Back to the caller, with the error: its place shows it. */
501
+ function giveBack(err) {
502
+ if (settled) return;
503
+ settled = true;
504
+ clearInterval(ticker);
505
+ el?.remove();
506
+ hold(false);
507
+ opts.onFail?.(err);
508
+ fail(err);
509
+ }
510
+
511
+ /** The answer came; the pop-up may not be open (a fast action). */
512
+ async function answered(ok, data, err) {
513
+ if (settled) return;
514
+ if (!ok && !d?.open) {
515
+ // Settled 5: a quick failure goes back where the place says it
516
+ // itself; elsewhere the Failure pop-up opens at once.
517
+ const network = !!err?.network || !answeredWithError(err);
518
+ if ((opts.inlineError || a.inline) && network) return giveBack(err);
519
+ if ((opts.quietFail || a.inline) && !network) return giveBack(err);
520
+ }
521
+ if (d?.open) {
522
+ const shown = Date.now() - openedAt;
523
+ if (shown < MIN_MS) await later(MIN_MS - shown);
524
+ }
525
+ if (settled) return;
526
+ if (ok) {
527
+ okData = data;
528
+ // Settled 6: held for a person: no success line, its page instead.
529
+ if (data && typeof data === "object" && data.held?.url) {
530
+ close(data);
531
+ hook.open(data.held.url);
532
+ return;
533
+ }
534
+ opts.onDone?.(data);
535
+ if (opts.skipDone?.(data)) return close(data);
536
+ if (reconnect) return waitBack(Date.now());
537
+ const node = opts.extra?.(data) ?? null;
538
+ // UK-2 (Ward): success never waits for a click. The pop-up closes at
539
+ // once and the toast says it, as for a fast action. Only `extra`
540
+ // (something to read) keeps it open, with Close.
541
+ if (!node) {
542
+ if (d?.open || opts.toastFast !== false)
543
+ hook.toast?.(
544
+ opts.success ? opts.success(data) : actionWord(a, "success", vars),
545
+ );
546
+ return close(data);
547
+ }
548
+ return paintSuccess(data, node);
549
+ }
550
+ // Reconnect: no answer is the product going down; wait for it.
551
+ if (reconnect && !answeredWithError(err)) return waitBack(Date.now());
552
+ paintFailure(err);
553
+ }
554
+
555
+ function attempt() {
556
+ // Try again: the same id only when no answer came back.
557
+ if (answeredWithError(lastErr)) id = newId();
558
+ lastErr = null;
559
+ lines = [];
560
+ const startedAt = Date.now();
561
+ state = "working";
562
+ hold(true);
563
+ if (d?.open) {
564
+ paintWorking(0);
565
+ tick(startedAt);
566
+ }
567
+ const opener = setTimeout(() => {
568
+ if (state === "working" && !settled && !d?.open) {
569
+ paintWorking(0);
570
+ tick(startedAt);
571
+ }
572
+ }, OPEN_MS);
573
+ Promise.resolve()
574
+ .then(() => run({ [hook.idHeader]: id }, progress))
575
+ .then(
576
+ (data) => {
577
+ clearTimeout(opener);
578
+ clearInterval(ticker);
579
+ return answered(true, data);
580
+ },
581
+ (err) => {
582
+ clearTimeout(opener);
583
+ clearInterval(ticker);
584
+ lastErr = err;
585
+ return answered(false, null, err);
586
+ },
587
+ );
588
+ }
589
+
590
+ /** Check again: how did this id end? Never resends. */
591
+ async function checkAgain() {
592
+ let st = null;
593
+ try {
594
+ // The product's adapter when it has one (its request(id)), else
595
+ // a GET of statusUrl(id).
596
+ if (hook.request) st = (await hook.request(id)) ?? null;
597
+ else {
598
+ const r = await fetch(hook.statusUrl(id), { cache: "no-store" });
599
+ st = r.ok ? await r.json() : null;
600
+ }
601
+ } catch {
602
+ st = null;
603
+ }
604
+ if (settled) return;
605
+ if (st?.state === "done") return answered(true, st.result ?? okData);
606
+ if (st?.state === "failed")
607
+ return answered(false, null, {
608
+ status: st.error?.code,
609
+ message: st.error?.message || undefined,
610
+ });
611
+ if (st?.state === "running") return paintNoAnswer(word("still_running"));
612
+ if (st?.state === "unknown")
613
+ return paintNoAnswer(word("noans_unknown", { who }));
614
+ return answered(false, null, { network: true });
615
+ }
616
+
617
+ /** Reconnect mode: poll until the product is back, 1 s backing off to 3 s. */
618
+ async function waitBack(startedAt) {
619
+ const rc = hook.reconnect;
620
+ if (!rc) return paintNoAnswer();
621
+ state = "working";
622
+ paintWorking(0);
623
+ let gap = POLL_MS;
624
+ const limit = Number(rc.waitMs?.(before)) || NO_ANSWER_MS;
625
+ while (!settled && Date.now() - startedAt < limit) {
626
+ await later(gap);
627
+ gap = Math.min(POLL_MAX_MS, gap + 500);
628
+ let now = null;
629
+ try {
630
+ const r = await fetch(rc.url, { cache: "no-store" });
631
+ now = r.ok ? await r.json() : null;
632
+ } catch {
633
+ now = null;
634
+ }
635
+ if (settled) return;
636
+ if (now && rc.back(now, before)) {
637
+ const v = rc.version?.(now) ?? "";
638
+ paintSuccess({ version: v }, null);
639
+ setTimeout(() => {
640
+ if (settled) return;
641
+ (rc.done ?? (() => location.reload()))(now);
642
+ close(now);
643
+ }, SUCCESS_CLOSE_MS);
644
+ return;
645
+ }
646
+ }
647
+ if (!settled) paintNoAnswer();
648
+ }
649
+
650
+ // Reconnect mode: how the product answered before it went away.
651
+ let before = opts.before ?? null;
652
+ if (reconnect && hook.reconnect && !before)
653
+ fetch(hook.reconnect.url, { cache: "no-store" })
654
+ .then((r) => (r.ok ? r.json() : null))
655
+ .catch(() => null)
656
+ .then((b) => {
657
+ before = b;
658
+ attempt();
659
+ });
660
+ else attempt();
661
+ return result;
662
+ }