Theme engine v3 step 5: SurfaceSet, the shell chrome reads it

themeDerive.ts: canvas, content, card, chrome, raised, panel, strong, accentFill and
tooltip, each with ink, inkSoft, link, line, hover, selected and focus solved on its
fill (both gradient ends). Hover and selected step back toward the fill until every
ink still reads on them; hover is neutral unless the theme sets one (no accent wash);
a strong gradient's end moves until one ink reads on both; targets no ink can reach
on a mid-tone fill are capped and noted. 5,000-palette property test.
chromeTheme.ts: legible() is the solver; the bevel title bar, selection and face inks
come from the strong and chrome surfaces. Chrome vars of the 13 built-ins: only the
faint/warn/danger inks move (closer to the theme colour, still 4.5:1).
This commit is contained in:
CRTkafa 2026-10-02 05:00:43 +07:00
parent e831d7a415
commit 9606c2a86e
4 changed files with 220 additions and 13 deletions

View file

@ -0,0 +1,138 @@
// Theme engine v3, step 5 (.omc/plans/theme-engine-v3.md 3.2): every surface the site and the shell
// paint, derived from a theme's tokens, with every ink solved for the fill it sits on (themeInk.ts).
// Pure. Consumers ask "what is the ink on the chrome", never "which palette role reads here".
//
// The input is the v3 palette shape; v2 documents reach it through `surfacesInputFromV2` until step 13
// makes v3 the stored format.
import { contrastRatio, relativeLuminance } from './themeApi.ts';
import { inkOn, inkOnEvery, mixOklab, TARGET } from './themeInk.ts';
export const SURFACE_NAMES = ['canvas', 'content', 'card', 'chrome', 'raised', 'panel', 'strong', 'accentFill', 'tooltip'] as const;
export type SurfaceName = typeof SURFACE_NAMES[number];
export type EdgeStyle = 'flat' | 'hairline' | 'outline' | 'bevel' | 'gloss';
export type DerivePalette = {
scheme?: 'light' | 'dark';
page?: string | null; bg: string; surface: string; elevated: string; face?: string | null;
border: string; text: string; muted: string; accent: string;
inverse?: string | null; inverse2?: string | null; onInverse?: string | null;
hover?: string | null; selected?: string | null;
};
export type DeriveInput = {
palette: DerivePalette;
edge?: { style?: EdgeStyle; strong?: boolean };
access?: 'standard' | 'high';
post?: { style?: 'flat' | 'cards' | 'bubbles' | 'compact' | 'broadsheet' };
};
export type Surface = {
/** The fill (`fill2`: the far end of a gradient fill; inks read on both). */
fill: string; fill2?: string;
ink: string; inkSoft: string; link: string; line: string;
hover: string; selected: string; focus: string;
};
export type SurfaceSet = Record<SurfaceName, Surface> & { scheme: 'light' | 'dark'; edge: EdgeStyle; notes: string[] };
const isDarkFill = (hex: string) => relativeLuminance(hex) < 0.18;
/** The best ratio any ink can reach on every one of `fills` (black or white on the worst of them). */
export const reachable = (fills: string[]) => Math.max(...['#000000', '#ffffff'].map(pole => Math.min(...fills.map(fill => contrastRatio(pole, fill)))));
/**
* One surface. Inks are solved on the fill (both ends of a gradient); the hover and selected states are
* then pulled back toward the fill until every ink still reads on them, so a hovered or selected row
* never costs contrast. A target no ink can reach on this fill (7:1 on a mid tone) is capped at the
* best there is and noted.
*/
function surface(name: SurfaceName, fill: string, p: DerivePalette, input: DeriveInput, notes: string[], opts: { fill2?: string; inkPreferred?: string; hover?: string | null; selected?: string | null } = {}): Surface {
const fills = opts.fill2 ? [fill, opts.fill2] : [fill];
const best = reachable(fills);
const cap = (target: number, what: string) => {
if (best >= target) return target;
notes.push(`${name}.${what}: ${target}:1 is out of reach on ${fills.join('/')}, ${best.toFixed(2)}:1 at most`);
return best;
};
const textTarget = cap(input.access === 'high' ? TARGET.high : TARGET.text, 'ink');
const softTarget = cap(TARGET.text, 'inkSoft');
const solve = (preferred: string, target: number, what: string) => {
const result = inkOnEvery(fills, preferred, target);
if (result.adjusted) notes.push(`${name}.${what} ${preferred} -> ${result.ink} (${result.ratio.toFixed(2)}:1)`);
return result.ink;
};
const ink = solve(opts.inkPreferred ?? p.text, textTarget, 'ink');
const inkSoft = solve(p.muted, softTarget, 'inkSoft');
const link = solve(p.accent, softTarget, 'link');
const reads = (state: string) => contrastRatio(ink, state) >= textTarget - 1e-9 && contrastRatio(inkSoft, state) >= softTarget - 1e-9 && contrastRatio(link, state) >= softTarget - 1e-9;
/** A state `t` of the way from the fill to `toward`, shrunk until the inks read on it. */
const state = (toward: string, t: number, what: string) => {
for (let k = t; k > 0.004; k /= 2) { const candidate = mixOklab(fill, toward, k); if (reads(candidate)) { if (k !== t) notes.push(`${name}.${what} step ${t} -> ${k.toFixed(3)}`); return candidate; } }
return fill;
};
const dark = isDarkFill(fill);
// States: the theme's own hover/selected when they keep every ink readable, else a neutral step toward the ink (never the accent hue for hover).
const hover = opts.hover && reads(opts.hover) ? opts.hover : state(ink, dark ? 0.08 : 0.05, 'hover');
const selected = opts.selected && reads(opts.selected) ? opts.selected : state(p.accent, 0.14, 'selected');
const strongLine = input.edge?.strong || input.access === 'high';
const lineTarget = Math.min(best, strongLine || input.edge?.style === 'outline' ? TARGET.nonText : 1.3);
return {
fill, ...(opts.fill2 ? { fill2: opts.fill2 } : {}),
ink, inkSoft, link,
line: strongLine ? ink : inkOnEvery(fills, p.border, lineTarget).ink,
hover, selected, focus: inkOnEvery(fills, p.accent, Math.min(best, TARGET.nonText)).ink,
};
}
/** Every surface of a theme. Notes list each ink the solver had to move. */
export function deriveSurfaces(input: DeriveInput): SurfaceSet {
const p = input.palette;
const notes: string[] = [];
const scheme = p.scheme ?? (relativeLuminance(p.bg) < relativeLuminance(p.text) ? 'dark' : 'light');
const edge = input.edge?.style ?? 'hairline';
const face = p.face ?? (edge === 'bevel' ? mixOklab(p.surface, p.border, 0.2) : p.surface);
const cards = input.post?.style === 'cards' || input.post?.style === 'bubbles';
// The strong fill (title bars, inverted buttons): its gradient end moves until one ink reads on both ends.
const inverse = p.inverse ?? p.text;
let inverse2 = p.inverse2 ?? inverse;
const strongPreferred = p.onInverse ?? p.bg;
if (inverse2 !== inverse) {
const both = inkOnEvery([inverse, inverse2], strongPreferred, TARGET.text);
if (both.ratio < TARGET.text) {
const ink = inkOn(inverse, strongPreferred, TARGET.text).ink;
const moved = inkOn(ink, inverse2, TARGET.text).ink;
notes.push(`strong.fill2 ${inverse2} -> ${moved} (one ink on both ends)`);
inverse2 = moved;
}
}
// The accent fill's label: white or the page colour, whichever reads better, then solved.
const accentLabel = contrastRatio('#ffffff', p.accent) >= contrastRatio(p.bg, p.accent) ? '#ffffff' : p.bg;
const tooltipFill = mixOklab(p.text, p.bg, 0.12);
const set = {
canvas: surface('canvas', p.page ?? p.bg, p, input, notes),
content: surface('content', p.bg, p, input, notes, { hover: p.hover, selected: p.selected }),
card: surface('card', cards ? p.surface : p.bg, p, input, notes, { hover: p.hover, selected: p.selected }),
chrome: surface('chrome', face, p, input, notes, { hover: p.hover, selected: p.selected }),
raised: surface('raised', p.elevated, p, input, notes),
panel: surface('panel', p.bg, p, input, notes, { hover: p.hover, selected: p.selected }),
strong: surface('strong', inverse, p, input, notes, { ...(inverse2 !== inverse ? { fill2: inverse2 } : {}), inkPreferred: strongPreferred }),
accentFill: surface('accentFill', p.accent, p, input, notes, { inkPreferred: accentLabel }),
tooltip: surface('tooltip', tooltipFill, p, input, notes, { inkPreferred: p.bg }),
} satisfies Record<SurfaceName, Surface>;
return { ...set, scheme, edge, notes };
}
/** The v2 palette and component hints as v3 derivation input (until the documents are v3, step 13). */
export function surfacesInputFromV2(colors: { bg: string; surface: string; elevated: string; border: string; text: string; muted: string; accent: string; page?: string | null; inverse?: string | null; onInverse?: string | null }, hints: { bevel?: boolean; high?: boolean; cards?: boolean } = {}): DeriveInput {
return {
palette: {
page: colors.page ?? null, bg: colors.bg, surface: colors.surface, elevated: colors.elevated, border: colors.border,
text: colors.text, muted: colors.muted, accent: colors.accent, inverse: colors.inverse ?? null, onInverse: colors.onInverse ?? null,
// A bevelled v2 theme draws its chrome from `page` (Windows 98: the silver face) and its title bar from inverse to accent.
face: hints.bevel ? colors.page ?? colors.elevated : null,
inverse2: hints.bevel ? colors.accent : null,
},
edge: { style: hints.bevel ? 'bevel' : 'hairline' },
access: hints.high ? 'high' : 'standard',
post: { style: hints.cards ? 'cards' : 'flat' },
};
}

View file

@ -79,6 +79,14 @@ export function composite(fill: string, over: string): string {
return `#${top.map((v, i) => Math.round(v * alpha + bottom[i]! * (1 - alpha)).toString(16).padStart(2, '0')).join('')}`; return `#${top.map((v, i) => Math.round(v * alpha + bottom[i]! * (1 - alpha)).toString(16).padStart(2, '0')).join('')}`;
} }
/** `a` moved `t` of the way to `b` in OKLab (perceptually even; states and tints). */
export function mixOklab(a: string, b: string, t: number): string {
const x = hexToOklch(a), y = hexToOklch(b);
const ax = x.c * Math.cos(x.h), bx = x.c * Math.sin(x.h), ay = y.c * Math.cos(y.h), by = y.c * Math.sin(y.h);
const A = ax + (ay - ax) * t, B = bx + (by - bx) * t;
return oklchToHex({ l: x.l + (y.l - x.l) * t, c: Math.hypot(A, B), h: Math.atan2(B, A) });
}
// --------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------
// The solver // The solver

View file

@ -0,0 +1,57 @@
// Theme engine v3, step 5: every surface and every role meets its target, for built-in-like and random palettes.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { contrastRatio } from '../src/themeApi.ts';
import { deriveSurfaces, reachable, surfacesInputFromV2, SURFACE_NAMES, type DeriveInput } from '../src/themeDerive.ts';
import { hexToOklch } from '../src/themeInk.ts';
function rng(seed: number) {
return () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
const randomHex = (r: () => number) => `#${Array.from({ length: 3 }, () => Math.floor(r() * 256).toString(16).padStart(2, '0')).join('')}`;
/** Every role of every surface against the fill(s) and states it sits on. */
function assertTargets(input: DeriveInput, label: string) {
const set = deriveSurfaces(input);
for (const name of SURFACE_NAMES) {
const s = set[name];
const grounds = [s.fill, ...(s.fill2 ? [s.fill2] : [])];
// The target, or the best any ink can do on this fill (a mid tone has no 7:1 ink; the deriver notes it).
const best = reachable(grounds);
const text = Math.min(best, input.access === 'high' ? 7 : 4.5);
const soft = Math.min(best, 4.5);
for (const g of [...grounds, s.hover, s.selected]) {
assert.ok(contrastRatio(s.ink, g) >= text - 1e-9, `${label} ${name}.ink ${s.ink} on ${g}`);
assert.ok(contrastRatio(s.inkSoft, g) >= soft - 1e-9, `${label} ${name}.inkSoft on ${g}`);
assert.ok(contrastRatio(s.link, g) >= soft - 1e-9, `${label} ${name}.link on ${g}`);
}
for (const g of grounds) assert.ok(contrastRatio(s.focus, g) >= Math.min(best, 3) - 1e-9, `${label} ${name}.focus on ${g}`);
// A hover state is a visible step but never a different colour family.
const step = contrastRatio(s.hover, s.fill);
if (!input.palette.hover) assert.ok(step <= 1.6, `${label} ${name}.hover step ${step.toFixed(3)}`);
}
return set;
}
test('Windows 98: silver chrome, navy-to-blue title bar with one readable ink, silver hover', () => {
const set = assertTargets(surfacesInputFromV2({ page: '#c0c0c0', bg: '#ffffff', surface: '#f4f4f4', elevated: '#dfdfdf', border: '#808080', text: '#000000', muted: '#3c3c3c', accent: '#0000a8', inverse: '#000080', onInverse: '#ffffff' }, { bevel: true }), 'w98');
assert.equal(set.chrome.fill, '#c0c0c0');
assert.equal(set.strong.fill, '#000080');
assert.ok(contrastRatio(set.strong.ink, set.strong.fill2 ?? set.strong.fill) >= 4.5);
assert.equal(set.edge, 'bevel');
});
test('the content hover is never an accent wash (the 1.0.2 lavender)', () => {
const set = deriveSurfaces(surfacesInputFromV2({ bg: '#ffffff', surface: '#f4f4f4', elevated: '#dfdfdf', border: '#808080', text: '#000000', muted: '#3c3c3c', accent: '#0000a8' }));
const hover = hexToOklch(set.content.hover);
assert.ok(hover.c < 0.01, `hover ${set.content.hover} has chroma ${hover.c.toFixed(3)}`);
});
test('5,000 random palettes: every surface and role meets its target (standard and high access)', () => {
const r = rng(5000);
for (let i = 0; i < 5000; i++) {
const bg = randomHex(r);
const palette = { bg, surface: randomHex(r), elevated: randomHex(r), border: randomHex(r), text: randomHex(r), muted: randomHex(r), accent: randomHex(r), page: randomHex(r), inverse: randomHex(r), inverse2: r() < 0.5 ? randomHex(r) : null };
assertTargets({ palette, edge: { style: r() < 0.3 ? 'bevel' : 'hairline' }, access: i % 5 === 0 ? 'high' : 'standard' }, `#${i}`);
}
});

View file

@ -2,6 +2,10 @@
// the shell's `--wb-c-*` (tabs, address bar, titlebar, menus) and the panel's `--wb-p-*` tokens, // the shell's `--wb-c-*` (tabs, address bar, titlebar, menus) and the panel's `--wb-p-*` tokens,
// which shell.css (and the app's panel CSS) read with Night Ink as the fallback. Pure (tests, // which shell.css (and the app's panel CSS) read with Night Ink as the fallback. Pure (tests,
// shell, panel). The app turns its theme documents into a `ChromeTheme` (site.themes.chrome). // shell, panel). The app turns its theme documents into a `ChromeTheme` (site.themes.chrome).
// Inks come from the engine's contrast solver and surfaces (theme engine v3, steps 4-5).
import { deriveSurfaces, surfacesInputFromV2, type SurfaceSet } from '../../../runtime/src/themeDerive.ts';
import { inkOn } from '../../../runtime/src/themeInk.ts';
/** The shell's own interface font (what an inheriting chrome role falls back to outside the page). */ /** The shell's own interface font (what an inheriting chrome role falls back to outside the page). */
export const SHELL_UI_FONT = "'Geist Variable', system-ui, sans-serif"; export const SHELL_UI_FONT = "'Geist Variable', system-ui, sans-serif";
@ -45,14 +49,14 @@ export function mix(a: string, b: string, t: number): string {
const channels = (hex: string) => hexToRgb(hex).join(' '); const channels = (hex: string) => hexToRgb(hex).join(' ');
/** Moves `color` toward `pole` until it reads at `ratio` on `surface`. */ /** The theme's surfaces (theme engine v3, themeDerive.ts): the chrome takes its title bar, face and selection from them. */
function legible(color: string, surface: string, ratio: number): string { export function chromeSurfaces(theme: ChromeTheme): SurfaceSet | null {
if (contrast(color, surface) >= ratio) return color; return theme.colors ? deriveSurfaces(surfacesInputFromV2(theme.colors, { bevel: theme.edges === 'bevel' })) : null;
const pole = luminance(surface) > 0.18 ? '#000000' : '#ffffff';
for (let t = 0.1; t <= 1; t += 0.1) { const next = mix(color, pole, t); if (contrast(next, surface) >= ratio) return next; }
return pole;
} }
/** The colour closest to `color` that reads at `ratio` on `surface` (the engine's solver, themeInk.ts). */
const legible = (color: string, surface: string, ratio: number) => inkOn(surface, color, ratio).ink;
/** /**
* CSS custom properties for the chrome in `theme`. A theme that keeps the site's colors changes * CSS custom properties for the chrome in `theme`. A theme that keeps the site's colors changes
* only the fonts (and keeps wayBetter's own corners and edges); `own` keeps wayBetter's own style * only the fonts (and keeps wayBetter's own corners and edges); `own` keeps wayBetter's own style
@ -107,19 +111,19 @@ export function chromeVars(theme: ChromeTheme, own = false): Record<string, stri
* accent, its label readable on both ends). * accent, its label readable on both ends).
*/ */
function bevelVars(colors: NonNullable<ChromeTheme['colors']>): Record<string, string> { function bevelVars(colors: NonNullable<ChromeTheme['colors']>): Record<string, string> {
const face = colors.page ?? colors.elevated; const set = deriveSurfaces(surfacesInputFromV2(colors, { bevel: true }));
const from = colors.inverse ?? colors.accent; const face = set.chrome.fill;
const titleText = colors.onInverse && contrast(colors.onInverse, from) >= 4.5 && contrast(colors.onInverse, colors.accent) >= 3 ? colors.onInverse const strong = set.strong;
: contrast('#ffffff', from) >= contrast('#000000', from) ? '#ffffff' : '#000000';
return { return {
'--wb-c-edges': 'bevel', '--wb-c-face': face, '--wb-c-face-text': legible(colors.text, face, 7), '--wb-c-edges': 'bevel', '--wb-c-face': face, '--wb-c-face-text': legible(colors.text, face, 7),
'--wb-c-bevel-hi': mix(face, '#ffffff', 1), '--wb-c-bevel-lt': mix(face, '#ffffff', 0.49), '--wb-c-bevel-hi': mix(face, '#ffffff', 1), '--wb-c-bevel-lt': mix(face, '#ffffff', 0.49),
'--wb-c-bevel-sh': mix(face, '#000000', 0.335), '--wb-c-bevel-dk': mix(face, '#000000', 0.95), '--wb-c-bevel-sh': mix(face, '#000000', 0.335), '--wb-c-bevel-dk': mix(face, '#000000', 0.95),
'--wb-c-title-from': from, '--wb-c-title-to': colors.accent, '--wb-c-title-text': titleText, // The active title bar is the strong surface: inverse to its gradient end, one ink readable on both.
'--wb-c-title-from': strong.fill, '--wb-c-title-to': strong.fill2 ?? strong.fill, '--wb-c-title-text': strong.ink,
// Selected rows (menus, lists): the title bar's own color, as in a 98 menu. // Selected rows (menus, lists): the title bar's own color, as in a 98 menu.
'--wb-c-select': from, '--wb-c-select-text': titleText, '--wb-c-select': strong.fill, '--wb-c-select-text': strong.ink,
// Menus are the face: status inks are measured on it. // Menus are the face: status inks are measured on it.
'--wb-c-muted': legible(colors.muted, face, 4.5), '--wb-c-faint': legible(colors.muted, face, 4.5), '--wb-c-muted': set.chrome.inkSoft, '--wb-c-faint': set.chrome.inkSoft,
'--wb-c-warn': legible('#806000', face, 4.5), '--wb-c-danger-ink': legible('#a00000', face, 4.5), '--wb-c-warn': legible('#806000', face, 4.5), '--wb-c-danger-ink': legible('#a00000', face, 4.5),
}; };
} }