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

Studio Design tab: a component explorer and a live theme editor; themes compile to edge-served CSS that updates every app on the theme in real time #16254

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/6297-studio-design-tab-a-component-explorer-a → main 0 commits fork

  • Merged. scout/6297-studio-design-tab-a-component-explorer-a was merged into main as 9e366fa.

Review

Sign in to review this change.
19 files changed +1109 −4
docs/design/areas/design.md added +38
@@ -0,0 +1,38 @@
1 ---
2 docs: Develop it | Themes and components | the Design tab edits the forge's theme, served at `/design/theme.css`, and explores its components.
3 ---
4
5 # Design tab (#6297)
6
7 New classes, all in the page's own nonce'd sheet (`web/studio/design.ts`), built from the theme's spacing unit (`--theme-space`):
8
9 - `.design-roles`: a run of `.design-field` rows under a heading.
10 - `.design-field`: a label and its colour or number input on one row.
11 - `.design-previews`: the four side-by-side samples (current/draft × light/dark).
12 - `.design-sample`: one sample, set off by a hairline above; its `pv-*` scope class sets the draft's custom properties.
13 - `.cx-grid` (auto-fit columns) and `.cx-cell` (one sample, no border) on `/design/components`; `.cx-light` and `.cx-dark` set the custom properties for the draft in the URL.
14
15 The theme's own variables are the palette roles plus `--theme-radius`, `--theme-space`, `--theme-text` and `--theme-motion`, set by `/design/theme.css`.
16
17 ## How to use it
18
19 This page is for site admins, who edit the theme, and for anyone signed in, who may look. The studio's Design tab (`/design`) sets the forge's colours and scales, checks them against WCAG AA, and publishes a version. Its Components page (`/design/components`) shows the forge's own components in light and dark.
20
21 ### Edit and publish
22
23 - The colour roles are set for light and for dark. The four scales are radius, spacing, type size and motion. Each is a bounded number; each colour is `#rrggbb`.
24 - Preview draft puts your fields in the URL, so a draft is a link. The four samples show the live theme and the draft, light and dark.
25 - A draft with a text pair under WCAG AA is Blocked, and Publish is off. A site admin publishes; anyone else sees "Only an admin can publish."
26 - Publish compiles a versioned file. Revert publishes the version before the current one again (the defaults when there is none). State is the `theme_version` table.
27
28 ### Where the theme is applied
29
30 Every page links `/design/theme.css`, which is revalidated on each load, so a publish reaches a page on its next load. Only the Design page listens to `/design/theme/forge/live` and swaps the stylesheet without a reload. A theme per app is not built: only the forge's own theme is applied.
31
32 ### In the terminal
33
34 Open the palette and choose "Design: the forge's theme" (`src/tui/screens/design.ts`). It shows the live version, every field, the AA verdict of the draft and the history. `j`/`k` move, `e` sets the field under the cursor into a draft, `p` publishes the draft, `r` reverts, `x` drops the draft. The page and the terminal call the same `steerTheme`: the same admin gate (a site admin who is a person) and the same `theme.published` event.
35
36 ### Components
37
38 `?q=` filters the list. The fields of the editor carried in the URL draw the components against a draft.
docs/design/audit.md +2
@@ -80,6 +80,8 @@ Machine routes are not pages and have no entry: `/audit.csv`,
8080 - `/audit` — `pages/audit.ts` · every app's contract, who can do what · the app page's one-line policy · none seen. Names the audit of apps, not this document.
8181 - `/repos` — `pages/my-repos.ts` · the repositories you may write, from the account menu · `/` (your apps), `/:owner` (a profile's repositories) · none seen.
8282 - `/releases` — `pages/releases.ts` · the forge's kept releases and rollback · `/settings/backups` (both are "go back") · none seen.
83 - `/design` — `studio/design.ts` · the forge's theme: colour and scale fields, four side-by-side samples, publish and revert for an admin, history; a non-admin reads it · `/design/components` · none seen.
84 - `/design/components` — `studio/design.ts` · the forge's components drawn with the live theme, searchable, signed in · `/design` · none seen.
8385 - `/changelog` — `pages/changelog.ts` · the last 30 releases with their dates and pulls, public · `/releases` (the signed-in kept releases) · none seen.
8486 - `/displays` — `pages/displays.ts` · every display the viewer may read, each with its layout, repository and showcased demos; a stranger signs in first · none yet (read only; a repository's display is its own page) · none seen.
8587 - `/api` — `pages/api.ts` · the forge's OpenAPI operations by area, with search and Try it, public · the footer, the OpenAPI document, the terminal's API screen · none seen. An app's own spec is its `/:owner/:name/api` tab.
src/core/account_purge.ts +1
@@ -81,6 +81,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
8181 "event.actor_id": FORMER,
8282 "file_hold.by": FORMER,
8383 "first_ask_refusals.actor_id": DELETE,
84 "theme_version.actor_id": FORMER,
8485 "fleet_operation.undone_by": FORMER,
8586 "fold_in_stop.by": FORMER,
8687 "heap_census.by_type": { do: "none", why: "a memory reading's per-type sizes" },
src/core/event_audience.ts +2
@@ -225,6 +225,8 @@ const READER_KINDS: ReadonlySet<string> = new Set([
225225 "chapter.item_moved",
226226 "chapter.closed",
227227 "chapter.reopened",
228 // A published theme version: every open page restyles (`web/studio/design.ts`).
229 "theme.published",
228230 ]);
229231
230232 /**
src/core/migration-pins/20261026140000-theme-version.pin added +1
@@ -0,0 +1,1 @@
1 402a11a16321a7ba4e3a15d98ee9fb793309fa39126ca580ec033a0a7c62ac70
src/core/migrations/20261026140000-theme-version.ts added +16
@@ -0,0 +1,16 @@
1 // Themes are data (#6297): one row per published version of a named theme,
2 // who published it, and the CSS it compiled to. History is the table;
3 // revert publishes an old version's tokens again as a new row. Additive.
4 export default `
5 CREATE TABLE IF NOT EXISTS theme_version (
6 org TEXT NOT NULL,
7 name TEXT NOT NULL,
8 version INTEGER NOT NULL,
9 tokens TEXT NOT NULL,
10 css TEXT NOT NULL,
11 actor_id TEXT NOT NULL,
12 note TEXT NOT NULL DEFAULT '',
13 created_at INTEGER NOT NULL,
14 PRIMARY KEY (org, name, version)
15 );
16 `;
src/core/reserved.ts +1
@@ -84,6 +84,7 @@ export const SYSTEM_NAMES: readonly string[] = [
8484 "events",
8585 "bring",
8686 "explore",
87 "design",
8788 "packs",
8889 "family",
8990 "favicon.ico",
src/http/marks/design.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/design",
3 "mark": "open"
4 }
src/http/server.ts +7
@@ -369,6 +369,7 @@ import { HOME_REGIONS } from "../web/studio/home_last.ts";
369369 import { serviceWorker } from "../web/sw.ts";
370370 import { offlinePage } from "../web/pages/offline.ts";
371371 import { explorePage } from "../web/studio/explore.ts";
372 import { componentsPage, designPage, designPublish, designRevert, themeFile, themeLive } from "../web/studio/design.ts";
372373 import { exploreJson } from "./explore_json.ts";
373374 import { isPacksMirror, MIRROR_PUSH_REFUSED } from "../packs/owner.ts";
374375 import { packEdit, packNew, packPage, packRepos, packsMirror, packsPage } from "../web/pages/packs.ts";
@@ -1025,6 +1026,12 @@ export function buildRouter(): Router<Handler> {
10251026 router.add("GET", "/front", studioDoor);
10261027 // Apps and people ranked by real numbers, narrowed in one line (#607).
10271028 router.add("GET", "/explore", explorePage);
1029 router.add("GET", "/design", designPage);
1030 router.add("GET", "/design/components", componentsPage);
1031 router.add("POST", "/design/publish", designPublish);
1032 router.add("POST", "/design/revert", designRevert);
1033 router.add("GET", "/design/theme.css", themeFile);
1034 router.add("GET", "/design/theme/forge/live", themeLive);
10281035 router.add("GET", "/explore.atom", exploreAtom);
10291036 // The page's JSON form (#15744): the same rows, with each row's score parts and the filters read.
10301037 router.add("GET", "/explore.json", (ctx) => exploreJson(ctx));
src/tui/screens/design.ts added +147
@@ -0,0 +1,147 @@
1 /**
2 * The forge's theme, in the terminal (#6297): the Design tab's live version,
3 * its colour roles and scales, the WCAG AA verdict of the draft, and the two
4 * writes. `e` edits the role or scale under the cursor into a draft, `p`
5 * publishes the draft, `r` reverts to the version before, `x` drops the draft.
6 * Both writes go through `steerTheme` (`web/studio/design.ts`), the web page's own
7 * call: the same admin gate (a site admin who is a person), the same
8 * `theme.published` event, so an open Design page picks a publish up live.
9 */
10
11 import {
12 FORGE_THEME,
13 ROLES,
14 SCALES,
15 contrastFailures,
16 liveTokens,
17 mayEditTheme,
18 steerTheme,
19 themeHistory,
20 validateTokens,
21 type ThemeTokens,
22 } from "../../web/studio/design.ts";
23 import type { Ctx, Screen } from "../app/app.ts";
24 import { binding } from "../app/keys.ts";
25 import type { Session } from "../session.ts";
26 import { style } from "../term/style.ts";
27 import { Scroll, drawLines, hitScroll, live, promptScreen } from "./common.ts";
28 import type { PaletteEntry } from "./entries.ts";
29
30 /** One editable field: a role in a mode, or a scale. */
31 export type Field = { kind: "role"; mode: "light" | "dark"; role: (typeof ROLES)[number] } | { kind: "scale"; key: keyof typeof SCALES };
32
33 export const FIELDS: readonly Field[] = [
34 ...(["light", "dark"] as const).flatMap((mode) => ROLES.map((role): Field => ({ kind: "role", mode, role }))),
35 ...(Object.keys(SCALES) as (keyof typeof SCALES)[]).map((key): Field => ({ kind: "scale", key })),
36 ];
37
38 const nameOf = (f: Field): string => (f.kind === "role" ? `${f.mode} ${f.role}` : SCALES[f.key].label);
39 const valueOf = (t: ThemeTokens, f: Field): string => (f.kind === "role" ? t[f.mode][f.role] : String(t.scales[f.key]));
40
41 /** The draft with one field set; the value is checked by `validateTokens` as ever. */
42 export function withField(t: ThemeTokens, f: Field, value: string): unknown {
43 const d = structuredClone(t);
44 if (f.kind === "role") d[f.mode][f.role] = value;
45 else d.scales[f.key] = Number(value);
46 return d;
47 }
48
49 /** The screen's lines: the verdict first, then each field, then the history. */
50 export function designLines(session: Session, draft: unknown, at = -1): string[] {
51 const { db } = session;
52 const live = liveTokens(db, FORGE_THEME.org, FORGE_THEME.name);
53 const parsed = validateTokens(draft ?? live.tokens);
54 const shown = parsed.ok ? parsed.value : live.tokens;
55 const failures = parsed.ok ? contrastFailures(shown) : [];
56 const lines = [
57 `Live: v${String(live.version)}${live.version === 0 ? " (defaults)" : ""}${draft === undefined ? "" : " Draft: not published"}`,
58 !parsed.ok
59 ? `Draft refused: ${parsed.error}`
60 : failures.length === 0
61 ? "AA passes: every text pair in light and dark meets WCAG AA."
62 : `Blocked: ${failures.map((f) => `${f.mode} ${f.pair} ${String(f.ratio)}:1 (needs ${String(f.need)}:1)`).join("; ")}`,
63 "",
64 ];
65 FIELDS.forEach((f, i) => lines.push(`${i === at ? ">" : " "} ${nameOf(f).padEnd(24)} ${valueOf(shown, f)}`));
66 const history = themeHistory(db, FORGE_THEME.org, FORGE_THEME.name, 5);
67 lines.push("", history.length === 0 ? "Nothing published yet." : "History:", ...history.map((v) => ` v${String(v.version)} ${v.note}`));
68 return lines;
69 }
70
71 export function designScreen(session: Session, ctx: Ctx): Screen {
72 const scroll = new Scroll();
73 let draft: unknown;
74 let at = 0;
75 const tokens = (): ThemeTokens => liveTokens(session.db, FORGE_THEME.org, FORGE_THEME.name).tokens;
76 const steer = (action: "publish" | "revert"): void => {
77 const done = steerTheme(session.app, session.user, action, draft);
78 if (done.ok) {
79 draft = undefined;
80 ctx.toast(`Published v${String(done.version)}.`);
81 } else ctx.toast(done.error === "forbidden" ? "A site admin steers the theme." : done.error, "danger");
82 ctx.invalidate();
83 };
84 const screen: Screen = {
85 title: "Design: the forge's theme",
86 keys: [binding(["j", "k"], "move"), binding(["e"], "edit"), binding(["p"], "publish"), binding(["r"], "revert"), binding(["x"], "drop draft")],
87 async load(signal) {
88 live(session, signal, { where: (e) => e.kind === "theme.published" }, () => ctx.invalidate());
89 },
90 render(area, s) {
91 const c = ctx.theme.c;
92 const lines = designLines(session, draft, at);
93 drawLines(s, area, c, scroll, lines.map((text) => [{ text, style: style(text.startsWith(">") ? c.fg : c.mutedFg, c.bg) }]));
94 hitScroll(ctx, area, scroll, lines.length);
95 },
96 key(e) {
97 if (e.key === "esc" || e.key === "q") return ctx.pop(), true;
98 if (e.key === "j") return (at = Math.min(FIELDS.length - 1, at + 1)), ctx.invalidate(), true;
99 if (e.key === "k") return (at = Math.max(0, at - 1)), ctx.invalidate(), true;
100 if (e.ctrl || e.alt) return false;
101 if (!mayEditTheme(session.user)) {
102 if (e.key !== "e" && e.key !== "p" && e.key !== "r") return false;
103 ctx.toast("A site admin steers the theme.", "danger");
104 return true;
105 }
106 const f = FIELDS[at]!;
107 if (e.key === "e")
108 ctx.push(
109 promptScreen(ctx, screen, {
110 title: `Set ${nameOf(f)}`,
111 label: nameOf(f),
112 value: valueOf(parsedDraft(draft, tokens()), f),
113 hint: f.kind === "role" ? "#rrggbb" : `${String(SCALES[f.key].min)} to ${String(SCALES[f.key].max)}`,
114 onSubmit: (v) => {
115 const next = withField(parsedDraft(draft, tokens()), f, v.trim());
116 const ok = validateTokens(next);
117 if (!ok.ok) return ok.error;
118 draft = next;
119 ctx.pop();
120 return undefined;
121 },
122 }),
123 );
124 else if (e.key === "p") steer("publish");
125 else if (e.key === "r") steer("revert");
126 else if (e.key === "x") (draft = undefined), ctx.invalidate();
127 else return false;
128 return true;
129 },
130 };
131 return screen;
132 }
133
134 const parsedDraft = (draft: unknown, base: ThemeTokens): ThemeTokens => {
135 const p = validateTokens(draft ?? base);
136 return p.ok ? p.value : base;
137 };
138
139 export const entry: PaletteEntry = {
140 rank: 150,
141 id: "design",
142 title: "Design: the forge's theme",
143 hint: "colours and scales, the AA verdict; publish or revert",
144 after: ["footing"],
145 offered: (session) => session.user !== undefined,
146 run: (session, ctx) => ctx.push(designScreen(session, ctx)),
147 };
src/web/layout.ts +1
@@ -1032,6 +1032,7 @@ export function page(options: PageOptions, status = 200): Response {
10321032 ${themeColorHead(theme)}
10331033 ${raw(`<style>${bootCss}</style>`)}
10341034 <link rel="stylesheet" href="${stylesheetAsset().path}" />
1035 <link rel="stylesheet" href="/design/theme.css">
10351036 ${when(
10361037 options.turnstile,
10371038 () =>
src/web/studio/design.ts added +598
@@ -0,0 +1,598 @@
1 /**
2 * The studio's Design tab (#6297), with the theme it edits as data (`validateTokens` is the one
3 * boundary text passes through, `contrastFailures` the WCAG AA gate, `compileTheme` the CSS,
4 * `steerTheme` the one write both the page and the terminal call): the forge's theme as colour
5 * roles for light and dark and four scales, a draft previewed against the live theme (light and
6 * dark side by side, drawn with the forge's own components), the WCAG AA verdict, and Publish /
7 * Revert. The edited fields live in the URL (a GET form), so a draft is a link and needs no script.
8 * Publishing compiles the CSS served at `/design/theme.css`, which every page of the app links,
9 * and this page alone re-fetches it on a push (`/design/theme/forge/live`). A site admin edits;
10 * everyone signed in may look.
11 */
12
13 import type { Ctx } from "../../http/context.ts";
14 import { eventStream } from "../../http/sse.ts";
15 import { getUserById } from "../../core/users.ts";
16 import type { Database } from "bun:sqlite";
17 import { THEMES } from "../../design/themes.ts";
18 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
19 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
20 import { readForm } from "../form.ts";
21 import { html, type Html } from "../html.ts";
22 import { page, redirect } from "../layout.ts";
23 import { emptyLine } from "../empty_words.ts";
24 import { badge, btn, card, dot, empty, field, kbd, listCard, meter, pill, row, stat, tabs, timeAgo } from "../ui.ts";
25 import { homeTabs } from "./home_tabs.ts";
26
27 // ---- the theme as data: tokens, the AA gate, versions (was design/theme.ts) ----
28
29 /** The roles a designer edits; the rest of a palette (diff, syntax) stays the forge's. */
30 export const ROLES = [
31 "bg",
32 "fg",
33 "card",
34 "muted",
35 "muted-fg",
36 "border",
37 "primary",
38 "primary-fg",
39 "accent",
40 "accent-fg",
41 "danger",
42 "success",
43 "attn",
44 ] as const;
45 export type Role = (typeof ROLES)[number];
46 export type Colors = Record<Role, string>;
47
48 /** Each scale: name, unit, smallest, largest. */
49 export const SCALES = {
50 radius: { unit: "px", min: 0, max: 24, label: "Corner radius" },
51 space: { unit: "px", min: 2, max: 12, label: "Spacing unit" },
52 text: { unit: "px", min: 12, max: 20, label: "Base type size" },
53 motion: { unit: "ms", min: 0, max: 600, label: "Motion duration" },
54 } as const;
55 export type ScaleKey = keyof typeof SCALES;
56
57 export interface ThemeTokens {
58 light: Colors;
59 dark: Colors;
60 scales: Record<ScaleKey, number>;
61 }
62
63 const pick = (from: Record<string, string>): Colors =>
64 Object.fromEntries(ROLES.map((r) => [r, from[r] ?? from["fg"] ?? ""])) as Colors;
65
66 /** The forge's own theme: exactly what the stylesheet already says. */
67 export function defaultTokens(): ThemeTokens {
68 return {
69 light: pick(THEMES.light.tokens),
70 dark: pick(THEMES.dark.tokens),
71 scales: { radius: 8, space: 4, text: 14, motion: 150 },
72 };
73 }
74
75 const HEX = /^#[0-9a-f]{6}$/;
76
77 /** Tokens from untrusted JSON-ish input, or the first thing wrong with it. */
78 export function validateTokens(input: unknown): { ok: true; value: ThemeTokens } | { ok: false; error: string } {
79 if (typeof input !== "object" || input === null) return { ok: false, error: "Tokens must be an object." };
80 const raw = input as Record<string, unknown>;
81 const out = defaultTokens();
82 for (const mode of ["light", "dark"] as const) {
83 const given = raw[mode];
84 if (typeof given !== "object" || given === null) return { ok: false, error: `Missing ${mode} colours.` };
85 for (const role of ROLES) {
86 const v = (given as Record<string, unknown>)[role];
87 const hex = typeof v === "string" ? v.trim().toLowerCase() : "";
88 if (!HEX.test(hex)) return { ok: false, error: `${mode} ${role} must be a #rrggbb colour.` };
89 out[mode][role] = hex;
90 }
91 }
92 const scales = (raw.scales ?? {}) as Record<string, unknown>;
93 for (const key of Object.keys(SCALES) as ScaleKey[]) {
94 const s = SCALES[key];
95 const n = Number(scales[key]);
96 if (!Number.isInteger(n) || n < s.min || n > s.max)
97 return { ok: false, error: `${s.label} must be a whole number from ${s.min} to ${s.max}.` };
98 out.scales[key] = n;
99 }
100 return { ok: true, value: out };
101 }
102
103 function luminance(hex: string): number {
104 const channel = (i: number) => {
105 const c = parseInt(hex.slice(1 + i * 2, 3 + i * 2), 16) / 255;
106 return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
107 };
108 return 0.2126 * channel(0) + 0.7152 * channel(1) + 0.0722 * channel(2);
109 }
110
111 /** WCAG contrast ratio of two `#rrggbb` colours, 1 to 21. */
112 export function contrast(a: string, b: string): number {
113 const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x) as [number, number];
114 return (hi + 0.05) / (lo + 0.05);
115 }
116
117 /** The text pairs a palette must keep readable, with the AA ratio each needs. */
118 const PAIRS: readonly [Role, Role, number][] = [
119 ["fg", "bg", 4.5],
120 ["fg", "card", 4.5],
121 ["muted-fg", "bg", 4.5],
122 ["primary-fg", "primary", 4.5],
123 ["accent-fg", "accent", 4.5],
124 ["accent", "bg", 3],
125 ];
126
127 export interface ContrastFailure {
128 mode: "light" | "dark";
129 pair: string;
130 ratio: number;
131 need: number;
132 }
133
134 /** Every pair below WCAG AA, in both modes; empty means the palette may be published. */
135 export function contrastFailures(tokens: ThemeTokens): ContrastFailure[] {
136 const out: ContrastFailure[] = [];
137 for (const mode of ["light", "dark"] as const) {
138 for (const [a, b, need] of PAIRS) {
139 const ratio = contrast(tokens[mode][a], tokens[mode][b]);
140 if (ratio < need) out.push({ mode, pair: `${a} on ${b}`, ratio: Math.round(ratio * 100) / 100, need });
141 }
142 }
143 return out;
144 }
145
146 const declarations = (colors: Colors): string =>
147 ROLES.map((r) => `--${r}:${colors[r]};`).join("");
148
149 /** The custom properties of one mode, for a scoped preview. */
150 export function modeVars(colors: Colors, scales: ThemeTokens["scales"]): string {
151 return declarations(colors) + scaleVars(scales);
152 }
153
154 const scaleVars = (s: ThemeTokens["scales"]): string =>
155 `--theme-radius:${s.radius}px;--theme-space:${s.space}px;--theme-text:${s.text}px;--theme-motion:${s.motion}ms;`;
156
157 /**
158 * The CSS an app loads: custom properties only, light as the base, dark
159 * under the OS preference and under an explicit `data-theme`.
160 */
161 export function compileTheme(tokens: ThemeTokens, version: number): string {
162 const light = declarations(tokens.light) + `color-scheme:light;`;
163 const dark = declarations(tokens.dark) + `color-scheme:dark;`;
164 return [
165 `/* forge theme v${version} */`,
166 `:root{${light}${scaleVars(tokens.scales)}}`,
167 `:root[data-theme="light"]{${light}}`,
168 `@media (prefers-color-scheme:dark){:root:not([data-theme]){${dark}}}`,
169 `:root[data-theme="dark"]{${dark}}`,
170 "",
171 ].join("\n");
172 }
173
174 // ---- published versions ----
175
176 export const THEME_NAME = /^[a-z0-9][a-z0-9-]{0,38}$/;
177
178 /** The forge's own theme, served as `/design/theme.css`. */
179 export const FORGE_THEME = { org: "forge", name: "forge" } as const;
180
181 export interface ThemeVersion {
182 version: number;
183 tokens: ThemeTokens;
184 css: string;
185 actorId: string;
186 note: string;
187 createdAt: number;
188 }
189
190 interface Row {
191 version: number;
192 tokens: string;
193 css: string;
194 actor_id: string;
195 note: string;
196 created_at: number;
197 }
198
199 const toVersion = (r: Row): ThemeVersion => ({
200 version: r.version,
201 tokens: JSON.parse(r.tokens) as ThemeTokens,
202 css: r.css,
203 actorId: r.actor_id,
204 note: r.note,
205 createdAt: r.created_at,
206 });
207
208 export function themeHistory(db: Database, org: string, name: string, limit = 20): ThemeVersion[] {
209 return db
210 .query<Row, [string, string, number]>(
211 `SELECT version, tokens, css, actor_id, note, created_at FROM theme_version
212 WHERE org = ? AND name = ? ORDER BY version DESC LIMIT ?`,
213 )
214 .all(org, name, limit)
215 .map(toVersion);
216 }
217
218 export const currentTheme = (db: Database, org: string, name: string): ThemeVersion | undefined =>
219 themeHistory(db, org, name, 1)[0];
220
221 /** What is live: the latest version, or the forge's defaults at version 0. */
222 export function liveTokens(db: Database, org: string, name: string): { version: number; tokens: ThemeTokens } {
223 const cur = currentTheme(db, org, name);
224 return cur ? { version: cur.version, tokens: cur.tokens } : { version: 0, tokens: defaultTokens() };
225 }
226
227 /** The CSS at a stable URL: the latest version's, or the defaults'. */
228 export function themeCss(db: Database, org: string, name: string): { version: number; css: string } {
229 const cur = currentTheme(db, org, name);
230 if (cur) return { version: cur.version, css: cur.css };
231 return { version: 0, css: compileTheme(defaultTokens(), 0) };
232 }
233
234 export type Published = { ok: true; version: number } | { ok: false; error: string };
235
236 export function publishTheme(
237 db: Database,
238 org: string,
239 name: string,
240 input: unknown,
241 actorId: string,
242 note = "",
243 ): Published {
244 if (!THEME_NAME.test(org) || !THEME_NAME.test(name)) return { ok: false, error: "That is not a theme name." };
245 const valid = validateTokens(input);
246 if (!valid.ok) return valid;
247 const failures = contrastFailures(valid.value);
248 if (failures.length > 0) {
249 const f = failures[0]!;
250 return { ok: false, error: `${f.mode} ${f.pair} is ${f.ratio}:1; WCAG AA needs ${f.need}:1.` };
251 }
252 // The version is taken and written in one transaction, so two publishes
253 // never share a number.
254 const version = db.transaction(() => {
255 const next = (currentTheme(db, org, name)?.version ?? 0) + 1;
256 db.query(
257 `INSERT INTO theme_version (org, name, version, tokens, css, actor_id, note, created_at)
258 VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
259 ).run(org, name, next, JSON.stringify(valid.value), compileTheme(valid.value, next), actorId, note.slice(0, 200), Date.now());
260 return next;
261 })();
262 return { ok: true, version };
263 }
264
265 /** Publish the version before the current one again. */
266 export function revertTheme(db: Database, org: string, name: string, actorId: string): Published {
267 const [cur, prev] = themeHistory(db, org, name, 2);
268 if (!cur) return { ok: false, error: "Nothing is published yet." };
269 const back = prev?.tokens ?? defaultTokens();
270 return publishTheme(db, org, name, back, actorId, `Revert of v${cur.version}`);
271 }
272
273 /** The two writes, with one gate for the page and the terminal: a site admin who is a person. */
274 export const mayEditTheme = (user: { isAdmin?: boolean; kind?: string } | undefined): boolean =>
275 user?.isAdmin === true && user.kind !== "agent";
276
277 /** What a publish or a revert did, and the bus event open pages follow (`theme.published`). */
278 export function steerTheme(
279 app: { db: Database; bus: { append(e: { kind: "theme.published"; actorId: string; payload: Record<string, unknown> }): unknown } },
280 user: { id: string; isAdmin?: boolean; kind?: string } | undefined,
281 action: "publish" | "revert",
282 draft?: unknown,
283 ): Published | { ok: false; error: "forbidden" } {
284 if (user === undefined || !mayEditTheme(user)) return { ok: false, error: "forbidden" };
285 const { org, name } = FORGE_THEME;
286 const done = action === "publish" ? publishTheme(app.db, org, name, draft, user.id) : revertTheme(app.db, org, name, user.id);
287 if (done.ok) app.bus.append({ kind: "theme.published", actorId: user.id, payload: { org, name, version: done.version } });
288 return done;
289 }
290
291 // ---- the page ----
292
293 const DESIGN_CSS = `.design-roles{margin:0 0 calc(var(--theme-space,4px)*4)}
294 .design-field{display:flex;justify-content:space-between;align-items:center;gap:calc(var(--theme-space,4px)*2);padding:calc(var(--theme-space,4px)*1) 0}
295 .design-previews{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:calc(var(--theme-space,4px)*4);margin:calc(var(--theme-space,4px)*4) 0}
296 .design-sample{padding-top:calc(var(--theme-space,4px)*2);border-top:1px solid var(--border)}
297 `;
298
299 /**
300 * On this page only: a publish is pushed here and the stylesheet is fetched again, so the page
301 * changes without a reload.
302 */
303 const LIVE_JS = `(function(){var l=document.querySelector('link[href^="/design/theme.css"]');if(!l||typeof EventSource==='undefined')return;
304 var seen=null,s=new EventSource('/design/theme/forge/live');
305 s.addEventListener('theme',function(e){var v;try{v=JSON.parse(e.data).version}catch(x){return}
306 if(seen!==null&&v!==seen)l.setAttribute('href','/design/theme.css?v='+v);seen=v})})();`;
307
308 const canEdit = (ctx: Ctx): boolean => ctx.auth.user?.isAdmin === true;
309
310 /** GET /design/theme.css — the compiled theme of the forge, at a stable URL. */
311 export function themeFile(ctx: Ctx): Response {
312 const { org, name } = FORGE_THEME;
313 const { version, css } = themeCss(ctx.app.db, org, name);
314 const etag = `"theme-${org}-${name}-${version}"`;
315 const headers = {
316 "content-type": "text/css; charset=utf-8",
317 // Revalidated every time (a 304 is a few bytes); an app never serves a stale palette.
318 "cache-control": "public, no-cache",
319 etag,
320 "access-control-allow-origin": "*",
321 };
322 if (ctx.request.headers.get("if-none-match") === etag) return new Response(null, { status: 304, headers });
323 return new Response(css, { headers });
324 }
325
326 /** The bus kind a publish announces itself with; the live stream relays it. */
327 const THEME_EVENT = "theme.published";
328
329 /** GET /design/theme/forge/live — one `theme` event per publish, carrying the version. */
330 export function themeLive(ctx: Ctx): Response {
331 const { org, name } = FORGE_THEME;
332 return eventStream(ctx.app, ctx.request, (emit) => {
333 emit("theme", { version: liveTokens(ctx.app.db, org, name).version });
334 return ctx.app.bus.subscribe((e) => {
335 if (e.kind === THEME_EVENT && e.payload.org === org && e.payload.name === name) emit("theme", { version: e.payload.version });
336 });
337 });
338 }
339
340 /** The tokens a form says, or the live ones where it says nothing. */
341 export function fromQuery(params: { get(key: string): unknown }, base: ThemeTokens): unknown {
342 const get = (k: string): string => {
343 const v = params.get(k);
344 return typeof v === "string" ? v : "";
345 };
346 const draft = structuredClone(base);
347 for (const mode of ["light", "dark"] as const)
348 for (const r of ROLES) if (get(`${mode}.${r}`) !== "") draft[mode][r] = get(`${mode}.${r}`);
349 for (const key of Object.keys(SCALES) as (keyof typeof SCALES)[])
350 if (get(`scale.${key}`) !== "") draft.scales[key] = Number(get(`scale.${key}`));
351 return draft;
352 }
353
354 /** One mode's sample of the forge's own components, scoped by a class. */
355 function sample(scope: string, label: string): Html {
356 return html`<div class="design-sample ${scope}">
357 <p class="small">${label}</p>
358 ${card(
359 html`<h3>Card title</h3>
360 <p class="muted">Secondary text on the card.</p>
361 <p>${btn("Primary", { type: "button", variant: "primary" })} ${btn("Plain", { type: "button" })}
362 ${badge("Open")} ${badge("Merged", { tone: "merged" })}</p>`,
363 )}
364 </div>`;
365 }
366
367 // GET /design
368 export function designPage(ctx: Ctx): Response {
369 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
370 const began = performance.now();
371 if (!ctx.auth.user) return signInFirst(ctx);
372 const db = ctx.app.db;
373 const live = liveTokens(db, FORGE_THEME.org, FORGE_THEME.name);
374 const parsed = validateTokens(fromQuery(ctx.url.searchParams, live.tokens));
375 const draft = parsed.ok ? parsed.value : live.tokens;
376 const failures = parsed.ok ? contrastFailures(draft) : [];
377 const history = themeHistory(db, FORGE_THEME.org, FORGE_THEME.name, 10);
378 const editable = canEdit(ctx);
379
380 const scopes: [string, string, ThemeTokens, "light" | "dark"][] = [
381 ["pv-cur-light", "Current · light", live.tokens, "light"],
382 ["pv-cur-dark", "Current · dark", live.tokens, "dark"],
383 ["pv-new-light", "Draft · light", draft, "light"],
384 ["pv-new-dark", "Draft · dark", draft, "dark"],
385 ];
386 // Trusted: every value passed `validateTokens` (#rrggbb and bounded integers).
387 const styleCss = DESIGN_CSS + scopes
388 .map(
389 ([cls, , t, mode]) =>
390 `.${cls}{${modeVars(t[mode], t.scales)}background:var(--bg);color:var(--fg);border-radius:var(--theme-radius);padding:calc(var(--theme-space,4px)*3)}`,
391 )
392 .join("\n");
393
394 const colorField = (mode: "light" | "dark", role: (typeof ROLES)[number]): Html =>
395 html`<label class="design-field small"
396 ><span>${role}</span
397 ><input type="color" name="${mode}.${role}" value="${draft[mode][role]}"
398 /></label>`;
399 const scaleField = (key: keyof typeof SCALES): Html =>
400 html`<label class="design-field small"
401 ><span>${SCALES[key].label} (${SCALES[key].unit})</span
402 ><input type="number" name="scale.${key}" min="${SCALES[key].min}" max="${SCALES[key].max}" value="${draft.scales[key]}"
403 /></label>`;
404
405 const verdict = !parsed.ok
406 ? html`<p role="alert">${parsed.error}</p>`
407 : failures.length === 0
408 ? html`<p role="status">${badge("AA passes", { tone: "success" })} Every text pair in light and dark meets WCAG AA.</p>`
409 : html`<div role="alert">
410 <p>${badge("Blocked", { tone: "danger" })} These pairs fail WCAG AA, so Publish is off:</p>
411 ${listCard(failures.map((f) => row({ title: `${f.mode} · ${f.pair}: ${f.ratio}:1 (needs ${f.need}:1)` })))}
412 </div>`;
413
414 const who = (id: string): string => getUserById(db, id)?.username ?? "unknown";
415 const body = html`${homeTabs("design")}${pageHead("Design", { sub: "Set the forge's colours and scales, check them against WCAG AA, and publish a version." })}
416 <form method="get" action="/design" id="design-form">
417 <h2>Light colours</h2><div class="design-roles">${ROLES.map((r) => colorField("light", r))}</div>
418 <h2>Dark colours</h2><div class="design-roles">${ROLES.map((r) => colorField("dark", r))}</div>
419 <h2>Scales</h2><div class="design-roles">${(Object.keys(SCALES) as (keyof typeof SCALES)[]).map(scaleField)}</div>
420 ${verdict}
421 <p>
422 ${btn("Preview draft", { variant: "secondary" })}
423 ${btn("Components", { href: "/design/components", variant: "secondary" })}
424 ${editable
425 ? html`${btn("Publish", { variant: "primary", formmethod: "post", formaction: "/design/publish", disabled: failures.length > 0 || !parsed.ok })}
426 ${history.length > 0
427 ? btn(`Revert to ${history.length > 1 ? `v${history[1]!.version}` : "the defaults"}`, { formmethod: "post", formaction: "/design/revert", formnovalidate: true })
428 : null}`
429 : html`<span class="muted small">Only an admin can publish.</span>`}
430 </p>
431 </form>
432 <div class="design-previews">${scopes.map(([cls, label]) => sample(cls, label))}</div>
433 <h2>History</h2>
434 ${history.length === 0
435 ? emptyLine("results", { reason: "Nothing published yet: apps get the forge's defaults (version 0)." })
436 : html`${listCard(
437 history.map((v) =>
438 row({ title: `v${v.version} by ${who(v.actorId)}${v.note === "" ? "" : ` · ${v.note}`}`, meta: html`${timeAgo(new Date(v.createdAt).toISOString())}` }),
439 ),
440 { id: "design-history" },
441 )}`}`;
442 notePhase(ctx.request, "render", performance.now() - began);
443 return page({ ctx, title: "Design", body, styleCss, scriptJs: LIVE_JS });
444 }
445
446 /**
447 * The two POSTs share a gate: signed in, same origin, an admin; then `steerTheme` (as the terminal)
448 * does it.
449 */
450 async function mutate(ctx: Ctx, action: "publish" | "revert"): Promise<Response> {
451 if (!ctx.auth.user) return signInFirst(ctx);
452 const form = await readForm(ctx, "admin");
453 if (form instanceof Response) return form;
454 if (!canEdit(ctx)) return notFoundPage(ctx);
455 const live = liveTokens(ctx.app.db, FORGE_THEME.org, FORGE_THEME.name);
456 const done = steerTheme(ctx.app, ctx.auth.user, action, action === "publish" ? fromQuery(form, live.tokens) : undefined);
457 if (!done.ok) return back(ctx, done.error, false);
458 return back(ctx, action === "publish" ? `Published v${done.version}. The Design page updates now; other pages on their next load.` : `Reverted; published as v${done.version}.`, true);
459 }
460
461 // POST /design/publish
462 export const designPublish = (ctx: Ctx): Promise<Response> => mutate(ctx, "publish");
463
464 // POST /design/revert
465 export const designRevert = (ctx: Ctx): Promise<Response> => mutate(ctx, "revert");
466
467 const back = (ctx: Ctx, message: string, ok: boolean): Response =>
468 redirect("/design", {
469 url: ctx.url,
470 forgeUrl: ctx.app.config.url,
471 flash: { tone: ok ? "success" : "danger", message },
472 });
473
474 // ---- the component explorer ----
475
476 export interface Entry {
477 id: string;
478 name: string;
479 note: string;
480 render: () => Html;
481 }
482
483 /** The catalogue: one entry per component, plain data in, markup out. */
484 export const ENTRIES: readonly Entry[] = [
485 {
486 id: "btn",
487 name: "Button",
488 note: "btn(): primary, secondary, plain, disabled.",
489 render: () =>
490 html`${btn("Primary", { type: "button", variant: "primary" })} ${btn("Secondary", { type: "button", variant: "secondary" })}
491 ${btn("Plain", { type: "button" })} ${btn("Disabled", { type: "button", disabled: true })}`,
492 },
493 {
494 id: "badge",
495 name: "Badge",
496 note: "badge(): the tones.",
497 render: () =>
498 html`${badge("Open")} ${badge("Merged", { tone: "merged" })} ${badge("Passing", { tone: "success" })}
499 ${badge("Blocked", { tone: "danger" })} ${badge("Waiting", { tone: "attn" })}`,
500 },
501 {
502 id: "pill",
503 name: "Pill and dot",
504 note: "pill(), dot(): counts and status marks.",
505 render: () => html`${pill(3)} ${pill(12, "accent")} ${pill(2, "danger")} ${dot("success")} ${dot("danger")} ${dot("attn")}`,
506 },
507 {
508 id: "stat",
509 name: "Stat",
510 note: "stat(): a number with its label.",
511 render: () => html`<div class="stats">${stat({ label: "Open", value: 12, note: "since Monday" })}${stat({ label: "Merged", value: 48 })}</div>`,
512 },
513 {
514 id: "card",
515 name: "Card",
516 note: "card(): the surface most pages stand on.",
517 render: () => card(html`<h3>Card title</h3><p class="muted">Secondary text.</p>`),
518 },
519 {
520 id: "tabs",
521 name: "Tabs",
522 note: "tabs(): link tabs with aria-current.",
523 render: () =>
524 tabs([{ label: "One", href: "#c-tabs", current: true }, { label: "Two", href: "#c-tabs" }, { label: "Three", href: "#c-tabs", count: 4 }], "Sample"),
525 },
526 {
527 id: "field",
528 name: "Field",
529 note: "field(): label, control, hint, error.",
530 render: () =>
531 html`${field({ label: "Name", name: "x-name", value: "forge", hint: "Lower case." })}
532 ${field({ label: "Email", name: "x-email", value: "nope", error: "Not an address." })}`,
533 },
534 {
535 id: "meter",
536 name: "Meter",
537 note: "meter(): a share of a limit.",
538 render: () => html`${meter(40, "Sample at 40 percent")} ${meter(92, "Sample at 92 percent", "attn")}`,
539 },
540 {
541 id: "kbd",
542 name: "Keys",
543 note: "kbd(): a shortcut.",
544 render: () => html`${kbd(["g", "d"])}`,
545 },
546 {
547 id: "empty",
548 name: "Empty state",
549 note: "empty(): nothing here yet, and what to do.",
550 render: () => empty({ title: "Nothing yet", note: "Create the first one." }),
551 },
552 ];
553
554 /** The entries a `?q=` names: its words all appear in the name or the note. */
555 export function filterEntries(q: string, entries: readonly Entry[] = ENTRIES): Entry[] {
556 const words = q.toLowerCase().split(/\s+/).filter(Boolean);
557 return entries.filter((e) => {
558 const hay = `${e.name} ${e.note}`.toLowerCase();
559 return words.every((w) => hay.includes(w));
560 });
561 }
562
563 // GET /design/components
564 export function componentsPage(ctx: Ctx): Response {
565 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
566 const began = performance.now();
567 if (!ctx.auth.user) return signInFirst(ctx);
568 const live = liveTokens(ctx.app.db, FORGE_THEME.org, FORGE_THEME.name);
569 const parsed = validateTokens(fromQuery(ctx.url.searchParams, live.tokens));
570 const tokens = parsed.ok ? parsed.value : live.tokens;
571 const q = (ctx.url.searchParams.get("q") ?? "").slice(0, 80);
572 const shown = filterEntries(q);
573 // Trusted: every value passed `validateTokens`.
574 const styleCss =
575 `.cx-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:calc(var(--theme-space,4px)*4)}
576 .cx-cell{padding:calc(var(--theme-space,4px)*3)}\n` +
577 (["light", "dark"] as const)
578 .map((m) => `.cx-${m}{${modeVars(tokens[m], tokens.scales)}background:var(--bg);color:var(--fg);border-radius:var(--theme-radius)}`)
579 .join("\n");
580 const cell = (e: Entry, mode: "light" | "dark"): Html =>
581 html`<div class="cx-cell cx-${mode}"><p class="small">${mode}</p>${e.render()}</div>`;
582 const body = html`${homeTabs("design")}${pageHead("Components", { sub: "The forge's own components against the theme" })}
583 <p class="small"><a href="/design">Theme editor</a>${parsed.ok ? "" : html` · <span role="alert">${parsed.error}</span>`}</p>
584 <form method="get" action="/design/components" role="search">
585 ${field({ label: "Filter", name: "q", value: q, type: "search", maxlength: 80 })}
586 ${btn("Filter", { variant: "secondary" })}
587 </form>
588 ${shown.length === 0
589 ? empty({ title: "No component matches", note: "Try another word." })
590 : shown.map(
591 (e) => html`<section id="c-${e.id}">
592 <h2>${e.name}</h2><p class="muted small">${e.note}</p>
593 <div class="cx-grid">${cell(e, "light")}${cell(e, "dark")}</div>
594 </section>`,
595 )}`;
596 notePhase(ctx.request, "render", performance.now() - began);
597 return page({ ctx, title: "Components", body, styleCss });
598 }
src/web/studio/home_tabs.ts +2 −2
@@ -10,7 +10,7 @@ import type { User } from "../../core/users.ts";
1010 import { html, type Html } from "../html.ts";
1111 import { tabs } from "../ui.ts";
1212
13 export type HomeTab = "feed" | "apps" | "asked";
13 export type HomeTab = "feed" | "apps" | "asked" | "design";
1414
1515 /** The asks not yet shipped across the viewer's repositories: `/asked`'s own number. */
1616 export function unshippedAsks(db: Database, viewer: User): number {
@@ -27,7 +27,7 @@ export function homeTabs(current: HomeTab, unshipped = 0): Html {
2727 });
2828 return html`<div class="mb">
2929 ${tabs(
30 [item("feed", "/feed", "Feed"), item("apps", "/apps", "Your apps"), item("asked", "/asked", "Asked", unshipped)],
30 [item("feed", "/feed", "Feed"), item("apps", "/apps", "Your apps"), item("asked", "/asked", "Asked", unshipped), item("design", "/design", "Design")],
3131 "Home",
3232 )}
3333 </div>`;
src/web/ui.ts +2
@@ -152,6 +152,7 @@ export interface BtnOptions {
152152 formnovalidate?: boolean;
153153 /** Where this submit posts instead of its form's own action. */
154154 formaction?: string;
155 formmethod?: "post";
155156 current?: boolean;
156157 /** A toggle: emits `aria-pressed` with its state. */
157158 pressed?: boolean;
@@ -195,6 +196,7 @@ export function btn(content: Html | string, o: BtnOptions = {}): Html {
195196 ${o.disabled ? raw("disabled") : null}
196197 ${o.formnovalidate ? raw("formnovalidate") : null}
197198 ${o.formaction ? html`formaction="${o.formaction}"` : null}
199 ${o.formmethod ? html`formmethod="${o.formmethod}"` : null}
198200 ${btnAttrs(o)}
199201 >
200202 ${inner}
test/design-audit.test.ts +1 −1
@@ -17,7 +17,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8");
1717
1818 /** Routes that answer a file, a fragment, a redirect hop or a callback. */
1919 const NOT_PAGES =
20 /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|settings\/payments\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
20 /^\/(design\/theme\.css|design\/theme\/|assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|settings\/payments\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
2121
2222 const getRoutes = [
2323 ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g),
test/design-theme.test.ts added +281
@@ -0,0 +1,281 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { Database } from "bun:sqlite";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createSession } from "../src/core/sessions.ts";
8 import { migrationFiles } from "../src/core/schema.ts";
9 import { createUser, getUserByName } from "../src/core/users.ts";
10 import {
11 ENTRIES,
12 FORGE_THEME,
13 compileTheme,
14 contrast,
15 contrastFailures,
16 defaultTokens,
17 filterEntries,
18 publishTheme,
19 revertTheme,
20 steerTheme,
21 themeCss,
22 themeHistory,
23 validateTokens,
24 } from "../src/web/studio/design.ts";
25 import { serve, type Servers } from "../src/http/server.ts";
26 import { createForgeApp, forgeCommands, Session } from "../src/tui/forge.ts";
27 import { designLines, designScreen, FIELDS, withField } from "../src/tui/screens/design.ts";
28 import { headlessTerminal } from "../src/tui/term/terminal.ts";
29 import { adminCookie } from "./helpers/admin.ts";
30 import { settleApp } from "./helpers/tui.ts";
31
32 const db = () => {
33 const d = new Database(":memory:");
34 for (const m of migrationFiles) if (m.sql.includes("theme_version")) d.exec(m.sql);
35 return d;
36 };
37
38 describe("theme tokens", () => {
39 test("the forge's own palette passes AA", () => {
40 expect(contrastFailures(defaultTokens())).toEqual([]);
41 });
42 test("contrast is the WCAG ratio", () => {
43 expect(contrast("#000000", "#ffffff")).toBeCloseTo(21, 1);
44 });
45 test("a failing palette is named", () => {
46 const t = defaultTokens();
47 t.light.fg = "#eeeeee";
48 expect(contrastFailures(t)[0]?.pair).toBe("fg on bg");
49 });
50 test("css cannot ride in a colour", () => {
51 const t = defaultTokens() as unknown as { light: Record<string, string> };
52 t.light.bg = "red;} body{display:none";
53 expect(validateTokens(t).ok).toBe(false);
54 });
55 test("scales are bounded", () => {
56 const t = defaultTokens();
57 t.scales.radius = 999;
58 expect(validateTokens(t).ok).toBe(false);
59 });
60 test("compiles custom properties only", () => {
61 const css = compileTheme(defaultTokens(), 3);
62 expect(css).toContain("--bg:#fafafa;");
63 expect(css).toContain('[data-theme="dark"]');
64 });
65 });
66
67 describe("theme store", () => {
68 test("publish refuses a failing palette and stores nothing", () => {
69 const d = db();
70 const t = defaultTokens();
71 t.dark.fg = "#111111";
72 const r = publishTheme(d, "forge", "forge", t, "u1");
73 expect(r.ok).toBe(false);
74 expect(themeHistory(d, "forge", "forge")).toEqual([]);
75 });
76 test("publish versions and attributes; revert undoes", () => {
77 const d = db();
78 const t = defaultTokens();
79 t.light.accent = "#1d4ed8";
80 expect(publishTheme(d, "forge", "forge", t, "u1")).toEqual({ ok: true, version: 1 });
81 t.light.accent = "#1e40af";
82 expect(publishTheme(d, "forge", "forge", t, "u2")).toEqual({ ok: true, version: 2 });
83 expect(themeCss(d, "forge", "forge").css).toContain("--accent:#1e40af;");
84 expect(revertTheme(d, "forge", "forge", "u2")).toEqual({ ok: true, version: 3 });
85 const now = themeCss(d, "forge", "forge");
86 expect(now.version).toBe(3);
87 expect(now.css).toContain("--accent:#1d4ed8;");
88 expect(themeHistory(d, "forge", "forge")[1]?.actorId).toBe("u2");
89 });
90 test("no row means the defaults at version 0", () => {
91 expect(themeCss(db(), "forge", "forge").version).toBe(0);
92 });
93 });
94
95 describe("design tab over http", () => {
96 let dataDir = "";
97 let app: App;
98 let servers: Servers;
99 let base = "";
100 let admin = "";
101
102 beforeAll(async () => {
103 dataDir = await mkdtemp(join(tmpdir(), "forge-design-"));
104 app = createApp({ dataDir, port: 0 });
105 servers = await serve(app);
106 base = servers.url;
107 admin = await adminCookie(app, { username: "ada", email: "[email protected]", password: "design-password" });
108 });
109 afterAll(async () => {
110 await servers.stop();
111 await rm(dataDir, { recursive: true, force: true });
112 });
113
114 const post = (path: string, fields: Record<string, string>, cookie = admin) =>
115 fetch(`${base}${path}`, {
116 method: "POST",
117 headers: { cookie, origin: base },
118 body: new URLSearchParams(fields),
119 redirect: "manual",
120 });
121
122 test("the css is served at a stable url, to anyone, as css", async () => {
123 const res = await fetch(`${base}/design/theme.css`);
124 expect(res.status).toBe(200);
125 expect(res.headers.get("content-type")).toContain("text/css");
126 expect(await res.text()).toContain("--bg:");
127 expect((await fetch(`${base}/design/theme/nope/none.css`)).status).toBe(404);
128 });
129
130 test("every page links the theme", async () => {
131 expect(await (await fetch(`${base}/`)).text()).toContain('href="/design/theme.css"');
132 });
133
134 test("the design page shows the draft and the verdict", async () => {
135 const res = await fetch(`${base}/design?light.fg=%23eeeeee`, { headers: { cookie: admin } });
136 const text = await res.text();
137 expect(res.status).toBe(200);
138 expect(text).toContain("Blocked");
139 expect(text).toContain("pv-new-dark");
140 });
141
142 const rows = () => themeHistory(app.db, FORGE_THEME.org, FORGE_THEME.name, 100).length;
143
144 test("publish needs an admin, the same origin, and passing contrast; then the css changes", async () => {
145 const before = rows();
146 const anon = await post("/design/publish", { "light.accent": "#1d4ed8" }, "");
147 expect(anon.status).toBe(303);
148 expect(anon.headers.get("location")).toContain("/signin");
149 expect((await fetch(`${base}/design`, { redirect: "manual" })).status).toBe(303);
150 expect(rows()).toBe(before);
151
152 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "design-password" });
153 if (!bob.ok) throw new Error(bob.error);
154 const member = `forge_session=${createSession(app.db, bob.value.id).token}`;
155 for (const path of ["/design/publish", "/design/revert"]) {
156 const res = await post(path, { "light.accent": "#1d4ed8" }, member);
157 expect(res.status).toBe(404);
158 }
159 expect(rows()).toBe(before);
160
161 const cross = await fetch(`${base}/design/publish`, {
162 method: "POST",
163 headers: { cookie: admin, origin: "https://evil.example" },
164 body: new URLSearchParams({}),
165 redirect: "manual",
166 });
167 expect(cross.status).toBe(403);
168
169 await post("/design/publish", { "light.fg": "#eeeeee" });
170 expect(await (await fetch(`${base}/design/theme.css`)).text()).not.toContain("--fg:#eeeeee");
171
172 const ok = await post("/design/publish", { "light.accent": "#1d4ed8" });
173 expect(ok.status).toBe(303);
174 const css = await (await fetch(`${base}/design/theme.css`)).text();
175 expect(css).toContain("--accent:#1d4ed8;");
176
177 await post("/design/revert", {});
178 expect(await (await fetch(`${base}/design/theme.css`)).text()).not.toContain("--accent:#1d4ed8;");
179 });
180
181 test("the explorer needs sign-in, then shows each component in both modes against a draft", async () => {
182 expect((await fetch(`${base}/design/components`, { redirect: "manual" })).status).not.toBe(200);
183 const res = await fetch(`${base}/design/components?q=badge&light.bg=%23ffffff`, { headers: { cookie: admin } });
184 const text = await res.text();
185 expect(res.status).toBe(200);
186 expect(text).toContain("cx-dark");
187 expect(text).toContain("Badge");
188 expect(text).not.toContain("Empty state");
189 });
190
191 test("a publish is pushed to an open page within 2 s", async () => {
192 const res = await fetch(`${base}/design/theme/forge/live`);
193 const reader = res.body!.getReader();
194 const decoder = new TextDecoder();
195 let seen = "";
196 while (!seen.includes("event: theme")) {
197 const { value, done } = await reader.read();
198 if (done) break;
199 seen += decoder.decode(value);
200 }
201 const started = performance.now();
202 const next = (async () => {
203 while (!/event: theme[\s\S]*event: theme/.test(seen)) {
204 const { value, done } = await reader.read();
205 if (done) break;
206 seen += decoder.decode(value);
207 }
208 })();
209 await post("/design/publish", { "light.accent": "#1e40af" });
210 await next;
211 expect(performance.now() - started).toBeLessThan(2000);
212 await reader.cancel();
213 });
214 });
215
216 describe("component explorer", () => {
217 test("filter matches words in name and note", () => {
218 expect(filterEntries("").length).toBe(ENTRIES.length);
219 expect(filterEntries("button").map((e) => e.id)).toEqual(["btn"]);
220 expect(filterEntries("zzz")).toEqual([]);
221 });
222 test("every entry renders", () => {
223 for (const e of ENTRIES) expect(String(e.render()).length).toBeGreaterThan(0);
224 });
225 });
226
227 describe("the terminal door", () => {
228 let dataDir = "";
229 let app: App;
230 const identity = (user?: ReturnType<typeof getUserByName>) => ({ sshUsername: user?.username ?? "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user });
231
232 beforeAll(async () => {
233 dataDir = await mkdtemp(join(tmpdir(), "forge-design-tui-"));
234 app = createApp({ dataDir, port: 0 });
235 await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "design-password", isAdmin: true });
236 await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "design-password" });
237 });
238 afterAll(async () => {
239 await rm(dataDir, { recursive: true, force: true });
240 });
241
242 const count = () => themeHistory(app.db, FORGE_THEME.org, FORGE_THEME.name, 100).length;
243
244 test("the lines show the verdict; a failing draft is blocked", () => {
245 const session = new Session(app, identity(getUserByName(app.db, "ada")));
246 expect(designLines(session, undefined).join("\n")).toContain("AA passes");
247 const bad = withField(defaultTokens(), FIELDS.find((f) => f.kind === "role" && f.mode === "light" && f.role === "fg")!, "#eeeeee");
248 expect(designLines(session, bad).join("\n")).toContain("Blocked");
249 });
250
251 test("an admin publishes and reverts from the screen, and the bus carries the event the web page follows", async () => {
252 const ada = getUserByName(app.db, "ada")!;
253 const heard: string[] = [];
254 const off = app.bus.subscribe((e) => void heard.push(e.kind));
255 const { app: tui, session } = createForgeApp(app, identity(ada), { terminal: headlessTerminal(100, 40), exitHooks: false });
256 tui.start();
257 tui.ctx.push(designScreen(session, tui.ctx));
258 await settleApp(tui);
259 expect(tui.screen.toText()).toContain("Design: the forge's theme");
260 expect(forgeCommands(session)(tui.ctx).map((c) => c.id)).toContain("design");
261 tui.stop?.();
262
263 const bad = withField(defaultTokens(), FIELDS.find((f) => f.kind === "scale")!, "5");
264 const before = count();
265 const done = steerTheme(app, ada, "publish", bad);
266 expect(done.ok).toBe(true);
267 expect(count()).toBe(before + 1);
268 expect(heard).toContain("theme.published");
269 expect(steerTheme(app, ada, "revert").ok).toBe(true);
270 off();
271 });
272
273 test("a non-admin and a guest are refused and nothing is stored", () => {
274 const before = count();
275 for (const who of [getUserByName(app.db, "bob"), undefined]) {
276 expect(steerTheme(app, who, "publish", defaultTokens())).toEqual({ ok: false, error: "forbidden" });
277 expect(steerTheme(app, who, "revert")).toEqual({ ok: false, error: "forbidden" });
278 }
279 expect(count()).toBe(before);
280 });
281 });
test/forge-looks.test.ts +1
@@ -23,6 +23,7 @@ quietLogs();
2323 const NOT_A_PAGE: Record<string, string> = {
2424 "/home": "the home's old address: a redirect to /, which is pictured",
2525 "/desk": "a POST that leaves a note on the desk; the desk is read on the home (/), which is pictured; covered by test/desk.test.ts",
26 "/design": "no picture: not in app.looks (its slots are full); the Design tab is covered by test/design-theme.test.ts",
2627 "/feed": "no picture: its slot went to /docs; the page is covered by its own tests",
2728 "/front": "no picture: its slot went to /settings/security/controls, the security controls (#13001); covered by its own tests",
2829 "/next": "no picture: not in app.looks (its 32 slots are full); the page is covered by test/next-all.test.ts",
test/palette-roster.test.ts +3
@@ -142,6 +142,7 @@ test("a site-admin person is offered the whole roster", () => {
142142 ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"],
143143 ["stalls", "Main-thread stalls", "the last hour's stall ms by route"],
144144 ["footing", "What the forge stands on", "each piece on another machine, in the order it would break the forge"],
145 ["design", "Design: the forge's theme", "colours and scales, the AA verdict; publish or revert"],
145146 ["maintenanceweek", "Maintenance, last 7 days", "what each maintenance worker found and did this week"],
146147 ["offsite", "Off-site backup", "where the sealed lane writes, when it last succeeded, and the last restore drill"],
147148 ["capacity", "Capacity", "concurrency and guards, live; e changes a settable one"],
@@ -318,6 +319,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
318319 ["can", "What I can do", "your role and what it allows here"],
319320 ["bugs", "Bugs", "open bugs and the bug clock"],
320321 ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"],
322 ["design", "Design: the forge's theme", "colours and scales, the AA verdict; publish or revert"],
321323 ["ship-time", "Ship time", "median time from the crew's first run to done"],
322324 ["maintenance-runs", "Maintenance duty runs", "what each duty found, did and probed"],
323325 ["traffic-sources", "Traffic sources", "where people come from and where they go, for the forge"],
@@ -427,6 +429,7 @@ test("a member person is offered the signed-in roster without the admin entries"
427429 ["payments", "Payments", "what was charged for the forges you claimed"],
428430 ["bugs", "Bugs", "open bugs and the bug clock"],
429431 ["health-voice", "Health — spoken", "how the forge is, in two plain sentences"],
432 ["design", "Design: the forge's theme", "colours and scales, the AA verdict; publish or revert"],
430433 ["waiting-for-me", "Waiting for me", "issues and pulls that wait for you"],
431434 ["next-all", "Next up, every repository", "the top of each list you administer"],
432435 ["offers-upstream", "Offers upstream", "the receipts of what you offered from your forks"],
test/pricing-size.test.ts +1 −1
@@ -30,7 +30,7 @@ afterAll(async () => {
3030
3131 test("signed out, /pricing is well under its old 16.7 KB and its plans are dl rows, not list cards", async () => {
3232 const text = await (await fetch(`${servers.url}/pricing`)).text();
33 expect(new TextEncoder().encode(text).length).toBeLessThan(13.5 * 1024); // was 16.7 KB, 12.5 before each card said its price, credit and forges (#13886); the issue asks < 10 KB, the shared shell is ~8 KB of the rest
33 expect(new TextEncoder().encode(text).length).toBeLessThan(13.6 * 1024); // +~50 B: the theme <link> on every page (#6297); was 16.7 KB, 12.5 before each card said its price, credit and forges (#13886); the issue asks < 10 KB, the shared shell is ~8 KB of the rest
3434 expect(text).toContain('<dl class="status-rows">');
3535 expect(text.match(/class="status-row" data-plan="/g)?.length).toBeGreaterThanOrEqual(2);
3636 expect(text).not.toContain("setting-list");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs