Public: anyone can read this; the crew can change it.

A fantastic component library: a living gallery, the missing parts (search picker first), a drift gate, and a cold-read UI audit #5888

Parked opened this in answer to
Closed without merging

mason/forge:mason/5817-a-fantastic-component-library-a-living-g → main 8 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +982 −6
docs/DEVELOP.md +11
@@ -5,6 +5,7 @@ Moved from README.md (its "## Develop" section), unchanged.
55 ```sh
66 bun test # protocol-level + adversarial suite
77 bun scripts/design-lint.ts # no colour or off-scale font-size beyond docs/design/baseline.json, no class docs/DESIGN.md §5 does not name
8 bun scripts/design-drift.ts # warning: markup a ui.ts part already draws, typed by hand (--all lists each file:line)
89 bun scripts/cold-read.ts <url> [--repo owner/name] [--write [--allow-text-only]] [--file-issues N [--file-into owner/name]] # cold-read audit (#5882): a no-context model reads the top pages (signed in with FORGE_TOKEN, sent only to FORGE_URL's forge; the signed-in pages go to the model endpoint, so use a throwaway account) at 390 and 1440 px; needs ANTHROPIC_API_KEY
910 bun x tsc --noEmit # zero type errors is the standard
1011 bun run check # exactly what the forge runs against every push
@@ -20,6 +21,16 @@ name; the message names the file or the class. The way out is to use a token
2021 --update` and commit the baseline; when it deletes the last rule for a class
2122 in the §5d register, strike the name there too. See `docs/design/plan.md`.
2223
24 The drift gate (`scripts/design-drift.ts`, #5817) runs in the check right
25 after the gate-list audit and never fails it: it counts the places a page
26 types a part's markup instead of calling the part in `src/web/ui.ts` (a
27 `<button class="btn">` for `btn()`, a `<ul class="list">` for `listCard()`,
28 a bare `<select>` for `selectField()` or `searchPicker()`, a page-local
29 `.x-empty`), and prints the count against `drift` in
30 `docs/design/baseline.json` with the files that hold the most. A pull that
31 pays some off runs `bun scripts/design-drift.ts --update` to write the lower
32 number down; once the count is driven low it becomes a refusal like the lint.
33
2334 `docs/DESIGN.md` is a spine: each of its sections is its own file under
2435 `docs/design/sections/` (§5d is `5d-page-local-classes.md`), linked from the
2536 spine in order, and the check reads them in that order. A new section is a
docs/design/audit.md +2 −1
@@ -33,7 +33,7 @@ their own vocabulary instead of composing the named one.
3333
3434 ## Finding 2 — the pages, and what each is for
3535
36 There are 62 top-level pages, one entry each: every static `GET` route in `src/http/server.ts`
36 There are 63 top-level pages, one entry each: every static `GET` route in `src/http/server.ts`
3737 that returns a page (`test/design-audit.test.ts` holds this list to the router,
3838 both ways). Each entry reads `route` — module · what it is for · what
3939 duplicates it · what breaks `docs/DESIGN.md`. "Breaks" counts colour literals
@@ -55,6 +55,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
5555 - `/big` — `pages/board.ts` (`bigRedirect`) · a redirect kept for old addresses into the board's wall mode · it is `/board` · none (no page of its own).
5656 - `/boards` — `pages/boards-view.ts` · saved queries as panels · `/board` · none seen.
5757 - `/boards/data` — `pages/boards.ts` · the boards' query/data surface · `/board` · none seen.
58 - `/design/components` — `pages/design_components.ts` · the living gallery: every part of `ui.ts` in each state, theme and width (#5817) · none · none seen.
5859 - `/asks` — `studio/asks_page.ts` · what the crew is waiting on me for · `/` "needs me" list · colours 2.
5960 - `/asked` — `studio/asked_page.ts` · what I answered, as a record · `/asks` · none seen.
6061 - `/review` — `studio/review_page.ts` · every ask waiting on me, one row each, newest first · `/asks` (same asks, with buttons) · none seen.
docs/design/baseline.json +2 −1
@@ -1,3 +1,4 @@
11 {
2 "files": {}
2 "files": {},
3 "drift": 258
34 }
docs/design/plan.md +4
@@ -7,6 +7,10 @@ define a class DESIGN.md §5 does not name. Paying down lowers the baseline
77 retired classes from the §5d register; neither ever grows back without a §5
88 entry first.
99
10 Pages also drift from the parts: `bun scripts/design-drift.ts` (in the check,
11 a warning for now, #5817) counts markup typed by hand where a `src/web/ui.ts`
12 part draws it, against `drift` in `baseline.json`. Each week's pulls drive it down.
13
1014 Each item is one filed issue, small enough for one run; items 4–9 wait for the screenshot sweep (#2690) in the map.
1115
1216 1. **#2690 Screenshot sweep** — every top-level page, desktop + 360px, light + dark,
forge.json +2 −2
@@ -15,8 +15,8 @@
1515 }
1616 },
1717 "check": {
18 "fast": "bun scripts/gate.ts && mkdir -p .forge-cache && GOMEMLIMIT=2GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --timeout 60000 --tier fast --diff $FORGE_CHECK_BASE..HEAD --learned \"$FORGE_CHECK_LEARNED\"",
19 "run": "bun scripts/gate.ts && mkdir -p .forge-cache && GOMEMLIMIT=2GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --timeout 60000 --gate --impact",
18 "fast": "bun scripts/gate.ts && bun scripts/design-drift.ts && mkdir -p .forge-cache && GOMEMLIMIT=2GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --timeout 60000 --tier fast --diff $FORGE_CHECK_BASE..HEAD --learned \"$FORGE_CHECK_LEARNED\"",
19 "run": "bun scripts/gate.ts && bun scripts/design-drift.ts && mkdir -p .forge-cache && GOMEMLIMIT=2GiB ./node_modules/typescript/bin/tsc --noEmit --incremental --tsBuildInfoFile .forge-cache/tsc.tsbuildinfo && bun scripts/test-shards.ts --timeout 60000 --gate --impact",
2020 "timeout": 7200,
2121 "limits": {
2222 "memory": 8192,
scripts/design-drift.ts added +139
@@ -0,0 +1,139 @@
1 /**
2 * The drift gate (#5817): a page may not hand-roll what a part in
3 * `src/web/ui.ts` already draws — a button, a list, an empty state, a
4 * picker. `design-lint.ts` keeps new classes out of the system; this keeps
5 * pages calling the parts instead of typing their markup, so a part's fix
6 * (its focus ring, its target size, its phone layout) reaches every page.
7 *
8 * It finds, in every `src/web` file but `ui.ts` and `style/`:
9 *
10 * markup a tag whose class is a part's own root class (`<button
11 * class="btn">`, `<ul class="list">`, `<div class="card empty">`),
12 * or a bare `<select>` — the part is the way to draw it
13 * one-off a class a page's own `/* css *\/` template defines whose name says
14 * button, list, empty, picker or the like: a lookalike of a part
15 *
16 * It is a warning with a count, not a refusal: `forge.json`'s check prints
17 * it and exits 0. `docs/design/baseline.json` holds last week's `drift`;
18 * the line says whether the count went up or down, and `--update` writes
19 * today's down once a pull has paid some off. `--all` lists every finding.
20 *
21 * Known gaps: a class built only in an interpolation (`class="${k}"`) and
22 * markup made in `client.ts` with `className` are not seen. Plain data in,
23 * plain data out: `driftIn` takes one file's text, `report` takes findings.
24 */
25
26 import { readFileSync, writeFileSync } from "node:fs";
27 import { join, relative } from "node:path";
28 import { blanked, sourceFiles } from "./design-lint.ts";
29
30 /** One hand-rolled part: where, what was typed, and the part to call. */
31 export type Drift = { file: string; line: number; part: string; text: string; use: string };
32
33 type Rule = { part: string; tags?: readonly string[]; classes: readonly string[]; use: string };
34
35 /** Each part's own root classes, and the call that draws them. */
36 export const RULES: readonly Rule[] = [
37 { part: "button", tags: ["a", "button"], classes: ["btn"], use: "btn() or iconBtn()" },
38 { part: "empty state", classes: ["empty", "empty-title"], use: "empty()" },
39 { part: "list", tags: ["ul", "ol"], classes: ["list"], use: "listCard() with row()" },
40 { part: "row", classes: ["row-main"], use: "row()" },
41 { part: "card", tags: ["div", "section"], classes: ["card"], use: "card()" },
42 { part: "field", classes: ["field"], use: "field() or selectField()" },
43 { part: "badge", classes: ["badge"], use: "badge()" },
44 { part: "pill", classes: ["pill"], use: "pill()" },
45 { part: "crumbs", classes: ["crumbs"], use: "crumbs()" },
46 { part: "tabs", classes: ["tabs"], use: "tabs()" },
47 { part: "segmented filter", classes: ["seg"], use: "seg()" },
48 { part: "pager", classes: ["pager"], use: "pager()" },
49 { part: "menu", classes: ["menu"], use: "menu()" },
50 { part: "avatar", classes: ["avatar"], use: "avatar()" },
51 { part: "stat", classes: ["stat"], use: "stat()" },
52 ];
53
54 /** A page-local class name that reads as one of the parts. */
55 const LOOKALIKE = /(?:^|-)(btn|button|list|empty|picker|chooser|pager|tabs|toast|skeleton|confirm)s?(?:-|$)/;
56
57 const SKIP = /^src\/web\/(ui\.ts$|style\/)/;
58
59 /** The class tokens of an attribute value, interpolations dropped (one cut short by a quote inside it too). */
60 function tokens(value: string): string[] {
61 return value.replace(/\$\{[^}]*(?:\}|$)/g, " ").split(/\s+/).filter(Boolean);
62 }
63
64 /** Every hand-rolled part in one file's text; `file` is repository-relative. */
65 export function driftIn(file: string, text: string): Drift[] {
66 if (SKIP.test(file)) return [];
67 const code = blanked(text);
68 const lineAt = (i: number) => code.slice(0, i).split("\n").length;
69 const out: Drift[] = [];
70 for (const m of code.matchAll(/<([a-z][a-z0-9]*)\b[^<>]*?\bclass="([^"]*)"/gi)) {
71 const tag = m[1]!.toLowerCase();
72 const have = tokens(m[2]!);
73 const rule = RULES.find((r) => (!r.tags || r.tags.includes(tag)) && r.classes.some((c) => have.includes(c)));
74 if (rule) out.push({ file, line: lineAt(m.index!), part: rule.part, text: `<${tag} class="${m[2]}">`, use: rule.use });
75 }
76 for (const m of code.matchAll(/<select\b/gi)) {
77 out.push({ file, line: lineAt(m.index!), part: "select", text: "<select>", use: "selectField(), or searchPicker() past a screenful" });
78 }
79 if (file.startsWith("src/web/pages/")) {
80 for (const css of text.matchAll(/\/\* css \*\/\s*`((?:[^`\\]|\\.)*)`/g)) {
81 const start = css.index! + css[0].length - 1 - css[1]!.length;
82 for (const sel of css[1]!.matchAll(/([^{};]+)\{/g)) {
83 for (const c of sel[1]!.matchAll(/\.([a-z][a-z0-9_-]*)/gi)) {
84 const hit = c[1]!.match(LOOKALIKE);
85 if (hit) out.push({ file, line: text.slice(0, start + sel.index! + c.index!).split("\n").length, part: `one-off ${hit[1]}`, text: `.${c[1]}`, use: "the part src/web/ui.ts has for it" });
86 }
87 }
88 }
89 }
90 return out.sort((a, b) => a.line - b.line);
91 }
92
93 /** Every hand-rolled part under `root`'s src/web. */
94 export function scanDrift(root: string): Drift[] {
95 return sourceFiles(root).flatMap((f) => driftIn(relative(root, f), readFileSync(f, "utf8")));
96 }
97
98 /**
99 * The check's lines: the count against the baseline, then the files with
100 * the most (every finding with `all`). Never a refusal.
101 */
102 export function report(found: readonly Drift[], baseline?: number, o: { all?: boolean; top?: number } = {}): string[] {
103 const n = found.length;
104 const by = new Map<string, Drift[]>();
105 for (const d of found) by.set(d.file, [...(by.get(d.file) ?? []), d]);
106 const trend =
107 baseline === undefined ? "no baseline yet"
108 : n > baseline ? `up ${n - baseline} from ${baseline}`
109 : n < baseline ? `down ${baseline - n} from ${baseline}; run bun scripts/design-drift.ts --update`
110 : `level at ${baseline}`;
111 const lines = [`design drift (warning): ${n} hand-rolled part${n === 1 ? "" : "s"} in ${by.size} file${by.size === 1 ? "" : "s"}, ${trend}`];
112 const files = [...by.entries()].sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]));
113 for (const [file, ds] of o.all ? files : files.slice(0, o.top ?? 10)) {
114 const parts = new Map<string, number>();
115 for (const d of ds) parts.set(d.part, (parts.get(d.part) ?? 0) + 1);
116 lines.push(` ${file}: ${ds.length} (${[...parts].sort((a, b) => b[1] - a[1]).map(([p, k]) => `${p} ×${k}`).join(", ")})`);
117 if (o.all) for (const d of ds) lines.push(` ${file}:${d.line} ${d.text} → use ${d.use}`);
118 }
119 if (!o.all && files.length > (o.top ?? 10)) lines.push(` … and ${files.length - (o.top ?? 10)} more files; --all lists every one`);
120 return lines;
121 }
122
123 const BASELINE = "docs/design/baseline.json";
124
125 if (import.meta.main) {
126 const root = process.cwd();
127 const found = scanDrift(root);
128 let base: { drift?: number } & Record<string, unknown> = {};
129 try {
130 base = JSON.parse(readFileSync(join(root, BASELINE), "utf8"));
131 } catch {}
132 if (process.argv.includes("--update")) {
133 writeFileSync(join(root, BASELINE), JSON.stringify({ ...base, drift: found.length }, null, 2) + "\n");
134 console.log(`wrote drift ${found.length} to ${BASELINE}`);
135 } else {
136 const baseline = typeof base.drift === "number" ? base.drift : undefined;
137 for (const line of report(found, baseline, { all: process.argv.includes("--all") })) console.log(line);
138 }
139 }
scripts/design-lint.ts +4 −2
@@ -132,7 +132,7 @@ export function countFile(text: string): Counts {
132132 }
133133
134134 /** Comments blanked but newlines kept, so an offset still maps to its line. */
135 const blanked = (text: string): string =>
135 export const blanked = (text: string): string =>
136136 text.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/(^|\s)\/\/.*$/gm, (_m, a) => a);
137137
138138 /** The token a colour literal on this line should be, from the property it sits in. */
@@ -317,7 +317,9 @@ if (import.meta.main) {
317317 const root = process.cwd();
318318 const now = scan(root);
319319 if (process.argv.includes("--update")) {
320 const baseline = { ...JSON.parse(readFileSync(join(root, BASELINE), "utf8")), files: now.files }; // keeps `coldRead` (#5882)
320 // Keep what other checks hold in the same file (design-drift.ts's `drift`, cold-read's `coldRead` #5882).
321 const old = JSON.parse(readFileSync(join(root, BASELINE), "utf8")) as Baseline;
322 const baseline: Baseline = { ...old, files: now.files };
321323 writeFileSync(join(root, BASELINE), JSON.stringify(baseline, null, 2) + "\n");
322324 console.log(`wrote ${BASELINE}`);
323325 } else {
src/core/reserved.ts +1
@@ -64,6 +64,7 @@ export const SYSTEM_NAMES: readonly string[] = [
6464 "big",
6565 "board",
6666 "boards",
67 "design",
6768 "contribute",
6869 "events",
6970 "explore",
src/http/server.ts +3
@@ -28,6 +28,7 @@ import { resiliencePage } from "../web/pages/resilience.ts";
2828 import { limitsPage, limitsSet, quotasSet, signupSet, inviteMint, inviteRevoke } from "../web/pages/admin-limits.ts";
2929 import { measureSubmit } from "./measure.ts";
3030 import { boardsPage } from "../web/pages/boards.ts";
31 import { designComponentsPage } from "../web/pages/design_components.ts";
3132 import { boardNew, boardPin, boardPost, pinPost } from "../web/pages/boards-edit.ts";
3233 import { boardLive, boardShow, boardsList } from "../web/pages/boards-view.ts";
3334 import {
@@ -884,6 +885,8 @@ export function buildRouter(): Router<Handler> {
884885 router.add("POST", "/settings/capacity", capacitySet);
885886 router.add("GET", "/boards", boardsList);
886887 router.add("GET", "/boards/data", boardsPage);
888 // The living gallery of the component library (#5817), for an admin who is a person.
889 router.add("GET", "/design/components", designComponentsPage);
887890 router.add("POST", "/boards/new", boardNew);
888891 router.add("POST", "/boards/pin", boardPin);
889892 for (const op of ["pin-panel", "unpin-panel", "move-pin"]) router.add("POST", `/boards/${op}`, pinPost);
src/web/client.ts +26
@@ -1375,6 +1375,32 @@ export const shellJs = /* js */ `
13751375 }, fallback);
13761376 });
13771377
1378 // ---- search pickers: typing narrows this page's rows; Enter asks the server ----
1379 doc.addEventListener('input', function (e) {
1380 var q = e.target;
1381 if (!q || !q.matches || !q.matches('[data-picker-q]')) return;
1382 var picker = q.closest('[data-picker]');
1383 if (!picker) return;
1384 var needle = q.value.trim().toLowerCase();
1385 var rows = picker.querySelectorAll('li[data-q]');
1386 var shown = 0;
1387 for (var i = 0; i < rows.length; i++) {
1388 var hit = needle === '' || rows[i].getAttribute('data-q').indexOf(needle) >= 0;
1389 rows[i].hidden = !hit;
1390 if (hit) shown++;
1391 }
1392 var count = picker.querySelector('[data-picker-count]');
1393 if (count) count.textContent = needle === '' ? count.getAttribute('data-picker-count') : String(shown);
1394 });
1395 doc.addEventListener('change', function (e) {
1396 var box = e.target;
1397 if (!box || box.type !== 'checkbox' || !box.closest) return;
1398 var picker = box.closest('[data-picker]');
1399 var out = picker ? picker.querySelector('[data-picker-picked]') : null;
1400 if (!out) return;
1401 out.textContent = String(picker.querySelectorAll('li input:checked, [data-picker-carried]').length);
1402 });
1403
13781404 // ---- code line ranges: shift-click extends #L3 to #L3-L9 ----
13791405 // Delegated, not bound to the table: the code browser swaps the file in
13801406 // place, and the new table must behave like the first one did.
src/web/layout.ts +2
@@ -232,6 +232,7 @@ function userMenu(
232232 : [
233233 { label: "Boards", href: "/boards", icon: "activity" as const },
234234 { label: "System memory", href: "/system", icon: "activity" as const },
235 { label: "Components", href: "/design/components", icon: "eye" as const },
235236 ]),
236237 ]
237238 : []),
@@ -329,6 +330,7 @@ function paletteIndex(ctx: Ctx, extra: PaletteItem[]): Html {
329330 ...(ctx.auth.user?.isAdmin
330331 ? [
331332 { t: "System", h: "/system", c: "Go to" },
333 { t: "Components", h: "/design/components", c: "Go to" },
332334 { t: "Forges you sent", h: "/forges", c: "Go to" },
333335 { t: "Family of forges", h: "/family", c: "Go to" },
334336 ]
src/web/pages/design_components.ts added +113
@@ -0,0 +1,113 @@
1 /**
2 * /design/components, for an admin who is a person (#5817): the living
3 * gallery — every part `ui.ts` draws, in every state it has
4 * (`web/gallery.ts`), the one place to judge the library. Two links pick
5 * what the gallery is seen in: `?theme=` any of the forge's themes, and
6 * `?w=390|1440` a phone's or a desktop's column. `?part=` narrows it to one
7 * part. Each is checked against what it may be, and anything else is the
8 * same as leaving it out.
9 *
10 * The width is a column, not a viewport: a part's media queries still read
11 * the window, so a phone's breakpoints are judged on a phone. It shows how a
12 * part wraps, truncates and overflows at that width, which is most of what
13 * drifts.
14 */
15 import { THEME_NAMES, isThemeName, type ThemeName } from "../../design/themes.ts";
16 import type { Ctx } from "../../http/context.ts";
17 import { notFoundPage } from "../chrome.ts";
18 import { GALLERY_SEARCH_FORM, SPECIMENS, type Specimen } from "../gallery.ts";
19 import { html, type Html } from "../html.ts";
20 import { page } from "../layout.ts";
21 import { card, seg } from "../ui.ts";
22
23 const WIDTHS = ["390", "1440"] as const;
24 type Width = (typeof WIDTHS)[number];
25
26 export interface GalleryQuery {
27 readonly theme: ThemeName | undefined;
28 readonly w: Width | undefined;
29 readonly part: string | undefined;
30 }
31
32 /** The query, each value kept only when it is one the gallery knows. */
33 export function readGalleryQuery(params: URLSearchParams): GalleryQuery {
34 const theme = params.get("theme") ?? "";
35 const w = params.get("w") ?? "";
36 const part = params.get("part") ?? "";
37 return {
38 theme: isThemeName(theme) ? theme : undefined,
39 w: (WIDTHS as readonly string[]).includes(w) ? (w as Width) : undefined,
40 part: SPECIMENS.some((s) => s.part === part) ? part : undefined,
41 };
42 }
43
44 /** This page's address with one value changed, the others kept. */
45 function hrefWith(q: GalleryQuery, change: Partial<Record<keyof GalleryQuery, string | undefined>>): string {
46 const next = { ...q, ...change };
47 const params = new URLSearchParams();
48 for (const key of ["theme", "w", "part"] as const) {
49 const value = next[key];
50 if (value !== undefined) params.set(key, value);
51 }
52 const query = params.toString();
53 return `/design/components${query === "" ? "" : `?${query}`}`;
54 }
55
56 function specimen(s: Specimen, q: GalleryQuery): Html {
57 return card(
58 html`<div class="stack">
59 ${s.states.map(
60 (st) => html`<div class="stack stack-tight" data-state="${st.state}">
61 <span class="muted small">${st.state}</span>
62 <div class="gallery-stage">${st.draw()}</div>
63 </div>`,
64 )}
65 </div>`,
66 {
67 id: `part-${s.part}`,
68 head: html`<div class="stack stack-tight">
69 <a class="mono" href="${hrefWith(q, { part: s.part })}"><strong>${s.part}</strong></a>
70 <span class="muted small">${s.note}</span>
71 </div>`,
72 },
73 );
74 }
75
76 // GET /design/components
77 export function designComponentsPage(ctx: Ctx): Response {
78 const user = ctx.auth.user;
79 if (user?.isAdmin !== true || user.kind === "agent") return notFoundPage(ctx);
80 const q = readGalleryQuery(ctx.url.searchParams);
81 const shown = q.part === undefined ? SPECIMENS : SPECIMENS.filter((s) => s.part === q.part);
82 const themes = seg([
83 { label: "Mine", href: hrefWith(q, { theme: undefined }), current: q.theme === undefined },
84 ...THEME_NAMES.map((name) => ({ label: name, href: hrefWith(q, { theme: name }), current: q.theme === name })),
85 ]);
86 const widths = seg([
87 { label: "Fluid", href: hrefWith(q, { w: undefined }), current: q.w === undefined },
88 ...WIDTHS.map((w) => ({ label: `${w} px`, href: hrefWith(q, { w }), current: q.w === w })),
89 ]);
90 const body = html`<div class="stack">
91 <h1>Components</h1>
92 <p class="muted">
93 Every part <span class="mono">src/web/ui.ts</span> draws, in each state it has.
94 ${shown.length === SPECIMENS.length
95 ? html`${SPECIMENS.length} parts.`
96 : html`One part of ${SPECIMENS.length}: <a href="${hrefWith(q, { part: undefined })}">show them all</a>.`}
97 </p>
98 <div class="bar">${themes}${widths}</div>
99 <form id="${GALLERY_SEARCH_FORM}" method="get" action="/design/components">
100 ${(["theme", "w", "part"] as const).map((key) => (q[key] === undefined ? null : html`<input type="hidden" name="${key}" value="${q[key]}" />`))}
101 </form>
102 <div class="gallery-frame" ${q.w === undefined ? null : html`data-w="${q.w}"`}>
103 <div class="stack">${shown.map((s) => specimen(s, q))}</div>
104 </div>
105 </div>`;
106 return page({
107 ctx: q.theme === undefined ? ctx : { ...ctx, theme: q.theme },
108 title: "Components",
109 wide: q.w === "1440",
110 crumbs: [{ label: "Components", href: "/design/components" }],
111 body,
112 });
113 }
src/web/style/components.ts +10
@@ -904,6 +904,16 @@ details[open] > summary.row > .row-lead { transform: rotate(90deg); }
904904 .palette .palette-input { font-size: 16px; }
905905 }
906906
907 /* ---- gallery (/design/components) ---- */
908 .gallery-frame { overflow-x: auto; }
909 .gallery-frame[data-w="390"] > .stack { width: 390px; }
910 .gallery-frame[data-w="1440"] > .stack { width: 1440px; }
911 .gallery-stage {
912 padding: 12px; border: 1px dashed var(--border); border-radius: var(--radius);
913 min-width: 0; overflow-wrap: anywhere;
914 }
915 .gallery-stage .list { max-height: 480px; overflow-y: auto; }
916
907917 /* Forced colours drop box-shadow rings and author colours: the focus ring is
908918 an outline the system paints. */
909919 @media (forced-colors: active) {
src/web/ui.ts +90
@@ -1236,6 +1236,96 @@ export function selectField(
12361236 </div>`;
12371237 }
12381238
1239 /** One choice in a `searchPicker`: what it submits, how it reads, and the words a filter matches. */
1240 export interface PickerOption {
1241 readonly value: string;
1242 readonly title: Html | string;
1243 readonly meta?: Html | string;
1244 /** The text the filter looks in; the title and anything else worth finding by. */
1245 readonly search: string;
1246 readonly checked?: boolean;
1247 }
1248
1249 /** Choices a picker draws per page; past it, the pager or the filter narrows. */
1250 export const PICKER_PAGE = 50;
1251
1252 /**
1253 * A long list a person picks from: a search box, a page of checkbox rows
1254 * (radios when `multiple` is false), and a pager. It does the filtering and
1255 * paging itself, from `q` and `page`, so a caller hands it every choice and
1256 * the words the reader typed. A checked choice off this page or outside the
1257 * filter rides along as a hidden input, so paging or narrowing never drops
1258 * a pick.
1259 *
1260 * Forms do not nest, so the search box belongs to the GET form named by
1261 * `searchForm` — a `<form id method="get">` the caller puts outside the
1262 * form the picks submit in. With script, typing narrows this page's rows at
1263 * once and the count follows (`client.ts`, "search pickers"); Enter asks the
1264 * server for every page.
1265 */
1266 export function searchPicker(o: {
1267 /** The picker's id; its parts' ids derive from it. */
1268 id: string;
1269 label: string;
1270 /** The name each pick submits under, once per chosen value. */
1271 name: string;
1272 options: readonly PickerOption[];
1273 q: string;
1274 searchForm: string;
1275 /** 1-based; out of range reads as the nearest page. */
1276 page: number;
1277 pageHref: (page: number) => string;
1278 pageSize?: number;
1279 multiple?: boolean;
1280 hint?: string;
1281 }): Html {
1282 const size = Math.max(1, Math.floor(o.pageSize ?? PICKER_PAGE));
1283 const needle = o.q.trim().toLowerCase();
1284 const matched = o.options.filter((opt) => needle === "" || opt.search.toLowerCase().includes(needle));
1285 const pages = Math.max(1, Math.ceil(matched.length / size));
1286 const page = Math.min(pages, Math.max(1, Number.isFinite(o.page) ? Math.floor(o.page) : 1));
1287 const shown = matched.slice((page - 1) * size, page * size);
1288 const onPage = new Set(shown.map((opt) => opt.value));
1289 const carried = o.options.filter((opt) => opt.checked === true && !onPage.has(opt.value));
1290 const picked = o.options.filter((opt) => opt.checked === true).length;
1291 const kind = o.multiple === false ? "radio" : "checkbox";
1292 const hintId = `${o.id}-hint`;
1293 return html`<div class="field" id="${o.id}" data-picker>
1294 <label for="${o.id}-q">${o.label}</label>
1295 <div class="bar">
1296 <input class="input grow" type="search" id="${o.id}-q" name="q" form="${o.searchForm}" value="${o.q}"
1297 placeholder="Filter" autocomplete="off" spellcheck="false" aria-controls="${o.id}-list"
1298 ${o.hint ? html`aria-describedby="${hintId}"` : null} data-picker-q />
1299 <span class="muted small num" aria-live="polite"
1300 ><span data-picker-count="${matched.length}">${matched.length}</span> of ${o.options.length}${kind === "checkbox"
1301 ? html` · <span data-picker-picked>${picked}</span> picked`
1302 : null}</span
1303 >
1304 </div>
1305 ${shown.length === 0
1306 ? html`<p class="muted small">${o.options.length === 0 ? "Nothing to pick from yet." : html`Nothing matches “${o.q.trim()}”.`}</p>`
1307 : html`<ul class="list" id="${o.id}-list" role="group" aria-label="${o.label}">
1308 ${shown.map(
1309 (opt) => html`<li data-q="${opt.search.toLowerCase()}">
1310 <label class="row">
1311 <span class="row-lead"><input type="${kind}" name="${o.name}" value="${opt.value}" ${opt.checked ? raw("checked") : null} /></span>
1312 <span class="row-main"><span class="row-title">${opt.title}</span>${opt.meta ? html`<span class="row-meta">${opt.meta}</span>` : null}</span>
1313 </label>
1314 </li>`,
1315 )}
1316 </ul>`}
1317 ${carried.map((opt) => html`<input type="hidden" name="${o.name}" value="${opt.value}" data-picker-carried />`)}
1318 ${pages > 1
1319 ? pager({
1320 ...(page > 1 ? { prev: o.pageHref(page - 1) } : {}),
1321 ...(page < pages ? { next: o.pageHref(page + 1) } : {}),
1322 note: `page ${page} of ${pages}`,
1323 })
1324 : null}
1325 ${o.hint ? html`<span class="hint" id="${hintId}">${o.hint}</span>` : null}
1326 </div>`;
1327 }
1328
12391329 /**
12401330 * A destructive action. With JS it opens a `<dialog>`; without it the button
12411331 * is a plain link to a confirm page, so nothing is ever one careless click
test/design-drift.test.ts added +77
@@ -0,0 +1,77 @@
1 import { describe, expect, test } from "bun:test";
2 import { readFileSync } from "node:fs";
3 import { driftIn, report, scanDrift } from "../scripts/design-drift.ts";
4
5 const parts = (file: string, text: string) => driftIn(file, text).map((d) => d.part);
6
7 describe("the drift gate (#5817)", () => {
8 test("a page's hand-typed part markup is found, with the line and the part to call", () => {
9 const page = [
10 "const a = html`<ul class=\"list\">",
11 ' <li><span class="row-main">x</span></li></ul>`;',
12 'const b = html`<button class="btn" type="submit">Go</button>`;',
13 "const c = html`<div class=\"card empty\"><p class=\"empty-title\">None</p></div>`;",
14 'const d = html`<select name="k"></select>`;',
15 'const e = html`<a class="btn${o.primary ? " primary" : ""}" href="/x">x</a>`;',
16 ].join("\n");
17 const found = driftIn("src/web/pages/x.ts", page);
18 expect(found.map((d) => [d.line, d.part])).toEqual([
19 [1, "list"],
20 [2, "row"],
21 [3, "button"],
22 [4, "empty state"],
23 [4, "empty state"],
24 [5, "select"],
25 [6, "button"],
26 ]);
27 expect(found[0]!.use).toBe("listCard() with row()");
28 expect(found[2]!.use).toBe("btn() or iconBtn()");
29 });
30
31 test("a tag that only shares a word is not a part: a list item, a div with .btn, a card's body", () => {
32 expect(parts("src/web/pages/x.ts", 'html`<li class="list-item"></li><div class="btn"></div><div class="card-body"></div>`')).toEqual([]);
33 });
34
35 test("the parts themselves, the stylesheets and comments are never drift", () => {
36 const markup = 'html`<button class="btn">x</button>`';
37 expect(driftIn("src/web/ui.ts", markup)).toEqual([]);
38 expect(driftIn("src/web/style/components.ts", markup)).toEqual([]);
39 expect(driftIn("src/web/pages/x.ts", `/* ${markup} */\n// <select>`)).toEqual([]);
40 });
41
42 test("a page's own css that defines a lookalike class is a one-off; an unrelated class is not", () => {
43 const page = "const CSS = /* css */ `\n.map-legend { gap: 4px }\n.map-empty { color: var(--fg) }\n.pick-list, .x { }\n`;";
44 const found = driftIn("src/web/pages/map.ts", page);
45 expect(found.map((d) => [d.line, d.part, d.text])).toEqual([
46 [3, "one-off empty", ".map-empty"],
47 [4, "one-off list", ".pick-list"],
48 ]);
49 });
50
51 test("the report is a warning with a count and its trend against the baseline", () => {
52 const found = driftIn("src/web/pages/x.ts", 'html`<button class="btn">a</button><button class="btn">b</button><select>`');
53 expect(report(found, 3)[0]).toBe("design drift (warning): 3 hand-rolled parts in 1 file, level at 3");
54 expect(report(found, 5)[0]).toContain("down 2 from 5; run bun scripts/design-drift.ts --update");
55 expect(report(found, 1)[0]).toContain("up 2 from 1");
56 expect(report(found)[0]).toContain("no baseline yet");
57 expect(report(found, 3)[1]).toBe(" src/web/pages/x.ts: 3 (button ×2, select ×1)");
58 expect(report(found, 3, { all: true })).toContain(" src/web/pages/x.ts:1 <select> → use selectField(), or searchPicker() past a screenful");
59 });
60
61 test("the tree is scanned, and the baseline holds a count for the check to compare against", () => {
62 const found = scanDrift(".");
63 expect(found.length).toBeGreaterThan(0);
64 expect(found.every((d) => d.file.startsWith("src/web/") && d.file !== "src/web/ui.ts")).toBe(true);
65 const base = JSON.parse(readFileSync("docs/design/baseline.json", "utf8"));
66 expect(typeof base.drift).toBe("number");
67 });
68
69 test("the check runs it, and it never fails the check", async () => {
70 const check = JSON.parse(readFileSync("forge.json", "utf8")).check;
71 for (const command of [check.run, check.fast]) expect(command).toContain("bun scripts/design-drift.ts && ");
72 const proc = Bun.spawn(["bun", "scripts/design-drift.ts"], { stdout: "pipe", stderr: "pipe" });
73 const out = await new Response(proc.stdout).text();
74 expect(await proc.exited).toBe(0);
75 expect(out).toMatch(/^design drift \(warning\): \d+ hand-rolled parts? in \d+ files?, /);
76 }, 30_000);
77 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs