1/**
2 * the status of the last build, in the corner of a page that the `Debugger` of
3 * `incremental.ts`
4 * served: a clover, colored by how the build went, or the progress spinner
5 * during one. hovering it says how long ago that was, and clicking it opens
6 * what the build did and its errors. a build that takes a while opens them
7 * with its progress. the page reloads when a build changes what it was
8 * served, unless it has input or plays media, when the clover blinks
9 * instead. a build that left nothing to serve covers the page with its
10 * errors until they are dismissed or fixed.
11 *
12 * @module
13 */
14
15const socketUrl = new URL("/.clover/socket", import.meta.url);
16socketUrl.protocol = "ws:";
17
18const params = new URL(import.meta.url).searchParams;
19/** the hash of the page as it was served, unless asking again would not give it back */
20let shown = params.get("page");
21let status: incremental.BuildStatus | null = null;
22let connected = false;
23/** when the build in progress began */
24let building: number | null = null;
25/** when the latest build began, so what it has not reached is what it may not use */
26let began = 0;
27/** how many steps ran since, which are named as they flash only while they are few */
28let ran = 0;
29/** when a build opened the panel for its progress, which stays long enough to read */
30let showing: number | null = null;
31/** the build whose progress was closed, which does not open it again */
32let quiet: number | null = null;
33/** the debugger's own page, and a page asked for before a build was served, which show the graph */
34const home = location.pathname.replace(/\/+$/, "") === "/.clover" || params.has("graph");
35const savedKey = "clover-debugger";
36/** what the last page of this tab showed as it went away, which a hard navigation shows again */
37let saved = JSON.parse(sessionStorage.getItem(savedKey) ?? "null") as Saved | null;
38/** the panel stays open */
39let open = home || (saved?.open ?? false);
40let maximized = home || (saved?.maximized ?? false);
41/** how wide the panel is dragged to, in pixels */
42let width = saved?.width ?? null;
43let tab: (typeof tabs)[number] = home ? "graph" : saved?.tab ?? "status";
44/** a build changed this page, which still shows what it was */
45let stale = false;
46/** the page has input that a reload would lose */
47let edited = false;
48/** the failed build whose errors were dismissed */
49let dismissed: incremental.BuildStatus | null = null;
50/** the build whose problems are listed */
51let listed: incremental.BuildStatus | null = null;
52/** the problems start folded, as the last fold of every one of them left them */
53let folded = saved?.folded ?? false;
54let timer: ReturnType<typeof setTimeout> | undefined;
55let ticking: ReturnType<typeof setTimeout> | undefined;
56let retry = 100;
57
58const tabs = ["status", "problems", "meta", "graph"] as const;
59interface Saved {
60 /** what the debugger's own page shows is not carried to the page after it */
61 open?: boolean;
62 maximized?: boolean;
63 width?: number;
64 tab?: (typeof tabs)[number];
65 folded: boolean;
66 view: typeof view;
67 alpha: number;
68 points: Array<[id: string, kind: Kind, label: string, x: number, y: number, vx: number, vy: number]>;
69 /** indices into `points` */
70 links: Array<[source: number, target: number]>;
71}
72const titles = {
73 offline: "Reconnecting…",
74 building: "Building…",
75 ok: "Up to date",
76 warnings: "Built with warnings",
77 failed: "Build failed",
78};
79
80type Kind = "step" | "lazy" | "code" | "file" | "directory" | "sqlite" | "output";
81interface Point {
82 id: string;
83 kind: Kind;
84 label: string;
85 /** what its ambient label names: a step's function, a sqlite table, or a file's folder */
86 group: string;
87 /** what last happened to it, and when */
88 state: keyof typeof states | null;
89 changed: number;
90 /** when it appeared, which it grows in from */
91 born: number;
92 x: number;
93 y: number;
94 vx: number;
95 vy: number;
96 /** where the point is held, like while it is dragged */
97 fx: number | null;
98 fy: number | null;
99}
100
101const kinds: Record<Kind, string> = {
102 step: "#ddd",
103 lazy: "#ff9de2",
104 code: "#4a9dff",
105 file: "#0cff10",
106 directory: "#0a8f0c",
107 sqlite: "#b47aff",
108 output: "#ff3bd0",
109};
110const sizes: Record<Kind, number> = { step: 3, lazy: 4, code: 4.5, file: 2.25, directory: 3, sqlite: 3, output: 2.25 };
111/** a flash dims to a third in this many milliseconds, and is gone in five times as many */
112const fade = 300;
113/** how long a change holds its ring before it dims, as the edit that a build follows from */
114const hold = 1500;
115const states: Record<Exclude<incremental.StepEvent["state"], "reused" | "kept"> | "changed", string> = {
116 changed: "#ff8b47",
117 checking: "#fcd330",
118 running: "#3ee6ff",
119 ran: "#fff",
120 failed: "#ff3b3b",
121};
122
123/** a problem or note that is open, and not folding away */
124const unfolded = "[open]:not(.folding)";
125
126/** how a fold comes to rest, fast and then exponentially slower, like the graph's motion */
127const ease = `linear(${
128 Array.from({ length: 17 }, (_, i) => ((1 - Math.exp(-6 * i / 16)) / (1 - Math.exp(-6))).toFixed(4))
129})`;
130const easeMs = 360;
131
132const tabButtons = tabs.map((name) =>
133 `<button type=button role=tab id=tab-${name} aria-controls=view-${name}>${name}</button>`
134).join("");
135
136const host = document.createElement("clover-debugger");
137const shadow = host.attachShadow({ mode: "open" });
138shadow.innerHTML = `<style>${css()}</style>
139<button class=clover type=button aria-label="build status" aria-describedby=tip aria-expanded=false
140 aria-controls=panel>${clover()}<div class=spinner></div></button>
141<div class=live role=status></div>
142<section id=panel class=panel aria-label="build status" hidden>
143 <div class=grip role=separator aria-orientation=vertical aria-label="panel width" tabindex=0></div>
144 <div class=tabs>
145 <div role=tablist>${tabButtons}</div>
146 <button type=button class=maximize aria-label=maximize aria-pressed=false>
147 <svg viewBox="0 0 12 12" aria-hidden=true>
148 <path class=max d="M1.5 1.5h9v9h-9zM1.5 3h9" />
149 <path class=restore d="M3.5 1.5h7v7M1.5 3.5h7v7h-7zM1.5 5h7" />
150 </svg>
151 </button>
152 </div>
153 <div class=body>
154 <div class=slot></div>
155 <div id=view-status class=view role=tabpanel aria-labelledby=tab-status>
156 <p class=notice>this page changed <button type=button class=reload>reload</button></p>
157 <table><tbody></tbody></table>
158 </div>
159 <div id=view-problems class=view role=tabpanel aria-labelledby=tab-problems>
160 <div class=problems></div><p class=empty>no problems</p>
161 </div>
162 <div id=view-meta class=view role=tabpanel aria-labelledby=tab-meta>
163 <div class=cards></div>
164 </div>
165 <div id=view-graph class=view role=tabpanel aria-labelledby=tab-graph>
166 <canvas role=img aria-label="the steps of the build, and what they read"></canvas>
167 <div class=legend>${legend()}</div>
168 <div class=point hidden></div>
169 </div>
170 </div>
171</section>
172<dialog aria-labelledby=failed tabindex=-1>
173 <div class=top><h2 id=failed>build failed</h2><button type=button class=dismiss></button></div>
174 <div class=slot></div>
175 <div class=problems></div>
176</dialog>
177<div id=tip class=tip role=tooltip><span class=title></span><span class=status></span></div>`;
178
179const find = <E extends Element = HTMLElement>(selector: string) => UNWRAP(shadow.querySelector<E>(selector));
180const button = find<HTMLButtonElement>(".clover");
181const live = find(".live");
182const panel = find(".panel");
183const maximize = find(".maximize");
184const grip = find(".grip");
185if (width) host.style.setProperty("--width", `${width}px`);
186const dialog = find<HTMLDialogElement>("dialog");
187const tree = document.createElement("div");
188
189// a node with no text or total draws as the spinner alone
190const spinner = new progress.Root();
191spinner.start("");
192progress.attachToDocument(spinner, find(".spinner"));
193
194function render() {
195 clearTimeout(timer);
196 const now = performance.now();
197 const state = !connected ? "offline" : building !== null ? "building" : status?.state ?? "offline";
198 const cover = status?.state === "failed" && dismissed !== status;
199
200 // a slow build opens its progress, as does any after errors, and it stays long enough to read
201 const wanted = building !== null && quiet !== building
202 && (now - building >= 500 || (status !== null && status.state !== "ok"));
203 if (wanted) showing ??= now;
204 else if (showing !== null && now - showing >= 1000) showing = null;
205 if (building !== null && !wanted && quiet !== building) timer = setTimeout(render, 500 - (now - building));
206 else if (showing !== null && !wanted) timer = setTimeout(render, 1000 - (now - showing));
207 const visible = open || showing !== null;
208
209 // what the last build did, while nothing newer is on its way
210 const last = connected && building === null ? status : null;
211 button.dataset.state = state;
212 button.classList.toggle("stale", stale);
213 button.setAttribute("aria-expanded", String(visible));
214 const ago = last && string.formatDurationLetters(-Math.round((Date.now() - last.at) / 1000));
215 find(".tip .title").innerHTML = `<b>${title(state)}</b>${ago ? `, last build ${ago}` : ""}`;
216 find(".tip .status").textContent = status?.statusLine ?? "";
217
218 panel.hidden = !visible;
219 panel.dataset.tab = tab;
220 panel.classList.toggle("max", maximized);
221 maximize.setAttribute("aria-pressed", String(maximized));
222 for (const name of tabs) {
223 const tabButton = find(`#tab-${name}`);
224 tabButton.setAttribute("aria-selected", String(name === tab));
225 tabButton.tabIndex = name === tab ? 0 : -1;
226 }
227 // during a build, its progress is its status
228 find("#view-status").hidden = tab !== "status" || (building !== null && !stale);
229 find("#view-problems").hidden = tab !== "problems";
230 find("#view-meta").hidden = tab !== "meta";
231 find("#view-graph").hidden = tab !== "graph";
232 if (visible && tab === "graph") showGraph();
233 if (visible && tab === "meta") showMeta();
234
235 const slot = UNWRAP((cover ? dialog : panel).querySelector<HTMLElement>(".slot"));
236 if (tree.parentElement !== slot) slot.append(tree);
237 for (const each of shadow.querySelectorAll<HTMLElement>(".slot")) each.hidden = building === null;
238 if (cover && !dialog.open) {
239 dialog.showModal();
240 // the errors take the focus, rather than the button that hides them
241 dialog.focus();
242 } else if (!cover && dialog.open) {
243 dialog.close();
244 }
245
246 find(".dismiss").textContent = status?.earlier ? "[view previous output]" : "[dismiss]";
247 find(".notice").hidden = !stale;
248 find("table").hidden = building !== null;
249 const rows: [string, string][] = [[
250 "state",
251 `<span data-state=${last?.state ?? state}>${title(last?.state ?? state)}</span>`,
252 ]];
253 if (last) {
254 const { stats, changed } = last;
255 rows.push(["time", duration(stats.duration)], ["steps", `${stats.ran} ran, ${stats.reused} reused`]);
256 rows.push(["written", `${stats.written} ${stats.written === 1 ? "file" : "files"}`]);
257 if (changed.length > 0) {
258 const files = changed.slice(0, 8).map(string.escapeHtmlContent).join("<br>");
259 const more = changed.length > 8 ? `<br>and ${changed.length - 8} more` : "";
260 rows.push(["changed", `<span class=mono>${files}${more}</span>`]);
261 }
262 rows.push(["cache", string.formatByteSize(stats.cacheBytes)], ["output", string.formatByteSize(stats.outputBytes)]);
263 }
264 const table = rows.map(([label, html]) => `<tr><th scope=row>${label}</th><td>${html}</td></tr>`);
265 find("tbody").innerHTML = table.join("");
266
267 const problems = status?.errors ?? [];
268 find("#view-problems .empty").hidden = problems.length > 0;
269 // what a reader folded stays folded until a build says something new
270 if (listed !== status) {
271 listed = status;
272 const html = fold + problems.map((problem) => diagnostic(problem)).join("");
273 for (const list of shadow.querySelectorAll<HTMLElement>(".problems")) {
274 list.hidden = problems.length === 0;
275 list.innerHTML = html;
276 }
277 showFold();
278 }
279}
280
281/** a button that folds every problem, or unfolds them all once none is open */
282const fold = `<button type=button class=fold><svg viewBox="0 0 12 12" aria-hidden=true>
283 <path d="M1.5 1.5h9v9h-9zM3.5 6h5" /><path class=unfold d="M6 3.5v5" /></svg></button>`;
284
285function showFold() {
286 const open = shadow.querySelector(`details.diagnostic${unfolded}`) !== null;
287 for (const button of shadow.querySelectorAll<HTMLElement>(".fold")) {
288 button.classList.toggle("folded", !open);
289 button.setAttribute("aria-label", open ? "fold every problem" : "unfold every problem");
290 }
291}
292
293const duration = (ms: number) => ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
294
295/** what a state is called, which for a build served with problems counts them */
296function title(state: keyof typeof titles): string {
297 if (state !== "warnings" || !status) return titles[state];
298 const severities = status.errors.flatMap(({ severity, similar }) => Array<string>(1 + similar.length).fill(severity));
299 const thrown = severities.filter((severity) => severity === "error").length;
300 const counts = [[thrown, "error"], [severities.length - thrown, "warning"]] as const;
301 const said = counts.filter(([n]) => n > 0).map(([n, noun]) => `${n} ${noun}${n === 1 ? "" : "s"}`);
302 return said.length > 0 ? `Built with ${said.join(" and ")}` : titles.warnings;
303}
304
305// -- problems --
306
307/**
308 * an error or a warning, laid out like the terminal prints it, with its stack
309 * folded. it folds itself down to its message and where it is.
310 */
311function diagnostic(of: stack.Diagnostic): string {
312 const head = (label: string, text: string) =>
313 `<b>${string.escapeHtmlContent(label)}</b><span class=colon>:</span> ${string.escapeHtmlContent(text)}`;
314 const where = of.location ? `<span class=where>${fileName(of.location)}</span>` : "";
315 let html = `<summary class=head>${chevron}${head(of.label, of.message)}${where}</summary>`;
316 if (of.location) html += excerpt(of.location, true);
317 if (of.fields.length > 0) {
318 const fields = of.fields.map(([name, json]) =>
319 `<div><dt>${string.escapeHtmlContent(name)}</dt><dd>${string.escapeHtmlContent(json)}</dd></div>`
320 );
321 html += `<dl class=fields>${fields.join("")}</dl>`;
322 }
323 for (const note of of.notes) {
324 html += note.frames.length > 0
325 ? `<details class=note><summary>${chevron}${head("note", note.text)}</summary>`
326 + `<div class=frames>${note.frames.map((frame) => excerpt(frame, false)).join("")}</div></details>`
327 : `<div class=note><p class=head>${head("note", note.text)}</p>`
328 + `${note.location ? excerpt(note.location, false) : ""}</div>`;
329 }
330 if (of.cause) {
331 html += `<div class=note><p class=head>${head("note", "caused by")}</p>`
332 + `<div class=nested>${diagnostic(of.cause)}</div></div>`;
333 }
334 for (const error of of.errors) html += `<div class=nested>${diagnostic(error)}</div>`;
335 if (of.similar.length > 0) {
336 const items = of.similar.map(({ message, from }) =>
337 `<li>${string.escapeHtmlContent(message)} <span class=from>${string.escapeHtmlContent(from)}</span></li>`
338 );
339 html += `<details class=note><summary>${chevron}and ${of.similar.length} more like it</summary>`
340 + `<ul class=similar>${items.join("")}</ul></details>`;
341 }
342 return `<details class="diagnostic ${of.severity}"${folded ? "" : " open"}>${html}</details>`;
343}
344
345const unknown = "[unknown source]";
346
347/** what folds a problem or note, so the rest of its line can be selected */
348const chevron =
349 `<span class=chevron><svg viewBox="0 0 12 12" aria-hidden=true><path d="M4.5 2.5 8 6l-3.5 3.5" /></svg></span>`;
350
351/** fold or unfold, keeping what folds away in sight until it is gone */
352function setOpen(details: HTMLDetailsElement, open: boolean) {
353 if (details.matches(unfolded) === open) return;
354 const from = details.offsetHeight;
355 for (const animation of details.getAnimations()) animation.cancel();
356 details.classList.toggle("folding", !open);
357 details.open = open;
358 const to = details.offsetHeight;
359 details.open = true;
360 const duration = matchMedia("(prefers-reduced-motion:reduce)").matches ? 0 : easeMs;
361 details.animate({ height: [`${from}px`, `${to}px`], overflow: ["clip", "clip"] }, { duration, easing: ease })
362 .finished.then(() => {
363 details.classList.remove("folding");
364 details.open = open;
365 }, () => {});
366}
367
368/** where a place is in its file: `:line:col`, or an anchor in a url */
369function positionOf({ file, line, col }: stack.Excerpt): string {
370 if (!line) return "";
371 return file?.startsWith("https://") ? `#L${line}` : `:${line}${col ? `:${col}` : ""}`;
372}
373
374/** a place and its code: the line it points at, and with `context`, the lines around it, faded */
375function excerpt(place: stack.Excerpt, context: boolean): string {
376 const { file, line, fn, code, first, span, internal } = place;
377 const where = fileName(place) + (fn ? ` at <span class=fn>${string.escapeHtmlContent(fn)}</span>` : "");
378
379 // blank lines around the line it points at say nothing
380 const shown = code.map((text, i) => ({ text, n: first + i }))
381 .filter(({ text, n }) => n === line || (context && text.trim()));
382 // the lines keep their indentation relative to each other
383 const indents = shown.filter(({ text }) => text.trim()).map(({ text }) => /^\s*/.exec(text)![0].length);
384 const indent = indents.length > 0 ? Math.min(...indents) : 0;
385 const digits = String(shown.at(-1)?.n ?? 0).length;
386 // the lines around fade away from it
387 const side = (n: number) => n === line ? " hit" : n < line! ? " before" : " after";
388 const lines = shown.map(({ text, n }) =>
389 `<span class="line${side(n)}"><span class=n style="min-width:${digits}ch">${n}</span>`
390 + `${codeLine(text, status?.tokens[`${file}:${n}`] ?? null, n === line ? span : null, indent)}</span>`
391 );
392 return `<figure class="excerpt${internal ? " internal" : ""}"><figcaption>${where}</figcaption>`
393 + (lines.length > 0 ? `<pre>${lines.join("")}</pre>` : "") + "</figure>";
394}
395
396/** a place's file, which opens in the editor, or for a runtime's own code, links to its source */
397function fileName(place: stack.Excerpt): string {
398 if (place.file === null) return unknown;
399 const at = place.file + positionOf(place);
400 if (at.startsWith("https://")) {
401 return `<a href="${string.escapeHtmlAttr(at)}" target=_blank>${string.escapeHtmlContent(at)}</a>`;
402 }
403 return `<button type=button class=path data-open="${string.escapeHtmlAttr(at)}">`
404 + `${string.escapeHtmlContent(place.file)}<span class=pos>${positionOf(place)}</span></button>`;
405}
406
407/** a longer line, like minified code, shows this much around what it points at */
408const widest = 160;
409
410/** a line of code from `indent`, colored by its tokens, with what `mark` covers underlined */
411function codeLine(text: string, tokens: string | null, mark: stack.Excerpt["span"], indent: number): string {
412 let from = indent;
413 let to = text.length;
414 if (to - from > widest) {
415 from = Math.max(from, Math.min((mark?.[0] ?? from) - widest / 4, to - widest));
416 to = from + widest;
417 }
418 const kind = (i: number) => tokens?.[i]?.trim() ?? "";
419 const marked = (i: number) => !!mark && i >= mark[0] && i < mark[1];
420 let html = from > indent ? "…" : "";
421 for (let i = from; i < to;) {
422 let j = i + 1;
423 while (j < to && kind(j) === kind(i) && marked(j) === marked(i)) j++;
424 let piece = string.escapeHtmlContent(text.slice(i, j));
425 if (kind(i)) piece = `<span class=t-${kind(i)}>${piece}</span>`;
426 html += marked(i) ? `<span class=mark>${piece}</span>` : piece;
427 i = j;
428 }
429 return html + (to < text.length ? "…" : "");
430}
431
432// -- the layout --
433
434/**
435 * a force-directed layout, as d3-force lays one out: points push each other
436 * apart, links pull their ends to a distance, and a weak pull to the center
437 * keeps what nothing links from drifting off. each tick moves things less than
438 * the last, until they settle. the push between every pair of points is summed
439 * with a quadtree (barnes-hut), where a square of points that is far enough
440 * away pushes as one, so a tick costs n log n.
441 */
442class Simulation {
443 nodes: Point[] = [];
444 links: Link[] = [];
445 /** how far a tick moves things, which decays toward `alphaTarget` */
446 alpha = 1;
447 alphaTarget = 0;
448 #strengths: number[] = [];
449 #biases: number[] = [];
450
451 /** start laying out `nodes`, placing those without a position on a spiral around the origin */
452 set(nodes: Point[], links: Link[]): void {
453 this.nodes = nodes;
454 this.links = links;
455 nodes.forEach((node, i) => {
456 if (Number.isFinite(node.x) && Number.isFinite(node.y)) return;
457 const radius = 10 * Math.sqrt(0.5 + i);
458 const angle = i * Math.PI * (3 - Math.sqrt(5));
459 node.x = radius * Math.cos(angle);
460 node.y = radius * Math.sin(angle);
461 });
462
463 // a link between busy nodes pulls weakly, and moves the busier end less
464 const degree = new Map<Point, number>();
465 for (const { source, target } of links) {
466 degree.set(source, (degree.get(source) ?? 0) + 1);
467 degree.set(target, (degree.get(target) ?? 0) + 1);
468 }
469 this.#strengths = links.map(({ source, target }) => 1 / Math.min(degree.get(source)!, degree.get(target)!));
470 this.#biases = links.map(({ source, target }) => {
471 const from = degree.get(source)!;
472 return from / (from + degree.get(target)!);
473 });
474 }
475
476 /** move everything once, returning whether it is still moving */
477 tick(): boolean {
478 if (this.alpha < alphaMin && this.alphaTarget < alphaMin) return false;
479 const alpha = this.alpha += (this.alphaTarget - this.alpha) * alphaDecay;
480
481 this.links.forEach(({ source, target }, i) => {
482 let x = target.x + target.vx - source.x - source.vx || jiggle();
483 let y = target.y + target.vy - source.y - source.vy || jiggle();
484 const length = Math.sqrt(x * x + y * y);
485 const pull = (length - linkDistance) / length * alpha * this.#strengths[i]!;
486 x *= pull;
487 y *= pull;
488 const bias = this.#biases[i]!;
489 target.vx -= x * bias;
490 target.vy -= y * bias;
491 source.vx += x * (1 - bias);
492 source.vy += y * (1 - bias);
493 });
494
495 const tree = this.#quadtree();
496 for (const node of this.nodes) {
497 if (tree) this.#push(node, tree.quad, tree.size, alpha);
498 node.vx -= node.x * gravity * alpha;
499 node.vy -= node.y * gravity * alpha;
500 }
501
502 for (const node of this.nodes) {
503 if (node.fx === null) node.x += node.vx *= friction;
504 else node.x = node.fx, node.vx = 0;
505 if (node.fy === null) node.y += node.vy *= friction;
506 else node.y = node.fy, node.vy = 0;
507 }
508 return true;
509 }
510
511 /** the nearest node to a point, if it is within `radius` */
512 find(x: number, y: number, radius: number): Point | null {
513 let found: Point | null = null;
514 let nearest = radius * radius;
515 for (const node of this.nodes) {
516 const distance = (node.x - x) ** 2 + (node.y - y) ** 2;
517 if (distance < nearest) found = node, nearest = distance;
518 }
519 return found;
520 }
521
522 /** a quadtree over every node, in a square that covers them */
523 #quadtree(): { quad: Quad; size: number } | null {
524 if (this.nodes.length === 0) return null;
525 let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
526 for (const { x, y } of this.nodes) {
527 x0 = Math.min(x0, x), y0 = Math.min(y0, y), x1 = Math.max(x1, x), y1 = Math.max(y1, y);
528 }
529 const size = Math.max(x1 - x0, y1 - y0, 1);
530 return { quad: this.#quad(this.nodes, x0, y0, size), size };
531 }
532
533 #quad(nodes: Point[], x0: number, y0: number, size: number): Quad {
534 const first = nodes[0]!;
535 const together = nodes.every((node) => node.x === first.x && node.y === first.y);
536 // squares stop splitting at a fraction of a pixel, where nodes are as good as together
537 if (together || size < 1e-3) {
538 return { nodes, children: null, charge: pointCharge * nodes.length, x: first.x, y: first.y };
539 }
540
541 const half = size / 2;
542 const parts: Point[][] = [[], [], [], []];
543 for (const node of nodes) parts[(node.x < x0 + half ? 0 : 1) + (node.y < y0 + half ? 0 : 2)]!.push(node);
544 const children = parts.map((part, i) =>
545 part.length === 0 ? null : this.#quad(part, x0 + (i & 1) * half, y0 + (i >> 1) * half, half)
546 );
547
548 let charge = 0, x = 0, y = 0;
549 for (const child of children) {
550 if (!child) continue;
551 charge += child.charge, x += child.x * child.charge, y += child.y * child.charge;
552 }
553 return { nodes: null, children, charge, x: x / charge, y: y / charge };
554 }
555
556 /** push `node` away from the nodes in `quad`, as one when the square is far enough */
557 #push(node: Point, quad: Quad, size: number, alpha: number): void {
558 let x = quad.x - node.x;
559 let y = quad.y - node.y;
560 let distance = x * x + y * y;
561
562 if (quad.children) {
563 if (size * size / (theta * theta) < distance) {
564 if (distance < 1) distance = Math.sqrt(distance);
565 node.vx += x * quad.charge * alpha / distance;
566 node.vy += y * quad.charge * alpha / distance;
567 return;
568 }
569 for (const child of quad.children) if (child) this.#push(node, child, size / 2, alpha);
570 return;
571 }
572
573 for (const other of UNWRAP(quad.nodes)) {
574 if (other === node) continue;
575 // nodes in one place are pushed apart in some direction
576 if (x === 0) x = jiggle(), distance += x * x;
577 if (y === 0) y = jiggle(), distance += y * y;
578 // very close nodes push like they are a pixel apart, which keeps them from flying off
579 if (distance < 1) distance = Math.sqrt(distance);
580 node.vx += x * pointCharge * alpha / distance;
581 node.vy += y * pointCharge * alpha / distance;
582 }
583 }
584}
585
586/** from a step to what it read or wrote */
587interface Link {
588 source: Point;
589 target: Point;
590}
591
592/** a square of the quadtree, with the charge of the points in it and their center */
593interface Quad {
594 /** the points of a leaf, which share a position or are alone in their square */
595 nodes: Point[] | null;
596 children: Array<Quad | null> | null;
597 charge: number;
598 x: number;
599 y: number;
600}
601
602/** below this, nothing moves enough to tick */
603const alphaMin = 0.001;
604/** a layout settles in 300 ticks */
605const alphaDecay = 1 - Math.pow(0.001, 1 / 300);
606/** the share of its velocity that a point keeps each tick */
607const friction = 0.6;
608/** the push of each point, negative to repel */
609const pointCharge = -30;
610/** how far apart a link holds its ends */
611const linkDistance = 30;
612/** how strongly everything is pulled to the origin */
613const gravity = 0.05;
614/** how small a square must look from a point to push as one */
615const theta = 0.9;
616const jiggle = () => (Math.random() - 0.5) * 1e-6;
617
618// -- meta: the cards that a shared link becomes --
619
620/** the page as the server sends it, which is all that a crawler sees, as none of them run its scripts */
621let reading: Promise<void> | null = null;
622
623function showMeta() {
624 reading ??= readMeta().catch(() => {
625 reading = null;
626 find(".cards").innerHTML = "<p class=empty>this page could not be read</p>";
627 });
628}
629
630async function readMeta() {
631 const page = await fetch(location.href, { headers: { accept: "text/html" }, cache: "no-store" });
632 const html = await page.text();
633 const scraped = meta.scrape(meta.readTags(new DOMParser().parseFromString(html, "text/html")));
634 const [embed, oEmbed] = await Promise.all([loadEmbed(scraped.discord), loadOEmbed(scraped.oEmbed)]);
635 const refused = refusal(page);
636 find(".cards").innerHTML = discordCard(scraped, embed, oEmbed, refused) + twitterCard(scraped, refused);
637}
638
639/** why a crawler reads nothing from a page that is served like this */
640function refusal(page: Response): string | null {
641 const type = page.headers.get("content-type") ?? "";
642 if (!page.ok) return `the page responds ${page.status}`;
643 if (!/^(text\/html|application\/xhtml\+xml)\b/i.test(type)) {
644 return `the page is served as ${type || "nothing"}, not html`;
645 }
646 if (/^attachment/i.test(page.headers.get("content-disposition") ?? "")) return "the page is served as a download";
647 return null;
648}
649
650/** a file that the page names on the host that it is published to, as the dev server has it at that path */
651async function fetchLocal(href: string): Promise<string | null> {
652 const url = new URL(href, location.href);
653 const response = await fetch(url.pathname + url.search, { cache: "no-store" }).catch(() => null);
654 return response?.ok ? response.text() : null;
655}
656
657type Embed = { component: Wire } | { problems: string[] };
658
659/** the component embed that the page holds or links to, or why Discord would not show it */
660async function loadEmbed(source: meta.Scraped["discord"]): Promise<Embed | null> {
661 if (!source) return null;
662 let text: string;
663 if ("text" in source) {
664 text = source.text;
665 } else {
666 const fetched = await fetchLocal(source.href);
667 if (fetched === null) return { problems: [`${source.href} could not be read`] };
668 text = fetched;
669 }
670 const problems: string[] = [];
671 const bytes = string.encodeUtf8(text).length;
672 if (bytes > 3000) problems.push(`the component embed is ${bytes} bytes, at most 3000`);
673 try {
674 const embed = JSON.parse(text) as meta.DiscordPayload;
675 problems.push(...meta.discordProblems(embed));
676 // a payload with no problems has the shapes of `Wire`
677 return problems.length > 0 ? { problems } : { component: embed.component as unknown as Wire };
678 } catch {
679 return { problems: ["the component embed is not json"] };
680 }
681}
682
683interface OEmbed {
684 title?: string;
685 thumbnail_url?: string;
686 thumbnail_width?: number;
687 thumbnail_height?: number;
688 author_name?: string;
689 provider_name?: string;
690}
691
692/** the fields of oEmbed json that Discord reads. it ignores a file that it can't read, too */
693async function loadOEmbed(href: string | null): Promise<OEmbed | null> {
694 const text = href && await fetchLocal(href);
695 try {
696 return text ? JSON.parse(text) as OEmbed : null;
697 } catch {
698 return null;
699 }
700}
701
702const hexColor = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;
703const esc = string.escapeHtmlContent;
704const attr = string.escapeHtmlAttr;
705
706/** an image of the page. a url that is published to may not have it yet, so the dev server's copy of its path is the fallback */
707function img(src: string, alt = "", cls = "") {
708 const url = new URL(src, location.href);
709 return `<img class="${cls}" src="${attr(url.href)}" data-local="${attr(location.origin + url.pathname + url.search)}"`
710 + ` alt="${attr(alt)}">`;
711}
712
713/** cut to a number of bytes, as Discord cuts a title and a description */
714function clip(text: string, bytes: number) {
715 const encoded = string.encodeUtf8(text);
716 if (encoded.length <= bytes) return text;
717 return string.decodeUtf8(encoded.subarray(0, bytes - 3)).replace(/\uFFFD$/, "") + "…";
718}
719
720/** the names of the tags that hold a url that Discord reads */
721const urlKey = /^(image|video|url)(:(url|secure_url))?$|^(image:src|player:stream)$/;
722
723/** what makes Discord drop a link's preview entirely, rather than trim it */
724function discordRefusal({ openGraph: og, twitter: tw }: meta.Scraped): string | null {
725 if ((og.site_name?.[0]?.length ?? 0) > 256) return "og:site_name is over 256 characters";
726 if ([og, tw].some((tags) => tags["image:alt"]?.some((alt) => alt.length > 4096))) {
727 return "image alt text is over 4096 characters";
728 }
729 const long = [og, tw].some((tags) =>
730 Object.entries(tags).some(([key, values]) => urlKey.test(key) && values.some((value) => value.length > 2048))
731 );
732 return long ? "a url is over 2048 characters" : null;
733}
734
735function discordCard(s: meta.Scraped, loaded: Embed | null, oEmbed: OEmbed | null, refused: string | null): string {
736 const { openGraph: og, twitter: tw } = s;
737 const notes: string[] = [];
738 const last = (values: string[] | undefined) => values?.at(-1);
739 const message = (card: string) =>
740 `<section class=preview>${card && `<div class=chat>${card}</div>`}`
741 + `${noteList(notes)}</section>`;
742
743 const stop = refused ?? discordRefusal(s);
744 if (stop) return notes.push(`${stop}, so Discord shows no preview`), message("");
745
746 if (loaded && "problems" in loaded) {
747 notes.push("the component embed has problems, so Discord shows the Open Graph card", ...loaded.problems);
748 } else if (loaded) {
749 // a component embed is a card of its own, rather than something in the Open Graph card
750 if (!og.title) notes.push("no og:title for Discord to fall back on");
751 return message(component(loaded.component));
752 }
753
754 let heading = og.title?.[0] ?? tw.title?.[0];
755 let text = og.description?.[0] ?? tw.description?.[0];
756 // the title and description tags are used together or not at all, and when the others have neither
757 if (!heading && !text) {
758 if (s.title && s.description) [heading, text] = [s.title, s.description];
759 else if (s.title || s.description) notes.push("<title> and <meta name=description> are used only as a pair");
760 }
761 heading ??= oEmbed?.title;
762 const images = [og.image, og["image:url"], og["image:secure_url"], tw.image, tw["image:src"]]
763 .find((values) => values?.length) ?? (oEmbed?.thumbnail_url && oEmbed.thumbnail_width && oEmbed.thumbnail_height
764 ? [oEmbed.thumbnail_url]
765 : []);
766 if (!heading && !text && images.length === 0) {
767 return notes.push("no og:title or og:description, so Discord shows no preview"), message("");
768 }
769
770 const color = s.themeColor && hexColor.test(s.themeColor) ? s.themeColor : null;
771 if (s.themeColor && !color) notes.push(`theme-color ${s.themeColor} is not #RRGGBB, so Discord leaves it out`);
772 const alt = og["image:alt"]?.[0] ?? tw["image:alt"]?.[0];
773 const kind = last(og.type);
774 const layout = last(tw.card);
775 const video = [og.video, og["video:url"], og["video:secure_url"], tw["player:stream"]]
776 .find((values) => values?.length)?.[0];
777 const site = oEmbed?.provider_name ?? og.site_name?.[0];
778
779 const first = images[0];
780 const lead = (site ? `<div class=d-site>${esc(site)}</div>` : "")
781 + (oEmbed?.author_name ? `<div class=d-site>${esc(oEmbed.author_name)}</div>` : "")
782 + (heading ? `<div class=d-title>${esc(clip(heading, 70))}</div>` : "");
783 const words = text ? `<div class=d-desc>${kind === "rich" ? markdown(text) : esc(clip(text, 350))}</div>` : "";
784 let card: string;
785 if (first && video && (kind?.startsWith("video") || layout === "player")) {
786 card = lead + `<div class="d-frame d-big">${img(first, alt)}<i class=play></i></div>`;
787 } else if (first && (layout === "photo" || kind === "instapp:photo")) {
788 card = lead + img(first, alt, "d-big");
789 } else if (first && images.length > 1) {
790 card = lead + words + gallery(images.slice(0, 4).map((src) => ({ media: { url: src }, description: alt })));
791 } else if (first && layout === "summary_large_image") {
792 card = lead + words + img(first, alt, "d-big");
793 } else {
794 card = `<div class=d-split><div>${lead}${words}</div>${first ? img(first, alt, "d-small") : ""}</div>`;
795 }
796 const style = color ? ` style="--accent:${attr(color)}"` : "";
797 return message(`<div class=discord${style}>${card}</div>`);
798}
799
800function twitterCard(s: meta.Scraped, refused: string | null): string {
801 const { openGraph: og, twitter: tw } = s;
802 const notes: string[] = [];
803 const shared = new URL(s.canonical ?? og.url?.[0] ?? location.href, location.href);
804 const tweet = (card: string) =>
805 `<section class=preview>${card && `<div class=tweet>${card}</div>`}`
806 + `${noteList(notes)}</section>`;
807
808 // twitter takes what a tag leaves out from the Open Graph tags, but not from <title>
809 const title = tw.title?.[0] ?? og.title?.[0];
810 const description = tw.description?.[0] ?? og.description?.[0];
811 const image = (tw.image ?? tw["image:src"] ?? og.image)?.[0];
812 const alt = tw["image:alt"]?.[0] ?? og["image:alt"]?.[0];
813 const layout = tw.card?.at(-1);
814 const stop = refused ?? (layout
815 ? title ? null : "there is no title"
816 : title && description
817 ? null
818 : "there is no twitter:card, nor an og:title and og:description to make a summary of");
819 if (stop) return notes.push(`${stop}, so twitter shows no card`), tweet("");
820 if (!layout) notes.push("no twitter:card, so twitter may show a summary");
821 else if (layout !== "summary" && layout !== "summary_large_image") {
822 notes.push(`twitter shows a ${layout} card as a summary here`);
823 }
824
825 // a summary without an image keeps its place, with a newspaper
826 const picture = image ? img(image, alt) : `<div class=x-blank>${newspaper}</div>`;
827 const card = layout === "summary_large_image" && image
828 ? `<div class=x-card><div class=x-image>${picture}<span class=x-over>${esc(title!)}</span></div></div>`
829 + `<div class=x-domain>From ${esc(shared.hostname)}</div>`
830 : `<div class="x-card x-summary">${picture}<div class=x-text><div class=x-domain>${esc(shared.hostname)}</div>`
831 + `<div class=x-title>${esc(title!)}</div>`
832 + (description ? `<div class=x-desc>${esc(description)}</div>` : "") + `</div></div>`;
833 return tweet(card);
834}
835
836const newspaper =
837 `<svg viewBox="0 0 24 24" aria-hidden=true><path d="M3 4h18v16H3zM6.5 8h5v4h-5zM14 8.5h3.5M14 11.5h3.5M6.5 16h11"/></svg>`;
838
839const noteList = (notes: string[]) =>
840 notes.length > 0 ? `<ul class=notes>${notes.map((note) => `<li>${esc(note)}</li>`).join("")}</ul>` : "";
841
842/** a component of a payload that `meta.discordProblems` found no problem with */
843type Wire =
844 | { type: 1; components: Wire[] }
845 | { type: 2; url: string; label?: string; emoji?: { id?: string; name?: string }; disabled?: boolean }
846 | { type: 9; components: Wire[]; accessory: Wire }
847 | { type: 10; content: string }
848 | ({ type: 11 } & WireMedia)
849 | { type: 12; items: WireMedia[] }
850 | { type: 14; spacing?: number | null; divider?: boolean | null }
851 | { type: 17; components: Wire[]; accent_color?: number | null; spoiler?: boolean };
852interface WireMedia {
853 media: { url: string };
854 description?: string | null;
855 spoiler?: boolean;
856}
857
858function gallery(items: WireMedia[]): string {
859 const cells = items.map(({ media, description, spoiler }) =>
860 `<div class="d-cell${spoiler ? " spoiler" : ""}">${img(media.url, description ?? "")}</div>`
861 );
862 return `<div class="d-gallery n${items.length}">${cells.join("")}</div>`;
863}
864
865/** a component of an embed, which is laid out as the app lays out a message */
866function component(c: Wire): string {
867 const spoiler = (of: { spoiler?: boolean }) => of.spoiler ? " spoiler" : "";
868 switch (c.type) {
869 case 1:
870 return `<div class=d-row>${c.components.map(component).join("")}</div>`;
871 case 2: {
872 const emoji = c.emoji?.id ? "" : c.emoji?.name;
873 return `<span class="d-button${c.disabled ? " disabled" : ""}">${
874 emoji ? `<span class=emoji>${esc(emoji)}</span>` : ""
875 }`
876 + `${esc(c.label ?? "")}${external}</span>`;
877 }
878 case 9:
879 return `<div class=d-section><div>${c.components.map(component).join("")}</div>${component(c.accessory)}</div>`;
880 case 10:
881 return `<div class=d-text>${markdown(c.content)}</div>`;
882 case 11:
883 return `<div class="d-thumb${spoiler(c)}">${img(c.media.url, c.description ?? "")}</div>`;
884 case 12:
885 return gallery(c.items);
886 case 14:
887 return `<hr class="d-sep${c.spacing === 2 ? " large" : ""}${c.divider === false ? " blank" : ""}">`;
888 case 17: {
889 const accent = c.accent_color == null
890 ? ""
891 : ` accent" style="--accent:#${c.accent_color.toString(16).padStart(6, "0")}`;
892 return `<div class="d-container${spoiler(c)}${accent}">${c.components.map(component).join("")}</div>`;
893 }
894 }
895}
896
897/** the arrow of a button that opens a link */
898const external = `<svg viewBox="0 0 24 24" aria-hidden=true><path d="M14 4h6v6M20 4l-9 9M18 14v6H4V6h6"/></svg>`;
899
900/** Discord markdown, in the parts that text in an embed uses */
901function markdown(text: string): string {
902 const inline = (raw: string) => {
903 // code is set aside so that nothing inside it is formatted
904 const codes: string[] = [];
905 const html = esc(raw).replace(/`([^`]+)`/g, (_, code) => `\0${codes.push(`<code>${code}</code>`) - 1}\0`)
906 .replace(/\[([^\]]+)\]\(https?:\/\/[^\s)]+\)/g, "<span class=link>$1</span>")
907 .replace(/(?<![\w>])https?:\/\/[^\s<]+/g, (url) => `<span class=link>${url}</span>`)
908 .replace(/\*\*\*(.+?)\*\*\*/g, "<b><i>$1</i></b>")
909 .replace(/\*\*(.+?)\*\*/g, "<b>$1</b>")
910 .replace(/__(.+?)__/g, "<u>$1</u>")
911 .replace(/~~(.+?)~~/g, "<s>$1</s>")
912 .replace(/\|\|(.+?)\|\|/g, "<span class=hidden>$1</span>")
913 .replace(/(?<![*\w])[*_](.+?)[*_](?![*\w])/g, "<i>$1</i>");
914 return html.replace(/\0(\d+)\0/g, (_, i) => codes[Number(i)]!);
915 };
916 return text.split(/```\w*\n?([\s\S]*?)```/).map((part, i) => {
917 if (i % 2 === 1) return `<pre>${esc(part.replace(/\n$/, ""))}</pre>`;
918 // a list goes on as the kind that it began as
919 let list: "bullet" | "number" | null = null;
920 return part.split("\n").map((line, n, lines) => {
921 // the line break that ends a block, or sits beside a code block, is not an empty line
922 if (!line && (n === 0 || n === lines.length - 1) && lines.length > 1) return "";
923 const item = /^\s*(?:([-*])|(\d+)\.) (.*)/.exec(line);
924 const was = list;
925 list = item ? list ?? (item[1] ? "bullet" : "number") : null;
926 if (item) {
927 const marker = list === "number" && item[2] ? ` data-n="${item[2]}."` : "";
928 return `<div class="li${marker ? " number" : ""}"${marker}>${inline(item[3]!)}</div>`;
929 }
930 const heading = /^(#{1,3}) (.*)/.exec(line);
931 if (heading) return `<div class=h${heading[1]!.length}>${inline(heading[2]!)}</div>`;
932 const sub = /^-# (.*)/.exec(line);
933 if (sub) return `<div class=sub>${inline(sub[1]!)}</div>`;
934 const quote = /^> ?(.*)/.exec(line);
935 if (quote) return `<div class=quote>${inline(quote[1]!)}</div>`;
936 return `<div>${inline(line) || "<br>"}</div>`;
937 }).join("");
938 }).join("");
939}
940
941// -- the graph: steps, the code that they run, and the inputs that they read --
942
943const canvas = find<HTMLCanvasElement>("canvas");
944const context = UNWRAP(canvas.getContext("2d"));
945const pointLabel = find(".point");
946const simulation = new Simulation();
947const points = new Map<string, Point>();
948/** what kind each input was, which decides whether it is drawn */
949const inputKinds = new Map<string, string>();
950/** what more than half of the steps read, like the build script, which is drawn without its links */
951const shared = new Set<string>();
952/** the project's url, which the paths of its files are relative to */
953let projectUrl = "";
954let loading: Promise<void> | null = null;
955/** what happened to steps, shown a little at a time, so a quick build still sweeps across */
956const sweep: incremental.StepEvent[] = [];
957/** data on its way along a link, from what was read to the step that read it, or from a step to what it wrote */
958let pulses: Array<{ link: Link; at: number }> = [];
959/** what a step stopped reading, and what the graph lost, which fade out in red */
960let goneLinks: Array<{ link: Link; at: number }> = [];
961let gonePoints: Array<{ point: Point; at: number }> = [];
962/** the pan, in pixels from the center, and the zoom */
963const view = { x: 0, y: 0, k: 1 };
964let hovered: Point | null = null;
965let dragging: { point: Point | null; x: number; y: number } | null = null;
966let frame = 0;
967let drawn = 0;
968
969if (saved) {
970 const restored = saved.points.map(([id, kind, label, x, y, vx, vy]) =>
971 Object.assign(place(id, kind, label), { x, y, vx, vy, born: -Infinity })
972 );
973 simulation.set(
974 restored,
975 saved.links.map(([source, target]) => ({ source: restored[source]!, target: restored[target]! })),
976 );
977 simulation.alpha = saved.alpha;
978 Object.assign(view, saved.view);
979}
980addEventListener("pagehide", () => {
981 const index = new Map(simulation.nodes.map((point, i) => [point, i]));
982 const links = simulation.links.flatMap(({ source, target }) => {
983 const ends = [index.get(source), index.get(target)];
984 return ends.every((end) => end !== undefined) ? [ends as [number, number]] : [];
985 });
986 sessionStorage.setItem(
987 savedKey,
988 JSON.stringify(
989 {
990 ...(!home && { open, maximized, tab }),
991 ...(width && { width }),
992 folded,
993 view,
994 alpha: simulation.alpha,
995 points: simulation.nodes.map(({ id, kind, label, x, y, vx, vy }) => [id, kind, label, x, y, vx, vy]),
996 links,
997 } satisfies Saved,
998 ),
999 );
1000});
1001
1002/** a glow in the color of each kind, which dims exponentially away from its center */
1003const halos = Object.fromEntries(
1004 Object.entries(kinds).map(([kind, color]) => {
1005 const sprite = document.createElement("canvas");
1006 sprite.width = sprite.height = 64;
1007 const sprites = UNWRAP(sprite.getContext("2d"));
1008 const falloff = sprites.createRadialGradient(32, 32, 0, 32, 32, 32);
1009 for (let i = 0; i <= 16; i++) falloff.addColorStop(i / 16, `rgb(255 255 255 / ${Math.exp(-6 * i / 16)})`);
1010 sprites.fillStyle = falloff;
1011 sprites.fillRect(0, 0, 64, 64);
1012 sprites.globalCompositeOperation = "source-in";
1013 sprites.fillStyle = color;
1014 sprites.fillRect(0, 0, 64, 64);
1015 return [kind, sprite];
1016 }),
1017) as Record<Kind, HTMLCanvasElement>;
1018/** where the far glows add up, at a quarter of the size, in floats so that the faint ones still add */
1019const glow = new OffscreenCanvas(1, 1);
1020const glows = UNWRAP(glow.getContext("2d", { colorType: "float16" }));
1021
1022/** the steps that find, load, and read modules fold into the code that they close over */
1023function stepKind(key: string, lazy: boolean): Kind | null {
1024 if (key.startsWith("closure:")) return "code";
1025 if (/^(load|resolve|package):/.test(key)) return null;
1026 return lazy ? "lazy" : "step";
1027}
1028
1029/** a probe for a file that is not there, and the graph's own options, are not drawn */
1030function inputKind(url: string): Kind | null {
1031 const kind = inputKinds.get(url) ?? "file";
1032 return kind === "file" || kind === "directory" || kind === "sqlite" ? kind : null;
1033}
1034
1035/** a file's path in the project, or the query of a row */
1036function labelOf(url: string, kind: Kind): string {
1037 const decoded = url.startsWith(projectUrl) ? decodeURI(url.slice(projectUrl.length)) : decodeURIComponent(url);
1038 if (kind !== "sqlite") return decoded;
1039 try {
1040 const { sql, args } = JSON.parse(decoded.slice(decoded.indexOf(":") + 1)) as { sql: string; args: unknown[] };
1041 return `${sql} ${JSON.stringify(args)}`;
1042 } catch {
1043 return decoded;
1044 }
1045}
1046
1047function groupOf(kind: Kind, label: string): string {
1048 if (kind === "step" || kind === "lazy") return label.split(" at ")[0]!;
1049 if (kind === "sqlite") return /from "?(\w+)/i.exec(label)?.[1] ?? "sqlite";
1050 const file = kind === "code" ? label.slice(label.indexOf(" ") + 1) : label;
1051 return file.split("/").slice(0, 2).join("/");
1052}
1053
1054/** `previous` is the point it takes over, whose place it keeps */
1055function place(id: string, kind: Kind, label: string, previous = points.get(id)): Point {
1056 const point = previous ?? {
1057 id,
1058 kind,
1059 label,
1060 group: "",
1061 x: NaN,
1062 y: NaN,
1063 vx: 0,
1064 vy: 0,
1065 fx: null,
1066 fy: null,
1067 state: null,
1068 changed: 0,
1069 born: performance.now(),
1070 };
1071 Object.assign(point, { id, kind, label, group: groupOf(kind, label) });
1072 points.set(id, point);
1073 return point;
1074}
1075
1076/** links from a step to the steps and inputs that it read, and to the files that it wrote */
1077function wire(
1078 point: Point,
1079 steps: string[],
1080 inputs: string[],
1081 outputs: string[],
1082 reuse?: Map<string, Point>,
1083): Link[] {
1084 const links: Link[] = [];
1085 for (const key of steps) {
1086 const target = points.get(key);
1087 if (target) links.push({ source: point, target });
1088 }
1089 // a module's code reads its source, which the step that loads it read
1090 const source = point.kind === "code" ? point.id.slice("closure:".length) : "";
1091 for (const url of inputKinds.has(source) && !inputs.includes(source) ? [...inputs, source] : inputs) {
1092 const kind = inputKind(url);
1093 if (kind) {
1094 links.push({ source: point, target: points.get(url) ?? place(url, kind, labelOf(url, kind), reuse?.get(url)) });
1095 }
1096 }
1097 for (const url of outputs) {
1098 links.push({
1099 source: point,
1100 target: points.get(url) ?? place(url, "output", labelOf(url, "output"), reuse?.get(url)),
1101 });
1102 }
1103 return links;
1104}
1105
1106/** links to what more than half of the steps read, which would pull everything into one knot, are not drawn */
1107function prune(links: Link[]): Link[] {
1108 let steps = 0;
1109 for (const point of points.values()) if (point.kind === "step" || point.kind === "lazy") steps++;
1110 const readers = new Map<string, number>();
1111 for (const { target } of links) readers.set(target.id, (readers.get(target.id) ?? 0) + 1);
1112 for (const [id, count] of readers) if (steps >= 20 && count > steps / 2) shared.add(id);
1113 return links.filter((link) => !shared.has(link.target.id));
1114}
1115
1116/**
1117 * lay out `links`, starting each new point about where they will hold it, so it
1118 * barely moves to get there: on the ring that its kind makes around the busiest
1119 * point it links to, facing the other points it links to
1120 */
1121function settle(links: Link[]) {
1122 const kept = prune(links);
1123 const placed = (point: Point) => !Number.isNaN(point.x);
1124 const near = new Map<Point, Point[]>();
1125 const mean = (list: Point[], of: (point: Point) => number) =>
1126 list.reduce((sum, point) => sum + of(point), 0) / list.length;
1127 const fresh = links.some(({ source, target }) => !placed(source) || !placed(target));
1128 for (const { source, target } of fresh ? links : []) {
1129 if (!near.has(source)) near.set(source, []);
1130 if (!near.has(target)) near.set(target, []);
1131 near.get(source)!.push(target);
1132 near.get(target)!.push(source);
1133 }
1134 for (let more = fresh; more;) {
1135 more = false;
1136 for (const [point, around] of near) {
1137 // what most steps read has no links to hold anything
1138 const anchors = placed(point) ? [] : around.filter((other) => placed(other) && !shared.has(other.id));
1139 if (anchors.length === 0) continue;
1140 more = true;
1141 const hub = anchors.reduce((busiest, anchor) =>
1142 near.get(anchor)!.length > near.get(busiest)!.length ? anchor : busiest
1143 );
1144 const others = anchors.filter((anchor) => anchor !== hub);
1145 const ring = near.get(hub)!.filter((other) => other.kind === point.kind && placed(other));
1146 const reach = ring.length > 0
1147 ? mean(ring, (other) => Math.hypot(other.x - hub.x, other.y - hub.y))
1148 : linkDistance;
1149 const angle = others.length > 0
1150 ? Math.atan2(mean(others, (other) => other.y) - hub.y, mean(others, (other) => other.x) - hub.x)
1151 + Math.random() - 0.5
1152 : Math.random() * 2 * Math.PI;
1153 point.x = hub.x + reach * Math.cos(angle);
1154 point.y = hub.y + reach * Math.sin(angle);
1155 }
1156 }
1157 // a point that links to nothing yet waits for its links, rather than starting out in the middle
1158 simulation.set(Array.from(points.values()).filter((point) => placed(point) || near.has(point)), kept);
1159 simulation.alpha = Math.max(simulation.alpha, 0.3);
1160}
1161
1162const linkId = ({ source, target }: Link) => `${source.id} ${target.id}`;
1163
1164/**
1165 * the point of a new step, which is the point of the step it replaces when
1166 * just one of `lost` is from the same code and read what it reads, `links`
1167 * being theirs. the files the new step writes take the places of as many
1168 * that one wrote.
1169 */
1170function succeed(
1171 point: Point,
1172 reads: Link[],
1173 outputs: string[],
1174 lost: Point[],
1175 links: Link[],
1176): Point {
1177 const read = (from: Point, links: Link[]) =>
1178 links.filter(({ source, target }) => source === from && target.kind !== "output" && !shared.has(target.id))
1179 .map(({ target }) => target.id).sort().join(" ");
1180 const wanted = read(point, reads);
1181 const same = lost.filter((other) =>
1182 other !== point && other.kind === point.kind && other.label === point.label && read(other, links) === wanted
1183 );
1184 if (same.length !== 1) return point;
1185 const heir = same[0]!;
1186 const wrote = links.filter((link) => link.source === heir && link.target.kind === "output").map((link) =>
1187 link.target
1188 );
1189 points.delete(heir.id);
1190 place(point.id, point.kind, point.label, heir);
1191 if (wrote.length === outputs.length && !outputs.some((url) => points.has(url))) {
1192 wrote.forEach((file, i) => {
1193 points.delete(file.id);
1194 place(outputs[i]!, "output", labelOf(outputs[i]!, "output"), file);
1195 });
1196 }
1197 return heir;
1198}
1199
1200async function loadGraph() {
1201 const response = await fetch("/.clover/graph", { cache: "no-store" });
1202 const snapshot = await response.json() as incremental.GraphSnapshot;
1203 projectUrl = snapshot.root;
1204 for (const input of snapshot.inputs) inputKinds.set(input.url, input.kind);
1205 const previous = new Map(points);
1206 points.clear();
1207 for (const step of snapshot.steps) {
1208 const kind = stepKind(step.key, step.lazy);
1209 if (kind) place(step.key, kind, step.label, previous.get(step.key));
1210 }
1211 const before = simulation.links;
1212 // a step new to the graph may replace one that the graph lost
1213 const lost = Array.from(previous.values()).filter((point) => !points.has(point.id));
1214 for (const step of snapshot.steps) {
1215 const point = points.get(step.key);
1216 if (!point || !Number.isNaN(point.x) || step.lazy) continue;
1217 const reads = wire(point, step.steps, step.inputs, [], previous);
1218 succeed(point, reads, step.outputs, lost.filter((other) => !points.has(other.id)), before);
1219 }
1220 // what most steps read is counted again from the whole graph, as a build sees only what it ran
1221 shared.clear();
1222 settle(snapshot.steps.flatMap((step) => {
1223 const point = points.get(step.key);
1224 return point ? wire(point, step.steps, step.inputs, step.outputs, previous) : [];
1225 }));
1226 // a graph carried over from the last page moves on as it was
1227 if (saved) simulation.alpha = saved.alpha, saved = null;
1228 // a graph mostly unseen is laid out before it shows, rather than unfolding
1229 if (points.size > 2 * previous.size) {
1230 const end = performance.now() + 150;
1231 while (performance.now() < end && simulation.tick()) {}
1232 }
1233
1234 // what the graph lost since it was last read
1235 const now = performance.now();
1236 for (const point of previous.values()) if (!points.has(point.id)) gonePoints.push({ point, at: now });
1237 const kept = new Set(simulation.links.map(linkId));
1238 for (const link of before) {
1239 if (!kept.has(linkId(link)) && !shared.has(link.target.id)) goneLinks.push({ link, at: now });
1240 }
1241}
1242
1243function showGraph() {
1244 loading ??= loadGraph().catch(() => void (loading = null));
1245 frame ||= requestAnimationFrame(draw);
1246}
1247
1248function draw() {
1249 frame = 0;
1250 if (panel.hidden || tab !== "graph") return void sweep.splice(0);
1251 const now = performance.now();
1252 // the same share of the queue drains in the same time, however often frames come
1253 const share = 1 - Math.exp(-(now - drawn) / 300);
1254 drawn = now;
1255 for (const event of sweep.splice(0, Math.ceil(sweep.length * share))) {
1256 // what the steps that load modules read are the sources of the code they fold into
1257 if ("inputs" in event) { for (const { url, kind } of event.inputs) inputKinds.set(url, kind); }
1258 const kind = stepKind(event.key, event.lazy);
1259 if (!kind) continue;
1260 let point = points.get(event.key) ?? place(event.key, kind, event.label);
1261 if ("steps" in event) {
1262 const inputs = event.inputs.map((input) => input.url);
1263 if (Number.isNaN(point.x) && !event.lazy) {
1264 // what the build has not reached is what it may not use
1265 const unused = simulation.nodes.filter((other) => other.changed < began);
1266 point = succeed(point, wire(point, event.steps, inputs, []), event.outputs, unused, simulation.links);
1267 }
1268
1269 // what a step read when it ran replaces what it read before, and flows into it, and out into what it wrote
1270 const reads = wire(point, event.steps, inputs, event.outputs);
1271 const still = new Set(reads.map(linkId));
1272 for (const link of simulation.links) {
1273 if (link.source === point && !still.has(linkId(link))) goneLinks.push({ link, at: now });
1274 }
1275 settle(simulation.links.filter((link) => link.source !== point).concat(reads));
1276 for (const link of reads) {
1277 if (shared.has(link.target.id)) continue;
1278 pulses.push({ link, at: now });
1279 if (link.target.kind === "output") Object.assign(link.target, { state: event.state, changed: now });
1280 }
1281 }
1282 // a rebuild reuses or keeps nearly every step, often right after one ran, so that only ends a check
1283 if (event.state !== "reused" && event.state !== "kept") {
1284 point.state = event.state;
1285 point.changed = now;
1286 } else if (point.state === "checking" || point.state === "running" || now - point.changed > 5 * fade) {
1287 point.state = null;
1288 point.changed = now;
1289 }
1290 }
1291 simulation.tick();
1292 paint(now);
1293 frame = requestAnimationFrame(draw);
1294}
1295
1296function paint(now: number) {
1297 const { width, height } = canvas.getBoundingClientRect();
1298 // an empty glow canvas throws when drawn, and an empty canvas shows nothing anyway
1299 if (!width || !height) return;
1300 const scale = devicePixelRatio;
1301 if (canvas.width !== Math.round(width * scale) || canvas.height !== Math.round(height * scale)) {
1302 canvas.width = Math.round(width * scale);
1303 canvas.height = Math.round(height * scale);
1304 glow.width = Math.ceil(width / 4);
1305 glow.height = Math.ceil(height / 4);
1306 }
1307
1308 // each point glows faintly far off, so a kind tints where it gathers, and a little brighter beside it
1309 glows.setTransform(1, 0, 0, 1, 0, 0);
1310 glows.clearRect(0, 0, glow.width, glow.height);
1311 glows.setTransform(view.k / 4, 0, 0, view.k / 4, (width / 2 + view.x) / 4, (height / 2 + view.y) / 4);
1312 glows.globalCompositeOperation = "lighter";
1313 glows.globalAlpha = 0.01;
1314 for (const { kind, x, y } of simulation.nodes) glows.drawImage(halos[kind], x - 250, y - 250, 500, 500);
1315 context.setTransform(1, 0, 0, 1, 0, 0);
1316 context.fillStyle = "#000";
1317 context.fillRect(0, 0, canvas.width, canvas.height);
1318 context.drawImage(glow, 0, 0, canvas.width, canvas.height);
1319 const zoom = scale * view.k;
1320 context.setTransform(zoom, 0, 0, zoom, scale * (width / 2 + view.x), scale * (height / 2 + view.y));
1321 context.globalCompositeOperation = "lighter";
1322 context.globalAlpha = 0.1;
1323 for (const { kind, x, y } of simulation.nodes) context.drawImage(halos[kind], x - 30, y - 30, 60, 60);
1324 context.globalCompositeOperation = "source-over";
1325 context.globalAlpha = 1;
1326
1327 const stroke = (links: Iterable<Link>, color: string, width: number) => {
1328 context.lineWidth = width / view.k;
1329 context.strokeStyle = color;
1330 context.beginPath();
1331 for (const { source, target } of links) {
1332 context.moveTo(source.x, source.y);
1333 context.lineTo(target.x, target.y);
1334 }
1335 context.stroke();
1336 };
1337 const touching = simulation.links.filter((link) => link.source === hovered || link.target === hovered);
1338 const near = new Set(touching.flatMap((link) => [link.source, link.target]));
1339 stroke(simulation.links, hovered ? "#ffffff18" : "#ffffff45", 1);
1340 stroke(touching, "#fffc", 1.5);
1341
1342 // what is gone flashes red as it fades
1343 goneLinks = goneLinks.filter(({ at }) => now - at < 5 * fade);
1344 for (const { link, at } of goneLinks) {
1345 context.globalAlpha = Math.exp(-(now - at) / fade);
1346 stroke([link], states.failed, 2.5);
1347 }
1348 // data runs from what was read to the step that read it, each end easing in as if lerped there each frame
1349 pulses = pulses.filter(({ at }) => now - at < 5 * fade);
1350 context.lineWidth = 2.5 / view.k;
1351 context.strokeStyle = "#fff";
1352 for (const { link: { source, target }, at } of pulses) {
1353 const [from, to] = target.kind === "output" ? [source, target] : [target, source];
1354 const head = 1 - Math.exp(-(now - at) / 80);
1355 const tail = 1 - Math.exp(-(now - at) / 240);
1356 const dx = to.x - from.x;
1357 const dy = to.y - from.y;
1358 context.globalAlpha = Math.exp(-(now - at) / fade);
1359 context.beginPath();
1360 context.moveTo(from.x + dx * tail, from.y + dy * tail);
1361 context.lineTo(from.x + dx * head, from.y + dy * head);
1362 context.stroke();
1363 }
1364
1365 for (const point of simulation.nodes) {
1366 const grown = 1 - Math.exp(-(now - point.born) / 60);
1367 const size = Math.max(sizes[point.kind], 1.5 / view.k) * grown;
1368 context.globalAlpha = hovered && !near.has(point) && point !== hovered ? 0.35 : 1;
1369 context.fillStyle = kinds[point.kind];
1370 context.fillRect(point.x - size, point.y - size, size * 2, size * 2);
1371 // a ring holds while a step is checked or run, and for a while after a change, and any other ring dims away
1372 const age = point.state === "checking" || point.state === "running" ? 0 : now - point.changed;
1373 const dimming = point.state === "changed" ? Math.max(0, age - hold) : age;
1374 if (!point.state || dimming > 5 * fade) continue;
1375 const flash = Math.exp(-dimming / fade);
1376 const ring = size + (2 + 6 * (1 - flash)) / view.k;
1377 context.globalAlpha = flash;
1378 context.lineWidth = (point.state === "changed" ? 3 : 2) / view.k;
1379 context.strokeStyle = states[point.state];
1380 context.strokeRect(point.x - ring, point.y - ring, ring * 2, ring * 2);
1381 if (point.state !== "changed") continue;
1382 // a change also ripples out twice, which shows however far out the view is
1383 for (const t of [age, age - 220]) {
1384 if (t < 0 || t > 5 * fade) continue;
1385 const wave = size + (4 + 56 * (1 - Math.exp(-t / 260))) / view.k;
1386 context.globalAlpha = Math.exp(-t / 200);
1387 context.lineWidth = 2 / view.k;
1388 context.strokeRect(point.x - wave, point.y - wave, wave * 2, wave * 2);
1389 }
1390 }
1391 gonePoints = gonePoints.filter(({ at }) => now - at < 5 * fade);
1392 for (const { point, at } of gonePoints) {
1393 const left = Math.exp(-(now - at) / fade);
1394 const size = sizes[point.kind] * left;
1395 const ring = sizes[point.kind] + (10 * (1 - left)) / view.k;
1396 context.globalAlpha = left;
1397 context.fillStyle = states.failed;
1398 context.fillRect(point.x - size, point.y - size, size * 2, size * 2);
1399 context.lineWidth = 2 / view.k;
1400 context.strokeStyle = states.failed;
1401 context.strokeRect(point.x - ring, point.y - ring, ring * 2, ring * 2);
1402 }
1403 context.globalAlpha = 1;
1404
1405 // names go where no other is yet, in screen pixels
1406 context.setTransform(scale, 0, 0, scale, 0, 0);
1407 context.textBaseline = "middle";
1408 context.lineWidth = 3;
1409 context.strokeStyle = "#000";
1410 const named: Array<{ left: number; top: number; right: number; bottom: number }> = [];
1411 const name = (text: string, x: number, y: number, size: number, color: string, align: "left" | "center") => {
1412 context.font = `${size}px Arial, sans-serif`;
1413 const width = context.measureText(text).width;
1414 const left = align === "left" ? x : x - width / 2;
1415 const box = { left, top: y - size / 2, right: left + width, bottom: y + size / 2 };
1416 if (
1417 named.some((other) =>
1418 box.left < other.right && other.left < box.right && box.top < other.bottom && other.top < box.bottom
1419 )
1420 ) return;
1421 named.push(box);
1422 context.textAlign = align;
1423 context.strokeText(text, x, y);
1424 context.fillStyle = color;
1425 context.fillText(text, x, y);
1426 };
1427 const screen = (x: number, y: number) => [width / 2 + view.x + x * view.k, height / 2 + view.y + y * view.k] as const;
1428
1429 // what flashes is named beside it while its ring is bright, a change first, unless the build just made
1430 // it, or ran so much that names would only cover it
1431 const dimming = (point: Point) => now - point.changed - (point.state === "changed" ? hold : 0);
1432 const flashing = simulation.nodes.filter((point) =>
1433 (point.state === "changed" || ran <= 32 && (point.state === "ran" || point.state === "failed"))
1434 && point.born < began && dimming(point) < 3 * fade
1435 );
1436 flashing.sort((a, b) => Number(b.state === "changed") - Number(a.state === "changed") || a.changed - b.changed);
1437 for (const point of flashing) {
1438 const [x, y] = screen(point.x, point.y);
1439 name(nameOf(point), x + sizes[point.kind] * view.k + 8, y, 12, states[point.state!], "left");
1440 }
1441
1442 // then each group that gathers, its points about a link apart for their number, over where it does
1443 const groups = new Map<string, { kind: Kind; name: string; x: number; y: number; squares: number; count: number }>();
1444 for (const { kind, group, x, y } of simulation.nodes) {
1445 const key = `${kind} ${group}`;
1446 const sum = groups.get(key) ?? { kind, name: group, x: 0, y: 0, squares: 0, count: 0 };
1447 groups.set(key, { ...sum, x: sum.x + x, y: sum.y + y, squares: sum.squares + x * x + y * y, count: sum.count + 1 });
1448 }
1449 for (const { kind, name: group, x, y, squares, count } of [...groups.values()].sort((a, b) => b.count - a.count)) {
1450 if (count < 3) break;
1451 const spread = squares / count - (x / count) ** 2 - (y / count) ** 2;
1452 if (spread > linkDistance ** 2 * count) continue;
1453 name(group, ...screen(x / count, y / count), (6 + Math.sqrt(count)) * view.k, kinds[kind], "center");
1454 }
1455}
1456
1457/** a step's function, a row's table, or a file's path, with hashes and long paths cut short */
1458function nameOf(point: Point): string {
1459 const text = point.kind === "step" || point.kind === "lazy" || point.kind === "sqlite" ? point.group : point.label;
1460 const short = text.replace(/[0-9a-f]{16,}/g, (hash) => hash.slice(0, 8) + "…");
1461 return short.length > 44 ? short.slice(0, 26) + "…" + short.slice(-14) : short;
1462}
1463
1464/** where a pointer is, in the graph's coordinates */
1465function toGraph(event: MouseEvent): [number, number] {
1466 const { left, top, width, height } = canvas.getBoundingClientRect();
1467 return [
1468 (event.clientX - left - width / 2 - view.x) / view.k,
1469 (event.clientY - top - height / 2 - view.y) / view.k,
1470 ];
1471}
1472
1473canvas.addEventListener("pointerdown", (event) => {
1474 const [x, y] = toGraph(event);
1475 const point = simulation.find(x, y, 8 / view.k);
1476 dragging = { point, x: event.clientX, y: event.clientY };
1477 canvas.setPointerCapture(event.pointerId);
1478 if (!point) return;
1479 point.fx = x;
1480 point.fy = y;
1481 simulation.alphaTarget = 0.3;
1482});
1483canvas.addEventListener("pointermove", (event) => {
1484 const [x, y] = toGraph(event);
1485 if (dragging?.point) {
1486 dragging.point.fx = x;
1487 dragging.point.fy = y;
1488 } else if (dragging) {
1489 view.x += event.clientX - dragging.x;
1490 view.y += event.clientY - dragging.y;
1491 dragging.x = event.clientX;
1492 dragging.y = event.clientY;
1493 }
1494 hovered = dragging?.point ?? simulation.find(x, y, 8 / view.k);
1495 pointLabel.hidden = !hovered;
1496 if (!hovered) return;
1497 pointLabel.textContent = `${hovered.kind}: ${hovered.label}`;
1498 const { left, top, width, height } = canvas.getBoundingClientRect();
1499 // a label that would run past the canvas goes on the other side of the pointer
1500 const place = (at: number, size: number, room: number) =>
1501 at + 22 + size > room ? Math.max(0, at - 12 - size) : at + 22;
1502 pointLabel.style.left = `${place(event.clientX - left, pointLabel.offsetWidth, width)}px`;
1503 pointLabel.style.top = `${place(event.clientY - top, pointLabel.offsetHeight, height)}px`;
1504});
1505canvas.addEventListener("pointerup", () => {
1506 if (dragging?.point) dragging.point.fx = dragging.point.fy = null;
1507 simulation.alphaTarget = 0;
1508 dragging = null;
1509});
1510canvas.addEventListener("pointerleave", () => {
1511 hovered = null;
1512 pointLabel.hidden = true;
1513});
1514canvas.addEventListener("wheel", (event) => {
1515 event.preventDefault();
1516 const [x, y] = toGraph(event);
1517 const { left, top, width, height } = canvas.getBoundingClientRect();
1518 view.k = Math.min(8, Math.max(0.1, view.k * Math.exp(-event.deltaY * 0.002)));
1519 // the point under the pointer stays under it
1520 view.x = event.clientX - left - width / 2 - x * view.k;
1521 view.y = event.clientY - top - height / 2 - y * view.k;
1522}, { passive: false });
1523
1524function legend() {
1525 const swatch = (color: string, name: string, ring = false) =>
1526 `<span><i style="${ring ? "border:2px solid " : "background:"}${color}"></i>${name}</span>`;
1527 return Object.entries(kinds).map(([name, color]) => swatch(color, name)).join("")
1528 + Object.entries(states).map(([name, color]) => swatch(color, name, true)).join("");
1529}
1530
1531function connect() {
1532 const socket = new WebSocket(socketUrl);
1533 const root = new progress.Root();
1534 let push!: ReadableStreamDefaultController<progress.StreamEvent>;
1535 const decoded = progress.decodeEventStream(
1536 new ReadableStream({ start: (controller) => void (push = controller) }),
1537 root,
1538 );
1539 const detach = progress.attachToDocument(root, tree);
1540
1541 socket.onopen = () => {
1542 connected = true;
1543 retry = 100;
1544 render();
1545 };
1546 socket.onmessage = (event) => {
1547 const message = JSON.parse(event.data) as incremental.DebuggerMessage;
1548 if (message[0] === "progress") return push.enqueue(message[1]);
1549 if (message[0] === "steps") {
1550 ran += message[1].filter((event) => event.state === "ran").length;
1551 return void (frame && sweep.push(...message[1]));
1552 }
1553 // what was asked for by a change is announced, unlike what a page hears when it connects
1554 if (message[0] === "building") {
1555 if (building === null) live.textContent = titles.building, ran = 0;
1556 building ??= performance.now();
1557 began = building;
1558 } else {
1559 status = message[1];
1560 if (building !== null) live.textContent = title(status.state);
1561 loading = reading = null;
1562 for (const file of status.changed) {
1563 const point = points.get(new URL(file, projectUrl || location.href).href);
1564 if (point) point.state = "changed", point.changed = performance.now();
1565 }
1566 building = null;
1567 void check().catch(() => {});
1568 }
1569 // the clover shows once there is something to say, rather than as offline while the page connects
1570 if (!host.isConnected) document.documentElement.append(host);
1571 render();
1572 };
1573 socket.onclose = () => {
1574 decoded.cancel();
1575 push.close();
1576 detach();
1577 connected = false;
1578 building = null;
1579 if (!host.isConnected) document.documentElement.append(host);
1580 render();
1581 setTimeout(connect, retry);
1582 retry = Math.min(retry * 2, 2000);
1583 };
1584}
1585
1586/** reload when what this url serves changed, unless that would lose something */
1587async function check() {
1588 if (shown === null) return;
1589 const page = await serving();
1590 if (page === null) return;
1591 stale = page !== shown;
1592 const media = document.querySelectorAll<HTMLMediaElement>("audio, video");
1593 if (stale && !edited && Array.from(media).every((element) => element.paused)) return location.reload();
1594 render();
1595}
1596
1597/** the hash of what this url serves now */
1598async function serving() {
1599 const response = await fetch(location.href, { headers: { "clover-page": "" }, cache: "no-store" });
1600 return response.headers.get("clover-page");
1601}
1602
1603button.addEventListener("click", () => {
1604 if (open || showing !== null) {
1605 open = false;
1606 showing = null;
1607 quiet = building;
1608 } else {
1609 open = true;
1610 }
1611 render();
1612});
1613// how long ago the last build was ticks while the tip shows, each time the rounded second turns
1614function tick() {
1615 clearTimeout(ticking);
1616 render();
1617 const since = Date.now() - (status?.at ?? Date.now());
1618 ticking = setTimeout(() => button.matches(":hover, :focus-visible") && tick(), 1000 - (since + 500) % 1000);
1619}
1620button.addEventListener("pointerenter", tick);
1621button.addEventListener("focus", tick);
1622// choosing a view keeps the panel open, even one that a build opened
1623// the left edge of the panel is dragged, or moved by the arrow keys, to the width a card is checked at
1624function resize(to: number) {
1625 width = Math.round(Math.min(Math.max(to, 320), innerWidth - 16));
1626 host.style.setProperty("--width", `${width}px`);
1627}
1628grip.addEventListener("pointerdown", (event) => grip.setPointerCapture(event.pointerId));
1629grip.addEventListener("pointermove", (event) => {
1630 if (grip.hasPointerCapture(event.pointerId)) resize(innerWidth - 8 - event.clientX);
1631});
1632grip.addEventListener("keydown", (event) => {
1633 const step = { ArrowLeft: 16, ArrowRight: -16 }[event.key];
1634 if (!step) return;
1635 event.preventDefault();
1636 resize(panel.offsetWidth + (event.shiftKey ? 4 * step : step));
1637});
1638maximize.addEventListener("click", () => {
1639 maximized = !maximized;
1640 open = true;
1641 render();
1642});
1643for (const name of tabs) {
1644 find(`#tab-${name}`).addEventListener("click", () => {
1645 tab = name;
1646 open = true;
1647 render();
1648 });
1649}
1650find("[role=tablist]").addEventListener("keydown", (event) => {
1651 const step = { ArrowLeft: -1, ArrowRight: 1 }[(event as KeyboardEvent).key];
1652 if (!step) return;
1653 tab = UNWRAP(tabs[(tabs.indexOf(tab) + step + tabs.length) % tabs.length]);
1654 open = true;
1655 render();
1656 find(`#tab-${tab}`).focus();
1657});
1658find(".reload").addEventListener("click", () => location.reload());
1659const dismiss = () => {
1660 dismissed = status;
1661 render();
1662};
1663find(".dismiss").addEventListener("click", dismiss);
1664dialog.addEventListener("cancel", (event) => {
1665 event.preventDefault();
1666 dismiss();
1667});
1668shadow.addEventListener("click", (event) => {
1669 const target = event.target as Element;
1670 const file = target.closest<HTMLElement>("[data-open]")?.dataset.open;
1671 if (file) return void fetch("/.clover/open", { method: "POST", body: file });
1672 const summary = target.closest("summary");
1673 if (summary) {
1674 event.preventDefault();
1675 // a click from the keyboard has no `detail`
1676 if ((event as MouseEvent).detail > 0 && !target.closest(".chevron")) return;
1677 const details = summary.parentElement as HTMLDetailsElement;
1678 setOpen(details, !details.matches(unfolded));
1679 } else if (target.closest(".fold")) {
1680 folded = shadow.querySelector(`details.diagnostic${unfolded}`) !== null;
1681 for (const problem of shadow.querySelectorAll<HTMLDetailsElement>("details.diagnostic")) setOpen(problem, !folded);
1682 } else {
1683 return;
1684 }
1685 showFold();
1686});
1687// a problem folded by hand can change what the button does
1688shadow.addEventListener("toggle", showFold, true);
1689// an image does not bubble its error, which the shadow root takes in the capture phase
1690shadow.addEventListener("error", ({ target }) => {
1691 if (target instanceof HTMLImageElement && target.dataset.local && target.src !== target.dataset.local) {
1692 target.src = target.dataset.local;
1693 }
1694}, true);
1695shadow.addEventListener("keydown", (event) => {
1696 if ((event as KeyboardEvent).key !== "Escape" || panel.hidden) return;
1697 open = false;
1698 showing = null;
1699 quiet = building;
1700 button.focus();
1701 render();
1702});
1703for (const type of ["input", "change"]) document.addEventListener(type, () => void (edited = true), true);
1704// a page that moves to another url, like the file viewer, is compared with what that url serves
1705globalThis.navigation?.addEventListener("currententrychange", () => {
1706 if (shown === null) return;
1707 stale = false;
1708 void serving().then((page) => void (shown = page ?? shown), () => {});
1709});
1710
1711// automated browsers, like the one that takes pictures of pages, get the page alone
1712if (!navigator.webdriver) connect();
1713
1714function css() {
1715 return `
1716:host{all:initial}
1717*{box-sizing:border-box}
1718[hidden]{display:none!important}
1719.clover,.panel,.tip{position:fixed;z-index:2147483647}
1720.panel,.tip,dialog{font:13px/1.3 Arial,Helvetica,sans-serif;color:#fff;color-scheme:dark}
1721button{appearance:none;margin:0;min-height:24px;padding:2px 10px;border:2px solid #999;border-radius:0;
1722 background:#444;color:#fff;font:inherit;cursor:pointer}
1723button:hover{background:#555;border-color:#bbb}
1724button:focus-visible{outline:2px solid #0cff10;outline-offset:1px}
1725
1726.clover{top:8px;right:8px;display:grid;place-items:center;width:30px;height:30px;min-height:0;padding:0;
1727 border:1px solid #fffa;background:#0008;--from:#80868f;--to:#cdd2d9}
1728.clover:hover{border-color:#fff;background:#0008}
1729.clover[aria-expanded=true]{border:2px solid #999;background:#222}
1730.clover svg{width:24px;height:24px}
1731.from{stop-color:var(--from)}
1732.to{stop-color:var(--to)}
1733.clover[data-state=ok]{--from:#5bbdfa;--to:#9dffff}
1734.clover[data-state=warnings]{--from:#eda800;--to:#fff27a}
1735.clover[data-state=failed]{--from:#dc2f38;--to:#ff9e8e}
1736.spinner{display:none;width:15px;height:23px}
1737.clover[data-state=building] svg{display:none}
1738.clover[data-state=building] .spinner{display:block}
1739.clover.stale svg{animation:blink 1s step-end infinite}
1740@keyframes blink{50%{opacity:.2}}
1741.live{position:fixed;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}
1742
1743.tip{display:none;top:8px;right:46px;max-width:min(300px,calc(100vw - 54px));padding:5px 8px;border:1px solid #000;
1744 background:#fff;color:#000;line-height:1.2;overflow-wrap:anywhere}
1745/* one stroke over the border's own, so its sides are as wide as the border and join it cleanly */
1746.tip::before{content:"";position:absolute;top:5px;left:100%;width:8px;height:18px;
1747 background:url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='8' height='18'><rect y='2' width='1' height='14' fill='%23fff'/><path d='M.5 0v2l7 7-7 7v2' fill='%23fff' stroke='%23000'/></svg>")}
1748.clover[aria-expanded=false]:is(:hover,:focus-visible)~.tip{display:block}
1749.tip>span{display:block}
1750
1751.panel{top:8px;right:8px;display:flex;flex-direction:column;width:min(var(--width,460px),calc(100vw - 16px));
1752 max-height:calc(100vh - 16px)}
1753.panel.max{left:8px;bottom:8px;width:auto;max-height:none}
1754.grip{position:absolute;left:-3px;top:30px;bottom:0;width:7px;z-index:1;cursor:ew-resize;touch-action:none;pointer-events:auto}
1755.grip:hover,.grip:focus-visible{background:#fff6;outline:0}
1756.panel.max .grip{display:none}
1757/* the tabs end at the clover, which is the last of them */
1758.tabs{display:flex;justify-content:flex-end;padding-right:34px}
1759/* the clover lies under the panel's box, and under the room the tabs leave it */
1760.panel,.tabs{pointer-events:none}
1761.tabs>*,.body{pointer-events:auto}
1762[role=tablist]{display:flex}
1763.tabs button{height:30px;padding:0 10px;margin-right:-2px;background:#222}
1764.tabs [aria-selected=true]{position:relative;z-index:1;padding-bottom:2px;border-bottom:0;background:#000}
1765.tabs .maximize{display:grid;place-items:center;width:30px;margin:0;padding:0}
1766.maximize svg{width:12px;height:12px;fill:none;stroke:#fff;stroke-width:1.5}
1767.maximize[aria-pressed=true] .max,.maximize[aria-pressed=false] .restore{display:none}
1768.body{display:flex;flex-direction:column;gap:10px;flex:1;min-height:0;margin-top:-2px;padding:10px;overflow:auto;
1769 background:#000;border:2px solid #999}
1770.view{display:flex;flex-direction:column;gap:10px}
1771
1772table{width:100%;border-collapse:collapse}
1773th,td{padding:3px 8px;border:2px solid #999;text-align:left;vertical-align:top;font-weight:400}
1774th{width:1%;white-space:nowrap;background:#444}
1775td{background:#222;font-variant-numeric:tabular-nums}
1776.mono,figcaption,.where,.fields,.excerpt pre{font-family:ui-monospace,Menlo,Consolas,monospace}
1777.mono{font-size:12px;overflow-wrap:anywhere}
1778td [data-state=ok]{color:#0cff10}
1779td [data-state=warnings]{color:#fcd330}
1780td [data-state=failed]{color:#ff3b3b}
1781.notice{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:0;padding:4px 4px 4px 10px;
1782 border:2px solid #fcd330;background:color-mix(in srgb,#fcd330 12%,#000)}
1783.empty{margin:0;color:#999}
1784.problems{position:relative}
1785.problems>details+details{margin-top:12px}
1786.diagnostic{min-width:0}
1787.diagnostic>*+*{margin-top:4px}
1788.diagnostic.error{--tone:#ff3b3b}
1789.diagnostic.warning{--tone:#fcd330}
1790.head{margin:0;line-height:1.35;white-space:pre-wrap;overflow-wrap:anywhere}
1791.head b{color:var(--tone)}
1792summary.head{display:block}
1793.note .head b,.note summary b{color:#ddd}
1794.note>summary,.note>.head{color:#bbb}
1795.colon{color:#999}
1796.where{display:none;font-size:12px;line-height:1.4;color:#999;white-space:normal}
1797:is(details:not([open]),.folding)>summary>.where{display:block}
1798/* the first problem leaves room for the button that folds them all */
1799.problems>details:first-of-type>summary{padding-right:26px}
1800.fold{position:absolute;top:-2px;right:-2px;display:grid;place-items:center;width:22px;height:22px;min-height:0;
1801 padding:0;border:0;background:none;color:#999}
1802.fold:hover{background:#333;border:0;color:#fff}
1803.fold svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:1.5}
1804.fold:not(.folded) .unfold{display:none}
1805.from{color:#999}
1806.excerpt{margin:0;background:#161616}
1807figcaption{padding:3px 8px 0;font-size:12px;line-height:1.4;color:#bbb;overflow-wrap:anywhere}
1808.pos{color:#888}
1809figcaption a{color:inherit;text-decoration:none}
1810figcaption a:hover,.path:hover{text-decoration:underline}
1811.path{all:unset;cursor:pointer}
1812.path:hover{background:none}
1813.fn{color:#3ee6ff}
1814.excerpt pre{margin:0;padding:1px 0 3px;overflow-x:auto;font-size:12px;line-height:1.45;color:#e6e6e6;tab-size:2}
1815.line{display:block;padding-right:8px;white-space:pre}
1816.before{mask-image:linear-gradient(#0003,#000b)}
1817.after{mask-image:linear-gradient(#000b,#0003)}
1818.hit{padding-bottom:2px}
1819.n{display:inline-block;box-sizing:content-box;margin-right:10px;padding-left:8px;text-align:right;color:#666;
1820 user-select:none}
1821.mark{color:var(--tone);font-weight:700;text-decoration:underline 2px var(--tone);text-underline-offset:4px;
1822 text-decoration-skip-ink:none}
1823.mark span{color:inherit}
1824.t-k{color:#ff9de2}
1825.t-l,.t-n{color:#ffb86c}
1826.t-s{color:#9ef09e}
1827.t-r{color:#3ee6ff}
1828.t-c{color:#8a8a8a}
1829.internal{opacity:.55}
1830.fields{margin:0;font-size:12px;line-height:1.5}
1831.fields div{display:flex;gap:6px}
1832.fields dt{color:#999}
1833.fields dt::after{content:":"}
1834.fields dd{margin:0;overflow-wrap:anywhere}
1835summary{list-style:none;line-height:1.35}
1836summary::-webkit-details-marker{display:none}
1837.chevron{display:inline-block;width:14px;color:#999;cursor:pointer;user-select:none}
1838.chevron:hover{color:#fff}
1839.chevron svg{width:10px;height:10px;vertical-align:-1px;fill:none;stroke:currentColor;stroke-width:1.5;
1840 transition:rotate ${easeMs}ms ${ease}}
1841${unfolded}>summary>.chevron svg{rotate:90deg}
1842.frames{display:flex;flex-direction:column;gap:4px;margin-top:4px}
1843.nested{padding-left:10px;border-left:2px solid #333}
1844.similar{margin:4px 0 0;padding-left:30px;font-size:12px;line-height:1.45}
1845
1846dialog{inset:0;width:auto;height:auto;max-width:none;max-height:none;margin:0;
1847 padding:12px max(16px,calc(50vw - 340px)) 24px;border:0;overflow:auto;background:#000;font-size:14px;line-height:1.4}
1848dialog:focus{outline:0}
1849dialog::backdrop{background:#000}
1850.top{display:flex;align-items:baseline;justify-content:space-between;gap:12px;margin-bottom:10px}
1851.dismiss{min-height:0;padding:0;border:0;background:none;color:#999}
1852.dismiss:hover{background:none;border:0;color:#fff;text-decoration:underline}
1853dialog h2{margin:0;font-size:22px;font-weight:400;color:#ff3b3b}
1854dialog .slot>div{margin-bottom:12px}
1855dialog .excerpt pre,dialog figcaption,dialog .fields{font-size:13px}
1856
1857#view-graph{position:relative}
1858canvas{display:block;width:100%;height:min(60vh,480px);cursor:grab;touch-action:none}
1859.panel.max canvas{height:calc(100vh - 48px)}
1860.legend{position:absolute;left:0;bottom:0;display:flex;flex-wrap:wrap;gap:2px 10px;padding:4px 6px;
1861 background:#000c;font-size:11px;color:#ccc;pointer-events:none}
1862.legend i{display:inline-block;box-sizing:border-box;width:9px;height:9px;margin-right:4px;vertical-align:-1px}
1863.point{position:absolute;width:max-content;max-width:320px;padding:4px 6px;background:#fff;color:#000;font-size:12px;
1864 line-height:1.2;overflow-wrap:anywhere;pointer-events:none}
1865/* a build's progress floats over the graph, which shows through */
1866.panel[data-tab=graph] .body{position:relative;padding:0}
1867.panel[data-tab=graph] .slot{position:absolute;top:10px;left:10px;right:10px;z-index:1;max-height:45%;
1868 overflow:hidden;padding:8px 10px;background:#000c;border:2px solid #999}
1869
1870.cards{display:flex;flex-direction:column;gap:14px}
1871.preview img{display:block;background:#0003}
1872.notes{margin:6px 0 0;padding-left:18px;font-size:12px;line-height:1.45;color:#fcd330}
1873/* the colors of a message in Discord's dark theme, sampled from what it draws */
1874.chat{--text:#f3f3f4;--link:#76aff6;--card:#383a41;--line:#43454c;--bar:#4b4d54;display:grid;gap:4px;padding:12px 16px;
1875 background:#31333a;color:var(--text);font:14px/1.375 "gg sans vf","gg sans","Noto Sans","Helvetica Neue",Helvetica,Arial,sans-serif;
1876 overflow-wrap:anywhere}
1877.discord{--accent:var(--bar);display:grid;gap:8px;width:fit-content;max-width:432px;padding:8px 16px 16px 12px;
1878 border:1px solid var(--line);border-left:4px solid var(--accent);border-radius:4px;background:var(--card)}
1879.d-site{font-size:12px;color:#b5bac1}
1880.d-title{font-size:16px;font-weight:600;line-height:24px;color:var(--link)}
1881.d-desc{line-height:1.25;white-space:pre-wrap}
1882.d-split{display:flex;justify-content:space-between;gap:16px}
1883.d-split>div{display:grid;gap:8px;align-content:start;min-width:0}
1884.d-small{width:80px;height:80px;flex:none;margin-top:2px;border-radius:4px;object-fit:cover}
1885.d-big{width:100%;max-height:300px;border-radius:4px;object-fit:cover}
1886.d-frame{position:relative}
1887.d-frame img{width:100%;max-height:300px;border-radius:4px;object-fit:cover}
1888.play{position:absolute;inset:0;margin:auto;width:48px;height:48px;border-radius:50%;background:#000a}
1889.play::after{content:"";position:absolute;left:19px;top:14px;border:10px solid transparent;border-left:16px solid #fff}
1890.d-gallery{display:grid;grid-template-columns:repeat(6,1fr);gap:4px;width:448px;max-width:100%;overflow:hidden;border-radius:8px}
1891.d-cell{position:relative;grid-column:span 2;aspect-ratio:1;min-height:0;overflow:hidden;border-radius:4px}
1892.d-cell img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
1893.n1>.d-cell{grid-column:span 6;aspect-ratio:auto}
1894.n1 img{position:static;height:auto;max-height:350px}
1895.n2>.d-cell,.n5>.d-cell:nth-child(-n+2),.n8>.d-cell:nth-child(-n+2){grid-column:span 3}
1896.n7>.d-cell:first-child,.n10>.d-cell:first-child{grid-column:span 6;aspect-ratio:1.69}
1897.n3,.n4{aspect-ratio:1.71;grid-template-columns:repeat(2,1fr);grid-template-rows:repeat(2,1fr)}
1898.n3>.d-cell,.n4>.d-cell{grid-column:auto;aspect-ratio:auto}
1899.n3{grid-template-columns:2fr 1fr}
1900.n3>:first-child{grid-row:span 2}
1901/* the images of a link are as wide as its card, and lay out differently from a gallery of components */
1902.discord .d-gallery{width:398px}
1903.discord>.d-big,.discord>.d-gallery,.discord>.d-frame{margin-top:8px}
1904.discord .n3,.discord .n4{aspect-ratio:1.33;grid-template-columns:repeat(2,1fr)}
1905.d-container{--accent:var(--bar);position:relative;display:grid;gap:8px;justify-self:start;width:fit-content;max-width:min(100%,482px);
1906 box-sizing:border-box;padding:16px;border:1px solid var(--line);border-radius:8px;background:var(--card)}
1907.d-container.accent::before{content:"";position:absolute;left:-1px;top:-1px;bottom:-1px;width:4px;border-radius:8px 0 0 8px;
1908 background:var(--accent)}
1909.d-section{display:flex;justify-content:space-between;gap:16px}
1910.d-section>:first-child{display:flex;flex-direction:column;justify-content:center;min-width:0}
1911.d-section:has(.d-thumb)>:first-child{justify-content:flex-start}
1912.d-section>:not(:first-child){align-self:flex-start}
1913.d-thumb{width:85px;height:85px;flex:none;border-radius:8px}
1914.d-thumb img{width:100%;height:100%;border-radius:8px;object-fit:cover}
1915.d-row{display:flex;flex-wrap:wrap;gap:8px}
1916.d-button{display:inline-flex;align-items:center;gap:7px;box-sizing:border-box;height:32px;padding:0 12px;border:1px solid #46484f;
1917 border-radius:8px;background:#43454c;color:#fff;font-size:14px;font-weight:500;white-space:nowrap}
1918.d-button.disabled{opacity:.5}
1919.d-button svg{width:18px;height:18px;margin-right:-2px;fill:none;stroke:currentColor;stroke-width:1.8}
1920.emoji{font-size:18px;line-height:1;margin-right:-1px}
1921.d-sep{width:100%;margin:0;border:0;border-top:1px solid #4b4d54}
1922.d-sep.large{margin:8px 0}
1923.d-sep.blank{border-color:transparent}
1924.spoiler{position:relative}
1925.spoiler::before{content:"";position:absolute;inset:0;z-index:1;border-radius:inherit;backdrop-filter:blur(24px) saturate(.5);
1926 background:#80808c8c;pointer-events:none}
1927.spoiler::after{content:"SPOILER";z-index:2;white-space:nowrap;position:absolute;left:50%;top:50%;translate:-50% -50%;padding:7px 12px;border-radius:999px;
1928 background:#282026d1;color:#e4e4e6;font:700 15px/1 "gg sans vf","gg sans",Arial,sans-serif;letter-spacing:.05em;pointer-events:none}
1929.d-text{font-size:14px;line-height:1.375}
1930.d-text>*{min-height:1.375em}
1931.h1,.h2,.h3{margin:16px 0 8px;font-weight:700}
1932.h1{font-size:24px}
1933.h2{font-size:20px}
1934.h3{font-size:16px}
1935.d-text>:first-child{margin-top:0}
1936.link{color:var(--link)}
1937.sub{font-size:12px;color:#b5bac1}
1938.d-text>div:not(.li,.quote)+:is(.li,.quote){margin-top:2px}
1939.li,.quote{position:relative;padding:2px 0 2px 16px}
1940.li::before{content:"";position:absolute;left:3px;top:.62em;width:5px;height:5px;border-radius:50%;background:currentColor}
1941.li.number::before{content:attr(data-n);top:2px;left:0;width:auto;height:auto;border-radius:0;background:none}
1942.quote::before{content:"";position:absolute;left:0;top:2px;bottom:2px;width:4px;border-radius:2px;background:#585a63}
1943.d-text code{padding:0 3px;border:1px solid #4e505e;border-radius:4px;background:#3b3d4e;font:85% ui-monospace,Menlo,Consolas,monospace}
1944.d-text pre{margin:2px 0 19px;padding:7px 8px;border:1px solid #4e505e;border-radius:4px;background:#3d3d4e;
1945 font:14px/18px ui-monospace,Menlo,Consolas,monospace;overflow:auto}
1946.hidden{border-radius:3px;background:#7c7e87;color:transparent}
1947/* a tweet in the dark theme, sampled from what Twitter draws */
1948.tweet{display:grid;gap:4px;padding:12px 16px;background:#000;color:#e7e9ea;font:15px/1.3 system-ui,Arial,sans-serif;
1949 overflow-wrap:anywhere}
1950.x-card{overflow:hidden;border:1px solid #2f3336;border-radius:16px}
1951.x-summary{display:flex}
1952.x-summary>img,.x-blank{width:130px;height:130px;flex:none;border-right:1px solid #2f3336}
1953.x-summary>img{object-fit:cover}
1954.x-blank{display:grid;place-items:center;background:#17181c;color:#71767b}
1955.x-blank svg{width:26px;height:26px;fill:none;stroke:currentColor;stroke-width:2}
1956.x-text{display:grid;gap:2px;align-content:center;min-width:0;padding:12px}
1957.x-domain{font-size:15px;color:#71767b}
1958.x-desc{display:-webkit-box;overflow:hidden;color:#71767b;-webkit-box-orient:vertical;-webkit-line-clamp:2}
1959.x-image{position:relative}
1960.x-image img{width:100%;aspect-ratio:1.91;object-fit:cover}
1961.x-over{position:absolute;left:12px;bottom:12px;max-width:calc(100% - 24px);padding:1px 6px;border-radius:4px;
1962 background:#000c;color:#fff;font-size:13px}
1963
1964@media (prefers-reduced-motion:reduce){.clover.stale svg{animation:none}.chevron svg{transition:none}}
1965`;
1966}
1967
1968/** clover's icon, whose fill is colored by the state of the build */
1969function clover() {
1970 return `<svg viewBox="0 0 128 128" aria-hidden=true>
1971 <linearGradient id=clover-fill x1=27.8421 y1=26.3816 x2=96.4874 y2=102.044 gradientUnits=userSpaceOnUse>
1972 <stop class=from /><stop offset=1 class=to />
1973 </linearGradient>
1974 <path fill=#000 d="M48.4615 61.1835L47.535 65.3309C49.8166 65.8405 52.0814 64.4121 52.6042 62.1339C53.127 59.8557 51.7115 57.5829 49.436 57.047L48.4615 61.1835ZM30.6697 23.8163L33.526 26.9634L30.6697 23.8163ZM52.9493 30.5395L48.7022 30.7057C48.7907 32.9656 50.6341 34.7604 52.8959 34.7888C55.1578 34.8173 57.0457 33.0694 57.1909 30.8124L52.9493 30.5395ZM72.1556 9.8294L73.6118 5.83697L72.1556 9.8294ZM71.3151 55.2579L68.012 52.5834C66.5717 54.3617 66.7982 56.9609 68.5244 58.4633C70.2506 59.9657 72.8567 59.8318 74.4197 58.1604L71.3151 55.2579ZM109.211 62.3987L108.137 58.2869C106.242 58.7817 104.93 60.5083 104.961 62.4671C104.993 64.426 106.36 66.1094 108.271 66.543L109.211 62.3987ZM113.502 84.3619L116.574 87.2997C116.599 87.2727 116.625 87.2454 116.65 87.2178L113.502 84.3619ZM67.5719 77.4622L69.9547 73.9432C68.7858 73.1519 67.3001 72.9925 65.9899 73.5179C64.6797 74.0432 63.7158 75.1846 63.4175 76.5642L67.5719 77.4622ZM89.3757 115.881L93.564 116.604C93.8709 114.828 93.0234 113.051 91.4495 112.172L89.3757 115.881ZM26.6675 93.5918L30.1359 96.0483C31.2567 94.4663 31.1646 92.3264 29.9119 90.8465C28.6592 89.3666 26.5636 88.922 24.8178 89.7657L26.6675 93.5918ZM36.9708 113.188L36.7974 108.942V108.942L36.9708 113.188ZM89.0962 117.499L86.4033 120.787C87.5731 121.745 89.1639 122.009 90.5808 121.481C91.9976 120.953 93.0272 119.712 93.2846 118.222L89.0962 117.499ZM48.4615 61.1835L49.3881 57.036C34.8729 53.7943 28.8667 48.0882 27.2049 43.2149C25.5853 38.4655 27.4464 32.4792 33.526 26.9634L30.6697 23.8163L27.8135 20.6691C20.3416 27.4481 16.0294 36.7798 19.159 45.9575C22.2463 55.0114 31.9116 61.8416 47.535 65.3309L48.4615 61.1835ZM30.6697 23.8163L33.526 26.9634C38.2853 22.6455 42.1719 22.2251 44.3513 22.9573C46.3805 23.6391 48.5129 25.8703 48.7022 30.7057L52.9493 30.5395L57.1964 30.3734C56.9104 23.0677 53.3348 17.0093 47.0589 14.9007C40.9331 12.8426 33.9176 15.1311 27.8135 20.6691L30.6697 23.8163ZM52.9493 30.5395L57.1909 30.8124C57.4228 27.2089 58.1343 21.3687 60.3679 17.2431C61.4444 15.2549 62.6821 14.0267 64.0473 13.4362C65.3409 12.8767 67.3858 12.6136 70.6994 13.8218L72.1556 9.8294L73.6118 5.83697C68.7937 4.08015 64.4308 4.00977 60.6721 5.63551C56.9849 7.2303 54.5257 10.1799 52.8922 13.197C49.7061 19.0818 48.9461 26.5618 48.7077 30.2666L52.9493 30.5395ZM72.1556 9.8294L70.6994 13.8218C74.6175 15.2505 76.5735 17.5698 77.5408 20.303C78.5836 23.2496 78.5942 27.0553 77.7192 31.3586C75.9604 40.0094 70.997 48.898 68.012 52.5834L71.3151 55.2579L74.6182 57.9324C78.3682 53.3026 83.9897 43.1832 86.0496 33.0518C87.084 27.964 87.3125 22.4349 85.5546 17.468C83.7213 12.2877 79.8583 8.11465 73.6118 5.83697L72.1556 9.8294ZM71.3151 55.2579L74.4197 58.1604C79.6116 52.6085 85.5009 45.6475 92.1894 41.2758C95.4581 39.1394 98.6274 37.8332 101.692 37.5654C104.652 37.3067 107.825 37.9855 111.292 40.3746L113.704 36.8757L116.116 33.3768C111.108 29.925 105.982 28.6587 100.951 29.0984C96.0247 29.529 91.5112 31.5648 87.538 34.1617C79.7428 39.2567 72.9124 47.3276 68.2104 52.3555L71.3151 55.2579ZM113.704 36.8757L111.292 40.3746C114.973 42.9118 116.219 45.1099 116.587 46.6386C116.952 48.1516 116.637 49.7621 115.636 51.5142C114.615 53.2998 113.014 54.9694 111.361 56.2762C110.55 56.9172 109.782 57.4275 109.149 57.7887C108.456 58.1843 108.117 58.2922 108.137 58.2869L109.211 62.3987L110.285 66.5105C112.136 66.0273 114.53 64.6064 116.634 62.9428C118.85 61.1906 121.299 58.7355 123.016 55.7321C124.752 52.6951 125.864 48.8524 124.852 44.6491C123.843 40.4615 120.91 36.6804 116.116 33.3768L113.704 36.8757ZM109.211 62.3987L108.271 66.543C108.252 66.5388 108.311 66.5514 108.45 66.6057C108.583 66.6577 108.76 66.7359 108.972 66.8459C109.4 67.0672 109.913 67.3856 110.452 67.7995C111.548 68.6416 112.578 69.7458 113.243 71.0017C113.882 72.2074 114.192 73.5516 113.94 75.0984C113.684 76.6788 112.78 78.8344 110.355 81.5061L113.502 84.3619L116.65 87.2178C119.893 83.6452 121.75 80.0384 122.331 76.4614C122.918 72.8509 122.142 69.6427 120.755 67.024C119.395 64.4554 117.458 62.4631 115.631 61.0595C113.875 59.7108 111.878 58.6461 110.152 58.2544L109.211 62.3987ZM113.502 84.3619L110.431 81.4242C106.849 85.1683 102.872 87.0534 97.0865 86.4584C90.8845 85.8207 82.2948 82.2963 69.9547 73.9432L67.5719 77.4622L65.1891 80.9812C77.8805 89.5722 87.8931 94.0572 96.217 94.9131C104.957 95.8119 111.43 92.6748 116.574 87.2997L113.502 84.3619ZM67.5719 77.4622L63.4231 78.3857C64.5022 83.2313 66.2315 91.1083 69.7102 98.8766C73.1843 106.634 78.5921 114.723 87.3018 119.59L89.3757 115.881L91.4495 112.172C84.9653 108.548 80.5558 102.297 77.4687 95.4034C74.3864 88.5205 72.8108 81.434 71.7207 76.5387L67.5719 77.4622ZM48.4615 61.1835L49.436 57.047C42.1013 55.3196 32.3642 54.2966 23.8216 56.6683C19.4883 57.8713 15.3188 59.9895 11.9906 63.4685C8.63535 66.9759 6.36305 71.6301 5.48403 77.5003L9.68754 78.1296L13.891 78.7589C14.5403 74.4234 16.1249 71.4433 18.1338 69.3434C20.1698 67.2151 22.8718 65.7528 26.0961 64.8577C32.6684 63.033 40.7901 63.7427 47.4871 65.3199L48.4615 61.1835ZM9.68754 78.1296L5.48403 77.5003C4.66493 82.9705 4.84593 87.4473 6.0519 90.9953C7.30706 94.6879 9.64023 97.2429 12.6522 98.631C15.5182 99.9518 18.6053 100.039 21.2496 99.6683C23.921 99.2939 26.4647 98.4099 28.5172 97.4179L26.6675 93.5918L24.8178 89.7657C23.4035 90.4491 21.7093 91.0215 20.0694 91.2513C18.4024 91.485 17.1047 91.3243 16.2104 90.9122C15.462 90.5673 14.6592 89.9042 14.1005 88.2605C13.4926 86.4722 13.1819 83.4945 13.891 78.7589L9.68754 78.1296ZM26.6675 93.5918L23.1992 91.1353C20.6353 94.7542 18.7127 101.061 20.0886 106.743C20.8166 109.75 22.5046 112.675 25.5625 114.725C28.5654 116.738 32.4663 117.625 37.1441 117.434L36.9708 113.188L36.7974 108.942C33.3302 109.083 31.3739 108.388 30.2965 107.666C29.2743 106.981 28.6591 106.017 28.3507 104.744C27.6536 101.864 28.7244 98.0405 30.1359 96.0483L26.6675 93.5918ZM36.9708 113.188L37.1441 117.434C42.1815 117.229 46.7299 115.026 50.5992 112.066C54.4752 109.101 57.9019 105.203 60.7821 101.158C66.4898 93.1433 70.5402 83.8459 71.7263 78.3602L67.5719 77.4622L63.4175 76.5642C62.5243 80.6952 59.045 88.9437 53.8572 96.2288C51.2897 99.8343 48.4273 103.025 45.4335 105.316C42.433 107.611 39.5308 108.83 36.7974 108.942L36.9708 113.188ZM67.5719 77.4622L63.5174 78.7372C67.0304 89.9045 68.8832 106.441 86.4033 120.787L89.0962 117.499L91.7892 114.211C76.7482 101.896 75.5695 88.7218 71.6265 76.1872L67.5719 77.4622ZM89.0962 117.499L93.2846 118.222L93.564 116.604L89.3757 115.881L85.1873 115.158L84.9079 116.776L89.0962 117.499Z" />
1975 <path fill="url(#clover-fill)" d="M47.6525 60.9984C18.3025 54.1218 17.2406 36 30.6697 23.8163C41.5332 13.9602 52.474 18.3985 52.9493 30.5395C53.4196 23.2312 55.8923 3.89927 72.1556 9.8294C92.4847 17.2421 78.0501 46.9427 71.3151 55.2579C81.2089 44.6781 96.7546 25.194 113.704 36.8757C130.653 48.5573 113.243 61.3462 109.211 62.3987C112.922 63.2408 124.837 71.8732 113.502 84.3619C104.777 93.4811 92.6034 94.4063 67.5719 77.4622C69.9446 85.0046 71.4211 93.7638 76.3781 102.572C79.4981 107.874 83.6818 112.699 89.3757 115.881L89.0962 117.499C83.1772 112.652 79.2098 107.604 76.3781 102.572C71.2061 93.7839 68.9573 83.6842 67.5983 77.5808L67.5719 77.4622C65.4927 87.0789 52.5123 112.554 36.9708 113.188C20.6808 113.853 22.6922 99.2029 26.6675 93.5918C19.734 96.9425 6.6311 98.5412 9.68755 78.1296C12.6858 58.1065 33.6114 57.8801 47.6525 60.9984Z" />
1976 <path fill=#fff d="M61.5683 7.70693C64.6721 6.36448 68.4194 6.34704 72.8377 7.95803C78.4655 10.0101 81.822 13.6905 83.4253 18.2209C84.9932 22.6513 84.8283 27.7225 83.8362 32.602C83.1517 35.9688 82.0523 39.3417 80.7608 42.4955C83.2729 40.1358 85.9589 37.891 88.7741 36.051C92.5601 33.5765 96.7168 31.7349 101.149 31.3476C105.629 30.956 110.236 32.0661 114.834 35.2354C119.332 38.3354 121.817 41.6962 122.656 45.1777C123.496 48.6664 122.596 51.9159 121.055 54.6115C119.523 57.2915 117.299 59.5384 115.233 61.1723C114.688 61.6029 114.136 62.0035 113.595 62.3676C113.815 62.5214 114.036 62.6823 114.254 62.8501C115.888 64.1045 117.584 65.8607 118.76 68.0806C119.948 70.3239 120.6 73.0369 120.102 76.0991C119.607 79.1459 118.003 82.3677 114.978 85.7011C114.966 85.714 114.953 85.7269 114.941 85.7395C110.213 90.681 104.403 93.4854 96.4482 92.6675C89.6435 91.9678 81.3977 88.6287 70.9762 82.0674C72.694 88.3469 74.3383 94.8737 78.0952 101.562L78.6679 102.51C81.5916 107.215 85.3783 111.364 90.3471 114.142C91.0848 114.554 91.4828 115.387 91.3391 116.22L91.0589 117.838C90.9383 118.536 90.4561 119.118 89.792 119.366C89.128 119.613 88.3824 119.489 87.8341 119.04C81.7308 114.043 77.609 108.813 74.6607 103.583L74.1679 102.726C70.7723 96.6952 68.6672 90.1784 67.2554 84.7724C65.3529 89.4079 62.4867 94.8711 58.9422 99.8487C56.145 103.777 52.8688 107.488 49.2271 110.273C45.5886 113.057 41.4772 114.998 37.052 115.178C32.6959 115.356 29.3115 114.521 26.8202 112.851C24.3031 111.163 22.9005 108.759 22.2838 106.212C21.5522 103.19 21.9034 99.9029 22.8037 97.0763C22.1908 97.2224 21.5663 97.3438 20.936 97.4322C18.5513 97.7664 15.9393 97.6607 13.5971 96.5813C11.1866 95.4704 9.26032 93.417 8.19015 90.2686C7.14315 87.1881 6.92723 83.1097 7.717 77.835C8.51928 72.4773 10.5455 68.3231 13.4539 65.2075C16.3513 62.1036 20.0243 60.1363 23.9658 58.9746C26.7592 58.1513 29.7185 57.7244 32.6951 57.5863C26.5793 54.1602 22.8016 49.8458 21.2255 45.0158C18.6343 37.0743 22.293 28.7267 29.3312 22.3412C35.0781 17.1273 41.2623 15.3343 46.3395 17.0401C48.7744 17.8582 50.7713 19.4182 52.2279 21.5381C52.8122 19.0746 53.6545 16.5316 54.8779 14.2718C56.3634 11.5281 58.4981 9.03495 61.5683 7.70693ZM71.4732 11.7006C67.76 10.3467 65.0992 10.5217 63.1507 11.3645C61.1686 12.2217 59.6062 13.9071 58.3819 16.1685C55.8954 20.7612 55.1707 27.0364 54.937 30.6669C54.869 31.725 53.9843 32.5448 52.9241 32.5315C51.864 32.518 51.0004 31.6765 50.9589 30.6171C50.7438 25.126 48.2279 21.8778 45.0705 20.817C41.8427 19.7326 37.1246 20.6502 32.0082 25.2921C25.6178 31.0901 23.0931 37.8949 25.0127 43.779C26.9468 49.7068 33.6928 55.677 48.0847 59.0535L48.5008 59.1489C48.6319 59.1789 48.7638 59.2097 48.8961 59.2392H48.8951C48.9027 59.241 48.9103 59.2426 48.9179 59.2444C49.9844 59.4956 50.6487 60.5609 50.4038 61.6288C50.1588 62.6967 49.0969 63.3667 48.0277 63.1281C47.9685 63.1149 47.9092 63.101 47.8502 63.0877C47.642 63.0392 47.4321 62.9904 47.2204 62.9434C40.3491 61.4175 31.9904 60.7642 25.0926 62.7971C21.673 63.8051 18.6745 65.4536 16.3664 67.926C14.0692 70.3869 12.3547 73.7707 11.6578 78.4244C10.9195 83.3551 11.1961 86.7315 11.9629 88.9871C12.7065 91.1746 13.9159 92.3402 15.2655 92.9622C16.6836 93.6156 18.4565 93.7572 20.383 93.4872C22.2968 93.219 24.2165 92.5633 25.8003 91.798C26.6186 91.4025 27.6017 91.6116 28.1888 92.3054C28.7755 92.9992 28.8178 94.0023 28.2926 94.7437C26.5752 97.1681 25.2789 101.651 26.1562 105.274C26.576 107.008 27.4757 108.493 29.0386 109.541C30.6274 110.606 33.1005 111.352 36.8891 111.198C40.2346 111.061 43.5751 109.581 46.8064 107.109C50.0345 104.639 53.0461 101.26 55.6966 97.538C61.0223 90.0591 64.6532 81.5321 65.6243 77.0413L65.6917 76.8047C65.8801 76.2657 66.2928 75.8292 66.83 75.6135C67.444 75.3673 68.1404 75.4419 68.6883 75.8128C81.1217 84.2291 90.0902 88.0082 96.856 88.7039C103.413 89.378 108.046 87.1707 112.037 83.0106C114.672 80.1045 115.827 77.5678 116.17 75.46C116.51 73.3653 116.076 71.526 115.239 69.9451C114.389 68.3406 113.118 67.0008 111.827 66.0095C110.504 64.9928 109.325 64.4669 108.771 64.3411C107.875 64.1379 107.234 63.3491 107.22 62.4309C107.205 61.5126 107.82 60.7028 108.708 60.4708C109.322 60.3106 110.908 59.5132 112.762 58.047C114.565 56.6219 116.391 54.7429 117.597 52.6339C118.793 50.5408 119.319 48.3377 118.782 46.1105C118.244 43.8757 116.55 41.2571 112.574 38.5163C108.698 35.845 105.005 35.0096 101.495 35.3164C97.9361 35.6274 94.4098 37.1273 90.9541 39.3858C83.9718 43.9495 77.8319 51.2056 72.7702 56.6182C72.0376 57.4017 70.8161 57.4647 70.0071 56.7604C69.1981 56.056 69.0923 54.8371 69.7674 54.0035C72.9557 50.067 78.093 40.8519 79.9317 31.8082C80.849 27.2966 80.9019 23.0332 79.6692 19.5501C78.4719 16.167 76.0098 13.3548 71.4732 11.7006Z" />
1977</svg>`;
1978}
1979
1980import { UNWRAP } from "../assert.ts";
1981import type * as incremental from "../incremental.ts";
1982import type * as stack from "../log/stack.ts";
1983import * as meta from "../meta.ts";
1984import * as progress from "../progress.ts";
1985import * as string from "../string.ts";