Skip to content

Commit 866c8aa

Browse files
adewaleclaude
andauthored
Replace figure CSS-text tests with rendered color contracts (#28)
* Measure every figure token in both themes in the browser check The browser check covered #19's figure design for --fig-ink only: its contrast, the SVG having no painted chip, and the ink changing between themes. Two unit tests still guarded the rest by reading site.css as text. scripts/figure_theme_contract.mjs now measures, in light and in dark, on the rendered page: - every token in the grammar's FIGURE_TOKENS_LIGHT/DARK resolves to a colour on the figures and equals the colour the grammar documents (compared as computed colours, not as spelled); - every stroke and fill painted through a token paints that token's colour; - every such stroke and fill changes colour between light and dark; - no figure SVG has a painted background, and the ink keeps 4.5:1. The existing ink, chip and recolour checks move into the module, so the browser check and a stand-alone probe can share one implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012eisRQmQvg4TphwztxhQGJ * Retire #19's two site.css text tests for the figure tokens The browser check now measures what both tests meant on the rendered page (scripts/figure_theme_contract.mjs). Planting each bug they targeted in site.css and its served copy fails the rendered check; two of those plants passed one of the text tests: - test_dark_mode_recolours_marginalia_figures_through_tokens asserted "--fig-ink" appears after the dark media query. "--fig-ink-soft" also matches, so deleting the dark --fig-ink passed it, while the page drew 1.26:1 ink on the dark background. - A chip under another selector (.cell-banner svg { background: ... }) passed both tests; the rendered chip check fails it. - test_site_css_defines_every_token_in_both_schemes failed when a token was respelled as the same colour (#521000 to rgb(82 16 0)); the rendered check compares computed colours and passes. Neither test held a non-text assertion. FigureThemeTokenContract keeps test_every_painted_colour_is_a_token_reference, and the docs that cited Contract 15 as a site.css check now point at the rendered check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012eisRQmQvg4TphwztxhQGJ * Check figure paints against the documented colour and split recolour failures A token redefined inside a figure used to pass because each paint was only compared with its own node's token. Compare with the grammar's colour too. Report missing figures, missing token paints and differing paint counts as separate failures instead of one misleading recolour message. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01N4DAa9EdQbgyvwGUWyEBAc --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 46e74ce commit 866c8aa

7 files changed

Lines changed: 136 additions & 44 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ git diff --check
125125
- Worker Cache API keys include the HTML version
126126
- prototype layout pages are not cached
127127

128-
`make browser-layout-test` launches headless Chrome against the local Worker. It checks the rendered Shiki code-block layout so generated line markup does not create visual blank rows, drives the runner, sharing, copy, search and keyboard navigation through the page, and measures computed styles (pressed states, touch targets, contrast in both themes, the reader's font size, reduced-transparency and more-contrast fallbacks) in place of unit tests that matched CSS text.
128+
`make browser-layout-test` launches headless Chrome against the local Worker. It checks the rendered Shiki code-block layout so generated line markup does not create visual blank rows, drives the runner, sharing, copy, search and keyboard navigation through the page, and measures computed styles (pressed states, touch targets, contrast in both themes, marginalia figure colours against the grammar's `--fig-*` tokens, the reader's font size, reduced-transparency and more-contrast fallbacks) in place of unit tests that matched CSS text.
129129

130130
## Asset fingerprinting and cache busting
131131

‎docs/example-figure-rubric.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,8 @@ the figure can merge.
145145
- **Both colour schemes, enforced.** Figures paint with the
146146
`var(--fig-*)` tokens; `public/site.css` defines all four in the
147147
light root and the dark media block with the grammar's values, so
148-
no figure needs a light chip in dark mode. *Contract 15.*
148+
no figure needs a light chip in dark mode. *Contract 15, measured on
149+
the rendered page by `scripts/figure_theme_contract.mjs`.*
149150
- **figcaption present and declarative.** Captions in the form
150151
"Two names share one mutable list — appending through one name
151152
changes the object visible through both." Not "this shows X" or

‎docs/visual-explainer-spec.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -232,8 +232,9 @@ explicitly. Re-introducing either is a defect.
232232
mode, dark mode, the gestalt pages and the social cards. There is
233233
no paper chip. Any HTML shell that embeds a figure outside
234234
`site.css` must define the tokens with
235-
`figure_token_css(FIGURE_TOKENS_LIGHT)`; Contract 15 checks that
236-
`site.css` carries both sets.
235+
`figure_token_css(FIGURE_TOKENS_LIGHT)`; the browser check
236+
(`scripts/figure_theme_contract.mjs`) measures that the rendered
237+
page resolves both sets.
237238
238239
4. **Typography follows the page and mono runs are pinned.** The
239240
grammar's mono and sans stacks are the page's own (the site loads no

‎scripts/check_browser_layout.mjs‎

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@ import { spawn } from 'node:child_process';
33
import { mkdtemp, rm } from 'node:fs/promises';
44
import { tmpdir } from 'node:os';
55
import path from 'node:path';
6+
import { documentedFigureTokens, figureThemeExpression, figureThemeFailures } from './figure_theme_contract.mjs';
67

78
const chromePath = process.env.CHROME_PATH || (process.platform === 'darwin'
89
? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
910
: '/usr/bin/google-chrome');
1011
const target = process.argv[2] || 'http://127.0.0.1:9696/examples/values';
1112
const url = `${target}${target.includes('?') ? '&' : '?'}browser_layout_check=${Date.now()}`;
1213
const port = 9333 + Math.floor(Math.random() * 1000);
14+
const figureTokens = documentedFigureTokens();
1315
const profile = await mkdtemp(path.join(tmpdir(), 'pythonbyexample-chrome-'));
1416

1517
const chrome = spawn(chromePath, [
@@ -454,25 +456,20 @@ try {
454456
const body = getComputedStyle(document.body);
455457
const run = getComputedStyle(document.querySelector('button[type="submit"]'));
456458
const terminal = getComputedStyle(document.querySelector('.output-panel pre'));
457-
const figure = document.querySelector('.cell-banner figure svg');
458-
const figureInkNode = figure?.querySelector('[stroke="var(--fig-ink)"]');
459-
const figureInk = figureInkNode ? getComputedStyle(figureInkNode).stroke : null;
460459
return {
461460
pageBackground: body.backgroundColor,
462461
pageLuminance: luminance(body.backgroundColor),
463462
textContrast: contrast(body.color, body.backgroundColor),
464463
runContrast: contrast(run.color, run.backgroundColor),
465464
terminalContrast: contrast(terminal.color, terminal.backgroundColor),
466-
figureChip: figure ? getComputedStyle(figure).backgroundColor : null,
467-
figureInk,
468-
figureInkContrast: figureInk?.startsWith('rgb') ? contrast(figureInk, body.backgroundColor) : null,
469465
};
470466
}; true`);
471467
const lightTheme = await evaluateValue(`({
472468
shikiColor: getComputedStyle(document.querySelector('.shiki-block span')).color,
473469
editorColors: [...new Set([...document.querySelectorAll('.cm-line span')].map(node => getComputedStyle(node).color))].sort(),
474470
...window.__pbeColors(),
475471
})`);
472+
const lightFigures = await evaluateValue(figureThemeExpression(figureTokens.light));
476473
await client.send('Emulation.setEmulatedMedia', {
477474
media: 'screen',
478475
features: [{ name: 'prefers-color-scheme', value: 'dark' }],
@@ -501,6 +498,7 @@ try {
501498
...window.__pbeColors(),
502499
};
503500
})()`);
501+
const darkFigures = await evaluateValue(figureThemeExpression(figureTokens.dark));
504502

505503
// Keep esm.sh import requests pending. The runner has no imports and is
506504
// emitted after its markup, so its controls must attach before the editor's
@@ -859,11 +857,7 @@ try {
859857
if (lightTheme.runContrast < 4.5) failures.push(`Light Run-button contrast is ${lightTheme.runContrast.toFixed(2)}:1`);
860858
// Figures paint with the --fig-* tokens, so dark mode recolours them with
861859
// the page instead of setting each SVG on a light paper chip.
862-
for (const [label, theme] of [['light', lightTheme], ['dark', darkTheme]]) {
863-
if (!(theme.figureInkContrast >= 4.5)) failures.push(`${label} marginalia figure ink contrast is ${theme.figureInkContrast?.toFixed(2)}:1 (ink ${theme.figureInk} on ${theme.pageBackground})`);
864-
if (theme.figureChip !== 'rgba(0, 0, 0, 0)') failures.push(`${label} marginalia figures sit on a painted chip (${theme.figureChip})`);
865-
}
866-
if (lightTheme.figureInk === darkTheme.figureInk) failures.push(`Marginalia figure ink did not recolour with the dark palette (${darkTheme.figureInk})`);
860+
failures.push(...figureThemeFailures({ light: lightFigures, dark: darkFigures }));
867861
if (offlineRunner.fallbackOverflow > 0.5) failures.push(`Fallback textarea overflows its panel by ${offlineRunner.fallbackOverflow.toFixed(1)}px`);
868862
if (rendered.fontSmoothing !== 'antialiased') failures.push('Body text is not antialiased');
869863
if (!String(rendered.headingWrap).includes('balance')) failures.push(`Headings do not balance their lines (${rendered.headingWrap})`);
@@ -904,6 +898,8 @@ try {
904898
searchFailure,
905899
lightTheme,
906900
darkTheme,
901+
lightFigures,
902+
darkFigures,
907903
offlineRunner,
908904
fragmentBound,
909905
turnstileRetry,

‎scripts/figure_theme_contract.mjs‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
// Rendered contract for the marginalia figure tokens.
2+
//
3+
// Figures paint with var(--fig-ink) and friends instead of literal colours,
4+
// so one paint function renders in both colour schemes. That holds only if
5+
// the page defines every token in light and dark, with the colours
6+
// src/marginalia_grammar.py documents (the social cards and gestalt pages
7+
// embed the same values). check_browser_layout.mjs measures each scheme on
8+
// the rendered page with figureThemeExpression() and reports
9+
// figureThemeFailures(); nothing here reads CSS text.
10+
import { execFileSync } from 'node:child_process';
11+
import path from 'node:path';
12+
import { fileURLToPath } from 'node:url';
13+
14+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
15+
16+
// The grammar's FIGURE_TOKENS_LIGHT and FIGURE_TOKENS_DARK, imported from Python.
17+
export function documentedFigureTokens() {
18+
const program = 'import json; from src.marginalia_grammar import FIGURE_TOKENS_DARK, FIGURE_TOKENS_LIGHT; '
19+
+ 'print(json.dumps({"light": FIGURE_TOKENS_LIGHT, "dark": FIGURE_TOKENS_DARK}))';
20+
const output = execFileSync('uv', ['run', '--python', '3.13', 'python', '-c', program], {
21+
cwd: root,
22+
encoding: 'utf8',
23+
stdio: ['ignore', 'pipe', 'pipe'],
24+
});
25+
return JSON.parse(output);
26+
}
27+
28+
// Runs in the page under the current colour scheme. `documented` maps each
29+
// token to the colour the grammar gives it in that scheme.
30+
function measureFigures(documented) {
31+
// Compare colours as the browser resolves them, not as they are spelled.
32+
const resolve = value => {
33+
const probe = document.createElement('span');
34+
probe.style.color = value;
35+
if (!probe.style.color) return null;
36+
document.body.append(probe);
37+
const colour = getComputedStyle(probe).color;
38+
probe.remove();
39+
return colour;
40+
};
41+
const luminance = colour => {
42+
const [r, g, b] = colour.match(/[\d.]+/g).slice(0, 3).map(value => {
43+
const channel = Number(value) / 255;
44+
return channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4;
45+
});
46+
return .2126 * r + .7152 * g + .0722 * b;
47+
};
48+
const contrast = (a, b) => {
49+
const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);
50+
return (high + .05) / (low + .05);
51+
};
52+
const pageBackground = getComputedStyle(document.body).backgroundColor;
53+
const svgs = [...document.querySelectorAll('.cell-banner figure svg')];
54+
const inherited = svgs[0] ? getComputedStyle(svgs[0]) : null;
55+
const tokens = {};
56+
for (const [name, value] of Object.entries(documented)) {
57+
tokens[name] = { value: inherited ? resolve(inherited.getPropertyValue(name).trim()) : null, documented: resolve(value) };
58+
}
59+
// Every stroke and fill a figure paints through a token, in document order.
60+
const paints = [];
61+
for (const node of svgs.flatMap(svg => [...svg.querySelectorAll('*')])) {
62+
for (const attr of ['stroke', 'fill']) {
63+
const token = /^var\((--fig-[a-z-]+)\)$/.exec(node.getAttribute(attr) || '')?.[1];
64+
if (!token) continue;
65+
const style = getComputedStyle(node);
66+
paints.push({ token, attr, painted: style[attr], tokenColour: resolve(style.getPropertyValue(token).trim()) });
67+
}
68+
}
69+
const ink = paints.find(paint => paint.token === '--fig-ink' && paint.attr === 'stroke')?.painted ?? null;
70+
return {
71+
figures: svgs.length,
72+
pageBackground,
73+
chips: svgs.map(svg => getComputedStyle(svg).backgroundColor),
74+
tokens,
75+
paints,
76+
ink,
77+
inkContrast: ink?.startsWith('rgb') ? contrast(ink, pageBackground) : null,
78+
};
79+
}
80+
81+
export function figureThemeExpression(documented) {
82+
return `(${measureFigures.toString()})(${JSON.stringify(documented)})`;
83+
}
84+
85+
export function figureThemeFailures({ light, dark }) {
86+
const failures = [];
87+
for (const [scheme, theme] of [['light', light], ['dark', dark]]) {
88+
if (!theme.figures) {
89+
failures.push(`${scheme}: no marginalia figure on the page to measure`);
90+
continue;
91+
}
92+
if (!(theme.inkContrast >= 4.5)) failures.push(`${scheme} marginalia figure ink contrast is ${theme.inkContrast?.toFixed(2)}:1 (ink ${theme.ink} on ${theme.pageBackground})`);
93+
// No light "paper chip" behind figures: the tokens do the work.
94+
const chips = [...new Set(theme.chips)].filter(chip => chip !== 'rgba(0, 0, 0, 0)');
95+
if (chips.length) failures.push(`${scheme} marginalia figures sit on a painted chip (${chips.join(', ')})`);
96+
for (const [name, token] of Object.entries(theme.tokens)) {
97+
if (!token.value) failures.push(`${scheme} figure token ${name} does not resolve to a colour`);
98+
else if (token.value !== token.documented) failures.push(`${scheme} figure token ${name} is ${token.value}, not the ${token.documented} src/marginalia_grammar.py documents`);
99+
}
100+
// Against the grammar's colour as well as the node's own token, so a
101+
// token redefined on the figure or inside it cannot pass by agreeing with itself.
102+
const offToken = theme.paints.filter(paint => !paint.tokenColour || paint.painted !== paint.tokenColour
103+
|| paint.painted !== theme.tokens[paint.token]?.documented);
104+
if (offToken.length) failures.push(`${scheme}: ${offToken.length} figure strokes/fills do not paint their token's colour (${offToken.slice(0, 3).map(paint => `${paint.attr}=var(${paint.token}) painted ${paint.painted}`).join('; ')})`);
105+
}
106+
// Dark mode recolours figures through the tokens, not with a second palette.
107+
if (!light.figures || !dark.figures) return failures;
108+
const kept = light.paints.filter((paint, index) => paint.painted === dark.paints[index]?.painted);
109+
if (!light.paints.length) failures.push('Marginalia figures paint no stroke or fill through a --fig-* token');
110+
else if (light.paints.length !== dark.paints.length) failures.push(`Marginalia figures paint ${light.paints.length} token strokes/fills in light but ${dark.paints.length} in dark`);
111+
else if (kept.length) failures.push(`Marginalia figures did not recolour with the dark palette (${kept.length} of ${light.paints.length} strokes/fills kept their light colour: ${[...new Set(kept.map(paint => paint.token))].join(', ')})`);
112+
return failures;
113+
}

‎tests/test_app.py‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -531,15 +531,9 @@ def test_dynamic_worker_code_wraps_user_example(self):
531531

532532

533533
class DarkModeAndAccessibilityTests(unittest.TestCase):
534-
def test_dark_mode_recolours_marginalia_figures_through_tokens(self):
535-
css = (ROOT / "public" / "site.css").read_text()
536-
dark_block = css.split("@media (prefers-color-scheme: dark)", 1)[1]
537-
for token in ("--fig-ink", "--fig-ink-soft", "--fig-accent", "--fig-soft"):
538-
self.assertIn(token, dark_block)
539-
# No light "paper chip" behind figures: the tokens do the work.
540-
self.assertNotIn("--figure-paper", css)
541-
self.assertNotIn(".cell-banner figure svg", dark_block)
542-
534+
# Figure colours in both themes (every --fig-* token defined, no paper
535+
# chip) are measured on the rendered page by
536+
# scripts/figure_theme_contract.mjs, run from check_browser_layout.mjs.
543537
def test_optional_highlighters_retain_readable_server_fallbacks(self):
544538
page = render_example_page(get_example("values"))
545539
self.assertIn('<pre><code class="language-python">', page)

‎tests/test_marginalia_geometry.py‎

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -847,30 +847,17 @@ def test_no_arrow_is_shorter_than_the_minimum(self):
847847

848848

849849
class FigureThemeTokenContract(unittest.TestCase):
850-
"""Contract 15: the page defines the figure tokens the grammar paints with.
850+
"""Contract 15: figures paint only through the --fig-* theme tokens.
851851
852852
Figures emit var(--fig-ink) and friends instead of literal colours so
853-
one paint function renders in both colour schemes. That only holds
854-
if public/site.css defines every token in both the light :root and
855-
the dark media block, with exactly the values the grammar documents;
856-
a missing token renders as black in light mode and invisible ink in
857-
dark mode, and neither is caught by the geometry contracts.
853+
one paint function renders in both colour schemes. The other half of
854+
the contract is measured on the rendered page, in light and dark, by
855+
scripts/figure_theme_contract.mjs (run from check_browser_layout.mjs):
856+
every token resolves to the colour FIGURE_TOKENS_LIGHT/DARK document,
857+
and every stroke and fill paints it. A missing token leaves strokes
858+
unpainted and fills black, which no geometry contract can see.
858859
"""
859860

860-
def test_site_css_defines_every_token_in_both_schemes(self):
861-
from pathlib import Path
862-
863-
from src.marginalia_grammar import FIGURE_TOKENS_DARK, FIGURE_TOKENS_LIGHT
864-
865-
css = (Path(__file__).resolve().parents[1] / "public" / "site.css").read_text()
866-
light, dark = css.split("@media (prefers-color-scheme: dark)", 1)
867-
failures: list[str] = []
868-
for scheme, block, tokens in (("light", light, FIGURE_TOKENS_LIGHT), ("dark", dark, FIGURE_TOKENS_DARK)):
869-
for name, value in tokens.items():
870-
if f"{name}: {value};" not in block:
871-
failures.append(f"{scheme}: expected `{name}: {value};`")
872-
self.assertEqual(failures, [], "\n " + "\n ".join(failures))
873-
874861
def test_every_painted_colour_is_a_token_reference(self):
875862
from src.marginalia_grammar import EMPHASIS, INK, INK_SOFT, SOFT_FILL
876863

0 commit comments

Comments
 (0)