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