@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/report.js ADDED
@@ -0,0 +1,909 @@
1
+ /**
2
+ * den-ui Report form: Report an issue, one dialog, three steps (Write,
3
+ * Include, Review and send). It opens on top of whatever is open
4
+ * (showModal stacks over another dialog) without closing it. Nothing is
5
+ * sent without the person's click on Review, which shows the exact text.
6
+ *
7
+ * configureReport({ lang, adapter, busy, mine, page, screenshot })
8
+ * adapter the product's server calls, all optional:
9
+ * fileReport(payload) → Promise<{ number, url } | { error }>
10
+ * payload: the form, its preview, and `shot`: the masked
11
+ * screenshot as a PNG data URL, or null ("Don't include")
12
+ * the simple way: on success the form says "Filed as #N"
13
+ * with the link. With no way to send, the form offers
14
+ * Copy report only.
15
+ * info() → { repos: [{ repo }], maxPerHour, captureSeconds }
16
+ * diagnostics() → { sections: { name: text } } shown on Include
17
+ * preview(form, headers) → { status, data: { title, body } }
18
+ * the text the product will post (its redactor's); else
19
+ * the kit makes one from the form
20
+ * send(form, headers) → { status, data } the full way: 200 ok
21
+ * (data.url, data.added), 409 duplicate / need github,
22
+ * 429 the hour's limit (data.nextAt, data.limit)
23
+ * githubSend(form, headers), githubPoll(id) a device-flow sign-in
24
+ * saveDraft(form, headers) → { status, data: { draft: { id } } }
25
+ * Finish later (hidden without it)
26
+ * busy(action, run, opts) the working pop-up (busy.js's busyAction
27
+ * with the product's words), for the slow calls
28
+ * mine() opens "My reports" (the link is hidden without it)
29
+ * page() the page's name for the Page section (else its path)
30
+ * screenshot false: no screenshot step (report-shot.js, loaded when
31
+ * a report opens)
32
+ * library html-to-image's URL on the product's origin (the
33
+ * screenshot's library)
34
+ * openReport({ prefill?, draft? }) opens it (one at a time: a second
35
+ * call focuses the first). prefill: { kind, title,
36
+ * description } (a per-item "Report this …" button)
37
+ *
38
+ * Words: the kit's (kit.report.*, en/es/ja). Look: report.css.
39
+ */
40
+ import { esc as kitEsc, kitT } from "./strings.js";
41
+ import { focusBack, openerOf } from "./dialog.js";
42
+
43
+ const cfg = {
44
+ lang: "en",
45
+ adapter: null,
46
+ busy: null,
47
+ mine: null,
48
+ page: null,
49
+ screenshot: true,
50
+ library: "",
51
+ };
52
+ const lang = () => (typeof cfg.lang === "function" ? cfg.lang() : cfg.lang);
53
+ const t = (key, vars) => kitT(lang(), key, vars);
54
+ const esc = kitEsc;
55
+
56
+ export function configureReport(o = {}) {
57
+ Object.assign(cfg, o);
58
+ }
59
+
60
+ /** The report as text, from the form alone (no product preview). */
61
+ export function localPreview(f) {
62
+ const lines = [
63
+ `**Kind:** ${f.kind}`,
64
+ `**Title:** ${f.title}`,
65
+ "",
66
+ f.description || "",
67
+ ];
68
+ const secs = { ...(f.diag || {}), ...(f.client || {}) };
69
+ for (const [name, on] of Object.entries(f.sections || {})) {
70
+ if (!on || secs[name] == null) continue;
71
+ const v = secs[name];
72
+ lines.push(
73
+ "",
74
+ `### ${name}`,
75
+ "",
76
+ "```",
77
+ typeof v === "string" ? v : JSON.stringify(v, null, 2),
78
+ "```",
79
+ );
80
+ }
81
+ return { title: f.title, body: lines.join("\n") };
82
+ }
83
+
84
+ /** Text to the clipboard (navigator.clipboard, else a selection's copy). */
85
+ export function copyReport(text) {
86
+ if (navigator.clipboard?.writeText)
87
+ return navigator.clipboard.writeText(text);
88
+ return new Promise((resolve, reject) => {
89
+ const ta = document.createElement("textarea");
90
+ ta.value = text;
91
+ ta.className = "kit-offscreen";
92
+ document.body.appendChild(ta);
93
+ ta.select();
94
+ try {
95
+ document.execCommand("copy") ? resolve() : reject(new Error("copy"));
96
+ } catch (e) {
97
+ reject(e);
98
+ } finally {
99
+ ta.remove();
100
+ }
101
+ });
102
+ }
103
+ /**
104
+ * report.css, once: the page's own <link> to it when there is one (a
105
+ * product loads it in its <head>), else one added beside this module.
106
+ */
107
+ function ensureCss() {
108
+ if (document.querySelector('link[rel="stylesheet"][href*="report.css"]'))
109
+ return Promise.resolve();
110
+ return new Promise((ok) => {
111
+ const l = document.createElement("link");
112
+ l.rel = "stylesheet";
113
+ l.href = new URL("./report.css", import.meta.url).href;
114
+ l.onload = l.onerror = () => ok();
115
+ document.head.append(l);
116
+ });
117
+ }
118
+
119
+ const KINDS = ["bug", "idea", "question"];
120
+
121
+ /** The browser's own sections: what it runs, never who or where. */
122
+ export function clientSections(win = window) {
123
+ const n = win.navigator || {};
124
+ const dark = win.matchMedia?.("(prefers-color-scheme: dark)")?.matches;
125
+ const open = [...(win.document?.querySelectorAll("dialog[open]") ?? [])]
126
+ .map((d) => d.getAttribute("aria-label") || d.className || "dialog")
127
+ .filter((x) => !/fb-dlg/.test(x));
128
+ return {
129
+ Browser: [
130
+ String(n.userAgent || "?"),
131
+ `viewport ${win.innerWidth}×${win.innerHeight} · ${win.devicePixelRatio || 1}×`,
132
+ `${document.documentElement.getAttribute("data-theme") || (dark ? "dark" : "light")} · ${document.documentElement.lang || "en"}`,
133
+ ].join("\n"),
134
+ Page: [
135
+ `page: ${(cfg.page && cfg.page()) || win.location.pathname}`,
136
+ `dialogs open: ${open.length ? open.join(", ") : "none"}`,
137
+ ].join("\n"),
138
+ };
139
+ }
140
+
141
+ /** Remembered Include choices (Remember my choices), this browser only. */
142
+ const PREF_KEY = "den.report.include";
143
+ function loadPrefs() {
144
+ try {
145
+ return JSON.parse(localStorage.getItem(PREF_KEY) || "null");
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+ function savePrefs(p) {
151
+ try {
152
+ if (p) localStorage.setItem(PREF_KEY, JSON.stringify(p));
153
+ else localStorage.removeItem(PREF_KEY);
154
+ } catch {
155
+ /* storage off: not remembered */
156
+ }
157
+ }
158
+
159
+ /**
160
+ * A write through the working pop-up (cfg.busy): it shows only when the
161
+ * answer is slow. The form's own answers (a 4xx: signed out, a duplicate,
162
+ * the hour's limit) are its to show; no answer or a 5xx is the pop-up's
163
+ * Failure, with Try again. `call(headers)` is the adapter's, resolving
164
+ * with { status, data }. `action` names it for the pop-up's words.
165
+ * Resolves with { status, data }, or null when it didn't get through.
166
+ */
167
+ async function write(call, action, button) {
168
+ let got = null;
169
+ const run = (headers) =>
170
+ Promise.resolve(call(headers || {})).then((r) => {
171
+ const res = r || { status: 0, data: {} };
172
+ res.data = res.data || {};
173
+ if (res.status === 0 || res.status >= 500) {
174
+ const e = new Error(res.data.error || "");
175
+ e.status = res.status;
176
+ throw e;
177
+ }
178
+ got = res;
179
+ return res.data;
180
+ });
181
+ if (!cfg.busy) {
182
+ try {
183
+ await run({});
184
+ } catch {
185
+ return null;
186
+ }
187
+ return got;
188
+ }
189
+ await cfg.busy(action, run, { button, toastFast: false });
190
+ return got;
191
+ }
192
+
193
+ let current = null;
194
+
195
+ /** Opens the dialog (one at a time: a second call focuses the first). */
196
+ export async function openReport(opts = {}) {
197
+ if (current) {
198
+ current.dlg.querySelector("h2")?.focus();
199
+ return current;
200
+ }
201
+ // What opened it, for focus to go back to when it closes (Safari doesn't
202
+ // focus a clicked button, so its own dialog restore finds the body).
203
+ const opener = openerOf(opts.opener);
204
+ ensureCss();
205
+ const dlg = document.createElement("dialog");
206
+ dlg.className = "fb-dlg";
207
+ dlg.setAttribute("aria-modal", "true");
208
+ const d = opts.draft || opts.prefill || {};
209
+ const prefs = loadPrefs();
210
+ const st = {
211
+ step: "write",
212
+ kind: KINDS.includes(d.kind) ? d.kind : "bug",
213
+ title: d.title || "",
214
+ description: d.description || "",
215
+ sections: d.sections || prefs?.sections || null,
216
+ redact:
217
+ d.redact !== undefined ? d.redact !== false : prefs?.redact !== false,
218
+ remember: !!prefs,
219
+ repo: d.repo || null,
220
+ draftId: d.id && d.by === "person" ? d.id : null,
221
+ agentDraftId: d.id && d.by !== "person" ? d.id : null,
222
+ info: null,
223
+ diag: {},
224
+ client: clientSections(),
225
+ preview: null,
226
+ error: "",
227
+ dup: null,
228
+ flow: null,
229
+ link: "",
230
+ sent: null,
231
+ limit: null,
232
+ addTo: null,
233
+ fileNew: false,
234
+ viaApp: false,
235
+ // The screenshot: a canvas, or null when the page couldn't be taken.
236
+ shot: null,
237
+ masks: [],
238
+ noShot: false,
239
+ drag: null,
240
+ saved: null,
241
+ };
242
+ const self = { dlg, st, close };
243
+ const sends = () => !!(ad.send || ad.fileReport);
244
+ current = self;
245
+
246
+ const ad = cfg.adapter || {};
247
+ const [info, diag, shots] = await Promise.all([
248
+ ad.info ? Promise.resolve(ad.info()).catch(() => ({})) : {},
249
+ ad.diagnostics ? Promise.resolve(ad.diagnostics()).catch(() => ({})) : {},
250
+ // Loaded only when a report opens: a page without the screenshot
251
+ // module (or a failed load) still has Report, with no screenshot.
252
+ cfg.screenshot === false
253
+ ? null
254
+ : import("./report-shot.js")
255
+ .then((m) => {
256
+ if (cfg.library) m.configureShots({ library: cfg.library });
257
+ return m;
258
+ })
259
+ .catch(() => null),
260
+ ensureCss(),
261
+ ]);
262
+ st.info = info || {};
263
+ // Taken before the dialog is on the page, so it shows what the person
264
+ // saw: the page and any pop-up open over it.
265
+ // A draft brings its own: Finish later's from this browser (with its
266
+ // masks), an agent's from its record.
267
+ const fromDraft = async () => {
268
+ if (d.by === "person" && d.id) {
269
+ const k = await shots.loadShot(d.id);
270
+ if (!k) return null;
271
+ st.masks = k.masks;
272
+ st.noShot = k.noShot;
273
+ return k.canvas;
274
+ }
275
+ return typeof d.shot === "string" ? shots.canvasOf(d.shot) : null;
276
+ };
277
+ st.shot = !shots
278
+ ? null
279
+ : opts.draft
280
+ ? await fromDraft()
281
+ : await shots.capture({
282
+ seconds: st.info.captureSeconds || 15,
283
+ skip: (el) => el.classList?.contains("fb-dlg"),
284
+ });
285
+ if (current !== self) return self;
286
+ document.body.append(dlg);
287
+ st.diag = diag?.sections || diag || {};
288
+ st.repo = st.repo || st.info.repos?.[0]?.repo || "";
289
+ if (!st.sections) {
290
+ st.sections = {};
291
+ for (const k of Object.keys(allSections())) st.sections[k] = true;
292
+ }
293
+
294
+ function allSections() {
295
+ return { ...st.diag, ...st.client };
296
+ }
297
+ /** Whether a screenshot goes with the report. */
298
+ function shotOn() {
299
+ return !!st.shot && !st.noShot;
300
+ }
301
+ function maskedShot() {
302
+ return shots.masked(st.shot, st.masks);
303
+ }
304
+ const pct = (v) => Math.round(v * 100);
305
+ /** Draws the screenshot with its masks (and one being dragged). */
306
+ function paintShot() {
307
+ const c = dlg.querySelector("canvas[data-shot]");
308
+ if (!c || !st.shot) return;
309
+ c.width = st.shot.width;
310
+ c.height = st.shot.height;
311
+ const g = c.getContext("2d");
312
+ g.drawImage(maskedShot(), 0, 0);
313
+ if (st.drag?.b) {
314
+ const r = shots.rectOf(st.drag.a, st.drag.b);
315
+ // Black at 60%: a mask being drawn (a mask hides; not a theme colour).
316
+ g.fillStyle = "black";
317
+ g.globalAlpha = 0.6;
318
+ g.fillRect(r.x * c.width, r.y * c.height, r.w * c.width, r.h * c.height);
319
+ g.globalAlpha = 1;
320
+ }
321
+ }
322
+ function dirty() {
323
+ return (
324
+ st.step !== "sent" &&
325
+ st.step !== "later" &&
326
+ (st.title.trim() !== (d.title || "") ||
327
+ st.description.trim() !== (d.description || ""))
328
+ );
329
+ }
330
+ function form() {
331
+ return {
332
+ kind: st.kind,
333
+ title: st.title,
334
+ description: st.description,
335
+ sections: st.sections,
336
+ client: st.client,
337
+ redact: st.redact,
338
+ repo: st.repo,
339
+ ...(st.draftId ? { draftId: st.draftId } : {}),
340
+ ...(st.agentDraftId ? { draftId: st.agentDraftId } : {}),
341
+ };
342
+ }
343
+
344
+ function stepsHtml(i) {
345
+ const names = [
346
+ t("kit.report.step1"),
347
+ t("kit.report.step2"),
348
+ t("kit.report.step3"),
349
+ ];
350
+ return `<div class="fb-steps" aria-live="polite"><span class="fb-wide">${names
351
+ .map((n, k) => (k === i ? `<b>${esc(n)}</b>` : esc(n)))
352
+ .join(" › ")}</span><span class="fb-narrow">${esc(
353
+ t("kit.report.stepOf", { i: i + 1, n: 3 }),
354
+ )} · <b>${esc(names[i].replace(/^\d+\s*/, ""))}</b></span></div>`;
355
+ }
356
+ // Finish later only where the product keeps drafts.
357
+ const laterBtn = (label, pri) =>
358
+ ad.saveDraft ? btn("later", label, pri) : "";
359
+ const btn = (act, label, pri) =>
360
+ `<button type="button" data-act="${act}"${pri ? ' class="fb-pri"' : ""}>${esc(label)}</button>`;
361
+ const linkBtn = (href, label, pri) =>
362
+ `<a href="${esc(href)}" target="_blank" rel="noopener"${pri ? ' class="fb-pri"' : ""}>${esc(label)}</a>`;
363
+
364
+ /** Draws the step; `focusSel` keeps focus where the person was. */
365
+ function render(focusSel) {
366
+ let h = "";
367
+ let role = "dialog";
368
+ let label = t("kit.report.title");
369
+ const err = st.error
370
+ ? `<p class="fb-err" role="alert">${esc(st.error)}</p>`
371
+ : "";
372
+ if (st.step === "write") {
373
+ h = `<h2 tabindex="-1">${esc(t("kit.report.title"))}</h2>
374
+ <p class="fb-sub">${esc(t("kit.report.sub"))}</p>${cfg.mine ? `<button type="button" class="fb-lk" data-act="mine">${esc(t("kit.report.mine"))}</button>` : ""}${stepsHtml(0)}
375
+ <div class="fb-h" id="fb-kind">${esc(t("kit.report.kind"))}</div>
376
+ <div class="fb-kinds" role="radiogroup" aria-labelledby="fb-kind">${KINDS.map(
377
+ (k) =>
378
+ `<label><input type="radio" name="fb-kind" value="${k}"${st.kind === k ? " checked" : ""}><span>${esc(t(`kit.report.k.${k}`))}</span></label>`,
379
+ ).join("")}</div>
380
+ <label class="fb-f">${esc(t("kit.report.titleL"))}<input type="text" data-f="title" maxlength="200" value="${esc(st.title)}"></label>
381
+ <label class="fb-f">${esc(t("kit.report.desc"))}<textarea data-f="description" maxlength="20000">${esc(st.description)}</textarea></label>
382
+ <div class="fb-h">${esc(t("kit.report.shot"))}</div>
383
+ ${
384
+ st.shot
385
+ ? `<p class="fb-fine">${esc(t("kit.report.shotNote"))}</p>
386
+ <div class="fb-shot"${st.noShot ? " hidden" : ""}><canvas data-shot role="img" aria-label="${esc(t("kit.report.shot"))}"></canvas></div>
387
+ <div class="fb-tools">${st.noShot ? "" : btn("undo", t("kit.report.undo"))}<label><input type="checkbox" data-f="noshot"${st.noShot ? " checked" : ""}> ${esc(t("kit.report.nos"))}</label><span class="fb-fine" aria-live="polite">${st.noShot ? "" : esc(t("kit.report.masks", { n: st.masks.length }))}</span></div>
388
+ ${
389
+ st.noShot
390
+ ? ""
391
+ : `<details class="fb-kbd"${st.kbd ? " open" : ""}><summary>${esc(t("kit.report.kbdMask"))}</summary>
392
+ <div class="fb-tools">${[
393
+ ["x", "kit.report.mx"],
394
+ ["y", "kit.report.my"],
395
+ ["w", "kit.report.mw"],
396
+ ["h", "kit.report.mh"],
397
+ ]
398
+ .map(
399
+ ([k, l]) =>
400
+ `<label>${esc(t(l))} <input type="number" data-m="${k}" min="0" max="100" step="1" value="${k === "w" || k === "h" ? 20 : 0}"></label>`,
401
+ )
402
+ .join(
403
+ "",
404
+ )}${btn("addmask", t("kit.report.addMask"))}${btn("maskall", t("kit.report.maskAll"))}</div>
405
+ <ul class="fb-masks">${st.masks
406
+ .map(
407
+ (m, i) =>
408
+ `<li>${esc(t("kit.report.area", { x: pct(m.x), y: pct(m.y), w: pct(m.w), h: pct(m.h) }))} <button type="button" data-act="rmmask" data-i="${i}">${esc(t("kit.report.rmMask"))}</button></li>`,
409
+ )
410
+ .join("")}</ul></details>`
411
+ }`
412
+ : `<p class="fb-fine" role="status">${esc(t("kit.report.ncap"))}</p>`
413
+ }${err}
414
+ <div class="fb-btns">${btn("next", t("kit.report.next"), true)}${laterBtn(t("kit.report.later"))}${btn("cancel", t("kit.report.cancel"))}</div>`;
415
+ } else if (st.step === "include") {
416
+ label = t("kit.report.incH");
417
+ const secs = allSections();
418
+ h = `<h2 tabindex="-1">${esc(t("kit.report.incH"))}</h2>${stepsHtml(1)}
419
+ <p class="fb-fine">${esc(t("kit.report.incN"))}</p>
420
+ <div class="fb-tools">${btn("all", t("kit.report.all"))}${btn("none", t("kit.report.none"))}</div>
421
+ ${Object.entries(secs)
422
+ .map(([name, v], i) => {
423
+ const nm =
424
+ t(`kit.report.sec.${name}`) === `kit.report.sec.${name}`
425
+ ? name
426
+ : t(`kit.report.sec.${name}`);
427
+ return `<details${i < 2 ? " open" : ""}><summary><input type="checkbox" data-sec="${esc(name)}" aria-label="${esc(nm)}"${st.sections[name] ? " checked" : ""}><b>${esc(nm)}</b><span class="fb-i" title="${esc(t("kit.report.dgi"))}" aria-label="${esc(t("kit.report.dgi"))}">i</span></summary><p class="fb-fine">${esc(t(`kit.report.use.${name}`) === `kit.report.use.${name}` ? "" : t(`kit.report.use.${name}`))}</p><pre>${esc(typeof v === "string" ? v : JSON.stringify(v, null, 2))}</pre></details>`;
428
+ })
429
+ .join("")}
430
+ <label class="fb-tools"><input type="checkbox" data-f="redact"${st.redact ? " checked" : ""}> ${esc(t("kit.report.redact"))}</label>
431
+ <label class="fb-tools"><input type="checkbox" data-f="remember"${st.remember ? " checked" : ""}> ${esc(t("kit.report.remember"))}</label>${err}
432
+ <div class="fb-btns">${btn("review", t("kit.report.step3"), true)}${btn("back-write", t("kit.report.back"))}</div>`;
433
+ } else if (st.step === "review") {
434
+ label = t("kit.report.revH");
435
+ const pv = st.preview;
436
+ const repos = st.info?.repos || [];
437
+ h = `<h2 tabindex="-1">${esc(t("kit.report.revH"))}</h2>${stepsHtml(2)}
438
+ ${
439
+ sends()
440
+ ? `<div class="fb-h">${esc(t("kit.report.dest"))}</div>
441
+ <div class="fb-dest">${
442
+ repos.length > 1
443
+ ? `<select data-f="repo" aria-label="${esc(t("kit.report.dest"))}">${repos
444
+ .map(
445
+ (r) =>
446
+ `<option${r.repo === st.repo ? " selected" : ""}>${esc(r.repo)}</option>`,
447
+ )
448
+ .join("")}</select>`
449
+ : `<b>${esc(st.repo)}</b>`
450
+ }<span class="fb-pill">${esc(t("kit.report.pub"))}</span></div>`
451
+ : ""
452
+ }
453
+ <pre data-preview>${esc(pv ? `${pv.title}\n\n${pv.body}` : "…")}</pre>${
454
+ shotOn()
455
+ ? `<div class="fb-h">${esc(t("kit.report.revShot", { n: st.masks.length }))}</div><div class="fb-shot"><img data-shot-review alt="${esc(t("kit.report.revShot", { n: st.masks.length }))}" src="${maskedShot().toDataURL("image/png")}"></div>`
456
+ : ""
457
+ }
458
+ ${sends() ? `<div class="fb-warn" role="note"><b>${esc(t("kit.report.pub"))}.</b> ${esc(t("kit.report.pubW"))}</div>` : ""}${err}${st.copied ? `<p class="fb-fine" role="status">${esc(t(st.copied === "ok" ? "kit.report.copied" : "kit.report.copyFailed"))}</p>` : ""}
459
+ <div class="fb-btns">${sends() ? btn("send", t("kit.report.send"), true) : btn("copy", t("kit.report.copy"), true)}${laterBtn(t("kit.report.later"))}${btn("back-include", t("kit.report.back"))}</div>`;
460
+ } else if (st.step === "signin") {
461
+ label = t("kit.report.siH");
462
+ const f = st.flow;
463
+ h = `<h2 tabindex="-1">${esc(t("kit.report.siH"))}</h2><p>${esc(t("kit.report.siB"))}</p>
464
+ ${
465
+ f
466
+ ? `<div class="fb-h">${esc(t("kit.report.codeL"))}</div><div class="fb-code" aria-live="polite">${esc(f.userCode)}</div><p class="fb-fine" aria-live="polite">${esc(t("kit.report.waiting"))}</p>`
467
+ : `<p>${esc(t("kit.report.noApp"))}</p>`
468
+ }${err}
469
+ <div class="fb-btns">${
470
+ f
471
+ ? linkBtn(
472
+ f.verificationUri || "https://github.com/login/device",
473
+ t("kit.report.open"),
474
+ true,
475
+ )
476
+ : ""
477
+ }${laterBtn(t("kit.report.later"), !f)}${btn("back-review", t("kit.report.back"))}</div>
478
+ ${st.link ? `<p class="fb-fine">${esc(t("kit.report.siAlt"))} ${linkBtn(st.link, t("kit.report.siAltLink"))}</p>` : ""}`;
479
+ } else if (st.step === "dup") {
480
+ role = "alertdialog";
481
+ label = t("kit.report.dupH");
482
+ h = `<h2 tabindex="-1">${esc(t("kit.report.dupH"))}</h2><p>${esc(
483
+ t("kit.report.dupB", { title: st.dup.title }),
484
+ )} ${linkBtn(st.dup.url, `#${st.dup.number}`)}</p>
485
+ <div class="fb-btns">${btn("addto", t("kit.report.addTo"), true)}${btn("filenew", t("kit.report.fileNew"))}${btn("back-review", t("kit.report.back"))}</div>`;
486
+ } else if (st.step === "sent") {
487
+ label = t("kit.report.sentH");
488
+ h = `<h2 tabindex="-1">${esc(t("kit.report.sentH"))}</h2>${
489
+ st.sent.filed
490
+ ? `<p>${esc(t("kit.report.filed", { n: st.sent.number }))}${st.sent.url ? ` ${linkBtn(st.sent.url, `#${st.sent.number}`)}` : ""}</p>`
491
+ : `<p>${esc(t(st.sent.added ? "kit.report.addedB" : "kit.report.sentB", { title: st.title }))}</p>`
492
+ }${
493
+ st.saved
494
+ ? `<p data-saved>${esc(t(st.saved.copied ? "kit.report.sentShot" : "kit.report.sentShotSaved"))}</p>`
495
+ : ""
496
+ }
497
+ <div class="fb-btns">${st.sent.url ? linkBtn(st.sent.url, t("kit.report.openIssue"), true) : ""}${btn("done", t("kit.report.done"), !st.sent.url)}</div>`;
498
+ } else if (st.step === "limit") {
499
+ role = "alertdialog";
500
+ label = t("kit.report.limH", { n: st.limit.n });
501
+ h = `<h2 tabindex="-1">${esc(label)}</h2><p>${esc(
502
+ t("kit.report.limB", { min: st.limit.min }),
503
+ )}</p>
504
+ <div class="fb-btns">${laterBtn(t("kit.report.later"), true)}${btn("cancel", t("kit.report.cancel"))}</div>`;
505
+ } else if (st.step === "failed") {
506
+ role = "alertdialog";
507
+ label = t("kit.report.failH");
508
+ h = `<h2 tabindex="-1">${esc(t("kit.report.failH"))}</h2><p>${esc(st.error)}</p>
509
+ <div class="fb-btns">${btn("retry", t("kit.report.retry"), true)}${st.link ? linkBtn(st.link, t("kit.report.siAltLink")) : ""}${laterBtn(t("kit.report.later"))}${btn("back-review", t("kit.report.back"))}</div>`;
510
+ } else if (st.step === "later") {
511
+ role = "status";
512
+ label = t("kit.report.latH");
513
+ h = `<h2 tabindex="-1">${esc(t("kit.report.latH"))}</h2><p>${esc(t("kit.report.latB"))}</p>
514
+ <div class="fb-btns">${btn("done", t("kit.report.done"), true)}</div>`;
515
+ } else if (st.step === "keep") {
516
+ role = "alertdialog";
517
+ label = t("kit.report.keepH");
518
+ h = `<h2 tabindex="-1">${esc(t("kit.report.keepH"))}</h2>
519
+ <div class="fb-btns">${laterBtn(t("kit.report.keep"), true)}${btn("discard", t("kit.report.discard"))}${btn("back-write", t("kit.report.back"))}</div>`;
520
+ }
521
+ dlg.setAttribute("role", role);
522
+ dlg.setAttribute("aria-label", label);
523
+ dlg.dataset.step = st.step;
524
+ dlg.innerHTML = `<div class="fb-b">${h}</div>`;
525
+ paintShot();
526
+ const focus =
527
+ (focusSel && dlg.querySelector(focusSel)) ||
528
+ (st.step === "write"
529
+ ? dlg.querySelector('[data-f="title"]')
530
+ : dlg.querySelector("h2"));
531
+ focus?.focus();
532
+ }
533
+
534
+ /** A step, with what went wrong to show on it (none by default). */
535
+ function go(step, error = "") {
536
+ st.step = step;
537
+ st.error = error;
538
+ render();
539
+ }
540
+
541
+ async function preview() {
542
+ if (!ad.preview) {
543
+ st.preview = localPreview({ ...form(), diag: st.diag });
544
+ return render();
545
+ }
546
+ const r = await write((h) => ad.preview(form(), h), "report-preview");
547
+ if (!r) return render();
548
+ if (r.status !== 200) {
549
+ st.error = r.data.error || `${r.status}`;
550
+ st.preview = null;
551
+ } else st.preview = r.data;
552
+ render();
553
+ }
554
+
555
+ async function saveDraft() {
556
+ const r = await write(
557
+ (h) =>
558
+ ad.saveDraft(
559
+ { ...form(), ...(st.draftId ? { id: st.draftId } : {}) },
560
+ h,
561
+ ),
562
+ "save-report-draft",
563
+ dlg.querySelector('[data-act="later"]'),
564
+ );
565
+ if (!r) return render();
566
+ if (r.status !== 200) {
567
+ st.error = r.data.error || `${r.status}`;
568
+ return render();
569
+ }
570
+ st.draftId = r.data.draft?.id || st.draftId;
571
+ // The screenshot stays in this browser, never on the product's server.
572
+ if (shots && st.draftId)
573
+ await (st.shot
574
+ ? shots.keepShot(st.draftId, st.shot, st.masks, st.noShot)
575
+ : shots.dropShot(st.draftId));
576
+ go("later");
577
+ }
578
+
579
+ /** Sent: then the masked screenshot is saved and copied to paste. */
580
+ function sent(data) {
581
+ st.sent = data || {};
582
+ if (shots && st.draftId) void shots.dropShot(st.draftId);
583
+ go("sent");
584
+ if (!shotOn()) return;
585
+ void shots.saveAndCopy(maskedShot()).then((r) => {
586
+ st.saved = r.saved || r.copied ? r : null;
587
+ if (current === self && st.step === "sent") render();
588
+ });
589
+ }
590
+
591
+ function onAnswer(r) {
592
+ if (r.status === 200 && r.data.ok) return sent(r.data);
593
+ if (r.status === 429) {
594
+ const next = r.data.nextAt ? Date.parse(r.data.nextAt) : Date.now();
595
+ st.limit = {
596
+ n: r.data.limit ?? st.info.maxPerHour,
597
+ min: Math.max(1, Math.ceil((next - Date.now()) / 60_000)),
598
+ };
599
+ return go("limit");
600
+ }
601
+ if (r.status === 409 && r.data.duplicate) {
602
+ st.dup = r.data.duplicate;
603
+ return go("dup");
604
+ }
605
+ st.link = r.data.newIssueUrl || st.link;
606
+ if (r.status === 409 && r.data.need === "github") {
607
+ if (r.data.deviceFlow && ad.githubSend) return viaApp();
608
+ st.flow = null;
609
+ return go("signin");
610
+ }
611
+ go("failed", r.data.error || `${r.status}`);
612
+ }
613
+
614
+ async function send() {
615
+ if (!ad.send && ad.fileReport) return fileIt();
616
+ if (st.viaApp) return viaApp();
617
+ const r = await write(
618
+ (h) =>
619
+ ad.send(
620
+ {
621
+ ...form(),
622
+ ...(st.addTo !== null ? { addTo: st.addTo } : {}),
623
+ ...(st.fileNew ? { fileNew: true } : {}),
624
+ },
625
+ h,
626
+ ),
627
+ "send-report",
628
+ dlg.querySelector(
629
+ '[data-act="send"],[data-act="addto"],[data-act="filenew"]',
630
+ ),
631
+ );
632
+ if (!r) return render();
633
+ onAnswer(r);
634
+ }
635
+
636
+ /** F4 with Den's GitHub App: show the code, wait for the approval. */
637
+ async function viaApp() {
638
+ st.viaApp = true;
639
+ const r = await write(
640
+ (h) =>
641
+ ad.githubSend(
642
+ {
643
+ ...form(),
644
+ ...(st.addTo !== null ? { addTo: st.addTo } : {}),
645
+ ...(st.fileNew ? { fileNew: true } : {}),
646
+ },
647
+ h,
648
+ ),
649
+ "send-report",
650
+ );
651
+ if (!r) return render();
652
+ st.link = r.data.newIssueUrl || st.link;
653
+ if (r.status !== 200 || !r.data.flow) {
654
+ if (r.status === 429 || (r.status === 409 && r.data.duplicate))
655
+ return onAnswer(r);
656
+ st.flow = null;
657
+ return go("signin", r.data.error || "");
658
+ }
659
+ st.flow = r.data.flow;
660
+ go("signin");
661
+ const id = st.flow.id;
662
+ const poll = async () => {
663
+ if (current !== self || st.step !== "signin" || st.flow?.id !== id)
664
+ return;
665
+ const p = await Promise.resolve(ad.githubPoll(id)).catch(() => ({
666
+ data: {},
667
+ }));
668
+ const f = p?.data?.flow;
669
+ if (!f || f.state === "pending") return setTimeout(poll, 2000);
670
+ if (f.state === "ok") return sent(f.result);
671
+ go(
672
+ "failed",
673
+ f.message ||
674
+ (f.state === "expired"
675
+ ? t("kit.report.expired")
676
+ : t("kit.report.denied")),
677
+ );
678
+ };
679
+ setTimeout(poll, 2000);
680
+ }
681
+
682
+ /**
683
+ * The simple adapter: fileReport(payload) → { number, url } or
684
+ * { error }. Filed: "Filed as #N" with its link.
685
+ */
686
+ async function fileIt() {
687
+ // The masked screenshot as a PNG data URL; null with "Don't include"
688
+ // (or none taken).
689
+ const payload = {
690
+ ...form(),
691
+ preview: st.preview,
692
+ shot: shotOn() ? maskedShot().toDataURL("image/png") : null,
693
+ };
694
+ let r = null;
695
+ const call = () =>
696
+ Promise.resolve(ad.fileReport(payload)).then((x) => {
697
+ r = x || { error: "" };
698
+ return { status: r.error ? 400 : 200, data: r };
699
+ });
700
+ await write(call, "send-report", dlg.querySelector('[data-act="send"]'));
701
+ if (!r) return render();
702
+ if (r.error || r.number == null) return go("failed", r.error || "");
703
+ sent({ filed: true, number: r.number, url: r.url || "" });
704
+ }
705
+
706
+ /** No adapter: the report as text, to paste where the team tracks issues. */
707
+ async function copyIt() {
708
+ const pv = st.preview || localPreview({ ...form(), diag: st.diag });
709
+ try {
710
+ await copyReport(`${pv.title}\n\n${pv.body}`);
711
+ st.copied = "ok";
712
+ } catch {
713
+ st.copied = "failed";
714
+ }
715
+ render('[data-act="copy"]');
716
+ }
717
+
718
+ function close() {
719
+ if (current === self) current = null;
720
+ if (dlg.open) dlg.close();
721
+ dlg.remove();
722
+ focusBack(opener);
723
+ }
724
+
725
+ /** Esc: back from "keep it?", ask when text was typed, else close. */
726
+ const onEsc = () => {
727
+ if (st.step === "keep") return go("write");
728
+ if (dirty()) return go("keep");
729
+ close();
730
+ };
731
+ dlg.addEventListener("cancel", (e) => {
732
+ e.preventDefault();
733
+ onEsc();
734
+ });
735
+ // The page's own Esc handlers may stop the dialog's cancel: Esc is
736
+ // handled here first.
737
+ // ⌘↵ (Ctrl+Enter) is the primary on Write and Include, as in every
738
+ // pop-up. Review is left out: nothing is sent without a click.
739
+ dlg.addEventListener("keydown", (e) => {
740
+ if (
741
+ e.key === "Enter" &&
742
+ (e.metaKey || e.ctrlKey) &&
743
+ !e.isComposing &&
744
+ (st.step === "write" || st.step === "include")
745
+ ) {
746
+ e.preventDefault();
747
+ e.stopPropagation();
748
+ dlg.querySelector(".fb-btns .fb-pri")?.click();
749
+ return;
750
+ }
751
+ if (e.key !== "Escape") return;
752
+ e.preventDefault();
753
+ e.stopPropagation();
754
+ onEsc();
755
+ });
756
+ // Chrome may close a dialog even when its cancel is stopped (no user
757
+ // activation since the last Esc): with text typed, it opens again and
758
+ // asks to keep it; else it is gone.
759
+ dlg.addEventListener("close", () => {
760
+ if (current !== self) return;
761
+ if (dirty() && st.step !== "keep") {
762
+ dlg.showModal();
763
+ return go("keep");
764
+ }
765
+ close();
766
+ });
767
+ dlg.addEventListener("input", (e) => {
768
+ const f = e.target.getAttribute?.("data-f");
769
+ if (f === "title" || f === "description") st[f] = e.target.value;
770
+ });
771
+ dlg.addEventListener("change", (e) => {
772
+ const el = e.target;
773
+ if (el.name === "fb-kind") st.kind = el.value;
774
+ const sec = el.getAttribute?.("data-sec");
775
+ if (sec) st.sections[sec] = el.checked;
776
+ const f = el.getAttribute?.("data-f");
777
+ if (f === "redact") st.redact = el.checked;
778
+ if (f === "remember") st.remember = el.checked;
779
+ if (f === "noshot") {
780
+ st.noShot = el.checked;
781
+ render('[data-f="noshot"]');
782
+ }
783
+ if (f === "repo") {
784
+ st.repo = el.value;
785
+ void preview();
786
+ }
787
+ });
788
+ // The mask tool: drag on the screenshot to black out a rectangle.
789
+ const frac = (e, c) => {
790
+ const r = c.getBoundingClientRect();
791
+ return {
792
+ x: (e.clientX - r.left) / r.width,
793
+ y: (e.clientY - r.top) / r.height,
794
+ };
795
+ };
796
+ dlg.addEventListener("pointerdown", (e) => {
797
+ const c = e.target.closest?.("canvas[data-shot]");
798
+ if (!c) return;
799
+ e.preventDefault();
800
+ c.setPointerCapture?.(e.pointerId);
801
+ st.drag = { a: frac(e, c), b: null };
802
+ });
803
+ dlg.addEventListener("pointermove", (e) => {
804
+ const c = e.target.closest?.("canvas[data-shot]");
805
+ if (!c || !st.drag) return;
806
+ st.drag.b = frac(e, c);
807
+ paintShot();
808
+ });
809
+ dlg.addEventListener("pointerup", (e) => {
810
+ const c = e.target.closest?.("canvas[data-shot]");
811
+ const d0 = st.drag;
812
+ st.drag = null;
813
+ if (!c || !d0) return;
814
+ const r = shots.rectOf(d0.a, frac(e, c));
815
+ if (r.w * r.h > 0.0001) st.masks.push(r);
816
+ render('[data-act="undo"]');
817
+ });
818
+ dlg.addEventListener("click", (e) => {
819
+ const b = e.target.closest?.("[data-act]");
820
+ if (!b) return;
821
+ const act = b.getAttribute("data-act");
822
+ if (act === "next") {
823
+ if (!st.title.trim()) {
824
+ st.error = t("kit.report.needTitle");
825
+ return render();
826
+ }
827
+ return go("include");
828
+ }
829
+ if (act === "undo") {
830
+ st.masks.pop();
831
+ return render('[data-act="undo"]');
832
+ }
833
+ if (act === "addmask") {
834
+ const v = (k) => dlg.querySelector(`[data-m="${k}"]`)?.value;
835
+ const m = shots.rectOfPercent(v("x"), v("y"), v("w"), v("h"));
836
+ st.kbd = true;
837
+ if (m.w > 0 && m.h > 0) st.masks.push(m);
838
+ return render('[data-act="addmask"]');
839
+ }
840
+ if (act === "maskall") {
841
+ st.kbd = true;
842
+ st.masks.push({ x: 0, y: 0, w: 1, h: 1 });
843
+ return render('[data-act="maskall"]');
844
+ }
845
+ if (act === "rmmask") {
846
+ st.masks.splice(Number(b.getAttribute("data-i")), 1);
847
+ return render('[data-act="addmask"]');
848
+ }
849
+ if (act === "all" || act === "none") {
850
+ for (const k of Object.keys(allSections()))
851
+ st.sections[k] = act === "all";
852
+ return render();
853
+ }
854
+ if (act === "review") {
855
+ savePrefs(
856
+ st.remember ? { sections: st.sections, redact: st.redact } : null,
857
+ );
858
+ st.preview = null;
859
+ go("review");
860
+ return void preview();
861
+ }
862
+ if (act === "send") return void send();
863
+ if (act === "copy") return void copyIt();
864
+ if (act === "addto") {
865
+ st.addTo = st.dup.number;
866
+ st.fileNew = false;
867
+ return void send();
868
+ }
869
+ if (act === "filenew") {
870
+ st.fileNew = true;
871
+ st.addTo = null;
872
+ return void send();
873
+ }
874
+ if (act === "later") return void saveDraft();
875
+ // A failed send: the same text again. The server answered the first
876
+ // (nothing was filed), so it goes as a new request.
877
+ if (act === "retry") return void send();
878
+ if (act === "mine") {
879
+ // Typed text is kept or discarded first, then My reports opens.
880
+ if (dirty()) {
881
+ st.then = "mine";
882
+ return go("keep");
883
+ }
884
+ close();
885
+ return void cfg.mine?.();
886
+ }
887
+ if (act === "back-write") {
888
+ st.then = null;
889
+ return go("write");
890
+ }
891
+ if (act === "back-include") return go("include");
892
+ if (act === "back-review") {
893
+ go("review");
894
+ return void preview();
895
+ }
896
+ if (act === "cancel") return dirty() ? go("keep") : close();
897
+ if (act === "discard" || act === "done") {
898
+ const then = st.then;
899
+ close();
900
+ if (then === "mine") void cfg.mine?.();
901
+ return;
902
+ }
903
+ });
904
+
905
+ render();
906
+ dlg.showModal();
907
+ render();
908
+ return self;
909
+ }