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 #6298
scout/forge:scout/6297-studio-design-tab-a-component-explorer-a → main 1 commit fork 3 threads · 3 unresolved
12 files
changed +716
−2
README.md +4
| @@ -2322,3 +2322,7 @@ not fit (`spawn/quota.ts`). | ||
| 2322 | 2322 | An open vision pull's page shows, to an admin of the repository, "Direction after the merge": today's direction beside the one an admin's merge will write, computed by the same `nextDirection` the merge uses (`src/crew/vision.ts`), so the two cannot differ. Repository settings (Crew) marks the direction's fenced block `follows docs/VISION.md` and the words around it `the owner's`. Today and After the merge stack vertically at every width. |
| 2323 | 2323 | |
| 2324 | 2324 | The same read is a second door: the MCP `vision` tool takes an optional `number`, and for an admin returns `preview` (`{ today, after }`, or `{ why }` the direction would stay) for that open vision pull, plus `directionParts` (the direction cut into `vision` and `owner` parts). The terminal (TUI) has no such view; it is not touched by this change. |
| 2325 | ||
| 2326 | ## Themes (`/design`) | |
| 2327 | ||
| 2328 | The studio's Design tab edits the forge's theme: light and dark colour roles plus radius, spacing, type and motion scales. A draft previews against the live theme (light and dark, side by side) and cannot be published if a text pair fails WCAG AA. Publish compiles a versioned file served at `/_theme/forge.css` (any `/_theme/<org>/<name>.css` that exists is served too); every page loads it and re-fetches it when a publish is pushed over `/_theme/forge/live`. Revert republishes the previous version. State is the `theme_version` table; no dependency was added. |
docs/design/areas/design.md added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | # Design tab (#6297) | |
| 2 | ||
| 3 | New classes, all in the page's own nonce'd sheet (`web/studio/design.ts`), built from existing tokens: | |
| 4 | ||
| 5 | - `.design-grid`: auto-fit columns of colour fieldsets. | |
| 6 | - `.design-field`: a label and its colour or number input on one row. | |
| 7 | - `.design-previews`: the four side-by-side samples (current/draft × light/dark). | |
| 8 | - `.design-sample`: one sample box; its `pv-*` scope class sets the draft's custom properties. | |
| 9 | ||
| 10 | The theme's own variables are the palette roles plus `--theme-radius`, `--theme-space`, `--theme-text` and `--theme-motion`, set by `/_theme/forge.css`. |
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
| @@ -67,6 +67,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 67 | 67 | "contribute", |
| 68 | 68 | "events", |
| 69 | 69 | "explore", |
| 70 | "design", | |
| 70 | 71 | "family", |
| 71 | 72 | "fleet", |
| 72 | 73 | "flow", |
src/design/theme_store.ts added +122
| @@ -0,0 +1,122 @@ | ||
| 1 | /** | |
| 2 | * Published themes (#6297): `publishTheme` refuses a palette that fails AA, | |
| 3 | * compiles, stores the version with its author, and tells every open page | |
| 4 | * (`onTheme`) so it re-fetches the CSS. `revertTheme` publishes the previous | |
| 5 | * version again, so undo is itself history. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { compileTheme, contrastFailures, defaultTokens, validateTokens, type ThemeTokens } from "./theme_tokens.ts"; | |
| 10 | ||
| 11 | export const THEME_NAME = /^[a-z0-9][a-z0-9-]{0,38}$/; | |
| 12 | ||
| 13 | /** The forge's own theme, served as `/_theme/forge.css`. */ | |
| 14 | export const FORGE_THEME = { org: "forge", name: "forge" } as const; | |
| 15 | ||
| 16 | export interface ThemeVersion { | |
| 17 | version: number; | |
| 18 | tokens: ThemeTokens; | |
| 19 | css: string; | |
| 20 | actorId: string; | |
| 21 | note: string; | |
| 22 | createdAt: number; | |
| 23 | } | |
| 24 | ||
| 25 | interface Row { | |
| 26 | version: number; | |
| 27 | tokens: string; | |
| 28 | css: string; | |
| 29 | actor_id: string; | |
| 30 | note: string; | |
| 31 | created_at: number; | |
| 32 | } | |
| 33 | ||
| 34 | const toVersion = (r: Row): ThemeVersion => ({ | |
| 35 | version: r.version, | |
| 36 | tokens: JSON.parse(r.tokens) as ThemeTokens, | |
| 37 | css: r.css, | |
| 38 | actorId: r.actor_id, | |
| 39 | note: r.note, | |
| 40 | createdAt: r.created_at, | |
| 41 | }); | |
| 42 | ||
| 43 | export function themeHistory(db: Database, org: string, name: string, limit = 20): ThemeVersion[] { | |
| 44 | return db | |
| 45 | .query<Row, [string, string, number]>( | |
| 46 | `SELECT version, tokens, css, actor_id, note, created_at FROM theme_version | |
| 47 | WHERE org = ? AND name = ? ORDER BY version DESC LIMIT ?`, | |
| 48 | ) | |
| 49 | .all(org, name, limit) | |
| 50 | .map(toVersion); | |
| 51 | } | |
| 52 | ||
| 53 | export const currentTheme = (db: Database, org: string, name: string): ThemeVersion | undefined => | |
| 54 | themeHistory(db, org, name, 1)[0]; | |
| 55 | ||
| 56 | /** What is live: the latest version, or the forge's defaults at version 0. */ | |
| 57 | export function liveTokens(db: Database, org: string, name: string): { version: number; tokens: ThemeTokens } { | |
| 58 | const cur = currentTheme(db, org, name); | |
| 59 | return cur ? { version: cur.version, tokens: cur.tokens } : { version: 0, tokens: defaultTokens() }; | |
| 60 | } | |
| 61 | ||
| 62 | /** The CSS at a stable URL: the latest version's, or the defaults'. */ | |
| 63 | export function themeCss(db: Database, org: string, name: string): { version: number; css: string } { | |
| 64 | const cur = currentTheme(db, org, name); | |
| 65 | if (cur) return { version: cur.version, css: cur.css }; | |
| 66 | return { version: 0, css: compileTheme(defaultTokens(), 0) }; | |
| 67 | } | |
| 68 | ||
| 69 | type Listener = (version: number) => void; | |
| 70 | const listeners = new Map<string, Set<Listener>>(); | |
| 71 | ||
| 72 | /** Subscribe to a theme's publishes; returns the unsubscribe. */ | |
| 73 | export function onTheme(org: string, name: string, fn: Listener): () => void { | |
| 74 | const key = `${org}/${name}`; | |
| 75 | const set = listeners.get(key) ?? new Set(); | |
| 76 | set.add(fn); | |
| 77 | listeners.set(key, set); | |
| 78 | return () => { | |
| 79 | set.delete(fn); | |
| 80 | if (set.size === 0) listeners.delete(key); | |
| 81 | }; | |
| 82 | } | |
| 83 | ||
| 84 | export type Published = { ok: true; version: number } | { ok: false; error: string }; | |
| 85 | ||
| 86 | export function publishTheme( | |
| 87 | db: Database, | |
| 88 | org: string, | |
| 89 | name: string, | |
| 90 | input: unknown, | |
| 91 | actorId: string, | |
| 92 | note = "", | |
| 93 | ): Published { | |
| 94 | if (!THEME_NAME.test(org) || !THEME_NAME.test(name)) return { ok: false, error: "That is not a theme name." }; | |
| 95 | const valid = validateTokens(input); | |
| 96 | if (!valid.ok) return valid; | |
| 97 | const failures = contrastFailures(valid.value); | |
| 98 | if (failures.length > 0) { | |
| 99 | const f = failures[0]!; | |
| 100 | return { ok: false, error: `${f.mode} ${f.pair} is ${f.ratio}:1; WCAG AA needs ${f.need}:1.` }; | |
| 101 | } | |
| 102 | // The version is taken and written in one transaction, so two publishes | |
| 103 | // never share a number. | |
| 104 | const version = db.transaction(() => { | |
| 105 | const next = (currentTheme(db, org, name)?.version ?? 0) + 1; | |
| 106 | db.query( | |
| 107 | `INSERT INTO theme_version (org, name, version, tokens, css, actor_id, note, created_at) | |
| 108 | VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, | |
| 109 | ).run(org, name, next, JSON.stringify(valid.value), compileTheme(valid.value, next), actorId, note.slice(0, 200), Date.now()); | |
| 110 | return next; | |
| 111 | })(); | |
| 112 | for (const fn of listeners.get(`${org}/${name}`) ?? []) fn(version); | |
| 113 | return { ok: true, version }; | |
| 114 | } | |
| 115 | ||
| 116 | /** Publish the version before the current one again. */ | |
| 117 | export function revertTheme(db: Database, org: string, name: string, actorId: string): Published { | |
| 118 | const [cur, prev] = themeHistory(db, org, name, 2); | |
| 119 | if (!cur) return { ok: false, error: "Nothing is published yet." }; | |
| 120 | const back = prev?.tokens ?? defaultTokens(); | |
| 121 | return publishTheme(db, org, name, back, actorId, `Revert of v${cur.version}`); | |
| 122 | } |
src/design/theme_tokens.ts added +155
| @@ -0,0 +1,155 @@ | ||
| 1 | /** | |
| 2 | * A published theme as data (#6297): the colour roles for light and dark, | |
| 3 | * and the radius, spacing, type and motion scales. `validateTokens` is the | |
| 4 | * one boundary text passes through, `contrastFailures` is the WCAG AA gate, | |
| 5 | * and `compileTheme` turns tokens into the CSS every app on the theme loads. | |
| 6 | * Pure: strings in, strings out. A colour is `#rrggbb` and a scale is a | |
| 7 | * bounded integer, so nothing validated can carry CSS of its own. | |
| 8 | */ | |
| 9 | ||
| 10 | import { THEMES } from "./themes.ts"; | |
| 11 | ||
| 12 | /** The roles a designer edits; the rest of a palette (diff, syntax) stays the forge's. */ | |
| 13 | export const ROLES = [ | |
| 14 | "bg", | |
| 15 | "fg", | |
| 16 | "card", | |
| 17 | "muted", | |
| 18 | "muted-fg", | |
| 19 | "border", | |
| 20 | "primary", | |
| 21 | "primary-fg", | |
| 22 | "accent", | |
| 23 | "accent-fg", | |
| 24 | "danger", | |
| 25 | "success", | |
| 26 | "attn", | |
| 27 | ] as const; | |
| 28 | export type Role = (typeof ROLES)[number]; | |
| 29 | export type Colors = Record<Role, string>; | |
| 30 | ||
| 31 | /** Each scale: name, unit, smallest, largest. */ | |
| 32 | export const SCALES = { | |
| 33 | radius: { unit: "px", min: 0, max: 24, label: "Corner radius" }, | |
| 34 | space: { unit: "px", min: 2, max: 12, label: "Spacing unit" }, | |
| 35 | text: { unit: "px", min: 12, max: 20, label: "Base type size" }, | |
| 36 | motion: { unit: "ms", min: 0, max: 600, label: "Motion duration" }, | |
| 37 | } as const; | |
| 38 | export type ScaleKey = keyof typeof SCALES; | |
| 39 | ||
| 40 | export interface ThemeTokens { | |
| 41 | light: Colors; | |
| 42 | dark: Colors; | |
| 43 | scales: Record<ScaleKey, number>; | |
| 44 | } | |
| 45 | ||
| 46 | const pick = (from: Record<string, string>): Colors => | |
| 47 | Object.fromEntries(ROLES.map((r) => [r, from[r] ?? "#000000"])) as Colors; | |
| 48 | ||
| 49 | /** The forge's own theme: exactly what the stylesheet already says. */ | |
| 50 | export function defaultTokens(): ThemeTokens { | |
| 51 | return { | |
| 52 | light: pick(THEMES.light.tokens), | |
| 53 | dark: pick(THEMES.dark.tokens), | |
| 54 | scales: { radius: 8, space: 4, text: 14, motion: 150 }, | |
| 55 | }; | |
| 56 | } | |
| 57 | ||
| 58 | const HEX = /^#[0-9a-f]{6}$/; | |
| 59 | ||
| 60 | /** Tokens from untrusted JSON-ish input, or the first thing wrong with it. */ | |
| 61 | export function validateTokens(input: unknown): { ok: true; value: ThemeTokens } | { ok: false; error: string } { | |
| 62 | if (typeof input !== "object" || input === null) return { ok: false, error: "Tokens must be an object." }; | |
| 63 | const raw = input as Record<string, unknown>; | |
| 64 | const out = defaultTokens(); | |
| 65 | for (const mode of ["light", "dark"] as const) { | |
| 66 | const given = raw[mode]; | |
| 67 | if (typeof given !== "object" || given === null) return { ok: false, error: `Missing ${mode} colours.` }; | |
| 68 | for (const role of ROLES) { | |
| 69 | const v = (given as Record<string, unknown>)[role]; | |
| 70 | const hex = typeof v === "string" ? v.trim().toLowerCase() : ""; | |
| 71 | if (!HEX.test(hex)) return { ok: false, error: `${mode} ${role} must be a #rrggbb colour.` }; | |
| 72 | out[mode][role] = hex; | |
| 73 | } | |
| 74 | } | |
| 75 | const scales = (raw.scales ?? {}) as Record<string, unknown>; | |
| 76 | for (const key of Object.keys(SCALES) as ScaleKey[]) { | |
| 77 | const s = SCALES[key]; | |
| 78 | const n = Number(scales[key]); | |
| 79 | if (!Number.isInteger(n) || n < s.min || n > s.max) | |
| 80 | return { ok: false, error: `${s.label} must be a whole number from ${s.min} to ${s.max}.` }; | |
| 81 | out.scales[key] = n; | |
| 82 | } | |
| 83 | return { ok: true, value: out }; | |
| 84 | } | |
| 85 | ||
| 86 | function luminance(hex: string): number { | |
| 87 | const channel = (i: number) => { | |
| 88 | const c = parseInt(hex.slice(1 + i * 2, 3 + i * 2), 16) / 255; | |
| 89 | return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; | |
| 90 | }; | |
| 91 | return 0.2126 * channel(0) + 0.7152 * channel(1) + 0.0722 * channel(2); | |
| 92 | } | |
| 93 | ||
| 94 | /** WCAG contrast ratio of two `#rrggbb` colours, 1 to 21. */ | |
| 95 | export function contrast(a: string, b: string): number { | |
| 96 | const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x) as [number, number]; | |
| 97 | return (hi + 0.05) / (lo + 0.05); | |
| 98 | } | |
| 99 | ||
| 100 | /** The text pairs a palette must keep readable, with the AA ratio each needs. */ | |
| 101 | const PAIRS: readonly [Role, Role, number][] = [ | |
| 102 | ["fg", "bg", 4.5], | |
| 103 | ["fg", "card", 4.5], | |
| 104 | ["muted-fg", "bg", 4.5], | |
| 105 | ["primary-fg", "primary", 4.5], | |
| 106 | ["accent-fg", "accent", 4.5], | |
| 107 | ["accent", "bg", 3], | |
| 108 | ]; | |
| 109 | ||
| 110 | export interface ContrastFailure { | |
| 111 | mode: "light" | "dark"; | |
| 112 | pair: string; | |
| 113 | ratio: number; | |
| 114 | need: number; | |
| 115 | } | |
| 116 | ||
| 117 | /** Every pair below WCAG AA, in both modes; empty means the palette may be published. */ | |
| 118 | export function contrastFailures(tokens: ThemeTokens): ContrastFailure[] { | |
| 119 | const out: ContrastFailure[] = []; | |
| 120 | for (const mode of ["light", "dark"] as const) { | |
| 121 | for (const [a, b, need] of PAIRS) { | |
| 122 | const ratio = contrast(tokens[mode][a], tokens[mode][b]); | |
| 123 | if (ratio < need) out.push({ mode, pair: `${a} on ${b}`, ratio: Math.round(ratio * 100) / 100, need }); | |
| 124 | } | |
| 125 | } | |
| 126 | return out; | |
| 127 | } | |
| 128 | ||
| 129 | const declarations = (colors: Colors): string => | |
| 130 | ROLES.map((r) => `--${r}:${colors[r]};`).join(""); | |
| 131 | ||
| 132 | /** The custom properties of one mode, for a scoped preview. */ | |
| 133 | export function modeVars(colors: Colors, scales: ThemeTokens["scales"]): string { | |
| 134 | return declarations(colors) + scaleVars(scales); | |
| 135 | } | |
| 136 | ||
| 137 | const scaleVars = (s: ThemeTokens["scales"]): string => | |
| 138 | `--theme-radius:${s.radius}px;--theme-space:${s.space}px;--theme-text:${s.text}px;--theme-motion:${s.motion}ms;`; | |
| 139 | ||
| 140 | /** | |
| 141 | * The CSS an app loads: custom properties only, light as the base, dark | |
| 142 | * under the OS preference and under an explicit `data-theme`. | |
| 143 | */ | |
| 144 | export function compileTheme(tokens: ThemeTokens, version: number): string { | |
| 145 | const light = declarations(tokens.light) + `color-scheme:light;`; | |
| 146 | const dark = declarations(tokens.dark) + `color-scheme:dark;`; | |
| 147 | return [ | |
| 148 | `/* forge theme v${version} */`, | |
| 149 | `:root{${light}${scaleVars(tokens.scales)}}`, | |
| 150 | `:root[data-theme="light"]{${light}}`, | |
| 151 | `@media (prefers-color-scheme:dark){:root:not([data-theme]){${dark}}}`, | |
| 152 | `:root[data-theme="dark"]{${dark}}`, | |
| 153 | "", | |
| 154 | ].join("\n"); | |
| 155 | } |
src/http/server.ts +7
| @@ -275,6 +275,7 @@ import { homeArchive, homeArchived, homeArchiveUndo } from "../web/studio/home_a | ||
| 275 | 275 | import { liveFeedFragment } from "../web/studio/feed.ts"; |
| 276 | 276 | import { serviceWorker } from "../web/sw.ts"; |
| 277 | 277 | import { explorePage } from "../web/studio/explore.ts"; |
| 278 | import { designPage, designPublish, designRevert, themeFile, themeLive } from "../web/studio/design.ts"; | |
| 278 | 279 | import { |
| 279 | 280 | makeItYoursPage, |
| 280 | 281 | makeItYoursSubmit, |
| @@ -720,6 +721,12 @@ export function buildRouter(): Router<Handler> { | ||
| 720 | 721 | router.add("GET", "/front", studioDoor); |
| 721 | 722 | // Apps and people ranked by real numbers, narrowed in one line (#607). |
| 722 | 723 | router.add("GET", "/explore", explorePage); |
| 724 | router.add("GET", "/design", designPage); | |
| 725 | router.add("POST", "/design/publish", designPublish); | |
| 726 | router.add("POST", "/design/revert", designRevert); | |
| 727 | router.add("GET", "/_theme/forge.css", themeFile); | |
| 728 | router.add("GET", "/_theme/forge/live", themeLive); | |
| 729 | router.add("GET", "/_theme/:org/:name.css", themeFile); | |
| 723 | 730 | router.add("POST", "/front", frontUpdate); |
| 724 | 731 | router.add("POST", "/home/archive", homeArchive); |
| 725 | 732 | router.add("GET", "/home/archived/:op", homeArchived); |
src/web/client.ts +14
| @@ -1279,6 +1279,20 @@ export const shellJs = /* js */ ` | ||
| 1279 | 1279 | // until one is: no dead buttons on a page with JavaScript switched off. |
| 1280 | 1280 | doc.documentElement.classList.add('js'); |
| 1281 | 1281 | |
| 1282 | // The forge's theme is a file at a stable URL; a publish is pushed here and | |
| 1283 | // the stylesheet is fetched again, so an open page changes without a reload. | |
| 1284 | var themeLink = doc.getElementById('forge-theme'); | |
| 1285 | if (themeLink && typeof EventSource !== 'undefined') { | |
| 1286 | var seen = null; | |
| 1287 | var themeSource = new EventSource('/_theme/forge/live'); | |
| 1288 | themeSource.addEventListener('theme', function (event) { | |
| 1289 | var v; | |
| 1290 | try { v = JSON.parse(event.data).version; } catch (err) { return; } | |
| 1291 | if (seen !== null && v !== seen) themeLink.setAttribute('href', '/_theme/forge.css?v=' + v); | |
| 1292 | seen = v; | |
| 1293 | }); | |
| 1294 | } | |
| 1295 | ||
| 1282 | 1296 | // ---- menus (details) ---- |
| 1283 | 1297 | function closeMenus(except) { |
| 1284 | 1298 | doc.querySelectorAll('details.menu[open]').forEach(function (m) { |
src/web/layout.ts +1
| @@ -629,6 +629,7 @@ export function page(options: PageOptions, status = 200): Response { | ||
| 629 | 629 | /> |
| 630 | 630 | ${raw(`<style nonce="${placeholder}">${bootCss}</style>`)} |
| 631 | 631 | <link rel="stylesheet" href="${stylesheetAsset().path}" /> |
| 632 | <link rel="stylesheet" href="/_theme/forge.css" id="forge-theme" /> | |
| 632 | 633 | ${when( |
| 633 | 634 | options.turnstile, |
| 634 | 635 | () => |
src/web/studio/design.ts added +207
| @@ -0,0 +1,207 @@ | ||
| 1 | /** | |
| 2 | * The studio's Design tab (#6297): the forge's theme as colour roles for | |
| 3 | * light and dark and four scales, a draft previewed against the live theme | |
| 4 | * (light and dark side by side, drawn with the forge's own components), the | |
| 5 | * WCAG AA verdict, and Publish / Revert. The edited fields live in the URL | |
| 6 | * (a GET form), so a draft is a link and needs no script. Publishing | |
| 7 | * compiles the CSS served at `/_theme/forge.css`, which every page of the | |
| 8 | * app loads and re-fetches when a publish is pushed (`/_theme/forge/live`). | |
| 9 | * A site admin edits; everyone signed in may look. | |
| 10 | */ | |
| 11 | ||
| 12 | import type { Ctx } from "../../http/context.ts"; | |
| 13 | import { eventStream } from "../../http/sse.ts"; | |
| 14 | import { getUserById } from "../../core/users.ts"; | |
| 15 | import { | |
| 16 | FORGE_THEME, | |
| 17 | THEME_NAME, | |
| 18 | liveTokens, | |
| 19 | onTheme, | |
| 20 | publishTheme, | |
| 21 | revertTheme, | |
| 22 | themeCss, | |
| 23 | themeHistory, | |
| 24 | } from "../../design/theme_store.ts"; | |
| 25 | import { | |
| 26 | ROLES, | |
| 27 | SCALES, | |
| 28 | contrastFailures, | |
| 29 | modeVars, | |
| 30 | validateTokens, | |
| 31 | type ThemeTokens, | |
| 32 | } from "../../design/theme_tokens.ts"; | |
| 33 | import { notFoundPage, pageHead, signInFirst } from "../chrome.ts"; | |
| 34 | import { readForm } from "../form.ts"; | |
| 35 | import { html, type Html } from "../html.ts"; | |
| 36 | import { page, redirect } from "../layout.ts"; | |
| 37 | import { badge, btn, card, timeAgo } from "../ui.ts"; | |
| 38 | import { homeTabs } from "./home_tabs.ts"; | |
| 39 | ||
| 40 | const DESIGN_CSS = `.design-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px} | |
| 41 | .design-field{display:flex;justify-content:space-between;align-items:center;gap:8px;margin:4px 0} | |
| 42 | .design-previews{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px;margin:16px 0} | |
| 43 | .design-sample{border:1px solid var(--border)}\n`; | |
| 44 | ||
| 45 | const canEdit = (ctx: Ctx): boolean => ctx.auth.user?.isAdmin === true; | |
| 46 | ||
| 47 | /** GET /_theme/forge.css and /_theme/:org/:name.css — the compiled theme, at a stable URL. */ | |
| 48 | export function themeFile(ctx: Ctx): Response { | |
| 49 | const org = ctx.params.org ?? FORGE_THEME.org; | |
| 50 | const name = ctx.params.name ?? FORGE_THEME.name; | |
| 51 | if (!THEME_NAME.test(org) || !THEME_NAME.test(name)) return new Response("not found", { status: 404 }); | |
| 52 | const { version, css } = themeCss(ctx.app.db, org, name); | |
| 53 | const etag = `"theme-${org}-${name}-${version}"`; | |
| 54 | const headers = { | |
| 55 | "content-type": "text/css; charset=utf-8", | |
| 56 | // Revalidated every time (a 304 is a few bytes); an app never serves a stale palette. | |
| 57 | "cache-control": "public, no-cache", | |
The preview's edge answers |
||
| 58 | etag, | |
| 59 | "access-control-allow-origin": "*", | |
| 60 | }; | |
| 61 | if (ctx.request.headers.get("if-none-match") === etag) return new Response(null, { status: 304, headers }); | |
| 62 | return new Response(css, { headers }); | |
| 63 | } | |
| 64 | ||
| 65 | /** GET /_theme/forge/live — one `theme` event per publish, carrying the version. */ | |
| 66 | export function themeLive(ctx: Ctx): Response { | |
| 67 | const { org, name } = FORGE_THEME; | |
| 68 | return eventStream(ctx.app, ctx.request, (emit) => { | |
| 69 | emit("theme", { version: liveTokens(ctx.app.db, org, name).version }); | |
| 70 | return onTheme(org, name, (version) => emit("theme", { version })); | |
| 71 | }); | |
| 72 | } | |
| 73 | ||
| 74 | /** The tokens a form says, or the live ones where it says nothing. */ | |
| 75 | function fromQuery(params: { get(key: string): unknown }, base: ThemeTokens): unknown { | |
| 76 | const get = (k: string): string => { | |
| 77 | const v = params.get(k); | |
| 78 | return typeof v === "string" ? v : ""; | |
| 79 | }; | |
| 80 | const draft = structuredClone(base); | |
| 81 | for (const mode of ["light", "dark"] as const) | |
| 82 | for (const r of ROLES) if (get(`${mode}.${r}`) !== "") draft[mode][r] = get(`${mode}.${r}`); | |
| 83 | for (const key of Object.keys(SCALES) as (keyof typeof SCALES)[]) | |
| 84 | if (get(`scale.${key}`) !== "") draft.scales[key] = Number(get(`scale.${key}`)); | |
| 85 | return draft; | |
| 86 | } | |
| 87 | ||
| 88 | /** One mode's sample of the forge's own components, scoped by a class. */ | |
| 89 | function sample(scope: string, label: string): Html { | |
| 90 | return html`<div class="design-sample ${scope}"> | |
| 91 | <p class="small">${label}</p> | |
| 92 | ${card( | |
| 93 | html`<h3>Card title</h3> | |
| 94 | <p class="muted">Secondary text on the card.</p> | |
| 95 | <p>${btn("Primary", { type: "button", variant: "primary" })} ${btn("Plain", { type: "button" })} | |
| 96 | ${badge("Open")} ${badge("Merged", { tone: "merged" })}</p>`, | |
| 97 | )} | |
| 98 | </div>`; | |
| 99 | } | |
| 100 | ||
| 101 | // GET /design | |
| 102 | export function designPage(ctx: Ctx): Response { | |
| 103 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 104 | const db = ctx.app.db; | |
| 105 | const live = liveTokens(db, FORGE_THEME.org, FORGE_THEME.name); | |
| 106 | const parsed = validateTokens(fromQuery(ctx.url.searchParams, live.tokens)); | |
| 107 | const draft = parsed.ok ? parsed.value : live.tokens; | |
| 108 | const failures = parsed.ok ? contrastFailures(draft) : []; | |
| 109 | const history = themeHistory(db, FORGE_THEME.org, FORGE_THEME.name, 10); | |
| 110 | const editable = canEdit(ctx); | |
| 111 | ||
| 112 | const scopes: [string, string, ThemeTokens, "light" | "dark"][] = [ | |
| 113 | ["pv-cur-light", "Current · light", live.tokens, "light"], | |
| 114 | ["pv-cur-dark", "Current · dark", live.tokens, "dark"], | |
| 115 | ["pv-new-light", "Draft · light", draft, "light"], | |
| 116 | ["pv-new-dark", "Draft · dark", draft, "dark"], | |
| 117 | ]; | |
| 118 | // Trusted: every value passed `validateTokens` (#rrggbb and bounded integers). | |
| 119 | const styleCss = DESIGN_CSS + scopes | |
| 120 | .map( | |
| 121 | ([cls, , t, mode]) => | |
| 122 | `.${cls}{${modeVars(t[mode], t.scales)}background:var(--bg);color:var(--fg);border-radius:var(--theme-radius);padding:12px}`, | |
| 123 | ) | |
| 124 | .join("\n"); | |
| 125 | ||
| 126 | const colorField = (mode: "light" | "dark", role: (typeof ROLES)[number]): Html => | |
| 127 | html`<label class="design-field small" | |
| 128 | ><span>${role}</span | |
| 129 | ><input type="color" name="${mode}.${role}" value="${draft[mode][role]}" | |
| 130 | /></label>`; | |
| 131 | const scaleField = (key: keyof typeof SCALES): Html => | |
| 132 | html`<label class="design-field small" | |
| 133 | ><span>${SCALES[key].label} (${SCALES[key].unit})</span | |
| 134 | ><input type="number" name="scale.${key}" min="${SCALES[key].min}" max="${SCALES[key].max}" value="${draft.scales[key]}" | |
| 135 | /></label>`; | |
| 136 | ||
| 137 | const verdict = !parsed.ok | |
| 138 | ? html`<p role="alert">${parsed.error}</p>` | |
| 139 | : failures.length === 0 | |
| 140 | ? html`<p role="status">${badge("AA passes", { tone: "success" })} Every text pair in light and dark meets WCAG AA.</p>` | |
| 141 | : html`<div role="alert"> | |
| 142 | <p>${badge("Blocked", { tone: "danger" })} These pairs fail WCAG AA, so Publish is off:</p> | |
| 143 | <ul>${failures.map((f) => html`<li>${f.mode} · ${f.pair}: ${f.ratio}:1 (needs ${f.need}:1)</li>`)}</ul> | |
| 144 | </div>`; | |
| 145 | ||
| 146 | const who = (id: string): string => getUserById(db, id)?.username ?? "unknown"; | |
| 147 | const body = html`${homeTabs("design")}${pageHead("Design", { sub: "The forge's theme, served at /_theme/forge.css" })} | |
| 148 | <form method="get" action="/design" id="design-form"> | |
| 149 | <div class="design-grid"> | |
| 150 | <fieldset><legend>Light colours</legend>${ROLES.map((r) => colorField("light", r))}</fieldset> | |
| 151 | <fieldset><legend>Dark colours</legend>${ROLES.map((r) => colorField("dark", r))}</fieldset> | |
| 152 | <fieldset><legend>Scales</legend>${(Object.keys(SCALES) as (keyof typeof SCALES)[]).map(scaleField)}</fieldset> | |
| 153 | </div> | |
| 154 | ${verdict} | |
| 155 | <p> | |
| 156 | ${btn("Preview draft", { variant: "secondary" })} | |
| 157 | ${editable | |
| 158 | ? html`<button class="btn" data-variant="primary" type="submit" formmethod="post" formaction="/design/publish" ${failures.length > 0 || !parsed.ok ? "disabled" : ""}>Publish</button> | |
Use |
||
| 159 | ${history.length > 0 | |
| 160 | ? html`<button class="btn" type="submit" formmethod="post" formaction="/design/revert" formnovalidate>Revert to v${Math.max(history.length > 1 ? history[1]!.version : 0, 0)}${history.length > 1 ? "" : " (defaults)"}</button>` | |
| 161 | : null}` | |
| 162 | : html`<span class="muted small">Only an admin can publish.</span>`} | |
| 163 | </p> | |
| 164 | </form> | |
| 165 | <div class="design-previews">${scopes.map(([cls, label]) => sample(cls, label))}</div> | |
| 166 | <h2>History</h2> | |
| 167 | ${history.length === 0 | |
| 168 | ? html`<p class="muted">Nothing published yet: apps get the forge's defaults (version 0).</p>` | |
| 169 | : html`<ul id="design-history">${history.map( | |
| 170 | (v) => html`<li>v${v.version} by ${who(v.actorId)} ${timeAgo(new Date(v.createdAt).toISOString())}${v.note === "" ? "" : ` · ${v.note}`}</li>`, | |
| 171 | )}</ul>`}`; | |
| 172 | return page({ ctx, title: "Design", body, styleCss }); | |
| 173 | } | |
| 174 | ||
| 175 | // POST /design/publish | |
| 176 | export async function designPublish(ctx: Ctx): Promise<Response> { | |
| 177 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 178 | const form = await readForm(ctx, "admin"); | |
| 179 | if (form instanceof Response) return form; | |
| 180 | if (!canEdit(ctx)) return notFoundPage(ctx); | |
| 181 | const live = liveTokens(ctx.app.db, FORGE_THEME.org, FORGE_THEME.name); | |
| 182 | const result = publishTheme( | |
| 183 | ctx.app.db, | |
| 184 | FORGE_THEME.org, | |
| 185 | FORGE_THEME.name, | |
| 186 | fromQuery(form, live.tokens), | |
| 187 | ctx.auth.user.id, | |
| 188 | ); | |
| 189 | return back(ctx, result.ok ? `Published v${result.version}. Open pages update now.` : result.error, result.ok); | |
| 190 | } | |
| 191 | ||
| 192 | // POST /design/revert | |
| 193 | export async function designRevert(ctx: Ctx): Promise<Response> { | |
| 194 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 195 | const form = await readForm(ctx, "admin"); | |
| 196 | if (form instanceof Response) return form; | |
| 197 | if (!canEdit(ctx)) return notFoundPage(ctx); | |
| 198 | const result = revertTheme(ctx.app.db, FORGE_THEME.org, FORGE_THEME.name, ctx.auth.user.id); | |
| 199 | return back(ctx, result.ok ? `Reverted; published as v${result.version}.` : result.error, result.ok); | |
| 200 | } | |
| 201 | ||
| 202 | const back = (ctx: Ctx, message: string, ok: boolean): Response => | |
| 203 | redirect("/design", { | |
| 204 | url: ctx.url, | |
| 205 | forgeUrl: ctx.app.config.url, | |
| 206 | flash: { tone: ok ? "success" : "danger", message }, | |
| 207 | }); |
src/web/studio/home_tabs.ts +2 −2
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | import { html, type Html } from "../html.ts"; |
| 8 | 8 | import { tabs } from "../ui.ts"; |
| 9 | 9 | |
| 10 | export type HomeTab = "feed" | "apps" | "asked"; | |
| 10 | export type HomeTab = "feed" | "apps" | "asked" | "design"; | |
| 11 | 11 | |
| 12 | 12 | /** §5's `tabs()` in a `.mb` block: link tabs, so `aria-current`. */ |
| 13 | 13 | export function homeTabs(current: HomeTab): Html { |
| @@ -18,7 +18,7 @@ export function homeTabs(current: HomeTab): Html { | ||
| 18 | 18 | }); |
| 19 | 19 | return html`<div class="mb"> |
| 20 | 20 | ${tabs( |
| 21 | [item("feed", "/", "Feed"), item("apps", "/apps", "Your apps"), item("asked", "/asked", "Asked")], | |
| 21 | [item("feed", "/", "Feed"), item("apps", "/apps", "Your apps"), item("asked", "/asked", "Asked"), item("design", "/design", "Design")], | |
| 22 | 22 | "Home", |
| 23 | 23 | )} |
| 24 | 24 | </div>`; |
test/design-theme.test.ts added +177
| @@ -0,0 +1,177 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { Database } from "bun:sqlite"; | |
| 3 | import { migrationFiles } from "../src/core/schema.ts"; | |
| 4 | import { compileTheme } from "../src/design/theme_tokens.ts"; | |
| 5 | import { | |
| 6 | contrast, | |
| 7 | contrastFailures, | |
| 8 | defaultTokens, | |
| 9 | validateTokens, | |
| 10 | } from "../src/design/theme_tokens.ts"; | |
| 11 | import { onTheme, publishTheme, revertTheme, themeCss, themeHistory } from "../src/design/theme_store.ts"; | |
| 12 | ||
| 13 | const db = () => { | |
| 14 | const d = new Database(":memory:"); | |
| 15 | for (const m of migrationFiles) if (m.sql.includes("theme_version")) d.exec(m.sql); | |
| 16 | return d; | |
| 17 | }; | |
| 18 | ||
| 19 | describe("theme tokens", () => { | |
| 20 | test("the forge's own palette passes AA", () => { | |
| 21 | expect(contrastFailures(defaultTokens())).toEqual([]); | |
| 22 | }); | |
| 23 | test("contrast is the WCAG ratio", () => { | |
| 24 | expect(contrast("#000000", "#ffffff")).toBeCloseTo(21, 1); | |
| 25 | }); | |
| 26 | test("a failing palette is named", () => { | |
| 27 | const t = defaultTokens(); | |
| 28 | t.light.fg = "#eeeeee"; | |
| 29 | expect(contrastFailures(t)[0]?.pair).toBe("fg on bg"); | |
| 30 | }); | |
| 31 | test("css cannot ride in a colour", () => { | |
| 32 | const t = defaultTokens() as unknown as { light: Record<string, string> }; | |
| 33 | t.light.bg = "red;} body{display:none"; | |
| 34 | expect(validateTokens(t).ok).toBe(false); | |
| 35 | }); | |
| 36 | test("scales are bounded", () => { | |
| 37 | const t = defaultTokens(); | |
| 38 | t.scales.radius = 999; | |
| 39 | expect(validateTokens(t).ok).toBe(false); | |
| 40 | }); | |
| 41 | test("compiles custom properties only", () => { | |
| 42 | const css = compileTheme(defaultTokens(), 3); | |
| 43 | expect(css).toContain("--bg:#fafafa;"); | |
| 44 | expect(css).toContain('[data-theme="dark"]'); | |
| 45 | }); | |
| 46 | }); | |
| 47 | ||
| 48 | describe("theme store", () => { | |
| 49 | test("publish refuses a failing palette and stores nothing", () => { | |
| 50 | const d = db(); | |
| 51 | const t = defaultTokens(); | |
| 52 | t.dark.fg = "#111111"; | |
| 53 | const r = publishTheme(d, "forge", "forge", t, "u1"); | |
| 54 | expect(r.ok).toBe(false); | |
| 55 | expect(themeHistory(d, "forge", "forge")).toEqual([]); | |
| 56 | }); | |
| 57 | test("publish versions, attributes, pushes; revert undoes", () => { | |
| 58 | const d = db(); | |
| 59 | const seen: number[] = []; | |
| 60 | const off = onTheme("forge", "forge", (v) => seen.push(v)); | |
| 61 | const t = defaultTokens(); | |
| 62 | t.light.accent = "#1d4ed8"; | |
| 63 | expect(publishTheme(d, "forge", "forge", t, "u1")).toEqual({ ok: true, version: 1 }); | |
| 64 | t.light.accent = "#1e40af"; | |
| 65 | expect(publishTheme(d, "forge", "forge", t, "u2")).toEqual({ ok: true, version: 2 }); | |
| 66 | expect(themeCss(d, "forge", "forge").css).toContain("--accent:#1e40af;"); | |
| 67 | expect(revertTheme(d, "forge", "forge", "u2")).toEqual({ ok: true, version: 3 }); | |
| 68 | const now = themeCss(d, "forge", "forge"); | |
| 69 | expect(now.version).toBe(3); | |
| 70 | expect(now.css).toContain("--accent:#1d4ed8;"); | |
| 71 | expect(themeHistory(d, "forge", "forge")[1]?.actorId).toBe("u2"); | |
| 72 | expect(seen).toEqual([1, 2, 3]); | |
| 73 | off(); | |
| 74 | }); | |
| 75 | test("no row means the defaults at version 0", () => { | |
| 76 | expect(themeCss(db(), "forge", "forge").version).toBe(0); | |
| 77 | }); | |
| 78 | }); | |
| 79 | ||
| 80 | import { afterAll, beforeAll } from "bun:test"; | |
| 81 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 82 | import { tmpdir } from "node:os"; | |
| 83 | import { join } from "node:path"; | |
| 84 | import { createApp, type App } from "../src/app.ts"; | |
| 85 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 86 | import { adminCookie } from "./helpers/admin.ts"; | |
| 87 | ||
| 88 | describe("design tab over http", () => { | |
| 89 | let dataDir = ""; | |
| 90 | let app: App; | |
| 91 | let servers: Servers; | |
| 92 | let base = ""; | |
| 93 | let admin = ""; | |
| 94 | ||
| 95 | beforeAll(async () => { | |
| 96 | dataDir = await mkdtemp(join(tmpdir(), "forge-design-")); | |
| 97 | app = createApp({ dataDir, port: 0 }); | |
| 98 | servers = await serve(app); | |
| 99 | base = servers.url; | |
| 100 | admin = await adminCookie(app, { username: "ada", email: "[email protected]", password: "design-password" }); | |
| 101 | }); | |
| 102 | afterAll(async () => { | |
| 103 | await servers.stop(); | |
| 104 | await rm(dataDir, { recursive: true, force: true }); | |
| 105 | }); | |
| 106 | ||
| 107 | const post = (path: string, fields: Record<string, string>, cookie = admin) => | |
| 108 | fetch(`${base}${path}`, { | |
| 109 | method: "POST", | |
| 110 | headers: { cookie, origin: base }, | |
| 111 | body: new URLSearchParams(fields), | |
| 112 | redirect: "manual", | |
| 113 | }); | |
| 114 | ||
| 115 | test("the css is served at a stable url, to anyone, as css", async () => { | |
| 116 | const res = await fetch(`${base}/_theme/forge.css`); | |
| 117 | expect(res.status).toBe(200); | |
| 118 | expect(res.headers.get("content-type")).toContain("text/css"); | |
| 119 | expect(await res.text()).toContain("--bg:"); | |
| 120 | expect((await fetch(`${base}/_theme/nope/none.css`)).status).toBe(200); | |
| 121 | expect((await fetch(`${base}/_theme/BAD/x.css`)).status).toBe(404); | |
| 122 | }); | |
| 123 | ||
| 124 | test("every page links the theme", async () => { | |
| 125 | expect(await (await fetch(`${base}/`)).text()).toContain('href="/_theme/forge.css"'); | |
| 126 | }); | |
| 127 | ||
| 128 | test("the design page shows the draft and the verdict", async () => { | |
| 129 | const res = await fetch(`${base}/design?light.fg=%23eeeeee`, { headers: { cookie: admin } }); | |
| 130 | const text = await res.text(); | |
| 131 | expect(res.status).toBe(200); | |
| 132 | expect(text).toContain("Blocked"); | |
| 133 | expect(text).toContain("pv-new-dark"); | |
| 134 | }); | |
| 135 | ||
| 136 | test("publish needs an admin, the same origin, and passing contrast; then the css changes", async () => { | |
| 137 | expect((await post("/design/publish", { "light.accent": "#1d4ed8" }, "")).headers.get("location")).not.toBe("/design"); | |
| 138 | const cross = await fetch(`${base}/design/publish`, { | |
| 139 | method: "POST", | |
| 140 | headers: { cookie: admin, origin: "https://evil.example" }, | |
| 141 | body: new URLSearchParams({}), | |
| 142 | redirect: "manual", | |
| 143 | }); | |
| 144 | expect(cross.status).toBe(403); | |
| 145 | ||
| 146 | await post("/design/publish", { "light.fg": "#eeeeee" }); | |
| 147 | expect(await (await fetch(`${base}/_theme/forge.css`)).text()).not.toContain("--fg:#eeeeee"); | |
| 148 | ||
| 149 | const ok = await post("/design/publish", { "light.accent": "#1d4ed8" }); | |
| 150 | expect(ok.status).toBe(303); | |
| 151 | const css = await (await fetch(`${base}/_theme/forge.css`)).text(); | |
| 152 | expect(css).toContain("--accent:#1d4ed8;"); | |
| 153 | ||
| 154 | await post("/design/revert", {}); | |
| 155 | expect(await (await fetch(`${base}/_theme/forge.css`)).text()).not.toContain("--accent:#1d4ed8;"); | |
| 156 | }); | |
| 157 | ||
| 158 | test("a publish is pushed to an open page within 2 s", async () => { | |
| 159 | const res = await fetch(`${base}/_theme/forge/live`); | |
| 160 | const reader = res.body!.getReader(); | |
| 161 | const decoder = new TextDecoder(); | |
| 162 | let seen = ""; | |
| 163 | const started = performance.now(); | |
| 164 | const next = (async () => { | |
| 165 | while (!/event: theme[\s\S]*event: theme/.test(seen)) { | |
| 166 | const { value, done } = await reader.read(); | |
| 167 | if (done) break; | |
| 168 | seen += decoder.decode(value); | |
| 169 | } | |
| 170 | })(); | |
| 171 | await Bun.sleep(100); | |
| 172 | await post("/design/publish", { "light.accent": "#1e40af" }); | |
| 173 | await next; | |
| 174 | expect(performance.now() - started).toBeLessThan(2000); | |
| 175 | await reader.cancel(); | |
| 176 | }); | |
| 177 | }); |
new above
offline
Every page, for guests too, now opens a second permanent EventSource. Ride the existing
/eventsstream, or subscribe only when a non-default theme is live.