astralis-devtools 0.1.0 → 0.3.0

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.
@@ -1,525 +1,583 @@
1
- import { animate, h, icon, store } from "./dom.mjs";
2
- import { FONT_FACES } from "./fonts.mjs";
3
- import { ICONS, MARK } from "./icons.mjs";
4
- import { createLauncher } from "./launcher.mjs";
5
- import { scanPage } from "./page.mjs";
6
- import { createPicker } from "./picker.mjs";
7
- import { recordConsoleErrors } from "./report.mjs";
8
- import { componentScreen } from "./screens/component.mjs";
9
- import { componentsScreen } from "./screens/components.mjs";
10
- import { findingsScreen } from "./screens/findings.mjs";
11
- import { homeScreen } from "./screens/home.mjs";
12
- import { reportScreen } from "./screens/report.mjs";
13
- import { STYLES } from "./styles.mjs";
14
-
15
- /* The Astralis DevTools overlay: a launcher that can sit anywhere on the
16
- page in development, and a panel with five screens.
17
-
18
- Home what is on this page, at a glance
19
- Components every astralis-ui component on the page; each opens a
20
- page of its own with its props, how it reaches the
21
- browser, and the findings about it
22
- Findings the validator's errors, live: what renders wrong
23
- Recommendations the validator's warnings: what works but could be better
24
- Report a problem opened as a GitHub issue from the reporter's own
25
- account, shown in full before anything is sent, and the
26
- issues they have opened so far
27
-
28
- Shift+Alt+A opens and closes it. Shift+Alt+C picks a component on the page
29
- and opens its page. Plain DOM in a shadow root, so it needs no framework and
30
- the page's CSS cannot reach it. Everything from the page or the bridge goes
31
- in as text. */
32
-
33
- const HOST_TAG = "astralis-devtools";
34
- const FONTS_ID = "astralis-devtools-fonts";
35
- const ROUTE_POLL_MS = 1000;
36
- const SCAN_DEBOUNCE_MS = 200;
37
- const PANEL_GAP = 10;
38
- /** How often a waiting sign-in is checked. The bridge polls GitHub; this asks the bridge. */
39
- const SIGN_IN_POLL_MS = 2000;
40
- const EDGE = 12;
41
-
42
- const NAV = [
43
- { screen: "home", label: "Home", icon: ICONS.home },
44
- { screen: "components", label: "Components", icon: ICONS.components },
45
- { screen: "findings", label: "Findings", icon: ICONS.findings },
46
- { screen: "recommendations", label: "Recommendations", icon: ICONS.recommendations },
47
- { screen: "report", label: "Report", icon: ICONS.report },
48
- ];
49
-
50
- const SHORTCUTS = { open: "KeyA", pick: "KeyC" };
51
-
52
- /**
53
- * Mount the overlay on this page. Returns a function that removes it and
54
- * everything it listens to. Mounting twice is a no-op.
55
- */
56
- export function mountOverlay({ base = "/api/astralis-devtools", framework = null } = {}) {
57
- if (typeof document === "undefined" || document.querySelector(HOST_TAG)) return () => {};
58
-
59
- const host = document.createElement(HOST_TAG);
60
- const shadow = host.attachShadow({ mode: "open" });
61
- shadow.append(h("style", {}, STYLES));
62
-
63
- // @font-face is ignored inside a shadow root, so the faces go on the document, under names no page uses.
64
- let fonts = document.getElementById(FONTS_ID);
65
- const ownFonts = !fonts;
66
- if (ownFonts) {
67
- fonts = h("style", { id: FONTS_ID }, FONT_FACES);
68
- document.head.append(fonts);
69
- }
70
-
71
- const remembered = store.read("sessionStorage", "panel") ?? {};
72
- const state = {
73
- open: false,
74
- screen: NAV.some((n) => n.screen === remembered.screen) ? remembered.screen : "home",
75
- selected: null,
76
- spec: null,
77
- info: null,
78
- findings: null,
79
- bridge: "connecting", // connecting | live | unreachable
80
- route: location.pathname,
81
- routeFiles: [],
82
- instances: [],
83
- github: null, // the bridge's GitHub status: { configured, repo, login, pending, error }
84
- issues: { list: null, loading: false, error: null },
85
- reportTab: "new",
86
- report: {
87
- title: "",
88
- happened: "",
89
- expected: "",
90
- includeText: false,
91
- includeFindings: true,
92
- includeConsole: false,
93
- screenshot: null,
94
- snapshot: null,
95
- problems: [],
96
- status: "idle", // idle | sending | sent | failed | notice
97
- message: "",
98
- url: null,
99
- },
100
- };
101
-
102
- const cleanups = [];
103
- const listen = (target, type, handler, options) => {
104
- target.addEventListener(type, handler, options);
105
- cleanups.push(() => target.removeEventListener(type, handler, options));
106
- };
107
-
108
- /* ---- the panel's frame ------------------------------------------------------ */
109
-
110
- const indicator = h("span", { class: "nav-indicator" });
111
- const navButtons = new Map();
112
- for (const item of NAV) {
113
- navButtons.set(
114
- item.screen,
115
- h(
116
- "button",
117
- { class: "nav-button", type: "button", "data-screen": item.screen, "aria-label": item.label, onclick: () => navigate(item.screen) },
118
- icon(item.icon),
119
- h("span", { class: "count", hidden: true }),
120
- h("span", { class: "tip", "aria-hidden": "true" }, item.label),
121
- ),
122
- );
123
- }
124
- const brand = h("button", { class: "brand", type: "button", "aria-label": "Home", onclick: () => navigate("home") }, icon(MARK));
125
- const sidebarPick = h(
126
- "button",
127
- { class: "nav-button", type: "button", "aria-label": "Pick a component", "aria-pressed": "false", onclick: () => startPicking() },
128
- icon(ICONS.pick),
129
- h("span", { class: "tip", "aria-hidden": "true" }, "Pick a component"),
130
- );
131
- const sidebar = h(
132
- "nav",
133
- { class: "sidebar", "aria-label": "DevTools" },
134
- brand,
135
- h("div", { class: "nav" }, indicator, [...navButtons.values()]),
136
- h("div", { class: "sidebar-end" }, sidebarPick),
137
- );
138
- const crumbs = h("div", { class: "crumbs" });
139
- const statusSlot = h("span", {});
140
- const closeButton = h("button", { class: "icon-button close", type: "button", "aria-label": "Close", title: "Close (Shift+Alt+A)", onclick: () => setOpen(false) }, icon(ICONS.close));
141
- const view = h("div", { class: "view" });
142
- const panel = h(
143
- "section",
144
- { class: "panel", role: "dialog", "aria-label": "Astralis DevTools", "data-open": "false", inert: true },
145
- sidebar,
146
- h("div", { class: "main" }, h("header", { class: "topbar" }, crumbs, statusSlot, closeButton), view),
147
- );
148
-
149
- const launcher = createLauncher({
150
- onToggle: () => setOpen(!state.open),
151
- onPick: () => (picker.picking ? picker.stop() : startPicking()),
152
- onMove: () => state.open && placePanel(),
153
- });
154
-
155
- const picker = createPicker({
156
- host,
157
- shadow,
158
- onPicked: (element) => {
159
- state.selected = element;
160
- const back = pickReturn;
161
- pickReturn = null;
162
- navigate(back ?? "component", { open: true });
163
- },
164
- onChange: (picking) => {
165
- // The panel steps aside while picking, so the whole page can be pointed at.
166
- showPanel(state.open && !picking);
167
- launcher.setPicking(picking);
168
- sidebarPick.setAttribute("aria-pressed", String(picking));
169
- },
170
- });
171
- let pickReturn = null; // the screen to go back to after a pick, set by every start
172
-
173
- shadow.append(panel, launcher.element);
174
- document.body.append(host);
175
- launcher.layout();
176
-
177
- /* ---- what the screens can do ---------------------------------------------------- */
178
-
179
- const consoleErrors = recordConsoleErrors(window);
180
- cleanups.push(() => consoleErrors.stop());
181
-
182
- const app = {
183
- state,
184
- base,
185
- framework,
186
- host,
187
- consoleErrors,
188
- navigate: (screen) => navigate(screen),
189
- openComponent(element) {
190
- state.selected = element;
191
- navigate("component", { open: true });
192
- },
193
- startPicking: (returnTo) => startPicking(returnTo),
194
- /** Outline an element on the page while the reader points at its row; null restores the default. */
195
- preview: (element) => picker.show(element ?? defaultOutline()),
196
- locate: (element) => picker.locate(element),
197
- /** The instance on the page a finding is most likely about, if the page has one. */
198
- instanceFor(finding) {
199
- const same = state.instances.filter((i) => i.chain.some((c) => c.name === finding.component));
200
- const exact = same.find((i) => {
201
- const props = i.chain.find((c) => c.name === finding.component)?.props ?? {};
202
- return finding.prop !== undefined && finding.prop in props && String(props[finding.prop]) === String(finding.value);
203
- });
204
- return exact ?? same[0] ?? null;
205
- },
206
- github: {
207
- reload: () => loadGitHub(),
208
- signIn: () => postGitHub("github/sign-in"),
209
- signOut: () => postGitHub("github/sign-out"),
210
- loadIssues: () => loadIssues(),
211
- },
212
- statusPill() {
213
- const label = { live: "Validator live", connecting: "Connecting…", unreachable: "Bridge offline" }[state.bridge];
214
- return h("span", { class: `status ${state.bridge}`, title: `DevTools bridge at ${base}` }, h("i"), label);
215
- },
216
- };
217
-
218
- /* ---- screens -------------------------------------------------------------------- */
219
-
220
- let current = null; // { screen, title, root, update, dispose?, element? }
221
-
222
- function build(screen) {
223
- switch (screen) {
224
- case "components":
225
- return componentsScreen(app);
226
- case "findings":
227
- case "recommendations":
228
- return findingsScreen(app, screen);
229
- case "report":
230
- return reportScreen(app);
231
- case "component":
232
- return state.selected ? componentScreen(app, state.selected) : componentsScreen(app);
233
- default:
234
- return homeScreen(app);
235
- }
236
- }
237
-
238
- function navigate(screen, { open = false } = {}) {
239
- if (screen === "component" && !state.selected) screen = "components";
240
- current?.dispose?.();
241
- state.screen = screen;
242
- current = { screen, ...build(screen) };
243
- view.replaceChildren(current.root);
244
- view.scrollTop = 0;
245
- animate(current.root, [{ opacity: 0, transform: "translateY(6px)" }, { opacity: 1, transform: "none" }], { duration: 240, easing: "cubic-bezier(0.22, 1, 0.36, 1)" });
246
- renderFrame();
247
- remember();
248
- if (open && !state.open) setOpen(true);
249
- picker.show(defaultOutline());
250
- if (state.open) current.focus?.();
251
- }
252
-
253
- /** The selection stays outlined while its page is open. */
254
- const defaultOutline = () => (state.open && current?.screen === "component" ? current.element : null);
255
-
256
- function renderFrame() {
257
- const active = state.screen === "component" ? "components" : state.screen;
258
- const index = NAV.findIndex((n) => n.screen === active);
259
- for (const [screen, button] of navButtons) {
260
- if (screen === active) button.setAttribute("aria-current", "page");
261
- else button.removeAttribute("aria-current");
262
- }
263
- indicator.style.transform = `translateY(${index * 44}px)`;
264
-
265
- const findings = state.findings && !state.findings.problem ? state.findings : null;
266
- const errors = findings?.errors ?? 0;
267
- const warnings = findings?.warnings ?? 0;
268
- const setCount = (screen, n, tone) => {
269
- const badge = navButtons.get(screen).querySelector(".count");
270
- badge.hidden = n === 0;
271
- badge.className = `count ${tone}`;
272
- badge.textContent = n > 99 ? "99+" : String(n);
273
- };
274
- setCount("findings", errors, "");
275
- setCount("recommendations", warnings, "advice");
276
- launcher.setCounts({ errors, warnings });
277
-
278
- crumbs.replaceChildren(
279
- ...(current?.title ?? []).flatMap((part, i, all) => {
280
- const last = i === all.length - 1;
281
- const node = last
282
- ? h("span", { class: `crumb-current${part.code ? " code" : ""}` }, part.label)
283
- : h("button", { class: "crumb-link", type: "button", onclick: () => navigate(part.screen) }, part.label);
284
- return last ? [node] : [node, icon(ICONS.chevron)];
285
- }),
286
- );
287
- statusSlot.replaceChildren(app.statusPill());
288
- }
289
-
290
- /** Data changed: redraw the frame and let the screen bring itself up to date. */
291
- function refresh(reason) {
292
- renderFrame();
293
- current?.update(reason);
294
- }
295
-
296
- function remember() {
297
- store.write("sessionStorage", "panel", { open: state.open, screen: state.screen === "component" ? "components" : state.screen });
298
- }
299
-
300
- /* ---- opening, and where the panel sits ------------------------------------------ */
301
-
302
- /** Above or below the launcher, centred on it near the middle, else on the side with room; always on screen. */
303
- function placePanel() {
304
- const anchor = launcher.rect();
305
- const width = panel.offsetWidth || Math.min(640, window.innerWidth - 24);
306
- const height = panel.offsetHeight || Math.min(560, window.innerHeight - 24);
307
- const centre = anchor.left + anchor.width / 2;
308
- const middle = Math.abs(centre - window.innerWidth / 2) < window.innerWidth * 0.15;
309
- const right = centre > window.innerWidth / 2;
310
- const below = anchor.top + anchor.height / 2 < window.innerHeight / 2;
311
- let x = middle ? centre - width / 2 : right ? anchor.right - width : anchor.left;
312
- let y = below ? anchor.bottom + PANEL_GAP : anchor.top - PANEL_GAP - height;
313
- x = Math.min(window.innerWidth - width - EDGE, Math.max(EDGE, x));
314
- y = Math.min(window.innerHeight - height - EDGE, Math.max(EDGE, y));
315
- panel.style.left = `${Math.round(x)}px`;
316
- panel.style.top = `${Math.round(y)}px`;
317
- panel.style.transformOrigin = `${middle ? "center" : right ? "right" : "left"} ${below ? "top" : "bottom"}`;
318
- }
319
-
320
- function showPanel(visible) {
321
- panel.dataset.open = String(visible);
322
- panel.toggleAttribute("inert", !visible);
323
- }
324
-
325
- function setOpen(open) {
326
- state.open = open;
327
- if (open) placePanel();
328
- showPanel(open && !picker.picking);
329
- launcher.setOpen(open);
330
- picker.show(defaultOutline());
331
- remember();
332
- if (open) current?.focus?.();
333
- }
334
-
335
- function startPicking(returnTo = null) {
336
- pickReturn = returnTo;
337
- picker.start();
338
- }
339
-
340
- /* ---- keyboard ---------------------------------------------------------------------- */
341
-
342
- function onKey(event) {
343
- if (event.shiftKey && event.altKey && !event.ctrlKey && !event.metaKey) {
344
- if (event.code === SHORTCUTS.open) {
345
- event.preventDefault();
346
- if (picker.picking) picker.stop();
347
- if (state.open) setOpen(false);
348
- else {
349
- if (state.screen !== "home") navigate("home");
350
- setOpen(true);
351
- }
352
- return;
353
- }
354
- if (event.code === SHORTCUTS.pick) {
355
- event.preventDefault();
356
- if (picker.picking) picker.stop();
357
- else startPicking();
358
- return;
359
- }
360
- }
361
- if (event.key === "Escape") {
362
- if (picker.picking) {
363
- event.preventDefault();
364
- picker.stop();
365
- } else if (state.open && event.composedPath?.().includes(host)) {
366
- event.preventDefault();
367
- setOpen(false);
368
- }
369
- }
370
- }
371
- listen(document, "keydown", onKey, true);
372
-
373
- /* ---- the page --------------------------------------------------------------------- */
374
-
375
- let scanTimer = null;
376
- function scan() {
377
- state.instances = scanPage(document, host);
378
- refresh("page");
379
- }
380
- const scheduleScan = () => {
381
- clearTimeout(scanTimer);
382
- scanTimer = setTimeout(scan, SCAN_DEBOUNCE_MS);
383
- };
384
- if (typeof MutationObserver !== "undefined") {
385
- const observer = new MutationObserver((records) => {
386
- if (records.every((r) => r.target === host || host.contains(r.target))) return;
387
- scheduleScan();
388
- });
389
- observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["data-astralis", "data-astralis-props"] });
390
- cleanups.push(() => observer.disconnect());
391
- }
392
- cleanups.push(() => clearTimeout(scanTimer));
393
-
394
- listen(window, "scroll", () => picker.refresh(), true);
395
- listen(window, "resize", () => {
396
- launcher.layout();
397
- if (state.open) placePanel();
398
- picker.refresh();
399
- });
400
- cleanups.push(() => picker.stop());
401
-
402
- /* ---- the bridge ------------------------------------------------------------------ */
403
-
404
- const getJson = (path) => fetch(`${base}/${path}`, { cache: "no-store" }).then((response) => (response.ok ? response.json() : null));
405
-
406
- getJson("spec")
407
- .then((spec) => {
408
- if (spec?.components) {
409
- state.spec = spec;
410
- refresh("spec");
411
- }
412
- })
413
- .catch(() => {});
414
- getJson("info")
415
- .then((info) => {
416
- if (info && !info.problem) {
417
- state.info = info;
418
- refresh("info");
419
- }
420
- })
421
- .catch(() => {});
422
-
423
- if (typeof EventSource !== "undefined") {
424
- const events = new EventSource(`${base}/events`);
425
- events.addEventListener("findings", (event) => {
426
- try {
427
- state.findings = JSON.parse(event.data);
428
- state.bridge = "live";
429
- refresh("findings");
430
- } catch {
431
- // a malformed event changes nothing
432
- }
433
- });
434
- events.addEventListener("error", () => {
435
- state.bridge = "unreachable";
436
- refresh("bridge");
437
- });
438
- cleanups.push(() => events.close());
439
- }
440
-
441
- /* ---- GitHub -------------------------------------------------------------------------- */
442
-
443
- let signInPoll = null;
444
- cleanups.push(() => clearTimeout(signInPoll));
445
-
446
- function setGitHub(status) {
447
- const before = state.github?.login ?? null;
448
- state.github = status;
449
- if (status.login !== before) {
450
- state.issues = { list: null, loading: false, error: null };
451
- if (status.login) loadIssues();
452
- }
453
- clearTimeout(signInPoll);
454
- if (status.pending) signInPoll = setTimeout(loadGitHub, SIGN_IN_POLL_MS);
455
- refresh("github");
456
- }
457
-
458
- function loadGitHub() {
459
- return getJson("github")
460
- .then((status) => status && setGitHub(status))
461
- .catch(() => {});
462
- }
463
-
464
- async function postGitHub(path) {
465
- try {
466
- const response = await fetch(`${base}/${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
467
- const result = await response.json();
468
- if (!response.ok) throw new Error(result?.error ?? `The bridge answered ${response.status}.`);
469
- setGitHub(result);
470
- } catch (error) {
471
- setGitHub({ ...(state.github ?? { configured: true, repo: null, login: null, pending: null }), error: error.message });
472
- }
473
- }
474
-
475
- async function loadIssues() {
476
- state.issues = { ...state.issues, loading: true, error: null };
477
- refresh("github");
478
- try {
479
- const response = await fetch(`${base}/github/issues`, { cache: "no-store" });
480
- const result = await response.json();
481
- if (response.status === 401) return loadGitHub();
482
- if (!response.ok) throw new Error(result?.error ?? `The bridge answered ${response.status}.`);
483
- state.issues = { list: result.issues, loading: false, error: null };
484
- } catch (error) {
485
- state.issues = { ...state.issues, loading: false, error: error.message };
486
- }
487
- refresh("github");
488
- }
489
-
490
- loadGitHub();
491
-
492
- function loadRouteFiles() {
493
- if (framework !== "next") return;
494
- getJson(`route-files?path=${encodeURIComponent(state.route)}`)
495
- .then((result) => {
496
- if (result?.path === state.route) {
497
- state.routeFiles = result.files ?? [];
498
- refresh("route");
499
- }
500
- })
501
- .catch(() => {});
502
- }
503
- loadRouteFiles();
504
- // Client-side navigation changes the URL without an event to hook reliably.
505
- const routePoll = setInterval(() => {
506
- if (location.pathname !== state.route) {
507
- state.route = location.pathname;
508
- state.routeFiles = [];
509
- loadRouteFiles();
510
- scan();
511
- }
512
- }, ROUTE_POLL_MS);
513
- cleanups.push(() => clearInterval(routePoll));
514
-
515
- state.instances = scanPage(document, host);
516
- navigate(state.screen);
517
- if (remembered.open) setOpen(true);
518
-
519
- return () => {
520
- current?.dispose?.();
521
- for (const cleanup of cleanups.splice(0)) cleanup();
522
- host.remove();
523
- if (ownFonts) fonts.remove();
524
- };
525
- }
1
+ import { animate, h, icon, store } from "./dom.mjs";
2
+ import { FONT_FACES } from "./fonts.mjs";
3
+ import { ICONS, MARK } from "./icons.mjs";
4
+ import { createLauncher } from "./launcher.mjs";
5
+ import { isOnPage, scanPage } from "./page.mjs";
6
+ import { createPicker } from "./picker.mjs";
7
+ import { recordConsoleErrors } from "./report.mjs";
8
+ import { componentScreen } from "./screens/component.mjs";
9
+ import { componentsScreen } from "./screens/components.mjs";
10
+ import { findingsScreen } from "./screens/findings.mjs";
11
+ import { homeScreen } from "./screens/home.mjs";
12
+ import { emptyReport, reportScreen } from "./screens/report.mjs";
13
+ import { STYLES } from "./styles.mjs";
14
+
15
+ /* The Astralis DevTools overlay: a launcher that can sit anywhere on the
16
+ page in development, and a panel with five screens.
17
+
18
+ Home what is on this page, at a glance
19
+ Components every astralis-ui component on the page; each opens a
20
+ page of its own with its props, how it reaches the
21
+ browser, and the findings about it
22
+ Findings the validator's errors, live: what renders wrong
23
+ Recommendations the validator's warnings: what works but could be better
24
+ Report a problem opened as a GitHub issue from the reporter's own
25
+ account, shown in full before anything is sent, and the
26
+ issues they have opened so far
27
+
28
+ Shift+Alt+A, the launcher's mark and the panel's minimize button fold it
29
+ down to the launcher and bring it back where it was; Escape folds it from
30
+ inside. A new page, loaded or navigated to, starts with it folded; which
31
+ screen it was on, and a report not yet sent, last the browser tab's session,
32
+ and where the launcher sits lasts across sessions. Shift+Alt+C picks a
33
+ component on the page and opens its page. Plain DOM in a shadow root, so it
34
+ needs no framework and the page's CSS cannot reach it. Everything from the page or the bridge goes
35
+ in as text. */
36
+
37
+ const HOST_TAG = "astralis-devtools";
38
+ const FONTS_ID = "astralis-devtools-fonts";
39
+ const ROUTE_POLL_MS = 1000;
40
+ const SCAN_DEBOUNCE_MS = 200;
41
+ const PANEL_GAP = 10;
42
+ /** How often a waiting sign-in is checked. The bridge polls GitHub; this asks the bridge. */
43
+ const SIGN_IN_POLL_MS = 2000;
44
+ /** GitHub's list can lag a moment behind a new issue, so it is read again after a send. */
45
+ const ISSUES_RETRY_MS = 3000;
46
+ const EDGE = 12;
47
+
48
+ const NAV = [
49
+ { screen: "home", label: "Home", icon: ICONS.home },
50
+ { screen: "components", label: "Components", icon: ICONS.components },
51
+ { screen: "findings", label: "Findings", icon: ICONS.findings },
52
+ { screen: "recommendations", label: "Recommendations", icon: ICONS.recommendations },
53
+ { screen: "report", label: "Report", icon: ICONS.report },
54
+ ];
55
+
56
+ const SHORTCUTS = { open: "KeyA", pick: "KeyC" };
57
+
58
+ /** The page a panel was open on when it was unmounted. A hot reload can remount the overlay
59
+ without a page load, and must not close it; a page load starts with a new window. */
60
+ const openWhenUnmounted = new WeakMap();
61
+
62
+ /** A report written on an earlier page in this tab and not sent. Only its words: what to include is asked afresh. */
63
+ function readDraft() {
64
+ const draft = store.read("sessionStorage", "draft") ?? {};
65
+ return Object.fromEntries(["title", "happened", "expected"].filter((key) => typeof draft[key] === "string").map((key) => [key, draft[key]]));
66
+ }
67
+
68
+ /**
69
+ * Mount the overlay on this page. Returns a function that removes it and
70
+ * everything it listens to. Mounting twice is a no-op.
71
+ */
72
+ export function mountOverlay({ base = "/api/astralis-devtools", framework = null } = {}) {
73
+ if (typeof document === "undefined" || document.querySelector(HOST_TAG)) return () => {};
74
+
75
+ const host = document.createElement(HOST_TAG);
76
+ const shadow = host.attachShadow({ mode: "open" });
77
+ shadow.append(h("style", {}, STYLES));
78
+
79
+ // @font-face is ignored inside a shadow root, so the faces go on the document, under names no page uses.
80
+ let fonts = document.getElementById(FONTS_ID);
81
+ const ownFonts = !fonts;
82
+ if (ownFonts) {
83
+ fonts = h("style", { id: FONTS_ID }, FONT_FACES);
84
+ document.head.append(fonts);
85
+ }
86
+
87
+ const remembered = store.read("sessionStorage", "panel") ?? {};
88
+ const remountedOpen = openWhenUnmounted.get(window) === location.pathname;
89
+ openWhenUnmounted.delete(window);
90
+ const state = {
91
+ open: false,
92
+ screen: NAV.some((n) => n.screen === remembered.screen) ? remembered.screen : "home",
93
+ selected: null,
94
+ spec: null,
95
+ info: null,
96
+ findings: null,
97
+ bridge: "connecting", // connecting | live | unreachable
98
+ route: location.pathname,
99
+ routeFiles: [],
100
+ instances: [],
101
+ github: null, // the bridge's GitHub status: { configured, repo, login, pending, error }
102
+ issues: { list: null, loading: false, error: null },
103
+ created: [], // issues just opened that GitHub's list does not have yet
104
+ sent: null, // the last report sent, { number, url, added }, until its confirmation has been seen
105
+ reportTab: "new",
106
+ report: { ...emptyReport(), ...readDraft() },
107
+ };
108
+
109
+ const cleanups = [];
110
+ const listen = (target, type, handler, options) => {
111
+ target.addEventListener(type, handler, options);
112
+ cleanups.push(() => target.removeEventListener(type, handler, options));
113
+ };
114
+
115
+ /* ---- the panel's frame ------------------------------------------------------ */
116
+
117
+ const indicator = h("span", { class: "nav-indicator" });
118
+ const navButtons = new Map();
119
+ for (const item of NAV) {
120
+ navButtons.set(
121
+ item.screen,
122
+ h(
123
+ "button",
124
+ { class: "nav-button", type: "button", "data-screen": item.screen, "aria-label": item.label, onclick: () => navigate(item.screen) },
125
+ icon(item.icon),
126
+ h("span", { class: "count", hidden: true }),
127
+ h("span", { class: "tip", "aria-hidden": "true" }, item.label),
128
+ ),
129
+ );
130
+ }
131
+ const brand = h("button", { class: "brand", type: "button", "aria-label": "Home", onclick: () => navigate("home") }, icon(MARK));
132
+ const sidebarPick = h(
133
+ "button",
134
+ { class: "nav-button", type: "button", "aria-label": "Pick a component", "aria-pressed": "false", onclick: () => startPicking() },
135
+ icon(ICONS.pick),
136
+ h("span", { class: "tip", "aria-hidden": "true" }, "Pick a component"),
137
+ );
138
+ const sidebar = h(
139
+ "nav",
140
+ { class: "sidebar", "aria-label": "DevTools" },
141
+ brand,
142
+ h("div", { class: "nav" }, indicator, [...navButtons.values()]),
143
+ h("div", { class: "sidebar-end" }, sidebarPick),
144
+ );
145
+ const crumbs = h("div", { class: "crumbs" });
146
+ const statusSlot = h("span", {});
147
+ const minimizeButton = h(
148
+ "button",
149
+ { class: "icon-button minimize", type: "button", "aria-label": "Minimize to the launcher", title: "Minimize (Shift+Alt+A or Esc)", onclick: () => setOpen(false) },
150
+ icon(ICONS.minimize),
151
+ );
152
+ const view = h("div", { class: "view" });
153
+ const panel = h(
154
+ "section",
155
+ { class: "panel", role: "dialog", "aria-label": "Astralis DevTools", "data-open": "false", inert: true },
156
+ sidebar,
157
+ h("div", { class: "main" }, h("header", { class: "topbar" }, crumbs, statusSlot, minimizeButton), view),
158
+ );
159
+
160
+ const launcher = createLauncher({
161
+ onToggle: () => setOpen(!state.open),
162
+ onPick: () => (picker.picking ? picker.stop() : startPicking()),
163
+ onMove: () => state.open && placePanel(),
164
+ });
165
+
166
+ const picker = createPicker({
167
+ host,
168
+ shadow,
169
+ onPicked: (element) => {
170
+ state.selected = element;
171
+ const back = pickReturn;
172
+ pickReturn = null;
173
+ navigate(back ?? "component", { open: true });
174
+ },
175
+ onChange: (picking) => {
176
+ // The panel steps aside while picking, so the whole page can be pointed at.
177
+ showPanel(state.open && !picking);
178
+ launcher.setPicking(picking);
179
+ sidebarPick.setAttribute("aria-pressed", String(picking));
180
+ },
181
+ });
182
+ let pickReturn = null; // the screen to go back to after a pick, set by every start
183
+
184
+ shadow.append(panel, launcher.element);
185
+ document.body.append(host);
186
+ launcher.layout();
187
+
188
+ /* ---- what the screens can do ---------------------------------------------------- */
189
+
190
+ const consoleErrors = recordConsoleErrors(window);
191
+ cleanups.push(() => consoleErrors.stop());
192
+
193
+ const app = {
194
+ state,
195
+ base,
196
+ framework,
197
+ host,
198
+ consoleErrors,
199
+ navigate: (screen) => navigate(screen),
200
+ openComponent(element) {
201
+ state.selected = element;
202
+ navigate("component", { open: true });
203
+ },
204
+ startPicking: (returnTo) => startPicking(returnTo),
205
+ /** Keep the report form's words for the next page in this tab. */
206
+ keepDraft: ({ title, happened, expected }) => store.write("sessionStorage", "draft", { title, happened, expected }),
207
+ /** A send ended, perhaps on a form that has since been rebuilt: the one on screen must show it. */
208
+ reportChanged: () => refresh("report"),
209
+ /** A report reached GitHub: show it among the reporter's issues. */
210
+ reportSent(sent, title) {
211
+ state.sent = sent;
212
+ if (!sent.added) {
213
+ const now = new Date().toISOString();
214
+ state.created.unshift({ number: sent.number, title, state: "open", stateReason: null, url: sent.url, comments: 0, labels: [], createdAt: now, updatedAt: now });
215
+ if (state.issues.list) state.issues.list = withCreated(state.issues.list);
216
+ }
217
+ state.reportTab = "issues";
218
+ store.write("sessionStorage", "draft", null);
219
+ loadIssues();
220
+ clearTimeout(issuesRetry);
221
+ issuesRetry = setTimeout(loadIssues, ISSUES_RETRY_MS);
222
+ refresh("sent");
223
+ },
224
+ /** Outline an element on the page while the reader points at its row; null restores the default. */
225
+ preview: (element) => picker.show(element ?? defaultOutline()),
226
+ locate: (element) => picker.locate(element),
227
+ /** The instance on the page a finding is most likely about, if the page has one. */
228
+ instanceFor(finding) {
229
+ const same = state.instances.filter((i) => i.chain.some((c) => c.name === finding.component));
230
+ const exact = same.find((i) => {
231
+ const props = i.chain.find((c) => c.name === finding.component)?.props ?? {};
232
+ return finding.prop !== undefined && finding.prop in props && String(props[finding.prop]) === String(finding.value);
233
+ });
234
+ return exact ?? same[0] ?? null;
235
+ },
236
+ github: {
237
+ reload: () => loadGitHub(),
238
+ signIn: () => postGitHub("github/sign-in"),
239
+ signOut: () => postGitHub("github/sign-out"),
240
+ loadIssues: () => loadIssues(),
241
+ },
242
+ statusPill() {
243
+ const label = { live: "Validator live", connecting: "Connecting…", unreachable: "Bridge offline" }[state.bridge];
244
+ return h("span", { class: `status ${state.bridge}`, title: `DevTools bridge at ${base}` }, h("i"), label);
245
+ },
246
+ };
247
+
248
+ /* ---- screens -------------------------------------------------------------------- */
249
+
250
+ let current = null; // { screen, title, root, update, dispose?, element? }
251
+
252
+ function build(screen) {
253
+ switch (screen) {
254
+ case "components":
255
+ return componentsScreen(app);
256
+ case "findings":
257
+ case "recommendations":
258
+ return findingsScreen(app, screen);
259
+ case "report":
260
+ return reportScreen(app);
261
+ case "component":
262
+ return state.selected ? componentScreen(app, state.selected) : componentsScreen(app);
263
+ default:
264
+ return homeScreen(app);
265
+ }
266
+ }
267
+
268
+ function navigate(screen, { open = false } = {}) {
269
+ if (screen === "component" && !state.selected) screen = "components";
270
+ current?.dispose?.();
271
+ state.screen = screen;
272
+ current = { screen, ...build(screen) };
273
+ view.replaceChildren(current.root);
274
+ view.scrollTop = 0;
275
+ animate(current.root, [{ opacity: 0, transform: "translateY(6px)" }, { opacity: 1, transform: "none" }], { duration: 240, easing: "cubic-bezier(0.22, 1, 0.36, 1)" });
276
+ renderFrame();
277
+ remember();
278
+ if (open && !state.open) setOpen(true);
279
+ picker.show(defaultOutline());
280
+ if (state.open) current.focus?.();
281
+ }
282
+
283
+ /** The selection stays outlined while its page is open. */
284
+ const defaultOutline = () => (state.open && current?.screen === "component" ? current.element : null);
285
+
286
+ function renderFrame() {
287
+ const active = state.screen === "component" ? "components" : state.screen;
288
+ const index = NAV.findIndex((n) => n.screen === active);
289
+ for (const [screen, button] of navButtons) {
290
+ if (screen === active) button.setAttribute("aria-current", "page");
291
+ else button.removeAttribute("aria-current");
292
+ }
293
+ indicator.style.transform = `translateY(${index * 44}px)`;
294
+
295
+ const findings = state.findings && !state.findings.problem ? state.findings : null;
296
+ const errors = findings?.errors ?? 0;
297
+ const warnings = findings?.warnings ?? 0;
298
+ const setCount = (screen, n, tone) => {
299
+ const badge = navButtons.get(screen).querySelector(".count");
300
+ badge.hidden = n === 0;
301
+ badge.className = `count ${tone}`;
302
+ badge.textContent = n > 99 ? "99+" : String(n);
303
+ };
304
+ setCount("findings", errors, "");
305
+ setCount("recommendations", warnings, "advice");
306
+ launcher.setCounts({ errors, warnings });
307
+
308
+ crumbs.replaceChildren(
309
+ ...(current?.title ?? []).flatMap((part, i, all) => {
310
+ const last = i === all.length - 1;
311
+ const node = last
312
+ ? h("span", { class: `crumb-current${part.code ? " code" : ""}` }, part.label)
313
+ : h("button", { class: "crumb-link", type: "button", onclick: () => navigate(part.screen) }, part.label);
314
+ return last ? [node] : [node, icon(ICONS.chevron)];
315
+ }),
316
+ );
317
+ statusSlot.replaceChildren(app.statusPill());
318
+ }
319
+
320
+ /** Data changed: redraw the frame and let the screen bring itself up to date. */
321
+ function refresh(reason) {
322
+ renderFrame();
323
+ current?.update(reason);
324
+ }
325
+
326
+ function remember() {
327
+ store.write("sessionStorage", "panel", { screen: state.screen === "component" ? "components" : state.screen });
328
+ }
329
+
330
+ /* ---- opening, and where the panel sits ------------------------------------------ */
331
+
332
+ /** Above or below the launcher, centred on it near the middle, else on the side with room; always on screen. */
333
+ function placePanel() {
334
+ const anchor = launcher.rect();
335
+ const width = panel.offsetWidth || Math.min(640, window.innerWidth - 24);
336
+ const height = panel.offsetHeight || Math.min(560, window.innerHeight - 24);
337
+ const centre = anchor.left + anchor.width / 2;
338
+ const middle = Math.abs(centre - window.innerWidth / 2) < window.innerWidth * 0.15;
339
+ const right = centre > window.innerWidth / 2;
340
+ const below = anchor.top + anchor.height / 2 < window.innerHeight / 2;
341
+ let x = middle ? centre - width / 2 : right ? anchor.right - width : anchor.left;
342
+ let y = below ? anchor.bottom + PANEL_GAP : anchor.top - PANEL_GAP - height;
343
+ x = Math.min(window.innerWidth - width - EDGE, Math.max(EDGE, x));
344
+ y = Math.min(window.innerHeight - height - EDGE, Math.max(EDGE, y));
345
+ panel.style.left = `${Math.round(x)}px`;
346
+ panel.style.top = `${Math.round(y)}px`;
347
+ panel.style.transformOrigin = `${middle ? "center" : right ? "right" : "left"} ${below ? "top" : "bottom"}`;
348
+ }
349
+
350
+ function showPanel(visible) {
351
+ panel.dataset.open = String(visible);
352
+ panel.toggleAttribute("inert", !visible);
353
+ }
354
+
355
+ function setOpen(open) {
356
+ // Focus left inside a panel going inert would fall to the page; the launcher brings it back.
357
+ if (!open && panel.contains(shadow.activeElement)) launcher.focus();
358
+ if (open && state.selected && !isOnPage(state.selected)) {
359
+ // Picked on a page that is gone, or rendered away while the panel was folded.
360
+ state.selected = null;
361
+ if (state.screen === "component" || state.screen === "report") navigate(state.screen);
362
+ }
363
+ state.open = open;
364
+ if (open) placePanel();
365
+ showPanel(open && !picker.picking);
366
+ launcher.setOpen(open);
367
+ picker.show(defaultOutline());
368
+ remember();
369
+ if (open) current?.focus?.();
370
+ }
371
+
372
+ function minimize() {
373
+ pickReturn = null;
374
+ picker.stop();
375
+ if (state.open) setOpen(false);
376
+ }
377
+
378
+ function startPicking(returnTo = null) {
379
+ pickReturn = returnTo;
380
+ picker.start();
381
+ }
382
+
383
+ /* ---- keyboard ---------------------------------------------------------------------- */
384
+
385
+ function onKey(event) {
386
+ if (event.shiftKey && event.altKey && !event.ctrlKey && !event.metaKey) {
387
+ if (event.code === SHORTCUTS.open) {
388
+ event.preventDefault();
389
+ if (picker.picking) picker.stop();
390
+ setOpen(!state.open);
391
+ return;
392
+ }
393
+ if (event.code === SHORTCUTS.pick) {
394
+ event.preventDefault();
395
+ if (picker.picking) picker.stop();
396
+ else startPicking();
397
+ return;
398
+ }
399
+ }
400
+ if (event.key === "Escape") {
401
+ if (picker.picking) {
402
+ event.preventDefault();
403
+ picker.stop();
404
+ } else if (state.open && event.composedPath?.().includes(host)) {
405
+ event.preventDefault();
406
+ setOpen(false);
407
+ }
408
+ }
409
+ }
410
+ listen(document, "keydown", onKey, true);
411
+
412
+ /* ---- the page --------------------------------------------------------------------- */
413
+
414
+ let scanTimer = null;
415
+ function scan() {
416
+ state.instances = scanPage(document, host);
417
+ refresh("page");
418
+ }
419
+ const scheduleScan = () => {
420
+ clearTimeout(scanTimer);
421
+ scanTimer = setTimeout(scan, SCAN_DEBOUNCE_MS);
422
+ };
423
+ if (typeof MutationObserver !== "undefined") {
424
+ const observer = new MutationObserver((records) => {
425
+ if (records.every((r) => r.target === host || host.contains(r.target))) return;
426
+ scheduleScan();
427
+ });
428
+ observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["data-astralis", "data-astralis-props"] });
429
+ cleanups.push(() => observer.disconnect());
430
+ }
431
+ cleanups.push(() => clearTimeout(scanTimer));
432
+
433
+ listen(window, "scroll", () => picker.refresh(), true);
434
+ listen(window, "resize", () => {
435
+ launcher.layout();
436
+ if (state.open) placePanel();
437
+ picker.refresh();
438
+ });
439
+ cleanups.push(() => picker.stop());
440
+
441
+ /* ---- the bridge ------------------------------------------------------------------ */
442
+
443
+ const getJson = (path) => fetch(`${base}/${path}`, { cache: "no-store" }).then((response) => (response.ok ? response.json() : null));
444
+
445
+ getJson("spec")
446
+ .then((spec) => {
447
+ if (spec?.components) {
448
+ state.spec = spec;
449
+ refresh("spec");
450
+ }
451
+ })
452
+ .catch(() => {});
453
+ getJson("info")
454
+ .then((info) => {
455
+ if (info && !info.problem) {
456
+ state.info = info;
457
+ refresh("info");
458
+ }
459
+ })
460
+ .catch(() => {});
461
+
462
+ if (typeof EventSource !== "undefined") {
463
+ const events = new EventSource(`${base}/events`);
464
+ events.addEventListener("findings", (event) => {
465
+ try {
466
+ state.findings = JSON.parse(event.data);
467
+ state.bridge = "live";
468
+ refresh("findings");
469
+ } catch {
470
+ // a malformed event changes nothing
471
+ }
472
+ });
473
+ events.addEventListener("error", () => {
474
+ state.bridge = "unreachable";
475
+ refresh("bridge");
476
+ });
477
+ cleanups.push(() => events.close());
478
+ }
479
+
480
+ /* ---- GitHub -------------------------------------------------------------------------- */
481
+
482
+ let signInPoll = null;
483
+ let issuesRetry = null;
484
+ cleanups.push(() => {
485
+ clearTimeout(signInPoll);
486
+ clearTimeout(issuesRetry);
487
+ });
488
+
489
+ /** GitHub's list, with the issues it does not show yet first. */
490
+ function withCreated(list) {
491
+ state.created = state.created.filter((issue) => !list.some((known) => known.number === issue.number));
492
+ return [...state.created, ...list];
493
+ }
494
+
495
+ function setGitHub(status) {
496
+ const before = state.github?.login ?? null;
497
+ state.github = status;
498
+ if (status.login !== before) {
499
+ state.issues = { list: null, loading: false, error: null };
500
+ state.created = [];
501
+ state.sent = null;
502
+ clearTimeout(issuesRetry);
503
+ if (status.login) loadIssues();
504
+ }
505
+ clearTimeout(signInPoll);
506
+ if (status.pending) signInPoll = setTimeout(loadGitHub, SIGN_IN_POLL_MS);
507
+ refresh("github");
508
+ }
509
+
510
+ function loadGitHub() {
511
+ return getJson("github")
512
+ .then((status) => status && setGitHub(status))
513
+ .catch(() => {});
514
+ }
515
+
516
+ async function postGitHub(path) {
517
+ try {
518
+ const response = await fetch(`${base}/${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
519
+ const result = await response.json();
520
+ if (!response.ok) throw new Error(result?.error ?? `The bridge answered ${response.status}.`);
521
+ setGitHub(result);
522
+ } catch (error) {
523
+ setGitHub({ ...(state.github ?? { configured: true, repo: null, login: null, pending: null }), error: error.message });
524
+ }
525
+ }
526
+
527
+ async function loadIssues() {
528
+ state.issues = { ...state.issues, loading: true, error: null };
529
+ refresh("github");
530
+ try {
531
+ const response = await fetch(`${base}/github/issues`, { cache: "no-store" });
532
+ const result = await response.json();
533
+ if (response.status === 401) return loadGitHub();
534
+ if (!response.ok) throw new Error(result?.error ?? `The bridge answered ${response.status}.`);
535
+ state.issues = { list: withCreated(result.issues), loading: false, error: null };
536
+ } catch (error) {
537
+ state.issues = { ...state.issues, loading: false, error: error.message };
538
+ }
539
+ refresh("github");
540
+ }
541
+
542
+ loadGitHub();
543
+
544
+ function loadRouteFiles() {
545
+ if (framework !== "next") return;
546
+ getJson(`route-files?path=${encodeURIComponent(state.route)}`)
547
+ .then((result) => {
548
+ if (result?.path === state.route) {
549
+ state.routeFiles = result.files ?? [];
550
+ refresh("route");
551
+ }
552
+ })
553
+ .catch(() => {});
554
+ }
555
+ loadRouteFiles();
556
+ function followRoute() {
557
+ if (location.pathname === state.route) return; // a new query or hash is still this page
558
+ state.route = location.pathname;
559
+ state.routeFiles = [];
560
+ minimize();
561
+ loadRouteFiles();
562
+ scan();
563
+ }
564
+ // The Navigation API reports client-side navigation at once; without it, only polling sees a pushState.
565
+ if (window.navigation?.addEventListener) listen(window.navigation, "currententrychange", followRoute);
566
+ listen(window, "popstate", followRoute);
567
+ const routePoll = setInterval(followRoute, ROUTE_POLL_MS);
568
+ cleanups.push(() => clearInterval(routePoll));
569
+ // The browser can bring a page back, on Back, exactly as it was left.
570
+ listen(window, "pagehide", minimize);
571
+
572
+ state.instances = scanPage(document, host);
573
+ navigate(state.screen);
574
+ if (remountedOpen) setOpen(true);
575
+
576
+ return () => {
577
+ if (state.open) openWhenUnmounted.set(window, location.pathname);
578
+ current?.dispose?.();
579
+ for (const cleanup of cleanups.splice(0)) cleanup();
580
+ host.remove();
581
+ if (ownFonts) fonts.remove();
582
+ };
583
+ }