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
mason/forge:mason/5817-a-fantastic-component-library-a-living-g → main 8 commits fork
18 files
changed +982
−6
docs/DEVELOP.md +11
| @@ -5,6 +5,7 @@ Moved from README.md (its "## Develop" section), unchanged. | ||
| 5 | 5 | sh |
| 6 | 6 | bun test # protocol-level + adversarial suite |
| 7 | 7 | 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) | |
| 8 | 9 | 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 |
| 9 | 10 | bun x tsc --noEmit # zero type errors is the standard |
| 10 | 11 | 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 | ||
| 20 | 21 | --update` and commit the baseline; when it deletes the last rule for a class |
| 21 | 22 | in the §5d register, strike the name there too. See `docs/design/plan.md`. |
| 22 | 23 | |
| 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 | ||
| 23 | 34 | `docs/DESIGN.md` is a spine: each of its sections is its own file under |
| 24 | 35 | `docs/design/sections/` (§5d is `5d-page-local-classes.md`), linked from the |
| 25 | 36 | spine in order, and the check reads them in that order. A new section is a |
docs/design/areas/gallery.md added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | # Gallery | |
| 2 | ||
| 3 | The living gallery at `/design/components` (#5817): every part `src/web/ui.ts` draws, in each state it has, specimens in | |
| 4 | `src/web/gallery.ts`, page in `src/web/pages/design_components.ts`, rules in `src/web/style/components.ts` under | |
| 5 | `/* ---- gallery (/design/components) ---- */`. A part with no specimen fails `test/design-gallery.test.ts`. | |
| 6 | ||
| 7 | - `.gallery-frame` — the column the specimens sit in; `data-w="390"` or `data-w="1440"` fixes it to a phone's or a desktop's width and scrolls sideways past the page. | |
| 8 | - `.gallery-stage` — one state of one part, inside a dashed hairline so its own edges show; a list inside it scrolls after 480px so 200 items stay one stage. | |
| 9 | ||
| 10 | The search picker (`searchPicker` in `src/web/ui.ts`) adds no class: it is a `.field` holding a search `.input`, a | |
| 11 | `.list` of `label.row`s with a checkbox (or radio) as `.row-lead`, and a `pager`. Its script is "search pickers" in | |
| 12 | `src/web/client.ts`, found by `data-picker`, `data-picker-q`, `data-picker-count` and `data-picker-picked`. |
docs/design/audit.md +2 −1
| @@ -33,7 +33,7 @@ their own vocabulary instead of composing the named one. | ||
| 33 | 33 | |
| 34 | 34 | ## Finding 2 — the pages, and what each is for |
| 35 | 35 | |
| 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` | |
| 37 | 37 | that returns a page (`test/design-audit.test.ts` holds this list to the router, |
| 38 | 38 | both ways). Each entry reads `route` — module · what it is for · what |
| 39 | 39 | 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`, | ||
| 55 | 55 | - `/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). |
| 56 | 56 | - `/boards` — `pages/boards-view.ts` · saved queries as panels · `/board` · none seen. |
| 57 | 57 | - `/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. | |
| 58 | 59 | - `/asks` — `studio/asks_page.ts` · what the crew is waiting on me for · `/` "needs me" list · colours 2. |
| 59 | 60 | - `/asked` — `studio/asked_page.ts` · what I answered, as a record · `/asks` · none seen. |
| 60 | 61 | - `/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 @@ | ||
| 1 | 1 | { |
| 2 | "files": {} | |
| 2 | "files": {}, | |
| 3 | "drift": 258 | |
| 3 | 4 | } |
docs/design/plan.md +4
| @@ -7,6 +7,10 @@ define a class DESIGN.md §5 does not name. Paying down lowers the baseline | ||
| 7 | 7 | retired classes from the §5d register; neither ever grows back without a §5 |
| 8 | 8 | entry first. |
| 9 | 9 | |
| 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 | ||
| 10 | 14 | Each item is one filed issue, small enough for one run; items 4–9 wait for the screenshot sweep (#2690) in the map. |
| 11 | 15 | |
| 12 | 16 | 1. **#2690 Screenshot sweep** — every top-level page, desktop + 360px, light + dark, |
forge.json +2 −2
| @@ -15,8 +15,8 @@ | ||
| 15 | 15 | } |
| 16 | 16 | }, |
| 17 | 17 | "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", | |
| 20 | 20 | "timeout": 7200, |
| 21 | 21 | "limits": { |
| 22 | 22 | "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 { | ||
| 132 | 132 | } |
| 133 | 133 | |
| 134 | 134 | /** 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 => | |
| 136 | 136 | text.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/(^|\s)\/\/.*$/gm, (_m, a) => a); |
| 137 | 137 | |
| 138 | 138 | /** The token a colour literal on this line should be, from the property it sits in. */ |
| @@ -317,7 +317,9 @@ if (import.meta.main) { | ||
| 317 | 317 | const root = process.cwd(); |
| 318 | 318 | const now = scan(root); |
| 319 | 319 | 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 }; | |
| 321 | 323 | writeFileSync(join(root, BASELINE), JSON.stringify(baseline, null, 2) + "\n"); |
| 322 | 324 | console.log(`wrote ${BASELINE}`); |
| 323 | 325 | } else { |
src/core/reserved.ts +1
| @@ -64,6 +64,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 64 | 64 | "big", |
| 65 | 65 | "board", |
| 66 | 66 | "boards", |
| 67 | "design", | |
| 67 | 68 | "contribute", |
| 68 | 69 | "events", |
| 69 | 70 | "explore", |
src/http/server.ts +3
| @@ -28,6 +28,7 @@ import { resiliencePage } from "../web/pages/resilience.ts"; | ||
| 28 | 28 | import { limitsPage, limitsSet, quotasSet, signupSet, inviteMint, inviteRevoke } from "../web/pages/admin-limits.ts"; |
| 29 | 29 | import { measureSubmit } from "./measure.ts"; |
| 30 | 30 | import { boardsPage } from "../web/pages/boards.ts"; |
| 31 | import { designComponentsPage } from "../web/pages/design_components.ts"; | |
| 31 | 32 | import { boardNew, boardPin, boardPost, pinPost } from "../web/pages/boards-edit.ts"; |
| 32 | 33 | import { boardLive, boardShow, boardsList } from "../web/pages/boards-view.ts"; |
| 33 | 34 | import { |
| @@ -884,6 +885,8 @@ export function buildRouter(): Router<Handler> { | ||
| 884 | 885 | router.add("POST", "/settings/capacity", capacitySet); |
| 885 | 886 | router.add("GET", "/boards", boardsList); |
| 886 | 887 | 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); | |
| 887 | 890 | router.add("POST", "/boards/new", boardNew); |
| 888 | 891 | router.add("POST", "/boards/pin", boardPin); |
| 889 | 892 | 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 */ ` | ||
| 1375 | 1375 | }, fallback); |
| 1376 | 1376 | }); |
| 1377 | 1377 | |
| 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 | ||
| 1378 | 1404 | // ---- code line ranges: shift-click extends #L3 to #L3-L9 ---- |
| 1379 | 1405 | // Delegated, not bound to the table: the code browser swaps the file in |
| 1380 | 1406 | // place, and the new table must behave like the first one did. |
src/web/gallery.ts added +313
| @@ -0,0 +1,313 @@ | ||
| 1 | /** | |
| 2 | * The living gallery's specimens (#5817): every part `ui.ts` draws, in the | |
| 3 | * states a page puts it in — its default, empty, loading, error, long text, | |
| 4 | * and 200 items where a part holds a list. `/design/components` renders them | |
| 5 | * (`pages/design_components.ts`); `test/design-gallery.test.ts` fails when a | |
| 6 | * part `ui.ts` exports has no specimen here, so the gallery cannot fall | |
| 7 | * behind the library it shows. | |
| 8 | * | |
| 9 | * Plain data: a part's name (its export), one line on what it is for, and | |
| 10 | * its states, each a label and a thunk that draws it from fixed fixtures. | |
| 11 | * Nothing here reads a request or the database — a specimen looks the same | |
| 12 | * on every forge. | |
| 13 | */ | |
| 14 | ||
| 15 | import type { EnvStatus } from "../apps/runtime.ts"; | |
| 16 | import { html, type Html } from "./html.ts"; | |
| 17 | import * as ui from "./ui.ts"; | |
| 18 | ||
| 19 | /** The states the gallery shows a part in; a part names only those it has. */ | |
| 20 | export const STATES = ["default", "variants", "empty", "loading", "error", "long text", "200 items"] as const; | |
| 21 | export type State = (typeof STATES)[number]; | |
| 22 | ||
| 23 | export interface Specimen { | |
| 24 | /** The export of `ui.ts` it shows. */ | |
| 25 | readonly part: keyof typeof ui; | |
| 26 | readonly note: string; | |
| 27 | readonly states: readonly { readonly state: State; readonly draw: () => Html }[]; | |
| 28 | } | |
| 29 | ||
| 30 | /** | |
| 31 | * Exports of `ui.ts` that return words or numbers rather than markup, or are | |
| 32 | * re-exported helpers: they are seen inside the parts that use them. | |
| 33 | */ | |
| 34 | export const NOT_DRAWN: ReadonlySet<string> = new Set([ | |
| 35 | "timeAgo", "servedPhrase", "queuedPhrase", "fileSize", "labelCss", "hueOf", "envTone", "envPhrase", "when", | |
| 36 | ]); | |
| 37 | ||
| 38 | const LONG = | |
| 39 | "A title someone typed without ever stopping to think about how wide a phone is, carrying on past every sensible width and then a path: src/web/pages/an-extremely-long-file-name-that-never-breaks-on-its-own.ts"; | |
| 40 | const LONG_NAME = "a-person-whose-login-is-much-longer-than-anyone-planned-for"; | |
| 41 | const AT = "2026-10-25T09:30:00.000Z"; | |
| 42 | const BEFORE = "2026-10-25T09:29:52.000Z"; | |
| 43 | const OID = "3f9c2a1e8b7d6c5f4e3d2c1b0a9f8e7d6c5b4a39"; | |
| 44 | const many = <T>(n: number, f: (i: number) => T): T[] => Array.from({ length: n }, (_, i) => f(i)); | |
| 45 | ||
| 46 | const env = (over: Partial<EnvStatus> = {}): EnvStatus => ({ | |
| 47 | env: "production", | |
| 48 | state: "running", | |
| 49 | commitOid: OID, | |
| 50 | url: "https://notes.forge.example", | |
| 51 | runId: "01run", | |
| 52 | since: AT, | |
| 53 | createdAt: BEFORE, | |
| 54 | deployStartedAt: BEFORE, | |
| 55 | servingAt: AT, | |
| 56 | ...over, | |
| 57 | }); | |
| 58 | const ENVS: Record<string, EnvStatus> = { | |
| 59 | live: env(), | |
| 60 | deploying: env({ state: "deploying", servingAt: undefined }), | |
| 61 | failed: env({ state: "failed", error: "exited with code 1 before /healthz answered" }), | |
| 62 | asleep: env({ env: "pull-12", state: "stopped", dormant: { since: AT, idleSince: BEFORE } }), | |
| 63 | }; | |
| 64 | ||
| 65 | const BASE = "/alice/notes"; | |
| 66 | const label = (name: string, color = "0e8a16") => ({ name, color }); | |
| 67 | const rows = (n: number) => | |
| 68 | many(n, (i) => | |
| 69 | ui.row({ href: `#r${i}`, title: `Row ${i + 1}`, meta: html`${ui.time(AT)}`, trail: ui.pill(i), state: i % 3 === 0 ? "closed" : "open" }), | |
| 70 | ); | |
| 71 | ||
| 72 | /** The GET form every picker specimen's search box belongs to (`pages/design_components.ts` draws it). */ | |
| 73 | export const GALLERY_SEARCH_FORM = "gallery-search"; | |
| 74 | const repos = (n: number, checked: readonly number[]): ui.PickerOption[] => | |
| 75 | many(n, (i) => ({ | |
| 76 | value: `github/alice/repo-${i + 1}`, | |
| 77 | title: html`<span class="mono">alice/repo-${i + 1}</span>`, | |
| 78 | meta: i % 4 === 0 ? html`${ui.badge("private")} notes and drafts` : "a repository", | |
| 79 | search: `alice/repo-${i + 1} ${i % 4 === 0 ? "notes and drafts" : "a repository"}`, | |
| 80 | checked: checked.includes(i), | |
| 81 | })); | |
| 82 | const picker = (o: { id?: string; options: readonly ui.PickerOption[]; q?: string; page?: number; multiple?: boolean }) => | |
| 83 | ui.searchPicker({ | |
| 84 | id: o.id ?? "g-picker", | |
| 85 | label: "Repositories", | |
| 86 | name: "pick", | |
| 87 | options: o.options, | |
| 88 | q: o.q ?? "", | |
| 89 | searchForm: GALLERY_SEARCH_FORM, | |
| 90 | page: o.page ?? 1, | |
| 91 | pageHref: (page) => `#page-${page}`, | |
| 92 | ...(o.multiple === undefined ? {} : { multiple: o.multiple }), | |
| 93 | hint: "Enter searches every page.", | |
| 94 | }); | |
| 95 | ||
| 96 | export const SPECIMENS: readonly Specimen[] = [ | |
| 97 | // ---- text and time ---- | |
| 98 | { | |
| 99 | part: "icon", | |
| 100 | note: "A Lucide drawing from the page's sprite.", | |
| 101 | states: [{ state: "variants", draw: () => html`${(["issue", "pull", "merge", "check", "alert", "copy", "loader", "search"] as const).map((n) => ui.icon(n))}` }], | |
| 102 | }, | |
| 103 | { part: "time", note: "Relative time for the eye, the exact instant for machines.", states: [{ state: "default", draw: () => ui.time(AT) }, { state: "error", draw: () => html`[${ui.time("not a date")}]` }] }, | |
| 104 | { | |
| 105 | part: "tokenCount", | |
| 106 | note: "A token count, only ever beside a size or a cost.", | |
| 107 | states: [{ state: "variants", draw: () => html`${ui.tokenCount(1234, "estimated", "prose")} · ${ui.tokenCount(980_000, "counted")}` }], | |
| 108 | }, | |
| 109 | { part: "sizeWithTokens", note: "A file's bytes, and its tokens when it is text.", states: [{ state: "variants", draw: () => html`${ui.sizeWithTokens(48_213, "README.md")} · ${ui.sizeWithTokens(2_400_000, "logo.png")}` }] }, | |
| 110 | // ---- buttons ---- | |
| 111 | { | |
| 112 | part: "btn", | |
| 113 | note: "A button, or a link that looks like one.", | |
| 114 | states: [ | |
| 115 | { state: "variants", draw: () => html`<div class="bar">${(["primary", "secondary", "outline", "ghost", "danger", "link"] as const).map((v) => ui.btn(v, { variant: v, type: "button" }))}</div>` }, | |
| 116 | { state: "default", draw: () => html`<div class="bar">${ui.btn("Small", { size: "sm", type: "button" })}${ui.btn("Large", { size: "lg", type: "button" })}${ui.btn("With icon", { icon: "plus", type: "button" })}${ui.btn("Disabled", { disabled: true, type: "button" })}</div>` }, | |
| 117 | { state: "loading", draw: () => html`<button type="button" class="btn" aria-busy="true">${ui.icon("loader")}Saving</button>` }, | |
| 118 | { state: "long text", draw: () => ui.btn(LONG, { type: "button" }) }, | |
| 119 | ], | |
| 120 | }, | |
| 121 | { part: "iconBtn", note: "Icon only; the label is its name and tooltip.", states: [{ state: "variants", draw: () => html`<div class="bar">${ui.iconBtn("copy", "Copy", { type: "button" })}${ui.iconBtn("x", "Close", { variant: "ghost", type: "button" })}${ui.iconBtn("trash", "Delete", { variant: "danger", type: "button" })}</div>` }] }, | |
| 122 | { | |
| 123 | part: "copyField", | |
| 124 | note: "A string people copy: a read-only field and a copy button.", | |
| 125 | states: [ | |
| 126 | { state: "default", draw: () => ui.copyField("g-copy-a", "git clone https://forge.example/alice/notes.git", "Clone address", "Copy clone address") }, | |
| 127 | { state: "long text", draw: () => ui.copyField("g-copy-b", `https://forge.example/oauth/callback?state=${"x".repeat(160)}`, "Redirect URI", "Copy redirect URI") }, | |
| 128 | ], | |
| 129 | }, | |
| 130 | // ---- badges, labels, pills, dots ---- | |
| 131 | { | |
| 132 | part: "badge", | |
| 133 | note: "A short word with a tone.", | |
| 134 | states: [ | |
| 135 | { state: "variants", draw: () => html`<div class="bar">${(["default", "success", "danger", "merged", "attn"] as const).map((t) => ui.badge(t, { tone: t }))}${ui.badge("secondary", { variant: "secondary" })}${ui.badge("outline", { variant: "outline" })}</div>` }, | |
| 136 | { state: "long text", draw: () => ui.badge(LONG) }, | |
| 137 | ], | |
| 138 | }, | |
| 139 | { | |
| 140 | part: "stat", | |
| 141 | note: "A number with a label: one tile of a `.stats` grid.", | |
| 142 | states: [ | |
| 143 | { state: "default", draw: () => html`<div class="stats">${ui.stat({ label: "Open pulls", value: 12, note: "3 waiting on review" })}${ui.stat({ label: "Spend", value: "$4.20", tone: "attn", href: "#" })}</div>` }, | |
| 144 | { state: "empty", draw: () => html`<div class="stats">${ui.stat({ label: "Runs today", value: 0 })}</div>` }, | |
| 145 | { state: "long text", draw: () => html`<div class="stats">${ui.stat({ label: LONG, value: "1,234,567,890", note: LONG, noteTitle: LONG })}</div>` }, | |
| 146 | ], | |
| 147 | }, | |
| 148 | { part: "stateBadge", note: "Open, closed, parked or merged — the same on every page.", states: [{ state: "variants", draw: () => html`<div class="bar">${ui.stateBadge("open")}${ui.stateBadge("closed")}${ui.stateBadge("closed", true)}${ui.stateBadge("merged")}</div>` }] }, | |
| 149 | { part: "verdictBadge", note: "What a reviewer said; muted once a push made it stale.", states: [{ state: "variants", draw: () => html`<div class="bar">${ui.verdictBadge("approved")}${ui.verdictBadge("changes_requested")}${ui.verdictBadge("commented")}${ui.verdictBadge("approved", { stale: true })}</div>` }] }, | |
| 150 | { part: "runStateBadge", note: "A run's state, worn by checks, rows and logs.", states: [{ state: "variants", draw: () => html`<div class="bar">${(["queued", "running", "ok", "failed", "cancelled"] as const).map((s) => ui.runStateBadge(s))}${ui.runStateBadge("ok", "agent")}</div>` }] }, | |
| 151 | { part: "envStateBadge", note: "What production or a preview is doing now.", states: [{ state: "variants", draw: () => html`<div class="bar">${(["stopped", "deploying", "running", "asleep", "failed"] as const).map((s) => ui.envStateBadge(s))}${ui.envStateBadge("stopped", true)}</div>` }] }, | |
| 152 | { part: "dormantNote", note: "Why a preview sleeps — never a failure's words.", states: [{ state: "default", draw: () => ui.dormantNote(ENVS.asleep!) ?? html`` }, { state: "empty", draw: () => ui.dormantNote(ENVS.live!) ?? html`<span class="muted small">(nothing: awake)</span>` }] }, | |
| 153 | { | |
| 154 | part: "envLine", | |
| 155 | note: "An environment's facts as row meta.", | |
| 156 | states: [{ state: "variants", draw: () => html`${Object.entries(ENVS).map(([k, e]) => html`<p class="muted small">${k}: ${ui.envLine(BASE, e).map((p, i) => html`${i > 0 ? " · " : ""}${p}`)}</p>`)}` }], | |
| 157 | }, | |
| 158 | { | |
| 159 | part: "envFacts", | |
| 160 | note: "An environment's facts in a card: commit, speed, uptime, notes, errors.", | |
| 161 | states: [ | |
| 162 | { state: "default", draw: () => ui.envFacts(BASE, ENVS.live!, { url: true }) }, | |
| 163 | { state: "loading", draw: () => ui.envFacts(BASE, ENVS.deploying!) }, | |
| 164 | { state: "error", draw: () => ui.envFacts(BASE, ENVS.failed!) }, | |
| 165 | { state: "long text", draw: () => ui.envFacts(BASE, env({ error: LONG, note: LONG, url: `https://${"long-".repeat(20)}app.forge.example` }), { url: true }) }, | |
| 166 | ], | |
| 167 | }, | |
| 168 | { part: "previewDataNote", note: "Whose data a preview holds.", states: [{ state: "default", draw: () => ui.previewDataNote("copy", AT) ?? html`` }, { state: "empty", draw: () => ui.previewDataNote("empty", AT) ?? html`<span class="muted small">(nothing: empty policy)</span>` }] }, | |
| 169 | { | |
| 170 | part: "terminalLine", | |
| 171 | note: "An environment's terminal command, or why it is off.", | |
| 172 | states: [ | |
| 173 | { state: "default", draw: () => ui.terminalLine({ command: "ssh -p 2222 [email protected]" }, "SHA256:3f9c2a1e8b7d6c5f4e3d2c1b0a9f8e7d") }, | |
| 174 | { state: "empty", draw: () => html`${ui.terminalLine({ reason: "no_tty" })}${ui.terminalLine({ reason: "no_listener" })}` }, | |
| 175 | ], | |
| 176 | }, | |
| 177 | { part: "terminalCommand", note: "A command, copyable as one wrapping line.", states: [{ state: "long text", draw: () => ui.terminalCommand(`ssh -p 2222 ${LONG_NAME}@forge.example`, "SHA256:3f9c2a1e8b7d6c5f4e3d2c1b0a9f8e7d", html`<a href="#">How to connect</a>`) }] }, | |
| 178 | { part: "envActions", note: "Redeploy and stop, for a writer; nothing for a reader.", states: [{ state: "default", draw: () => html`<div class="bar">${ui.envActions(BASE, ENVS.live!, true)}</div>` }, { state: "empty", draw: () => ui.envActions(BASE, ENVS.live!, false) }] }, | |
| 179 | { | |
| 180 | part: "labelChip", | |
| 181 | note: "A label, its colour from `labelCss`.", | |
| 182 | states: [ | |
| 183 | { state: "variants", draw: () => html`<div class="bar">${ui.labelChip(label("bug", "d73a4a"))}${ui.labelChip(label("design", "5319e7"), "#")}${ui.labelChip(label("good first issue"))}</div>` }, | |
| 184 | { state: "long text", draw: () => ui.labelChip(label(LONG, "fbca04")) }, | |
| 185 | ], | |
| 186 | }, | |
| 187 | { part: "counts", note: "Icon-and-number facts; zero is never drawn.", states: [{ state: "default", draw: () => ui.counts([{ icon: "comment", value: 4, label: "4 comments" }, { icon: "fork", value: 1200, label: "1200 forks" }]) }, { state: "empty", draw: () => html`[${ui.counts([{ icon: "comment", value: 0, label: "none" }])}]` }] }, | |
| 188 | { part: "repoCounts", note: "Open issues and pulls on a repository row.", states: [{ state: "default", draw: () => ui.repoCounts({ openIssues: 7, openPulls: 2 }) }, { state: "empty", draw: () => html`[${ui.repoCounts({ openIssues: 0, openPulls: null })}]` }] }, | |
| 189 | { part: "pill", note: "A count beside a word.", states: [{ state: "variants", draw: () => html`<div class="bar">${ui.pill(3)}${ui.pill(12, "accent")}${ui.pill("99+", "danger")}</div>` }] }, | |
| 190 | { part: "dot", note: "A list's one-glance state.", states: [{ state: "variants", draw: () => html`<div class="bar">${(["default", "success", "danger", "merged", "attn"] as const).map((t) => ui.dot(t))}</div>` }] }, | |
| 191 | { part: "seriesDot", note: "A chart series' swatch.", states: [{ state: "variants", draw: () => html`<div class="bar">${many(6, (i) => ui.seriesDot(i + 1))}</div>` }] }, | |
| 192 | { part: "meter", note: "A share as a bar; `attn` when it is a limit reached.", states: [{ state: "variants", draw: () => html`<div class="stack">${ui.meter(0, "empty")}${ui.meter(42, "some")}${ui.meter(96, "nearly full", "attn")}${ui.meter(140, "clamped")}</div>` }] }, | |
| 193 | { | |
| 194 | part: "chartBox", | |
| 195 | note: "A drawn chart in the box that holds its space.", | |
| 196 | states: [ | |
| 197 | { state: "default", draw: () => ui.chartBox("bar", many(7, (i) => ({ label: `d${i + 1}`, value: (i * 7) % 11 })), "Runs a day") }, | |
| 198 | { state: "empty", draw: () => ui.chartBox("line", [], "No runs yet") }, | |
| 199 | { state: "200 items", draw: () => ui.chartBox("line", many(200, (i) => ({ label: `t${i}`, value: Math.round(50 + 40 * Math.sin(i / 9)) })), "200 points") }, | |
| 200 | ], | |
| 201 | }, | |
| 202 | { part: "sha", note: "A short object id, always seven characters.", states: [{ state: "variants", draw: () => html`<div class="bar">${ui.sha(OID)}${ui.sha(OID, "#")}</div>` }] }, | |
| 203 | { part: "kbd", note: "A key chord.", states: [{ state: "default", draw: () => ui.kbd(["⌘", "K"]) }] }, | |
| 204 | // ---- identity ---- | |
| 205 | { part: "avatar", note: "Initials on a stable hue.", states: [{ state: "variants", draw: () => html`<div class="bar">${ui.avatar("alice")}${ui.avatar("bob builder", "md")}${ui.avatar("mason", "lg")}</div>` }] }, | |
| 206 | { part: "userTag", note: "An author inside something that is already a link.", states: [{ state: "variants", draw: () => html`<div class="bar">${ui.userTag("alice", { mark: "owner" })}${ui.userTag("mason", { mark: "crew" })}${ui.userTag("bob", { avatar: false })}</div>` }, { state: "long text", draw: () => ui.userTag(LONG_NAME) }] }, | |
| 207 | { part: "originTag", note: "An author who is not an account here.", states: [{ state: "default", draw: () => ui.originTag("octocat", "globe") }] }, | |
| 208 | { part: "nameMark", note: "The owner's or the crew's mark beside a name.", states: [{ state: "variants", draw: () => html`<div class="bar">${ui.nameMark("owner")}${ui.nameMark("crew")}</div>` }] }, | |
| 209 | { part: "userLink", note: "An author as a link to their profile.", states: [{ state: "default", draw: () => ui.userLink("alice", { mark: "owner" }) }, { state: "long text", draw: () => ui.userLink(LONG_NAME, { display: LONG }) }] }, | |
| 210 | // ---- surfaces ---- | |
| 211 | { | |
| 212 | part: "card", | |
| 213 | note: "The one surface: head, body, foot, and a tone.", | |
| 214 | states: [ | |
| 215 | { state: "default", draw: () => ui.card(html`<p>Body text.</p>`, { head: html`<strong>Head</strong>`, foot: ui.btn("Action", { size: "sm", type: "button" }) }) }, | |
| 216 | { state: "variants", draw: () => html`<div class="stack">${(["success", "danger", "attn"] as const).map((t) => ui.card(html`<p>${t}</p>`, { tone: t }))}</div>` }, | |
| 217 | { state: "long text", draw: () => ui.card(html`<p>${LONG}</p>`, { head: html`<strong>${LONG}</strong>` }) }, | |
| 218 | ], | |
| 219 | }, | |
| 220 | { | |
| 221 | part: "listCard", | |
| 222 | note: "A card around a list of rows — the shape every listing takes.", | |
| 223 | states: [ | |
| 224 | { state: "default", draw: () => ui.listCard(rows(3)) }, | |
| 225 | { state: "empty", draw: () => ui.listCard([]) }, | |
| 226 | { state: "200 items", draw: () => ui.listCard(rows(200)) }, | |
| 227 | ], | |
| 228 | }, | |
| 229 | { part: "messageText", note: "Written text kept as typed — a commit message, a report body.", states: [{ state: "default", draw: () => ui.messageText("Fold the empty states into one part\n\nEvery page drew its own; now they call empty().") }, { state: "long text", draw: () => ui.messageText(LONG) }] }, | |
| 230 | { part: "disclosure", note: "Closed until asked for.", states: [{ state: "default", draw: () => ui.disclosure("Show the details", html`<p>The details.</p>`) }, { state: "variants", draw: () => ui.disclosure("Small, muted", html`<p>Tucked away.</p>`, { small: true }) }, { state: "long text", draw: () => ui.disclosure(LONG, html`<p>${LONG}</p>`) }] }, | |
| 231 | { | |
| 232 | part: "row", | |
| 233 | note: "One list row: a link, its own controls, or a fold.", | |
| 234 | states: [ | |
| 235 | { | |
| 236 | state: "variants", | |
| 237 | draw: () => | |
| 238 | html`<ul class="list">${ui.row({ href: "#", title: "A link row", meta: html`opened ${ui.time(AT)}`, lead: ui.dot("success"), trail: ui.pill(4), state: "open" })}${ui.row({ title: "A row with controls", trail: ui.btn("Act", { size: "sm", type: "button" }) })}${ui.row({ title: "The current row", current: true })}${ui.row({ title: "A folded row", fold: { id: "g-fold", open: false, body: html`<p class="muted small">Folded body.</p>` } })}${ui.row({ title: "A parent", children: [ui.row({ title: "A child" })] })}</ul>`, | |
| 239 | }, | |
| 240 | { state: "long text", draw: () => html`<ul class="list">${ui.row({ href: "#", title: LONG, titleAttr: LONG, meta: html`${LONG}`, trail: ui.badge("trail") })}</ul>` }, | |
| 241 | ], | |
| 242 | }, | |
| 243 | // ---- navigation ---- | |
| 244 | { | |
| 245 | part: "tabs", | |
| 246 | note: "Link tabs: navigation, so `aria-current`.", | |
| 247 | states: [ | |
| 248 | { state: "default", draw: () => ui.tabs([{ label: "Code", href: "#", icon: "code", current: true }, { label: "Issues", href: "#", icon: "issue", count: 7 }, { label: "Pulls", href: "#", icon: "pull", count: 0 }], "Repository") }, | |
| 249 | { state: "200 items", draw: () => ui.tabs(many(200, (i) => ({ label: `Tab ${i + 1}`, href: "#", count: i, current: i === 0 })), "Many tabs") }, | |
| 250 | ], | |
| 251 | }, | |
| 252 | { | |
| 253 | part: "seg", | |
| 254 | note: "A segmented filter built from links.", | |
| 255 | states: [ | |
| 256 | { state: "default", draw: () => ui.seg([{ label: "Open", href: "#", current: true, count: 12 }, { label: "Closed", href: "#", current: false }, { label: "All", href: "#", current: false }]) }, | |
| 257 | { state: "long text", draw: () => ui.seg([{ label: LONG, href: "#", current: true }, { label: "Short", href: "#", current: false }]) }, | |
| 258 | ], | |
| 259 | }, | |
| 260 | { part: "crumbs", note: "Where you are.", states: [{ state: "default", draw: () => ui.crumbs([{ label: "alice", href: "#" }, { label: "notes", href: "#" }, { label: "src" }]) }, { state: "long text", draw: () => ui.crumbs(many(8, (i) => ({ label: `${LONG_NAME}-${i}`, href: "#" })), { mono: true }) }] }, | |
| 261 | { part: "pager", note: "Cursor pagination with an honest end.", states: [{ state: "default", draw: () => ui.pager({ prev: "#", next: "#", note: "21–40" }) }, { state: "variants", draw: () => ui.pager({ next: "#" }) }, { state: "empty", draw: () => html`[${ui.pager({})}]` }] }, | |
| 262 | { | |
| 263 | part: "menu", | |
| 264 | note: "A dropdown on `<details>`, correct with JS off.", | |
| 265 | states: [ | |
| 266 | { state: "default", draw: () => ui.menu({ trigger: html`${ui.icon("chevronDown")}Menu`, title: "Actions", items: [{ label: "Open", href: "#", icon: "external", current: true }, { separator: true, label: "" }, { label: "Delete", post: "#", icon: "trash" }, { label: "Archive", disabled: "Only the owner can archive" }] }) }, | |
| 267 | { state: "200 items", draw: () => ui.menu({ trigger: "200 items", items: many(200, (i) => ({ label: `Item ${i + 1}`, href: "#" })) }) }, | |
| 268 | ], | |
| 269 | }, | |
| 270 | // ---- forms ---- | |
| 271 | { | |
| 272 | part: "field", | |
| 273 | note: "Label, control, hint and error, wired with `aria-describedby`.", | |
| 274 | states: [ | |
| 275 | { state: "default", draw: () => ui.field({ label: "Name", name: "g-name", hint: "Letters, digits and dashes.", placeholder: "my-app" }) }, | |
| 276 | { state: "error", draw: () => ui.field({ label: "Name", name: "g-name-err", value: "My App!", error: "Use letters, digits and dashes only." }) }, | |
| 277 | { state: "variants", draw: () => ui.field({ label: "Description", name: "g-desc", type: "textarea", rows: 3 }) }, | |
| 278 | { state: "long text", draw: () => ui.field({ label: LONG, name: "g-long", value: LONG, hint: LONG, error: LONG }) }, | |
| 279 | ], | |
| 280 | }, | |
| 281 | { | |
| 282 | part: "selectField", | |
| 283 | note: "A select with the field's anatomy.", | |
| 284 | states: [ | |
| 285 | { state: "default", draw: () => ui.selectField({ label: "Visibility", name: "g-vis", options: [{ value: "private", label: "Private", selected: true }, { value: "public", label: "Public" }] }) }, | |
| 286 | { state: "error", draw: () => ui.selectField({ label: "Visibility", name: "g-vis-err", error: "Choose one.", options: [{ value: "", label: "—" }] }) }, | |
| 287 | { state: "200 items", draw: () => ui.selectField({ label: "Repository", name: "g-many", options: many(200, (i) => ({ value: String(i), label: `repository-${i + 1}` })) }) }, | |
| 288 | ], | |
| 289 | }, | |
| 290 | { | |
| 291 | part: "searchPicker", | |
| 292 | note: "A long list to pick from: searchable, paged, multi-select; picks off the page ride along.", | |
| 293 | states: [ | |
| 294 | { state: "default", draw: () => picker({ options: repos(6, [1, 4]) }) }, | |
| 295 | { state: "variants", draw: () => picker({ id: "g-picker-one", options: repos(4, [2]), multiple: false }) }, | |
| 296 | { state: "empty", draw: () => html`<div class="stack">${picker({ id: "g-picker-none", options: [] })}${picker({ id: "g-picker-miss", options: repos(6, []), q: "zzz" })}</div>` }, | |
| 297 | { state: "long text", draw: () => picker({ id: "g-picker-long", options: [{ value: "long", title: LONG, meta: LONG, search: LONG }] }) }, | |
| 298 | { state: "200 items", draw: () => picker({ id: "g-picker-many", options: repos(200, [3, 120]), page: 2 }) }, | |
| 299 | ], | |
| 300 | }, | |
| 301 | { part: "confirmAction", note: "A destructive action, never one careless click away.", states: [{ state: "default", draw: () => ui.confirmAction({ action: "/alice/notes/settings/delete", verb: "Delete repository", size: "sm" }) }] }, | |
| 302 | // ---- states ---- | |
| 303 | { | |
| 304 | part: "empty", | |
| 305 | note: "What a list says when it holds nothing, and the next step.", | |
| 306 | states: [ | |
| 307 | { state: "default", draw: () => ui.empty({ icon: "issue", title: "No open issues", note: "Issues are how people tell the crew what to do.", action: ui.btn("New issue", { href: "#", variant: "primary", size: "sm" }) }) }, | |
| 308 | { state: "long text", draw: () => ui.empty({ title: LONG, note: LONG }) }, | |
| 309 | ], | |
| 310 | }, | |
| 311 | { part: "tlEvent", note: "A low-emphasis timeline row.", states: [{ state: "variants", draw: () => html`<div class="timeline">${ui.tlEvent({ icon: "merge", tone: "merged", body: html`<span>alice merged this ${ui.time(AT)}</span>` })}${ui.tlEvent({ icon: "x", tone: "danger", body: html`<span>the check failed</span>` })}</div>` }] }, | |
| 312 | { part: "tlComment", note: "A comment-weight timeline row.", states: [{ state: "default", draw: () => html`<div class="timeline">${ui.tlComment(ui.card(html`<p>Looks good to me.</p>`, { head: ui.userLink("bob") }))}</div>` }] }, | |
| 313 | ]; |
src/web/layout.ts +2
| @@ -232,6 +232,7 @@ function userMenu( | ||
| 232 | 232 | : [ |
| 233 | 233 | { label: "Boards", href: "/boards", icon: "activity" as const }, |
| 234 | 234 | { label: "System memory", href: "/system", icon: "activity" as const }, |
| 235 | { label: "Components", href: "/design/components", icon: "eye" as const }, | |
| 235 | 236 | ]), |
| 236 | 237 | ] |
| 237 | 238 | : []), |
| @@ -329,6 +330,7 @@ function paletteIndex(ctx: Ctx, extra: PaletteItem[]): Html { | ||
| 329 | 330 | ...(ctx.auth.user?.isAdmin |
| 330 | 331 | ? [ |
| 331 | 332 | { t: "System", h: "/system", c: "Go to" }, |
| 333 | { t: "Components", h: "/design/components", c: "Go to" }, | |
| 332 | 334 | { t: "Forges you sent", h: "/forges", c: "Go to" }, |
| 333 | 335 | { t: "Family of forges", h: "/family", c: "Go to" }, |
| 334 | 336 | ] |
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); } | ||
| 904 | 904 | .palette .palette-input { font-size: 16px; } |
| 905 | 905 | } |
| 906 | 906 | |
| 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 | ||
| 907 | 917 | /* Forced colours drop box-shadow rings and author colours: the focus ring is |
| 908 | 918 | an outline the system paints. */ |
| 909 | 919 | @media (forced-colors: active) { |
src/web/ui.ts +90
| @@ -1236,6 +1236,96 @@ export function selectField( | ||
| 1236 | 1236 | </div>`; |
| 1237 | 1237 | } |
| 1238 | 1238 | |
| 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 | ||
| 1239 | 1329 | /** |
| 1240 | 1330 | * A destructive action. With JS it opens a `<dialog>`; without it the button |
| 1241 | 1331 | * 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 | }); |
test/design-gallery.test.ts added +171
| @@ -0,0 +1,171 @@ | ||
| 1 | /** | |
| 2 | * The living gallery (#5817): every part `ui.ts` draws has a specimen, the | |
| 3 | * states the issue names are all shown, `/design/components` answers an | |
| 4 | * admin with every part and anyone else with the not-found page, and its | |
| 5 | * query takes only the themes and widths it knows. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp } from "../src/app.ts"; | |
| 12 | import { createToken } from "../src/core/tokens.ts"; | |
| 13 | import { createUser } from "../src/core/users.ts"; | |
| 14 | import { serve } from "../src/http/server.ts"; | |
| 15 | import { NOT_DRAWN, SPECIMENS, STATES } from "../src/web/gallery.ts"; | |
| 16 | import { readGalleryQuery } from "../src/web/pages/design_components.ts"; | |
| 17 | import * as ui from "../src/web/ui.ts"; | |
| 18 | ||
| 19 | describe("the specimens", () => { | |
| 20 | test("every function ui.ts exports is drawn in the gallery or named as not drawn", () => { | |
| 21 | const parts = Object.entries(ui) | |
| 22 | .filter(([, value]) => typeof value === "function") | |
| 23 | .map(([name]) => name); | |
| 24 | const drawn = new Set(SPECIMENS.map((s) => s.part)); | |
| 25 | expect(parts.filter((p) => !drawn.has(p as keyof typeof ui) && !NOT_DRAWN.has(p))).toEqual([]); | |
| 26 | expect([...NOT_DRAWN].filter((p) => !parts.includes(p))).toEqual([]); | |
| 27 | }); | |
| 28 | ||
| 29 | test("a part appears once, and every state draws markup", () => { | |
| 30 | expect(new Set(SPECIMENS.map((s) => s.part)).size).toBe(SPECIMENS.length); | |
| 31 | for (const s of SPECIMENS) { | |
| 32 | expect(s.states.length).toBeGreaterThan(0); | |
| 33 | for (const st of s.states) expect(typeof st.draw().text).toBe("string"); | |
| 34 | } | |
| 35 | }); | |
| 36 | ||
| 37 | test("each state the issue names is shown by some part", () => { | |
| 38 | const shown = new Set(SPECIMENS.flatMap((s) => s.states.map((st) => st.state))); | |
| 39 | for (const state of ["empty", "loading", "error", "long text", "200 items"] as const) expect(shown.has(state)).toBe(true); | |
| 40 | expect([...shown].every((s) => (STATES as readonly string[]).includes(s))).toBe(true); | |
| 41 | }); | |
| 42 | ||
| 43 | test("the lists that hold many rows are shown holding 200", () => { | |
| 44 | for (const part of ["listCard", "menu", "selectField", "tabs", "chartBox"]) { | |
| 45 | const s = SPECIMENS.find((x) => x.part === part)!; | |
| 46 | const many = s.states.find((st) => st.state === "200 items"); | |
| 47 | expect(many).toBeDefined(); | |
| 48 | } | |
| 49 | const list = SPECIMENS.find((x) => x.part === "listCard")!.states.find((st) => st.state === "200 items")!.draw().text; | |
| 50 | expect(list.match(/<li/g)?.length).toBe(200); | |
| 51 | }); | |
| 52 | }); | |
| 53 | ||
| 54 | describe("the query", () => { | |
| 55 | test("keeps a known theme, width and part, and drops anything else", () => { | |
| 56 | expect(readGalleryQuery(new URLSearchParams("theme=dark&w=390&part=btn"))).toEqual({ theme: "dark", w: "390", part: "btn" }); | |
| 57 | expect(readGalleryQuery(new URLSearchParams("theme=%22%3E%3Cscript%3E&w=391&part=constructor"))).toEqual({ | |
| 58 | theme: undefined, | |
| 59 | w: undefined, | |
| 60 | part: undefined, | |
| 61 | }); | |
| 62 | }); | |
| 63 | }); | |
| 64 | ||
| 65 | describe("/design/components", () => { | |
| 66 | let dir: string; | |
| 67 | let app: ReturnType<typeof createApp>; | |
| 68 | let servers: Awaited<ReturnType<typeof serve>>; | |
| 69 | const tok: Record<string, string> = {}; | |
| 70 | const get = (path: string, who: string | null) => | |
| 71 | fetch(servers.url + path, { headers: who ? { authorization: `Bearer ${tok[who]}` } : {} }); | |
| 72 | ||
| 73 | beforeAll(async () => { | |
| 74 | dir = await mkdtemp(join(tmpdir(), "forge-design-gallery-")); | |
| 75 | app = createApp({ dataDir: dir, port: 0 }); | |
| 76 | servers = await serve(app); | |
| 77 | const mk = async (username: string, adminIfFirst?: boolean) => { | |
| 78 | const r = await createUser(app.db, { | |
| 79 | origin: "seed", | |
| 80 | trusted: true, | |
| 81 | username, | |
| 82 | email: `${username}@forge.local`, | |
| 83 | password: "a-good-passphrase", | |
| 84 | ...(adminIfFirst ? { adminIfFirst } : {}), | |
| 85 | }); | |
| 86 | if (!r.ok) throw new Error(r.error); | |
| 87 | return r.value; | |
| 88 | }; | |
| 89 | const alice = await mk("alice", true); | |
| 90 | const bob = await mk("bob"); | |
| 91 | tok.admin = createToken(app.db, alice.id, "t", "admin").token; | |
| 92 | tok.bob = createToken(app.db, bob.id, "t", "admin").token; | |
| 93 | }); | |
| 94 | ||
| 95 | afterAll(async () => { | |
| 96 | servers.stop(); | |
| 97 | app.close(); | |
| 98 | await rm(dir, { recursive: true, force: true }); | |
| 99 | }); | |
| 100 | ||
| 101 | test("an admin sees every part, and the page keeps the security floor", async () => { | |
| 102 | const res = await get("/design/components", "admin"); | |
| 103 | expect(res.status).toBe(200); | |
| 104 | expect(res.headers.get("content-security-policy")).toContain("frame-ancestors 'none'"); | |
| 105 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 106 | const body = await res.text(); | |
| 107 | for (const s of SPECIMENS) expect(body).toContain(`id="part-${s.part}"`); | |
| 108 | expect(body).toContain('data-state="200 items"'); | |
| 109 | }); | |
| 110 | ||
| 111 | test("a theme and a width are applied, and a part narrows the page to one", async () => { | |
| 112 | const body = await (await get("/design/components?theme=dark&w=390&part=btn", "admin")).text(); | |
| 113 | expect(body).toMatch(/<html lang="en"\s+data-theme="dark"/); | |
| 114 | expect(body).toContain('class="gallery-frame" data-w="390"'); | |
| 115 | expect(body).toContain('id="part-btn"'); | |
| 116 | expect(body).not.toContain('id="part-row"'); | |
| 117 | }); | |
| 118 | ||
| 119 | test("a value the gallery does not know is ignored, never echoed", async () => { | |
| 120 | const body = await (await get("/design/components?theme=%22%3E%3Cb%3Ex&w=9999", "admin")).text(); | |
| 121 | expect(body).not.toContain("<b>x"); | |
| 122 | expect(body).not.toContain('data-w="9999"'); | |
| 123 | }); | |
| 124 | ||
| 125 | test("anyone but an admin gets the not-found page", async () => { | |
| 126 | expect((await get("/design/components", "bob")).status).toBe(404); | |
| 127 | expect((await get("/design/components", null)).status).toBe(404); | |
| 128 | }); | |
| 129 | ||
| 130 | test("the admin menu links to it", async () => { | |
| 131 | const body = await (await get("/", "admin")).text(); | |
| 132 | expect(body).toContain('href="/design/components"'); | |
| 133 | }); | |
| 134 | }); | |
| 135 | ||
| 136 | describe("searchPicker", () => { | |
| 137 | const opts = (n: number, checked: number[] = []) => | |
| 138 | Array.from({ length: n }, (_, i) => ({ value: `v${i}`, title: `repo-${i}`, search: `repo-${i}${i === 7 ? " needle" : ""}`, checked: checked.includes(i) })); | |
| 139 | const draw = (o: Partial<Parameters<typeof ui.searchPicker>[0]> = {}) => | |
| 140 | ui.searchPicker({ id: "p", label: "Repos", name: "pick", options: opts(120, [0, 110]), q: "", searchForm: "s", page: 1, pageHref: (p) => `/x?page=${p}`, ...o }).text; | |
| 141 | const boxes = (text: string) => [...text.matchAll(/type="checkbox" name="pick" value="(v\d+)"/g)].map((m) => m[1]); | |
| 142 | ||
| 143 | test("draws one page, links the next, and carries a pick from another page", () => { | |
| 144 | const text = draw(); | |
| 145 | expect(boxes(text)).toHaveLength(ui.PICKER_PAGE); | |
| 146 | expect(text).toContain('href="/x?page=2"'); | |
| 147 | expect(text).toContain("page 1 of 3"); | |
| 148 | expect(text).toMatch(/type="hidden" name="pick" value="v110"/); | |
| 149 | expect(text).not.toMatch(/type="hidden" name="pick" value="v0"/); | |
| 150 | }); | |
| 151 | ||
| 152 | test("filters by its search words, and a pick the filter hides still rides along", () => { | |
| 153 | const text = draw({ q: " NEEDLE " }); | |
| 154 | expect(boxes(text)).toEqual(["v7"]); | |
| 155 | expect(text).toMatch(/type="hidden" name="pick" value="v0"/); | |
| 156 | expect(text).not.toContain("page 1 of"); | |
| 157 | }); | |
| 158 | ||
| 159 | test("an out-of-range page reads as the nearest, and nothing matching says so", () => { | |
| 160 | expect(draw({ page: 99 })).toContain("page 3 of 3"); | |
| 161 | expect(draw({ page: Number.NaN })).toContain("page 1 of 3"); | |
| 162 | expect(draw({ q: "<b>zzz" })).toContain("Nothing matches “<b>zzz”."); | |
| 163 | expect(draw({ options: [] })).toContain("Nothing to pick from yet."); | |
| 164 | }); | |
| 165 | ||
| 166 | test("the search box belongs to the GET form, and a single pick is a radio", () => { | |
| 167 | expect(draw()).toMatch(/type="search"[^>]*name="q"[^>]*form="s"/); | |
| 168 | expect(draw({ multiple: false })).toContain('type="radio" name="pick"'); | |
| 169 | expect(draw({ multiple: false })).not.toContain("data-picker-picked"); | |
| 170 | }); | |
| 171 | }); |
new above
offline