diff --git a/.dependency-cruiser.cjs b/.dependency-cruiser.cjs index a8ddc9c9..f7282278 100644 --- a/.dependency-cruiser.cjs +++ b/.dependency-cruiser.cjs @@ -1,5 +1,17 @@ module.exports = { forbidden: [ + { + name: "color-only-color", + severity: "error", + from: { path: "^src/color/" }, + to: { path: "^src/", pathNot: "^src/color/" }, + }, + { + name: "color-is-independent", + severity: "error", + from: { path: "^src/", pathNot: "^src/color/" }, + to: { path: "^src/color/" }, + }, { name: "dom-no-element", severity: "error", diff --git a/.gitignore b/.gitignore index 63a497ba..f3d0b61e 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,6 @@ output/ # Agent loop state (scripts/agent-loop) .loop/ + +# Archived colour research inputs +.cache/colour/ diff --git a/.prettierignore b/.prettierignore index 91afc9a8..bfbc71e8 100644 --- a/.prettierignore +++ b/.prettierignore @@ -11,3 +11,5 @@ source-map.schema.json etc test/fixtures CHANGELOG.md + +.cache/colour diff --git a/.size-limit.js b/.size-limit.js index 94c2deda..76bbf80f 100644 --- a/.size-limit.js +++ b/.size-limit.js @@ -1,6 +1,13 @@ // Size Limit externalizes peer dependencies by default. Measure actual consumer bytes. // Margin = min(1000 B, 3% of measured gzip), rounded down. const cases = [ + { + name: "colour palette and checks (without DOM or Zod)", + path: "dist/color/index.js", + gzip: true, + // Measured 3416 B + 102 B margin. + limit: "3518 B", + }, { name: "web component (pre-resolved map; with Zod)", path: "dist/element.js", diff --git a/README.md b/README.md index 8b84ad29..f39ba664 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,21 @@ and [automatic layout](docs/LAYOUT.md). Framework examples: [React](docs/frameworks/react.md), [Vue](docs/frameworks/vue.md), and [Svelte](docs/frameworks/svelte.md). +## Choose and check colours + +Generate light and dark palettes or check host colours with the independent +[`@metronforge/concept-map/color` entry](docs/COLOR.md). It emits CSS custom +properties without loading the player, layout engines or Zod. + +All ten examples and 18 of 23 book maps use at most four layers. The measured +lane labels pass text contrast, but some layer pairs and layer–accent pairs +become hard to tell apart under simulated colour vision deficiencies. The +generator checks all four vision models. Its two- through six-layer palettes +beat the book's existing colours, including when the book accent stays fixed. +See the [comparison and measured distances](docs/evidence/colour/palette-comparison.md). +Applying a palette is an explicit host choice; lane labels and CSS defaults +are unchanged. + ## Lay out on the server Install the optional engine with `npm install @dagrejs/dagre`. Read the source diff --git a/docs/COLOR.md b/docs/COLOR.md new file mode 100644 index 00000000..3ee62a68 --- /dev/null +++ b/docs/COLOR.md @@ -0,0 +1,61 @@ +# Colour palettes and checks + +Import the independent core entry in Node or a browser: + +```ts +import { + palette, + checkColors, + ColorError, +} from "@metronforge/concept-map/color"; + +const p = palette(["client", "server", "queue"], { + fixed: { light: { server: "#753646" } }, + accentHue: 255, +}); +const css = p.toCss({ light: ".map-ui", dark: "[data-theme=dark] .map-ui" }); +const report = checkColors(p.light); +``` + +`p.light` and `p.dark` each contain neutral `base` roles (`bg`, `node`, `fg`, +`mutedFg`, `border`), one reserved `accent`, and a `layers` record. The search +is deterministic for the same ordered layer ids and options. Ids must be unique +and follow the map identifier grammar: a letter, then letters, digits, `_` or `-`. +Empty lists are allowed. Generated colours are lower-case six-digit sRGB hex. +Fixed colours retain their spelling and participate in the search. They are +not repaired; check the result when supplying host colours. + +`accentHue` is an OKLCH angle in degrees (default 255; whole turns wrap). +To preserve an exact host accent, pass `accent: { light: "#285bb5" }` and/or +`accent.dark`. Its measured hue determines the layer exclusion window in that +theme. The generator accepts `#rgb` and `#rrggbb`, as does the checker. + +`toCss` returns two rules using the supplied selectors verbatim. It emits the +existing background, node, foreground, muted foreground, border, accent and +per-layer custom properties. Add the text to a host stylesheet. It does not +apply styles or change the library's defaults. Selectors are trusted stylesheet +source supplied by the host. + +`checkColors(theme)` returns `defects` and `metrics`. It checks opaque colours: +text needs WCAG contrast 4.5:1, meaningful lines need 3:1, and layer–layer and +layer–accent distances use the minimum OKLab distance across normal vision +and Machado protanopia, deuteranopia and tritanopia simulations. Distances below +0.04 are hard defects; below 0.06 are advice. More than six layers adds advice. +Optional `ghost: { text, line }` roles need 2:1 and 1.3:1 respectively and must +keep ghost contrast below normal contrast, with normal no higher than current. + +Invalid colour values throw `ColorError` with a `path`. With +`checkColors(theme, { strict: true })`, hard defects also throw `ColorError`, +with the full report on `error.report`. Advice alone never throws. + +Layer colours are intended for lines and marks with area. Lane labels still +use layer colours in the current renderer and can require more contrast than +these palettes guarantee. Moving lane labels to the text colour and adding a +swatch is a separate drawing change. Painted states, transparency and status +colours also need their own checks; this entry does not inspect CSS or SVG. +Today's fallback layer and accent have a known hard distance defect, recorded +in the [colour findings](evidence/colour/README.md). Generating a +palette does not silently replace those defaults. + +See the [generated palette measurements](evidence/colour/palette.md) for +2–8-layer results, fixed-colour cases, targets and search decisions. diff --git a/docs/CSS.md b/docs/CSS.md index ffb521a4..fa75d8ff 100644 --- a/docs/CSS.md +++ b/docs/CSS.md @@ -30,6 +30,40 @@ There is no built-in layer list or special case for a layer named `app`. } ``` +## Generate or check a host palette + +The independent `@metronforge/concept-map/color` entry generates neutral base +roles, layer colours and a reserved current-step accent for light and dark themes: + +```ts +import { palette, checkColors } from "@metronforge/concept-map/color"; + +const p = palette(["service", "guest"]); +const css = p.toCss({ light: ".map-ui", dark: "[data-theme=dark] .map-ui" }); +const report = checkColors(p.light); +``` + +Add `css` to the host stylesheet. The two rules set `--cmap-bg`, `--cmap-node`, +`--cmap-fg`, `--cmap-muted-fg`, `--cmap-border`, `--cmap-accent` and each +`--cmap-layer-`. Other properties above keep their existing values. Selectors +are trusted stylesheet text. The function returns text and does not insert it. + +The checker requires 4.5:1 for text roles and 3:1 for meaningful lines. It +measures layer–layer and layer–accent separation under normal vision and three +colour vision deficiency simulations: below 0.04 OKLab distance is a hard +defect, below 0.06 is advice. APCA Lc is informational. Host colours can be +checked directly; fixed generator colours remain as supplied and may fail. +See [the colour API](COLOR.md) for fixed colours, exact accents and strict errors. + +The measured book lane labels pass text contrast; its colour pairs can still +be confused under simulation. Generated layers are intended for lines and +marks with area, so lane labels need a separate drawing change before they +can use these palettes without their own text contrast check. Today's fallback +layer and accent retain their recorded hard separation defect. Generating CSS +does not replace the defaults automatically. + +## Existing host integration + The old named properties (for example `--cmap-`) and internal aliases (for example `--client`), and concept references to `--pw-*`, are removed. Hosts can map existing colours to `--cmap-layer-` themselves. `--c` and diff --git a/docs/adr/0030-perceptual-colour.md b/docs/adr/0030-perceptual-colour.md index d12c0c47..e39c195c 100644 --- a/docs/adr/0030-perceptual-colour.md +++ b/docs/adr/0030-perceptual-colour.md @@ -2,7 +2,7 @@ Status: accepted (approved by the author by merging the pull request that set this status). The author chose a generator in the library, and WCAG 2 as the -hard norm with APCA for information only; the ghost rules were delegated. +hard norm; the ghost rules were delegated. ## Context @@ -58,8 +58,8 @@ layer hues. OKLab. Colours are emitted as sRGB hex for compatibility. **Contrast.** WCAG 2.2 is the hard norm: 4.5:1 for text (1.4.3), 3:1 for -lines and marks that carry meaning (1.4.11). APCA Lc values are reported for -information only, because WCAG 3 is a draft. +lines and marks that carry meaning (1.4.11). +APCA was dropped for licence reasons; WCAG contrast is the only contrast measure. **Not colour alone (1.4.1).** Every layer keeps a text label. Lane labels use the text colour; the layer colour moves to marks with area (lane tint, diff --git a/docs/evidence/colour/README.md b/docs/evidence/colour/README.md new file mode 100644 index 00000000..b328f4c7 --- /dev/null +++ b/docs/evidence/colour/README.md @@ -0,0 +1,172 @@ +# Colour findings and palette measurements + +The raw catalogue and its original research scripts are preserved on +`archive/colour-catalogue-140`, commit `040827a`. They are deliberately excluded +from this branch. The frozen book inputs record stylesheet and map hashes in +`book-input/provenance.json`; the site checkout was read only. These are source +colour measurements, not a deployed-site or browser-cascade audit. + +## Reproduce + +From the repository root, restore only the archived inputs to the ignored cache: + +```sh +mkdir -p .cache/colour/archive +git archive 040827a docs/evidence/colour/catalogue/book-input | tar -x -C .cache/colour/archive +npm run build +node scripts/colour-findings.mjs --check +node scripts/colour-palette.mjs --check +node scripts/colour-palette-comparison.mjs --check +npm run size +``` + +Omit `--check` to update the corresponding summary, never the raw catalogue. +`scripts/colour-findings.mjs` reproduces every number in the two tables below +and the default defect. It reads the archived book inputs and current local +examples and CSS. To inspect historical raw rows, use `git show +040827a:docs/evidence/colour/catalogue/patterns/opaque.md` and +`git show 040827a:docs/evidence/colour/catalogue/patterns/layers.md`. +The archive also holds the painted-state reports and their reproduction scripts; +those broader research inventories are not required by these summaries. + +## Counted findings + +Counts are role-pair cases repeated across map, host and theme contexts, not +independent colours, readers or visible-object counts. Local includes defaults, +standalone examples and comparison hosts; light and dark reuse the same colours +because these hosts have no dark override. Book themes have separate colours. +Lane text is checked against its 6% layer / 94% background fill in encoded sRGB. + +| Context | Finding | Affected cases | +| -------------------------------- | ------------------------------------------- | -------------- | +| book light | layer–accent hard | 18 out of 82 | +| book light | layer–accent advice only | 16 out of 82 | +| book light | layer–accent hard only under simulation | 18 out of 82 | +| book light | layer–accent hard under protanopia alone | 0 out of 82 | +| book light | layer–accent hard under deuteranopia alone | 18 out of 82 | +| book light | layer–accent hard under tritanopia alone | 0 out of 82 | +| book light | layer–layer hard | 41 out of 123 | +| book light | layer–layer advice only | 25 out of 123 | +| book light | layer–layer hard only under simulation | 39 out of 123 | +| book light | layer–layer hard under protanopia alone | 0 out of 123 | +| book light | layer–layer hard under deuteranopia alone | 10 out of 123 | +| book light | layer–layer hard under tritanopia alone | 25 out of 123 | +| book light | lane text below 4.5:1 | 0 out of 67 | +| book light | opaque role contrast below its minimum | 0 out of 348 | +| book light | contexts with more than six declared layers | 0 out of 23 | +| local (including defaults) light | layer–accent hard | 21 out of 21 | +| local (including defaults) light | layer–accent advice only | 0 out of 21 | +| local (including defaults) light | layer–accent hard only under simulation | 21 out of 21 | +| local (including defaults) light | layer–accent hard under protanopia alone | 0 out of 21 | +| local (including defaults) light | layer–accent hard under deuteranopia alone | 0 out of 21 | +| local (including defaults) light | layer–accent hard under tritanopia alone | 21 out of 21 | +| local (including defaults) light | layer–layer hard | 3 out of 3 | +| local (including defaults) light | layer–layer advice only | 0 out of 3 | +| local (including defaults) light | layer–layer hard only under simulation | 0 out of 3 | +| local (including defaults) light | layer–layer hard under protanopia alone | 0 out of 3 | +| local (including defaults) light | layer–layer hard under deuteranopia alone | 0 out of 3 | +| local (including defaults) light | layer–layer hard under tritanopia alone | 0 out of 3 | +| local (including defaults) light | lane text below 4.5:1 | 0 out of 3 | +| local (including defaults) light | opaque role contrast below its minimum | 0 out of 186 | +| local (including defaults) light | contexts with more than six declared layers | 0 out of 18 | +| book dark | layer–accent hard | 8 out of 82 | +| book dark | layer–accent advice only | 10 out of 82 | +| book dark | layer–accent hard only under simulation | 8 out of 82 | +| book dark | layer–accent hard under protanopia alone | 0 out of 82 | +| book dark | layer–accent hard under deuteranopia alone | 0 out of 82 | +| book dark | layer–accent hard under tritanopia alone | 8 out of 82 | +| book dark | layer–layer hard | 21 out of 123 | +| book dark | layer–layer advice only | 49 out of 123 | +| book dark | layer–layer hard only under simulation | 19 out of 123 | +| book dark | layer–layer hard under protanopia alone | 3 out of 123 | +| book dark | layer–layer hard under deuteranopia alone | 6 out of 123 | +| book dark | layer–layer hard under tritanopia alone | 10 out of 123 | +| book dark | lane text below 4.5:1 | 0 out of 67 | +| book dark | opaque role contrast below its minimum | 0 out of 348 | +| book dark | contexts with more than six declared layers | 0 out of 23 | +| local (including defaults) dark | layer–accent hard | 21 out of 21 | +| local (including defaults) dark | layer–accent advice only | 0 out of 21 | +| local (including defaults) dark | layer–accent hard only under simulation | 21 out of 21 | +| local (including defaults) dark | layer–accent hard under protanopia alone | 0 out of 21 | +| local (including defaults) dark | layer–accent hard under deuteranopia alone | 0 out of 21 | +| local (including defaults) dark | layer–accent hard under tritanopia alone | 21 out of 21 | +| local (including defaults) dark | layer–layer hard | 3 out of 3 | +| local (including defaults) dark | layer–layer advice only | 0 out of 3 | +| local (including defaults) dark | layer–layer hard only under simulation | 0 out of 3 | +| local (including defaults) dark | layer–layer hard under protanopia alone | 0 out of 3 | +| local (including defaults) dark | layer–layer hard under deuteranopia alone | 0 out of 3 | +| local (including defaults) dark | layer–layer hard under tritanopia alone | 0 out of 3 | +| local (including defaults) dark | lane text below 4.5:1 | 0 out of 3 | +| local (including defaults) dark | opaque role contrast below its minimum | 0 out of 186 | +| local (including defaults) dark | contexts with more than six declared layers | 0 out of 18 | + +Hard means worst OKLab distance below 0.04; advice only is 0.04 to below 0.06. +Simulation-only hard pairs pass the normal-vision hard band, but may fail under +several simulations. A failure under one simulation alone passes the hard band +under normal vision and both other simulations. No checker bands were changed. + +Book lane text contrast fails in 0 out of 67 cases per theme. The main problem +is colour confusion: book layer–accent failures occur under deuteranopia alone +in light and tritanopia alone in dark. Many layer–layer hard failures also pass +normal vision. Normal text contrast therefore cannot stand in for these checks. + +## Layer counts + +Each source map is counted once. Used means referenced by nodes, lanes or +concept groups. Book fixtures are not counted again alongside source maps. + +| Inventory | Layers | Range | Affected maps | +| ----------- | -------- | ------------- | ------------- | +| examples | declared | exactly 1 | 7 out of 10 | +| examples | declared | exactly 2 | 3 out of 10 | +| examples | declared | at most four | 10 out of 10 | +| examples | declared | more than six | 0 out of 10 | +| examples | used | exactly 1 | 7 out of 10 | +| examples | used | exactly 2 | 3 out of 10 | +| examples | used | at most four | 10 out of 10 | +| examples | used | more than six | 0 out of 10 | +| book source | declared | exactly 1 | 2 out of 23 | +| book source | declared | exactly 2 | 2 out of 23 | +| book source | declared | exactly 3 | 6 out of 23 | +| book source | declared | exactly 4 | 8 out of 23 | +| book source | declared | exactly 5 | 4 out of 23 | +| book source | declared | exactly 6 | 1 out of 23 | +| book source | declared | at most four | 18 out of 23 | +| book source | declared | more than six | 0 out of 23 | +| book source | used | exactly 1 | 2 out of 23 | +| book source | used | exactly 2 | 2 out of 23 | +| book source | used | exactly 3 | 6 out of 23 | +| book source | used | exactly 4 | 8 out of 23 | +| book source | used | exactly 5 | 4 out of 23 | +| book source | used | exactly 6 | 1 out of 23 | +| book source | used | at most four | 18 out of 23 | +| book source | used | more than six | 0 out of 23 | + +All examples and most book maps use at most four layers, making four-layer +separation the priority. The generator still measures the larger counts. + +## Known default defect + +The library fallback `#526a8a` and accent `#285bb5` have exactly one hard +checker defect, `indistinct`, and no others. The same defaults apply in both +modes. Their four distances, reproduced by `scripts/colour-findings.mjs`, are: + +| Normal | Protanopia | Deuteranopia | Tritanopia | Worst model | +| ----------- | ----------- | ------------ | ----------- | ----------- | +| 0.099688426 | 0.096414599 | 0.111558507 | 0.036455690 | tritanopia | + +A unit test pins this defect. Replacing the CSS defaults is separate work. + +## Generated results and scope + +[Palette measurements](palette.md), produced by `scripts/colour-palette.mjs`, +cover two through eight layers with and without one fixed layer, plus one-layer +fixed-accent fallback candidates. [Book comparison](palette-comparison.md), +produced by `scripts/colour-palette-comparison.mjs`, covers two through six +layers under all four vision models, with generated and exact book accents. +That script reads the same archived theme inputs. Gzip size comes from +`npm run size`; the colour entry has its own limit. + +APCA was removed for licence reasons; WCAG contrast is the only contrast +measure. Lane-label rendering, CSS defaults and SVG remain unchanged. Combined +painted states and route-dependent token contrast are outside this task. diff --git a/docs/evidence/colour/palette-comparison.md b/docs/evidence/colour/palette-comparison.md new file mode 100644 index 00000000..e7fefbbe --- /dev/null +++ b/docs/evidence/colour/palette-comparison.md @@ -0,0 +1,81 @@ +# Generated palettes compared with book colours + +Reproduce: `npm run build && node scripts/colour-palette-comparison.mjs`. +Check without writing: `node scripts/colour-palette-comparison.mjs --check`. +Inputs: frozen book theme colours from `archive/colour-catalogue-140` at +`040827a`. Restore them using [the findings reproduction command](README.md#reproduce); +source hashes remain in the archived `book-input/provenance.json`. +The public `./color` API supplies generated palettes. No CSS changes. + +Each model column is the minimum distance over every layer–layer and +layer–accent pair under that model; the limiting pair can differ by column. +Worst ΔE is the minimum of all four columns. Values use final hex colours; +assertions use unrounded values. Larger distances mean greater separation. + +For each count, enumerate every subset of the nine book layer ids, retaining +its existing accent. Select the subset with the largest worst ΔE (ties keep +source order). This is a stronger reference than selecting a failing map: +no subset of the current book palette at that count has a better worst pair. +The ids in the table identify the selected subset. These are synthetic subsets, +not counts of maps that use those exact colours. Equal colours on distinct ids +remain eligible. Generated ids follow the same ordered list in each run. + +Generated rows either use the default blue accent or keep the book's exact +light/dark accent. Both generated variants beat the strongest book subset at +every count from two through six, and all 20 generated themes have no hard +checker defects. This compares separation, not painted states or lane-text +contrast; fixed accents are checked against the generator's default bases. + +| Layers | Theme | Palette | Accent | Normal | Protanopia | Deuteranopia | Tritanopia | Worst ΔE | Worst model | Layer ids | +| ------ | ----- | ---------------------- | ------- | ----------- | ----------- | ------------ | ----------- | ----------- | ------------ | ---------------------------------------------- | +| 2 | light | best book subset | #ad4f0d | 0.168728452 | 0.136731141 | 0.110936681 | 0.087885662 | 0.087885662 | tritanopia | runner, protocol | +| 2 | light | generated | #0061be | 0.229498498 | 0.243308495 | 0.212485677 | 0.212477678 | 0.212477678 | tritanopia | layer1, layer2 | +| 2 | light | generated, book accent | #ad4f0d | 0.238748222 | 0.215037983 | 0.184556958 | 0.250506197 | 0.184556958 | deuteranopia | layer1, layer2 | +| 2 | dark | best book subset | #f08a3c | 0.150948835 | 0.115744675 | 0.081334169 | 0.111238779 | 0.081334169 | deuteranopia | runner, protocol | +| 2 | dark | generated | #65a7fa | 0.186396642 | 0.176146839 | 0.144390788 | 0.149483201 | 0.144390788 | deuteranopia | layer1, layer2 | +| 2 | dark | generated, book accent | #f08a3c | 0.206208229 | 0.192342589 | 0.163029955 | 0.155332454 | 0.155332454 | tritanopia | layer1, layer2 | +| 3 | light | best book subset | #ad4f0d | 0.096760386 | 0.056436309 | 0.048919980 | 0.067142636 | 0.048919980 | deuteranopia | runner, server, page | +| 3 | light | generated | #0061be | 0.169216253 | 0.152723037 | 0.135025740 | 0.155661842 | 0.135025740 | deuteranopia | layer1, layer2, layer3 | +| 3 | light | generated, book accent | #ad4f0d | 0.210961007 | 0.167592625 | 0.166742409 | 0.161292281 | 0.161292281 | tritanopia | layer1, layer2, layer3 | +| 3 | dark | best book subset | #f08a3c | 0.085359615 | 0.084987744 | 0.069503884 | 0.055116411 | 0.055116411 | tritanopia | runner, server, protocol | +| 3 | dark | generated | #65a7fa | 0.151872061 | 0.148861498 | 0.117923199 | 0.119868973 | 0.117923199 | deuteranopia | layer1, layer2, layer3 | +| 3 | dark | generated, book accent | #f08a3c | 0.175545892 | 0.129651436 | 0.129891295 | 0.128887839 | 0.128887839 | tritanopia | layer1, layer2, layer3 | +| 4 | light | best book subset | #ad4f0d | 0.102110528 | 0.061751368 | 0.041312806 | 0.039601898 | 0.039601898 | tritanopia | client, server, page, app | +| 4 | light | generated | #0061be | 0.156919975 | 0.139087794 | 0.114808904 | 0.113704161 | 0.113704161 | tritanopia | layer1, layer2, layer3, layer4 | +| 4 | light | generated, book accent | #ad4f0d | 0.182604389 | 0.126611553 | 0.140159746 | 0.124394269 | 0.124394269 | tritanopia | layer1, layer2, layer3, layer4 | +| 4 | dark | best book subset | #f08a3c | 0.085359615 | 0.042278013 | 0.049296862 | 0.055116411 | 0.042278013 | protanopia | runner, server, browser, protocol | +| 4 | dark | generated | #65a7fa | 0.145797891 | 0.137326337 | 0.130083194 | 0.103253862 | 0.103253862 | tritanopia | layer1, layer2, layer3, layer4 | +| 4 | dark | generated, book accent | #f08a3c | 0.152804770 | 0.115422484 | 0.118499477 | 0.118835923 | 0.115422484 | protanopia | layer1, layer2, layer3, layer4 | +| 5 | light | best book subset | #ad4f0d | 0.085679884 | 0.056436309 | 0.038866970 | 0.032104987 | 0.032104987 | tritanopia | runner, server, page, app, protocol | +| 5 | light | generated | #0061be | 0.129044142 | 0.110917375 | 0.097533816 | 0.092163855 | 0.092163855 | tritanopia | layer1, layer2, layer3, layer4, layer5 | +| 5 | light | generated, book accent | #ad4f0d | 0.154300884 | 0.098991492 | 0.128368329 | 0.103118954 | 0.098991492 | protanopia | layer1, layer2, layer3, layer4, layer5 | +| 5 | dark | best book subset | #f08a3c | 0.073996191 | 0.033547710 | 0.042343935 | 0.025724854 | 0.025724854 | tritanopia | runner, server, page, browser, fail | +| 5 | dark | generated | #65a7fa | 0.146900495 | 0.112168550 | 0.103491040 | 0.106169197 | 0.103491040 | deuteranopia | layer1, layer2, layer3, layer4, layer5 | +| 5 | dark | generated, book accent | #f08a3c | 0.102975091 | 0.088654585 | 0.087977833 | 0.101571389 | 0.087977833 | deuteranopia | layer1, layer2, layer3, layer4, layer5 | +| 6 | light | best book subset | #ad4f0d | 0.064345627 | 0.044593131 | 0.015610655 | 0.032104987 | 0.015610655 | deuteranopia | runner, server, page, app, protocol, fail | +| 6 | light | generated | #0061be | 0.154827853 | 0.106615761 | 0.102335472 | 0.097306530 | 0.097306530 | tritanopia | layer1, layer2, layer3, layer4, layer5, layer6 | +| 6 | light | generated, book accent | #ad4f0d | 0.130524311 | 0.085375224 | 0.070091223 | 0.080962165 | 0.070091223 | deuteranopia | layer1, layer2, layer3, layer4, layer5, layer6 | +| 6 | dark | best book subset | #f08a3c | 0.073996191 | 0.033547710 | 0.022466342 | 0.025724854 | 0.022466342 | deuteranopia | runner, server, page, browser, protocol, fail | +| 6 | dark | generated | #65a7fa | 0.138644124 | 0.087231180 | 0.091771443 | 0.090254202 | 0.087231180 | protanopia | layer1, layer2, layer3, layer4, layer5, layer6 | +| 6 | dark | generated, book accent | #f08a3c | 0.094142041 | 0.083894982 | 0.076821526 | 0.077290646 | 0.076821526 | deuteranopia | layer1, layer2, layer3, layer4, layer5, layer6 | + +## Four layers first + +All 10 examples and 18 of 23 book maps use at most four layers. At four layers, +the strongest book subset reaches 0.039601898 light and 0.042278013 dark. +Generated defaults reach 0.113704161 and 0.103253862; keeping the book accent +reaches 0.124394269 and 0.115422484. All exceed the 0.06 advice boundary under +every vision model. The original 4/6/8-layer prototype targets and fixed-layer +cases remain in [the palette measurements](palette.md). + +The [counted opaque findings](README.md#counted-findings) show layer–accent +hard confusion in 18 of 82 light cases (deuteranopia alone) and 8 of 82 dark +cases (tritanopia alone). Layer–layer hard confusion affects 41 of 123 light +and 21 of 123 dark cases; 39 and 19 respectively pass the normal-vision hard +band. Lane-text contrast fails in 0 of 67 book cases per theme. Counts describe +role pairs repeated across maps, not independent colours or people. + +The existing search already scores all four models and spreads lightness as +well as hue. These results require no further grid, hue-window or threshold +change. Catalogue expansion stops here by the author's decision; combined +paint states and route-dependent token contrast remain outside this report. diff --git a/docs/evidence/colour/palette.md b/docs/evidence/colour/palette.md new file mode 100644 index 00000000..fd347601 --- /dev/null +++ b/docs/evidence/colour/palette.md @@ -0,0 +1,85 @@ +# Generated palette distances + +Reproduce: `npm run build && node scripts/colour-palette.mjs`. +Check without writing: `node scripts/colour-palette.mjs --check`. +This measures the public `./color` palette API. Measure its combined generator, +checker and CSS serializer gzip with `npm run size` (the colour entry). + +Each distance is the minimum across all layer–layer and layer–accent pairs, +under normal vision and the three Machado simulations, after hex rounding. +Fixed colours are retained, including their spelling. Both themes keep all +text and line contrast requirements. These 28 cases have no hard defects; +seven and eight layers still receive the layer-count advice. + +| Layers | Theme | Fixed layer1 | Worst distance | Vision | Limiting pair | Hard defects | +| ------ | ----- | ------------ | -------------- | ------------ | ----------------------------- | ------------ | +| 2 | light | none | 0.212477678 | tritanopia | layers.layer2 / accent | 0 | +| 2 | light | #753646 | 0.194331536 | protanopia | layers.layer1 / layers.layer2 | 0 | +| 2 | dark | none | 0.144390788 | deuteranopia | layers.layer1 / accent | 0 | +| 2 | dark | #daa4b2 | 0.117615133 | protanopia | layers.layer1 / accent | 0 | +| 3 | light | none | 0.135025740 | deuteranopia | layers.layer1 / accent | 0 | +| 3 | light | #753646 | 0.144214762 | protanopia | layers.layer1 / layers.layer2 | 0 | +| 3 | dark | none | 0.117923199 | deuteranopia | layers.layer3 / accent | 0 | +| 3 | dark | #daa4b2 | 0.117615133 | protanopia | layers.layer1 / accent | 0 | +| 4 | light | none | 0.113704161 | tritanopia | layers.layer3 / accent | 0 | +| 4 | light | #753646 | 0.114423220 | tritanopia | layers.layer2 / layers.layer3 | 0 | +| 4 | dark | none | 0.103253862 | tritanopia | layers.layer3 / accent | 0 | +| 4 | dark | #daa4b2 | 0.109387236 | tritanopia | layers.layer2 / layers.layer3 | 0 | +| 5 | light | none | 0.092163855 | tritanopia | layers.layer5 / accent | 0 | +| 5 | light | #753646 | 0.094079596 | tritanopia | layers.layer2 / accent | 0 | +| 5 | dark | none | 0.103491040 | deuteranopia | layers.layer1 / accent | 0 | +| 5 | dark | #daa4b2 | 0.094597420 | deuteranopia | layers.layer4 / layers.layer5 | 0 | +| 6 | light | none | 0.097306530 | tritanopia | layers.layer6 / accent | 0 | +| 6 | light | #753646 | 0.087708292 | tritanopia | layers.layer5 / accent | 0 | +| 6 | dark | none | 0.087231180 | protanopia | layers.layer3 / layers.layer5 | 0 | +| 6 | dark | #daa4b2 | 0.075726567 | deuteranopia | layers.layer4 / layers.layer6 | 0 | +| 7 | light | none | 0.079455692 | deuteranopia | layers.layer2 / layers.layer7 | 0 | +| 7 | light | #753646 | 0.085920508 | protanopia | layers.layer2 / layers.layer5 | 0 | +| 7 | dark | none | 0.077058335 | tritanopia | layers.layer4 / layers.layer6 | 0 | +| 7 | dark | #daa4b2 | 0.068914507 | tritanopia | layers.layer5 / layers.layer6 | 0 | +| 8 | light | none | 0.066233277 | deuteranopia | layers.layer1 / layers.layer8 | 0 | +| 8 | light | #753646 | 0.064687044 | deuteranopia | layers.layer1 / layers.layer8 | 0 | +| 8 | dark | none | 0.069343370 | deuteranopia | layers.layer1 / layers.layer4 | 0 | +| 8 | dark | #daa4b2 | 0.067501296 | protanopia | layers.layer5 / layers.layer6 | 0 | + +## Fixed-accent fallback candidates + +The one-layer search also accepts an exact host accent, without gamut mapping +or changing its hex spelling. Its measured OKLCH hue sets the exclusion window; +`accentHue` controls only generated accents. The light case uses today's library +CSS accent; the dark case fixes the generated dark accent. These are candidates +for a later CSS change, not new CSS defaults. Both pass all hard checker rules. + +| Theme | Fixed accent | Generated fallback | Worst distance | Vision | Hard defects | +| ----- | ------------ | ------------------ | -------------- | ------------ | ------------ | +| light | #285bb5 | #511902 | 0.276083531 | deuteranopia | 0 | +| dark | #65a7fa | #d88015 | 0.278158602 | deuteranopia | 0 | + +## Decisions taken + +The opaque catalogue counts at most four used layers in 18 out of 23 book maps +and 10 out of 10 examples. Four-layer separation therefore has priority. +Layer–accent hard failures affect 18 out of 82 book light pairs under +deuteranopia alone and 8 out of 82 dark pairs under tritanopia alone. The +search scores all four vision models; hue spacing alone cannot protect them. + +The prescribed light grid reached only 0.097589603 for four layers in the +previous experiment, below the 0.102 target. Reducing accent chroma alone +reaches 0.097632280. Add L=0.30 to the light grid, retaining every original +candidate and the dark grid. This reaches all six prototype targets without +changing the hue exclusion, contrast rules or distance bands. Three coordinate +sweeps start with greedy selection; strict improvements keep tie handling +deterministic. Offsets rotate in four-degree steps along the allowed 280° arc. + +The prescribed light accent is outside sRGB (red channel -0.038038226). +For accents only, reduce chroma by 24 bisection steps at the requested hue +and lightness until in gamut, then round to hex. The default accents become +light #0061be and dark #65a7fa. Layer candidates outside gamut are rejected, +not mapped. Each score and contrast test uses the final hex channels. + +A fixed host colour can still conflict or have low contrast. The generator +preserves it; the checker remains responsible for reporting such defects. +These generated roles do not change CSS defaults, drawing, lane text or +painted-state findings. Catalogue expansion has stopped by the author's decision. +See [the book comparison](palette-comparison.md) for all four vision models +at 2–6 layers, with generated and exact book accents. diff --git a/eslint.config.mjs b/eslint.config.mjs index 12b42465..ef5939f0 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -18,10 +18,11 @@ export default [ "src/schema.ts", "src/schema/**/*.ts", "src/model/**/*.ts", + "src/color/**/*.ts", "src/render/**/*.ts", "src/layout/**/*.ts", ], - ignores: ["src/layout/errors.ts"], + ignores: ["src/layout/errors.ts", "src/color/errors.ts"], rules: { "no-restricted-syntax": [ "error", diff --git a/etc/color.api.md b/etc/color.api.md new file mode 100644 index 00000000..e3a49430 --- /dev/null +++ b/etc/color.api.md @@ -0,0 +1,127 @@ +## API Report File for "@metronforge/concept-map" + +> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). + +```ts + +// @public +export function checkColors(theme: Theme, options?: { + strict?: boolean; +}): ColorReport; + +// @public (undocumented) +export interface ColorDefect { + // (undocumented) + kind: "contrast" | "indistinct" | "ghostFloor" | "ghostOrder" | "tooManyLayers"; + // (undocumented) + path: string; + // (undocumented) + severity: "hard" | "advice"; + // (undocumented) + values: Record; +} + +// @public +export class ColorError extends Error { + constructor(message: string, path?: string | undefined, report?: ColorReport | undefined); + // (undocumented) + readonly path?: string | undefined; + // (undocumented) + readonly report?: ColorReport | undefined; +} + +// @public (undocumented) +export interface ColorReport { + // (undocumented) + defects: ColorDefect[]; + // (undocumented) + metrics: { + contrasts: ContrastMetric[]; + pairs: PairMetric[]; + }; +} + +// @public (undocumented) +export interface ContrastMetric { + // (undocumented) + background: string; + // (undocumented) + minimum: number; + // (undocumented) + path: string; + // (undocumented) + ratio: number; +} + +// @public (undocumented) +export interface PairMetric { + // (undocumented) + distance: number; + // (undocumented) + distances: Record; + // (undocumented) + other: string; + // (undocumented) + path: string; + // (undocumented) + vision: Vision; +} + +// @public (undocumented) +export interface Palette { + // (undocumented) + dark: Theme; + // (undocumented) + light: Theme; + // (undocumented) + toCss(selectors: { + light: string; + dark: string; + }): string; +} + +// @public +export function palette(ids: readonly string[], options?: PaletteOptions): Palette; + +// @public (undocumented) +export interface PaletteOptions { + accent?: { + light?: string; + dark?: string; + }; + // (undocumented) + accentHue?: number; + // (undocumented) + fixed?: { + light?: Record; + dark?: Record; + }; +} + +// @public +export interface Theme { + // (undocumented) + accent: string; + // (undocumented) + base: { + bg: string; + node: string; + fg: string; + mutedFg: string; + border: string; + }; + // (undocumented) + ghost?: { + text: string; + line: string; + }; + // (undocumented) + layers: Record; +} + +// @public (undocumented) +export type Vision = "normal" | "protanopia" | "deuteranopia" | "tritanopia"; + +// (No @packageDocumentation comment for this package) + +``` diff --git a/package.json b/package.json index b4d7a4b4..0a186d12 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,10 @@ "./element": { "types": "./dist/element.d.ts", "import": "./dist/element.js" + }, + "./color": { + "types": "./dist/color/index.d.ts", + "import": "./dist/color/index.js" } }, "peerDependencies": { diff --git a/scripts/api.mjs b/scripts/api.mjs index dab6f854..cdc32b04 100644 --- a/scripts/api.mjs +++ b/scripts/api.mjs @@ -8,6 +8,7 @@ for (const [name, entry] of Object.entries({ dagre: "layout/dagre", elk: "layout/elk", browser: "dom/measureLabel", + color: "color/index", })) { const config = ExtractorConfig.prepare({ configObject: { diff --git a/scripts/colour-findings.mjs b/scripts/colour-findings.mjs new file mode 100644 index 00000000..28409f30 --- /dev/null +++ b/scripts/colour-findings.mjs @@ -0,0 +1,271 @@ +import assert from "node:assert/strict"; +import { globSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; +import { format } from "prettier"; +import { checkColors } from "../dist/color/index.js"; +import { contrast } from "../dist/color/contrast.js"; +import { parseHex } from "../dist/color/hex.js"; + +const read = (path) => readFileSync(path, "utf8"); +const input = ".cache/colour/archive/docs/evidence/colour/catalogue/book-input"; +const book = JSON.parse(read(`${input}/themes.json`)); +const maps = globSync(`${input}/[0-9]*.json`) + .sort() + .map((path) => JSON.parse(read(path))); +const examples = globSync("examples/**/map.json", { + exclude: ["**/node_modules/**"], +}).sort(); +const declarations = (text) => + Object.fromEntries( + [...text.matchAll(/--cmap-([\w-]+)\s*:\s*(#[\da-f]+)\s*;/gi)].map( + ([, key, value]) => [key, value.toLowerCase()], + ), + ); +const css = read("css/concept-map.css"); +assert.ok( + css.includes("fill: color-mix(in srgb, var(--c) 6%, var(--cmap-bg))"), + "Revisit lane fill formula", +); +const defaults = declarations(css.split("}")[0]); +const localTheme = (properties, ids) => ({ + base: Object.fromEntries( + ["bg", "node", "fg", "mutedFg", "border"].map((key) => [ + key, + properties[key === "mutedFg" ? "muted-fg" : key], + ]), + ), + accent: properties.accent, + layers: Object.fromEntries( + ids.map((id) => [id, properties[`layer-${id}`] ?? properties.layer]), + ), +}); +const local = [{ theme: localTheme(defaults, ["fallback"]), lanes: {} }]; +for (const path of examples) { + const map = JSON.parse(read(path)); + const html = `${dirname(path)}/index.html`; + const overrides = globSync(html).length ? declarations(read(html)) : {}; + const contexts = [{ ...defaults, ...overrides }]; + if (!path.startsWith("examples/frameworks/")) contexts.push(defaults); + for (const properties of contexts) + local.push({ + theme: localTheme(properties, Object.keys(map.layers)), + lanes: map.lanes ?? {}, + }); +} +const table = (heads, rows) => + [heads, heads.map(() => "---"), ...rows] + .map((row) => `| ${row.join(" | ")} |`) + .join("\n"); +const count = (rows, predicate) => + `${rows.filter(predicate).length} out of ${rows.length}`; +const findings = []; +for (const mode of ["light", "dark"]) { + for (const [name, contexts] of [ + [ + "book", + maps.map((map) => ({ + theme: { + ...book[mode], + layers: Object.fromEntries( + map.declared.map((id) => [id, book[mode].layers[id]]), + ), + }, + lanes: map.lanes, + })), + ], + ["local (including defaults)", local], + ]) { + const reports = contexts.map(({ theme }) => checkColors(theme)); + const pairs = reports.flatMap((report) => report.metrics.pairs); + for (const [kind, selected] of [ + ["layer–accent", pairs.filter((pair) => pair.other === "accent")], + ["layer–layer", pairs.filter((pair) => pair.other !== "accent")], + ]) { + const add = (finding, predicate) => + findings.push([ + `${name} ${mode}`, + `${kind} ${finding}`, + count(selected, predicate), + ]); + add("hard", (pair) => pair.distance < 0.04); + add( + "advice only", + (pair) => pair.distance >= 0.04 && pair.distance < 0.06, + ); + add( + "hard only under simulation", + (pair) => pair.distances.normal >= 0.04 && pair.distance < 0.04, + ); + for (const vision of ["protanopia", "deuteranopia", "tritanopia"]) + add( + `hard under ${vision} alone`, + (pair) => + pair.distances[vision] < 0.04 && + Object.entries(pair.distances).every( + ([model, distance]) => model === vision || distance >= 0.04, + ), + ); + } + const lanes = contexts.flatMap(({ theme, lanes }) => + Object.values(lanes).map(({ layer }) => { + const color = parseHex(theme.layers[layer], `layers.${layer}`); + const bg = parseHex(theme.base.bg, "base.bg"); + return contrast( + color, + bg.map((channel, i) => 0.06 * color[i] + 0.94 * channel), + ); + }), + ); + findings.push([ + `${name} ${mode}`, + "lane text below 4.5:1", + count(lanes, (ratio) => ratio < 4.5), + ]); + const contrasts = reports.flatMap((report) => report.metrics.contrasts); + findings.push([ + `${name} ${mode}`, + "opaque role contrast below its minimum", + count(contrasts, (m) => m.ratio < m.minimum), + ]); + findings.push([ + `${name} ${mode}`, + "contexts with more than six declared layers", + count(contexts, ({ theme }) => Object.keys(theme.layers).length > 6), + ]); + } +} +const layers = []; +const used = (map) => [ + ...new Set( + ["nodes", "lanes", "concepts"].flatMap((key) => + Object.values(map[key] ?? {}) + .map((entry) => entry.layer) + .filter(Boolean), + ), + ), +]; +for (const [name, inventory] of [ + [ + "examples", + examples.map((path) => { + const map = JSON.parse(read(path)); + return { declared: Object.keys(map.layers), used: used(map) }; + }), + ], + ["book source", maps], +]) { + for (const field of ["declared", "used"]) { + const values = inventory.map((map) => map[field].length); + for (const n of [...new Set(values)].sort((a, b) => a - b)) + layers.push([ + name, + field, + `exactly ${n}`, + count(values, (value) => value === n), + ]); + layers.push([name, field, "at most four", count(values, (n) => n <= 4)]); + layers.push([name, field, "more than six", count(values, (n) => n > 6)]); + } +} +const defaultReport = checkColors(local[0].theme); +const defaultPair = defaultReport.metrics.pairs[0]; +assert.deepEqual( + defaultReport.defects.map(({ kind, severity }) => [kind, severity]), + [["indistinct", "hard"]], +); +const report = await format( + `# Colour findings and palette measurements + +The raw catalogue and its original research scripts are preserved on +\`archive/colour-catalogue-140\`, commit \`040827a\`. They are deliberately excluded +from this branch. The frozen book inputs record stylesheet and map hashes in +\`book-input/provenance.json\`; the site checkout was read only. These are source +colour measurements, not a deployed-site or browser-cascade audit. + +## Reproduce + +From the repository root, restore only the archived inputs to the ignored cache: + +\`\`\`sh +mkdir -p .cache/colour/archive +git archive 040827a docs/evidence/colour/catalogue/book-input | tar -x -C .cache/colour/archive +npm run build +node scripts/colour-findings.mjs --check +node scripts/colour-palette.mjs --check +node scripts/colour-palette-comparison.mjs --check +npm run size +\`\`\` + +Omit \`--check\` to update the corresponding summary, never the raw catalogue. +\`scripts/colour-findings.mjs\` reproduces every number in the two tables below +and the default defect. It reads the archived book inputs and current local +examples and CSS. To inspect historical raw rows, use \`git show +040827a:docs/evidence/colour/catalogue/patterns/opaque.md\` and +\`git show 040827a:docs/evidence/colour/catalogue/patterns/layers.md\`. +The archive also holds the painted-state reports and their reproduction scripts; +those broader research inventories are not required by these summaries. + +## Counted findings + +Counts are role-pair cases repeated across map, host and theme contexts, not +independent colours, readers or visible-object counts. Local includes defaults, +standalone examples and comparison hosts; light and dark reuse the same colours +because these hosts have no dark override. Book themes have separate colours. +Lane text is checked against its 6% layer / 94% background fill in encoded sRGB. + +${table(["Context", "Finding", "Affected cases"], findings)} + +Hard means worst OKLab distance below 0.04; advice only is 0.04 to below 0.06. +Simulation-only hard pairs pass the normal-vision hard band, but may fail under +several simulations. A failure under one simulation alone passes the hard band +under normal vision and both other simulations. No checker bands were changed. + +Book lane text contrast fails in 0 out of 67 cases per theme. The main problem +is colour confusion: book layer–accent failures occur under deuteranopia alone +in light and tritanopia alone in dark. Many layer–layer hard failures also pass +normal vision. Normal text contrast therefore cannot stand in for these checks. + +## Layer counts + +Each source map is counted once. Used means referenced by nodes, lanes or +concept groups. Book fixtures are not counted again alongside source maps. + +${table(["Inventory", "Layers", "Range", "Affected maps"], layers)} + +All examples and most book maps use at most four layers, making four-layer +separation the priority. The generator still measures the larger counts. + +## Known default defect + +The library fallback \`#526a8a\` and accent \`#285bb5\` have exactly one hard +checker defect, \`indistinct\`, and no others. The same defaults apply in both +modes. Their four distances, reproduced by \`scripts/colour-findings.mjs\`, are: + +${table(["Normal", "Protanopia", "Deuteranopia", "Tritanopia", "Worst model"], [[...Object.values(defaultPair.distances).map((n) => n.toFixed(9)), defaultPair.vision]])} + +A unit test pins this defect. Replacing the CSS defaults is separate work. + +## Generated results and scope + +[Palette measurements](palette.md), produced by \`scripts/colour-palette.mjs\`, +cover two through eight layers with and without one fixed layer, plus one-layer +fixed-accent fallback candidates. [Book comparison](palette-comparison.md), +produced by \`scripts/colour-palette-comparison.mjs\`, covers two through six +layers under all four vision models, with generated and exact book accents. +That script reads the same archived theme inputs. Gzip size comes from +\`npm run size\`; the colour entry has its own limit. + +APCA was removed for licence reasons; WCAG contrast is the only contrast +measure. Lane-label rendering, CSS defaults and SVG remain unchanged. Combined +painted states and route-dependent token contrast are outside this task. +`, + { parser: "markdown" }, +); +assert.ok(report.split("\n").length <= 500); +const path = "docs/evidence/colour/README.md"; +if (process.argv.includes("--check")) + assert.equal(read(path), report, `${path} is stale`); +else writeFileSync(path, report); +console.log( + `Colour findings: ${findings.length} counts, ${layers.length} layer distributions, one pinned default defect`, +); diff --git a/scripts/colour-palette-comparison.mjs b/scripts/colour-palette-comparison.mjs new file mode 100644 index 00000000..663cfac3 --- /dev/null +++ b/scripts/colour-palette-comparison.mjs @@ -0,0 +1,161 @@ +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync } from "node:fs"; +import { format } from "prettier"; +import { palette, checkColors } from "../dist/color/index.js"; + +const book = JSON.parse( + readFileSync( + ".cache/colour/archive/docs/evidence/colour/catalogue/book-input/themes.json", + "utf8", + ), +); +const visions = ["normal", "protanopia", "deuteranopia", "tritanopia"]; +const rows = []; +function subsets(entries, n) { + if (n === 0) return [[]]; + return entries.flatMap((entry, i) => + subsets(entries.slice(i + 1), n - 1).map((rest) => [entry, ...rest]), + ); +} +function measure(theme) { + const report = checkColors(theme); + const minima = visions.map((vision) => + Math.min(...report.metrics.pairs.map((pair) => pair.distances[vision])), + ); + return { + minima, + worst: Math.min(...minima), + hard: report.defects.filter((d) => d.severity === "hard").length, + }; +} +function row(n, mode, kind, theme, measured) { + rows.push([ + n, + mode, + kind, + theme.accent, + ...measured.minima.map((d) => d.toFixed(9)), + measured.worst.toFixed(9), + visions[measured.minima.indexOf(measured.worst)], + Object.keys(theme.layers).join(", "), + ]); +} +for (let n = 2; n <= 6; n++) { + const ids = Array.from({ length: n }, (_, i) => `layer${i + 1}`); + for (const mode of ["light", "dark"]) { + // Pick the strongest book subset, not a convenient failing map or prefix. + const candidates = subsets(Object.entries(book[mode].layers), n).map( + (entries) => { + const theme = { ...book[mode], layers: Object.fromEntries(entries) }; + return { theme, measured: measure(theme) }; + }, + ); + const best = candidates.reduce((a, b) => + a.measured.worst >= b.measured.worst ? a : b, + ); + row(n, mode, "best book subset", best.theme, best.measured); + for (const fixed of [false, true]) { + const theme = palette( + ids, + fixed ? { accent: { [mode]: book[mode].accent } } : {}, + )[mode]; + const measured = measure(theme); + assert.equal(measured.hard, 0, `${n} ${mode} fixed accent=${fixed}`); + assert.ok( + measured.worst > best.measured.worst, + `${n} ${mode} fixed accent=${fixed} must beat the best book subset`, + ); + if (fixed) assert.equal(theme.accent, book[mode].accent); + row( + n, + mode, + fixed ? "generated, book accent" : "generated", + theme, + measured, + ); + } + } +} +const table = [ + [ + "Layers", + "Theme", + "Palette", + "Accent", + "Normal", + "Protanopia", + "Deuteranopia", + "Tritanopia", + "Worst ΔE", + "Worst model", + "Layer ids", + ], + Array(11).fill("---"), + ...rows, +] + .map((r) => `| ${r.join(" | ")} |`) + .join("\n"); +const four = (kind, mode) => + rows.find((r) => r[0] === 4 && r[1] === mode && r[2] === kind)[8]; +const report = await format( + `# Generated palettes compared with book colours + +Reproduce: \`npm run build && node scripts/colour-palette-comparison.mjs\`. +Check without writing: \`node scripts/colour-palette-comparison.mjs --check\`. +Inputs: frozen book theme colours from \`archive/colour-catalogue-140\` at +\`040827a\`. Restore them using [the findings reproduction command](README.md#reproduce); +source hashes remain in the archived \`book-input/provenance.json\`. +The public \`./color\` API supplies generated palettes. No CSS changes. + +Each model column is the minimum distance over every layer–layer and +layer–accent pair under that model; the limiting pair can differ by column. +Worst ΔE is the minimum of all four columns. Values use final hex colours; +assertions use unrounded values. Larger distances mean greater separation. + +For each count, enumerate every subset of the nine book layer ids, retaining +its existing accent. Select the subset with the largest worst ΔE (ties keep +source order). This is a stronger reference than selecting a failing map: +no subset of the current book palette at that count has a better worst pair. +The ids in the table identify the selected subset. These are synthetic subsets, +not counts of maps that use those exact colours. Equal colours on distinct ids +remain eligible. Generated ids follow the same ordered list in each run. + +Generated rows either use the default blue accent or keep the book's exact +light/dark accent. Both generated variants beat the strongest book subset at +every count from two through six, and all 20 generated themes have no hard +checker defects. This compares separation, not painted states or lane-text +contrast; fixed accents are checked against the generator's default bases. + +${table} + +## Four layers first + +All 10 examples and 18 of 23 book maps use at most four layers. At four layers, +the strongest book subset reaches ${four("best book subset", "light")} light and ${four("best book subset", "dark")} dark. +Generated defaults reach ${four("generated", "light")} and ${four("generated", "dark")}; keeping the book accent +reaches ${four("generated, book accent", "light")} and ${four("generated, book accent", "dark")}. All exceed the 0.06 advice boundary under +every vision model. The original 4/6/8-layer prototype targets and fixed-layer +cases remain in [the palette measurements](palette.md). + +The [counted opaque findings](README.md#counted-findings) show layer–accent +hard confusion in 18 of 82 light cases (deuteranopia alone) and 8 of 82 dark +cases (tritanopia alone). Layer–layer hard confusion affects 41 of 123 light +and 21 of 123 dark cases; 39 and 19 respectively pass the normal-vision hard +band. Lane-text contrast fails in 0 of 67 book cases per theme. Counts describe +role pairs repeated across maps, not independent colours or people. + +The existing search already scores all four models and spreads lightness as +well as hue. These results require no further grid, hue-window or threshold +change. Catalogue expansion stops here by the author's decision; combined +paint states and route-dependent token contrast remain outside this report. +`, + { parser: "markdown" }, +); +const path = "docs/evidence/colour/palette-comparison.md"; +assert.ok(report.split("\n").length <= 500); +if (process.argv.includes("--check")) + assert.equal(readFileSync(path, "utf8"), report, `${path} is stale`); +else writeFileSync(path, report); +console.log( + "Palette comparison: 10 best book subsets, 20 generated themes; all beat the reference with no hard defects", +); diff --git a/scripts/colour-palette.mjs b/scripts/colour-palette.mjs new file mode 100644 index 00000000..3211d502 --- /dev/null +++ b/scripts/colour-palette.mjs @@ -0,0 +1,107 @@ +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync } from "node:fs"; +import { format } from "prettier"; +import { palette, checkColors } from "../dist/color/index.js"; + +const rows = []; +for (let n = 2; n <= 8; n++) { + const ids = Array.from({ length: n }, (_, i) => `layer${i + 1}`); + for (const mode of ["light", "dark"]) { + for (const fixed of [false, true]) { + const color = mode === "light" ? "#753646" : "#daa4b2"; + const theme = palette(ids, { + fixed: { [mode]: fixed ? { layer1: color } : {} }, + })[mode]; + const report = checkColors(theme); + const pair = report.metrics.pairs.reduce((a, b) => + a.distance <= b.distance ? a : b, + ); + const hard = report.defects.filter((d) => d.severity === "hard").length; + assert.equal(hard, 0, `${n} ${mode} fixed=${fixed} has hard defects`); + if (fixed) assert.equal(theme.layers.layer1, color); + rows.push( + `| ${n} | ${mode} | ${fixed ? color : "none"} | ${pair.distance.toFixed(9)} | ${pair.vision} | ${pair.path} / ${pair.other} | ${hard} |`, + ); + } + } +} +const fallbacks = []; +for (const mode of ["light", "dark"]) { + const accent = mode === "light" ? "#285bb5" : "#65a7fa"; + const theme = palette(["fallback"], { accent: { [mode]: accent } })[mode]; + const checked = checkColors(theme); + const pair = checked.metrics.pairs[0]; + assert.equal(theme.accent, accent); + assert.equal(checked.defects.filter((d) => d.severity === "hard").length, 0); + fallbacks.push( + `| ${mode} | ${accent} | ${theme.layers.fallback} | ${pair.distance.toFixed(9)} | ${pair.vision} | 0 |`, + ); +} +const report = await format( + `# Generated palette distances + +Reproduce: \`npm run build && node scripts/colour-palette.mjs\`. +Check without writing: \`node scripts/colour-palette.mjs --check\`. +This measures the public \`./color\` palette API. Measure its combined generator, +checker and CSS serializer gzip with \`npm run size\` (the colour entry). + +Each distance is the minimum across all layer–layer and layer–accent pairs, +under normal vision and the three Machado simulations, after hex rounding. +Fixed colours are retained, including their spelling. Both themes keep all +text and line contrast requirements. These 28 cases have no hard defects; +seven and eight layers still receive the layer-count advice. + +| Layers | Theme | Fixed layer1 | Worst distance | Vision | Limiting pair | Hard defects | +| --- | --- | --- | --- | --- | --- | --- | +${rows.join("\n")} + +## Fixed-accent fallback candidates + +The one-layer search also accepts an exact host accent, without gamut mapping +or changing its hex spelling. Its measured OKLCH hue sets the exclusion window; +\`accentHue\` controls only generated accents. The light case uses today's library +CSS accent; the dark case fixes the generated dark accent. These are candidates +for a later CSS change, not new CSS defaults. Both pass all hard checker rules. + +| Theme | Fixed accent | Generated fallback | Worst distance | Vision | Hard defects | +| --- | --- | --- | --- | --- | --- | +${fallbacks.join("\n")} + +## Decisions taken + +The opaque catalogue counts at most four used layers in 18 out of 23 book maps +and 10 out of 10 examples. Four-layer separation therefore has priority. +Layer–accent hard failures affect 18 out of 82 book light pairs under +deuteranopia alone and 8 out of 82 dark pairs under tritanopia alone. The +search scores all four vision models; hue spacing alone cannot protect them. + +The prescribed light grid reached only 0.097589603 for four layers in the +previous experiment, below the 0.102 target. Reducing accent chroma alone +reaches 0.097632280. Add L=0.30 to the light grid, retaining every original +candidate and the dark grid. This reaches all six prototype targets without +changing the hue exclusion, contrast rules or distance bands. Three coordinate +sweeps start with greedy selection; strict improvements keep tie handling +deterministic. Offsets rotate in four-degree steps along the allowed 280° arc. + +The prescribed light accent is outside sRGB (red channel -0.038038226). +For accents only, reduce chroma by 24 bisection steps at the requested hue +and lightness until in gamut, then round to hex. The default accents become +light #0061be and dark #65a7fa. Layer candidates outside gamut are rejected, +not mapped. Each score and contrast test uses the final hex channels. + +A fixed host colour can still conflict or have low contrast. The generator +preserves it; the checker remains responsible for reporting such defects. +These generated roles do not change CSS defaults, drawing, lane text or +painted-state findings. Catalogue expansion has stopped by the author's decision. +See [the book comparison](palette-comparison.md) for all four vision models +at 2–6 layers, with generated and exact book accents. +`, + { parser: "markdown" }, +); +const path = "docs/evidence/colour/palette.md"; +if (process.argv.includes("--check")) + assert.equal(readFileSync(path, "utf8"), report, `${path} is stale`); +else writeFileSync(path, report); +console.log( + `Palette: ${rows.length} theme/fixed cases and ${fallbacks.length} fixed-accent fallbacks, no hard defects`, +); diff --git a/scripts/guards.mjs b/scripts/guards.mjs index 5f4a334b..742d4e5c 100644 --- a/scripts/guards.mjs +++ b/scripts/guards.mjs @@ -19,6 +19,7 @@ assert.deepEqual(Object.keys(pkg.exports), [ "./layout/browser", "./dom", "./element", + "./color", ]); const ts = JSON.parse(readFileSync("tsconfig.json", "utf8")).compilerOptions; if (ts.sourceMap || ts.declarationMap) diff --git a/src/color/candidates.ts b/src/color/candidates.ts new file mode 100644 index 00000000..39a430db --- /dev/null +++ b/src/color/candidates.ts @@ -0,0 +1,78 @@ +import { contrast } from "./contrast.js"; +import { parseHex } from "./hex.js"; +import { deltaE, fromOklab, fromOklch, toOklab, type Triple } from "./space.js"; +import { simulate } from "./vision.js"; + +export interface Candidate { + hex: string; + views: Triple[]; +} + +export function candidate(hex: string): Candidate { + const rgb = parseHex(hex, "colour"); + return { + hex, + views: ( + ["normal", "protanopia", "deuteranopia", "tritanopia"] as const + ).map((vision) => toOklab(simulate(rgb, vision))), + }; +} + +export function separation(a: Candidate, b: Candidate): number { + return Math.min(...a.views.map((view, i) => deltaE(view, b.views[i]))); +} + +const inGamut = (rgb: Triple): boolean => rgb.every((c) => c >= 0 && c <= 1); + +/** Preserve lightness and hue when an accent needs less chroma to fit sRGB. */ +export function lchHex( + L: number, + C: number, + h: number, + map = false, +): string | undefined { + const rgbAt = (chroma: number) => fromOklab(fromOklch([L, chroma, h])); + let rgb = rgbAt(C); + if (!inGamut(rgb) && map) { + let low = 0; + let high = C; + for (let i = 0; i < 24; i++) { + const mid = (low + high) / 2; + if (inGamut(rgbAt(mid))) low = mid; + else high = mid; + } + rgb = rgbAt(low); + } + if (!inGamut(rgb)) return undefined; + return ( + "#" + + rgb + .map((c) => + Math.round(c * 255) + .toString(16) + .padStart(2, "0"), + ) + .join("") + ); +} + +/** Quantize before scoring: all constraints apply to the emitted colours. */ +export function candidates( + hue: number, + dark: boolean, + backgrounds: Triple[], +): Candidate[] { + const result: Candidate[] = []; + const levels = dark ? [0.62, 0.68, 0.74, 0.8] : [0.3, 0.42, 0.48, 0.54, 0.6]; + for (const L of levels) { + for (const C of [0.09, 0.12, 0.15]) { + const hex = lchHex(L, C, hue); + if ( + hex && + backgrounds.every((bg) => contrast(parseHex(hex, "colour"), bg) >= 3) + ) + result.push(candidate(hex)); + } + } + return result; +} diff --git a/src/color/check.ts b/src/color/check.ts new file mode 100644 index 00000000..0783a2aa --- /dev/null +++ b/src/color/check.ts @@ -0,0 +1,25 @@ +import { ColorError } from "./errors.js"; +import { parseTheme } from "./hex.js"; +import { checkRoles } from "./roles.js"; +import { checkPairs } from "./pairs.js"; +import { checkGhostOrder } from "./ghost.js"; +import type { ColorReport, Theme } from "./types.js"; + +/** Check opaque host roles without changing their colours. */ +export function checkColors( + theme: Theme, + options: { strict?: boolean } = {}, +): ColorReport { + const colors = parseTheme(theme); + const report: ColorReport = { + defects: [], + metrics: { contrasts: [], pairs: [] }, + }; + checkRoles(colors, report); + checkPairs(colors, report); + checkGhostOrder(colors, report); + if (options.strict && report.defects.some((d) => d.severity === "hard")) { + throw new ColorError("Theme has hard colour defects", undefined, report); + } + return report; +} diff --git a/src/color/contrast.ts b/src/color/contrast.ts new file mode 100644 index 00000000..7b820fbb --- /dev/null +++ b/src/color/contrast.ts @@ -0,0 +1,14 @@ +import { toLinear, type Triple } from "./space.js"; + +// https://www.w3.org/TR/WCAG22/#dfn-relative-luminance +function luminance(rgb: Triple): number { + const [r, g, b] = toLinear(rgb); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +/** WCAG 2.2 contrast ratio for opaque, encoded sRGB coordinates in [0, 1]. */ +export function contrast(a: Triple, b: Triple): number { + const x = luminance(a); + const y = luminance(b); + return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); +} diff --git a/src/color/errors.ts b/src/color/errors.ts new file mode 100644 index 00000000..01bdd38b --- /dev/null +++ b/src/color/errors.ts @@ -0,0 +1,13 @@ +import type { ColorReport } from "./types.js"; + +/** Invalid host input or a hard defect at the strict checker boundary. */ +export class ColorError extends Error { + constructor( + message: string, + public readonly path?: string, + public readonly report?: ColorReport, + ) { + super(message); + this.name = "ColorError"; + } +} diff --git a/src/color/generate.ts b/src/color/generate.ts new file mode 100644 index 00000000..a5b5304f --- /dev/null +++ b/src/color/generate.ts @@ -0,0 +1,74 @@ +import { candidate, lchHex } from "./candidates.js"; +import { ColorError } from "./errors.js"; +import { parseHex } from "./hex.js"; +import { search } from "./search.js"; +import { toOklab, toOklch } from "./space.js"; +import type { Theme } from "./types.js"; + +const bases: Record<"light" | "dark", Theme["base"]> = { + light: { + bg: "#ffffff", + node: "#ffffff", + fg: "#202124", + mutedFg: "#666666", + border: "#b4b8be", + }, + dark: { + bg: "#17191d", + node: "#1f2227", + fg: "#e6e7ea", + mutedFg: "#a4a8b0", + border: "#626975", + }, +}; + +interface ThemeOptions { + fixed?: Record; + accentHue?: number; + /** Exact host accent; its measured hue sets the layer exclusion window. */ + accent?: string; +} + +function accentColor(options: ThemeOptions, dark: boolean) { + const rawHue = options.accentHue ?? 255; + if (!Number.isFinite(rawHue)) + throw new ColorError("Expected a finite accentHue", "accentHue"); + if (options.accent !== undefined) { + const rgb = parseHex(options.accent, "accent"); + return { hex: options.accent, hue: toOklch(toOklab(rgb))[2] }; + } + const hue = ((rawHue % 360) + 360) % 360; + return { + hex: lchHex(dark ? 0.72 : 0.5, dark ? 0.14 : 0.17, hue, true)!, + hue, + }; +} + +/** Search one theme; the public palette combines light and dark. */ +export function generateTheme( + ids: readonly string[], + mode: "light" | "dark", + options: ThemeOptions = {}, +): Theme { + const dark = mode === "dark"; + const base = { ...bases[mode] }; + const { hex: accent, hue } = accentColor(options, dark); + const fixed = ids.map((id) => { + const hex = + options.fixed && Object.hasOwn(options.fixed, id) + ? options.fixed[id] + : undefined; + if (hex === undefined) return undefined; + parseHex(hex, `layers.${id}`); + return candidate(hex); + }); + const colors = search(fixed, candidate(accent), hue, dark, [ + parseHex(base.bg, "base.bg"), + parseHex(base.node, "base.node"), + ]); + return { + base, + accent, + layers: Object.fromEntries(ids.map((id, i) => [id, colors[i].hex])), + }; +} diff --git a/src/color/ghost.ts b/src/color/ghost.ts new file mode 100644 index 00000000..ad2d1835 --- /dev/null +++ b/src/color/ghost.ts @@ -0,0 +1,38 @@ +import { contrast } from "./contrast.js"; +import type { Colors } from "./hex.js"; +import type { ColorReport } from "./types.js"; + +export function checkGhostOrder(colors: Colors, report: ColorReport): void { + if (!colors.has("ghost.text")) return; + const lines = [ + "base.mutedFg", + ...[...colors.keys()].filter((key) => key.startsWith("layers.")), + ]; + for (const path of ["ghost.text", "ghost.line"]) { + const normals = path === "ghost.text" ? ["base.fg", "base.mutedFg"] : lines; + // Current nodes retain their normal text; current strokes use the accent. + const currentPath = path === "ghost.text" ? "base.fg" : "accent"; + for (const background of ["base.bg", "base.node"]) { + const bg = colors.get(background)!; + const ghost = contrast(colors.get(path)!, bg); + const current = contrast(colors.get(currentPath)!, bg); + for (const normalPath of normals) { + const normal = contrast(colors.get(normalPath)!, bg); + if (!(ghost < normal && normal <= current)) + report.defects.push({ + kind: "ghostOrder", + severity: "hard", + path, + values: { + background, + normalPath, + currentPath, + ghost, + normal, + current, + }, + }); + } + } + } +} diff --git a/src/color/hex.ts b/src/color/hex.ts new file mode 100644 index 00000000..d216a533 --- /dev/null +++ b/src/color/hex.ts @@ -0,0 +1,48 @@ +import { ColorError } from "./errors.js"; +import type { Triple } from "./space.js"; +import type { Theme } from "./types.js"; + +export function parseHex(value: unknown, path: string): Triple { + if ( + typeof value !== "string" || + !/^#(?:[\da-f]{3}|[\da-f]{6})$/i.test(value) || + (value.length !== 4 && value.length !== 7) + ) + throw new ColorError(`Expected #rgb or #rrggbb at ${path}`, path); + const hex = + value.length === 4 + ? [...value.slice(1)].map((c) => c + c).join("") + : value.slice(1); + return [0, 2, 4].map( + (i) => parseInt(hex.slice(i, i + 2), 16) / 255, + ) as unknown as Triple; +} + +export type Colors = Map; + +export function parseTheme(theme: Theme): Colors { + if (!theme || typeof theme !== "object" || Array.isArray(theme)) { + throw new ColorError("Expected a theme object at theme", "theme"); + } + const colors: Colors = new Map(); + for (const key of ["bg", "node", "fg", "mutedFg", "border"] as const) { + colors.set(`base.${key}`, parseHex(theme.base?.[key], `base.${key}`)); + } + colors.set("accent", parseHex(theme.accent, "accent")); + if ( + !theme.layers || + typeof theme.layers !== "object" || + Array.isArray(theme.layers) + ) { + throw new ColorError("Expected a colour record at layers", "layers"); + } + for (const [id, hex] of Object.entries(theme.layers)) { + colors.set(`layers.${id}`, parseHex(hex, `layers.${id}`)); + } + if (theme.ghost !== undefined) { + for (const key of ["text", "line"] as const) { + colors.set(`ghost.${key}`, parseHex(theme.ghost?.[key], `ghost.${key}`)); + } + } + return colors; +} diff --git a/src/color/index.ts b/src/color/index.ts new file mode 100644 index 00000000..4b996dcd --- /dev/null +++ b/src/color/index.ts @@ -0,0 +1,73 @@ +import { generateTheme } from "./generate.js"; +import { ColorError } from "./errors.js"; +import type { Theme } from "./types.js"; + +export { checkColors } from "./check.js"; +export { ColorError } from "./errors.js"; +export type { Vision } from "./vision.js"; +export type { + Theme, + ColorDefect, + ColorReport, + ContrastMetric, + PairMetric, +} from "./types.js"; + +export interface PaletteOptions { + fixed?: { light?: Record; dark?: Record }; + accentHue?: number; + /** Exact host accents; their measured hues set the exclusion windows. */ + accent?: { light?: string; dark?: string }; +} + +export interface Palette { + light: Theme; + dark: Theme; + toCss(selectors: { light: string; dark: string }): string; +} + +function css(theme: Theme, selector: string): string { + const props = { + bg: theme.base.bg, + node: theme.base.node, + fg: theme.base.fg, + "muted-fg": theme.base.mutedFg, + border: theme.base.border, + accent: theme.accent, + ...Object.fromEntries( + Object.entries(theme.layers).map(([id, hex]) => [`layer-${id}`, hex]), + ), + }; + return `${selector} {\n${Object.entries(props) + .map(([key, hex]) => ` --cmap-${key}: ${hex};`) + .join("\n")}\n}`; +} + +/** Generate independent light and dark themes without changing host colours. */ +export function palette( + ids: readonly string[], + options: PaletteOptions = {}, +): Palette { + if ( + new Set(ids).size !== ids.length || + ids.some((id) => !/^[A-Za-z][A-Za-z0-9_-]*$/.test(id)) + ) + throw new ColorError("Expected unique CSS-safe layer ids", "layers"); + const themes = Object.fromEntries( + (["light", "dark"] as const).map((mode) => [ + mode, + generateTheme(ids, mode, { + fixed: options.fixed?.[mode], + accentHue: options.accentHue, + accent: options.accent?.[mode], + }), + ]), + ) as { light: Theme; dark: Theme }; + return { + ...themes, + toCss: (selectors) => + css(themes.light, selectors.light) + + "\n" + + css(themes.dark, selectors.dark), + }; +} diff --git a/src/color/pairs.ts b/src/color/pairs.ts new file mode 100644 index 00000000..c94ba556 --- /dev/null +++ b/src/color/pairs.ts @@ -0,0 +1,44 @@ +import { deltaE, toOklab } from "./space.js"; +import { simulate, worstPair, type Vision } from "./vision.js"; +import type { Colors } from "./hex.js"; +import type { ColorReport } from "./types.js"; + +export function checkPairs(colors: Colors, report: ColorReport): void { + const layers = [...colors.keys()].filter((key) => key.startsWith("layers.")); + const paths = [...layers, "accent"]; + for (let i = 0; i < layers.length; i++) { + for (const other of paths.slice(i + 1)) { + const path = paths[i]; + const a = colors.get(path)!; + const b = colors.get(other)!; + const pair = worstPair(a, b); + const distances = {} as Record; + for (const vision of [ + "normal", + "protanopia", + "deuteranopia", + "tritanopia", + ] as const) { + distances[vision] = deltaE( + toOklab(simulate(a, vision)), + toOklab(simulate(b, vision)), + ); + } + report.metrics.pairs.push({ path, other, ...pair, distances }); + if (pair.distance < 0.06) + report.defects.push({ + kind: "indistinct", + severity: pair.distance < 0.04 ? "hard" : "advice", + path, + values: { other, ...pair }, + }); + } + } + if (layers.length > 6) + report.defects.push({ + kind: "tooManyLayers", + severity: "advice", + path: "layers", + values: { count: layers.length, maximum: 6 }, + }); +} diff --git a/src/color/roles.ts b/src/color/roles.ts new file mode 100644 index 00000000..addb660e --- /dev/null +++ b/src/color/roles.ts @@ -0,0 +1,35 @@ +import { contrast } from "./contrast.js"; +import type { Colors } from "./hex.js"; +import type { ColorReport } from "./types.js"; + +export function checkRoles(colors: Colors, report: ColorReport): void { + for (const [path, color] of colors) { + if (path === "base.bg" || path === "base.node") continue; + const ghost = path.startsWith("ghost."); + const minimum = minimumContrast(path); + for (const background of ["base.bg", "base.node"]) { + const ratio = contrast(color, colors.get(background)!); + report.metrics.contrasts.push({ + path, + background, + ratio, + minimum, + }); + if (ratio < minimum) + report.defects.push({ + kind: ghost ? "ghostFloor" : "contrast", + severity: "hard", + path, + values: { background, ratio, minimum }, + }); + } + } +} + +function minimumContrast(path: string): number { + if (path === "ghost.text") return 2; + if (path === "ghost.line") return 1.3; + // The base border frames controls and the map; it carries no layer meaning. + if (path === "base.border") return 1; + return path === "base.fg" || path === "base.mutedFg" ? 4.5 : 3; +} diff --git a/src/color/search.ts b/src/color/search.ts new file mode 100644 index 00000000..2792697d --- /dev/null +++ b/src/color/search.ts @@ -0,0 +1,78 @@ +import { candidates, separation, type Candidate } from "./candidates.js"; +import { ColorError } from "./errors.js"; +import type { Triple } from "./space.js"; + +function nearest(color: Candidate, others: Candidate[]): number { + return Math.min(...others.map((other) => separation(color, other))); +} + +function score(colors: Candidate[], accent: Candidate): number { + return Math.min( + ...colors.map((color, i) => + nearest(color, [accent, ...colors.slice(i + 1)]), + ), + ); +} + +function ascend(pools: Candidate[][], accent: Candidate): Candidate[] { + const selected: Candidate[] = []; + for (const pool of pools) { + let best = pool[0]; + for (const color of pool) + if ( + nearest(color, [accent, ...selected]) > + nearest(best, [accent, ...selected]) + ) + best = color; + selected.push(best); + } + for (let sweep = 0; sweep < 3; sweep++) { + for (let i = 0; i < pools.length; i++) { + const others = [accent, ...selected.filter((_, j) => j !== i)]; + let distance = nearest(selected[i], others); + for (const color of pools[i]) { + const next = nearest(color, others); + if (next > distance) { + selected[i] = color; + distance = next; + } + } + } + } + return selected; +} + +/** Rotate in four-degree steps within the allowed 280-degree arc. */ +export function search( + fixed: (Candidate | undefined)[], + accent: Candidate, + hue: number, + dark: boolean, + backgrounds: Triple[], +): Candidate[] { + let best: Candidate[] = []; + let bestScore = -Infinity; + for (let offset = 0; offset < 280; offset += 4) { + const pools = fixed.map((color, i) => + color + ? [color] + : candidates( + hue + 40 + (((i * 280) / fixed.length + offset) % 280), + dark, + backgrounds, + ), + ); + if (pools.some((pool) => pool.length === 0)) continue; + const selected = ascend(pools, accent); + const distance = score(selected, accent); + if (distance > bestScore) { + best = selected; + bestScore = distance; + } + } + if (best.length !== fixed.length) + throw new ColorError( + "No in-gamut palette candidates for the requested hue", + ); + return best; +} diff --git a/src/color/space.ts b/src/color/space.ts new file mode 100644 index 00000000..4f69808a --- /dev/null +++ b/src/color/space.ts @@ -0,0 +1,72 @@ +/** Internal colour coordinates: encoded sRGB, linear RGB, OKLab or OKLCH. */ +export type Triple = readonly [number, number, number]; + +// sRGB transfer function, WCAG 2.2 relative luminance definition. +export function toLinear(rgb: Triple): Triple { + return rgb.map((c) => + c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4, + ) as unknown as Triple; +} + +export function fromLinear(rgb: Triple): Triple { + return rgb.map((c) => + c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055, + ) as unknown as Triple; +} + +// Ottosson's updated linear-sRGB matrices (2021-01-25). +// https://bottosson.github.io/posts/oklab/ +export function toOklab(rgb: Triple): Triple { + const [r, g, b] = toLinear(rgb); + const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + return [ + 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, + 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, + 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s, + ]; +} + +/** Unclamped: the generator must be able to reject out-of-gamut colours. */ +export function fromOklab([L, a, b]: Triple): Triple { + // Inverses of the forward matrices, retaining precision for round trips. + const l = + (0.9999999984505201 * L + + 0.3963377921737678 * a + + 0.21580375806075877 * b) ** + 3; + const m = + (1.0000000088817607 * L - + 0.10556134232365634 * a - + 0.0638541747717059 * b) ** + 3; + const s = + (1.0000000546724108 * L - + 0.08948418209496575 * a - + 1.2914855378640917 * b) ** + 3; + return fromLinear([ + 4.076741661347994 * l - 3.3077115904081937 * m + 0.23096992872942781 * s, + -1.2684380040921763 * l + 2.609757400663372 * m - 0.34131939631021957 * s, + -0.004196086541837074 * l - 0.7034186144594495 * m + 1.7076147009309446 * s, + ]); +} + +export function toOklch([L, a, b]: Triple): Triple { + return [ + L, + Math.hypot(a, b), + ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360, + ]; +} + +export function fromOklch([L, C, h]: Triple): Triple { + const radians = (h * Math.PI) / 180; + return [L, C * Math.cos(radians), C * Math.sin(radians)]; +} + +/** Euclidean OKLab distance, unscaled (black to white is 1). */ +export function deltaE(a: Triple, b: Triple): number { + return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]); +} diff --git a/src/color/types.ts b/src/color/types.ts new file mode 100644 index 00000000..ce9270b6 --- /dev/null +++ b/src/color/types.ts @@ -0,0 +1,43 @@ +import type { Vision } from "./vision.js"; + +/** Opaque host colours; the boundary accepts #rgb and #rrggbb only. */ +export interface Theme { + base: { + bg: string; + node: string; + fg: string; + mutedFg: string; + border: string; + }; + accent: string; + layers: Record; + ghost?: { text: string; line: string }; +} + +export interface ColorDefect { + kind: + "contrast" | "indistinct" | "ghostFloor" | "ghostOrder" | "tooManyLayers"; + severity: "hard" | "advice"; + path: string; + values: Record; +} + +export interface ContrastMetric { + path: string; + background: string; + ratio: number; + minimum: number; +} + +export interface PairMetric { + path: string; + other: string; + distance: number; + vision: Vision; + distances: Record; +} + +export interface ColorReport { + defects: ColorDefect[]; + metrics: { contrasts: ContrastMetric[]; pairs: PairMetric[] }; +} diff --git a/src/color/vision.ts b/src/color/vision.ts new file mode 100644 index 00000000..7a951d74 --- /dev/null +++ b/src/color/vision.ts @@ -0,0 +1,53 @@ +import { deltaE, fromLinear, toLinear, toOklab, type Triple } from "./space.js"; + +export type Vision = "normal" | "protanopia" | "deuteranopia" | "tritanopia"; + +// Machado et al. (2009), severity 1.0, applied to linear sRGB. +const matrices: Record, readonly Triple[]> = { + protanopia: [ + [0.152286, 1.052583, -0.204868], + [0.114503, 0.786281, 0.099216], + [-0.003882, -0.048116, 1.051998], + ], + deuteranopia: [ + [0.367322, 0.860646, -0.227968], + [0.280085, 0.672501, 0.047413], + [-0.01182, 0.04294, 0.968881], + ], + tritanopia: [ + [1.255528, -0.076749, -0.178779], + [-0.078411, 0.930809, 0.147602], + [0.004733, 0.691367, 0.3039], + ], +}; + +export function simulate(rgb: Triple, vision: Vision): Triple { + if (vision === "normal") return rgb; + const [r, g, b] = toLinear(rgb); + const result = matrices[vision].map(([x, y, z]) => + Math.max(0, Math.min(1, x * r + y * g + z * b)), + ); + return fromLinear(result as unknown as Triple); +} + +/** Ties keep normal vision, then the first simulation in the declared order. */ +export function worstPair( + a: Triple, + b: Triple, +): { distance: number; vision: Vision } { + const visions: Vision[] = [ + "normal", + "protanopia", + "deuteranopia", + "tritanopia", + ]; + let result = { distance: Infinity, vision: "normal" as Vision }; + for (const vision of visions) { + const distance = deltaE( + toOklab(simulate(a, vision)), + toOklab(simulate(b, vision)), + ); + if (distance < result.distance) result = { distance, vision }; + } + return result; +} diff --git a/test/unit/color-check.test.ts b/test/unit/color-check.test.ts new file mode 100644 index 00000000..1eea46b6 --- /dev/null +++ b/test/unit/color-check.test.ts @@ -0,0 +1,218 @@ +import { expect, test } from "vitest"; +import fc from "fast-check"; +import { checkColors } from "../../src/color/check.js"; +import { ColorError } from "../../src/color/errors.js"; +import type { Theme } from "../../src/color/types.js"; + +const defaults: Theme = { + base: { + bg: "#ffffff", + node: "#ffffff", + fg: "#202124", + mutedFg: "#666666", + border: "#b4b8be", + }, + accent: "#285bb5", + layers: { fallback: "#526a8a" }, +}; +const clean = (): Theme => ({ ...defaults, layers: {} }); + +test("today's defaults have exactly the approved layer/accent hard defect", () => { + const report = checkColors(defaults); + expect(report.defects).toHaveLength(1); + expect(report.defects[0]).toMatchObject({ + kind: "indistinct", + severity: "hard", + path: "layers.fallback", + values: { other: "accent", vision: "tritanopia" }, + }); + expect(report.defects[0].values.distance).toBeCloseTo( + 0.036455690156507334, + 12, + ); + expect(report.metrics.pairs[0].distances.normal).toBeGreaterThan(0.04); + expect(Object.keys(report.metrics.pairs[0].distances)).toHaveLength(4); +}); + +test("text and meaningful lines are checked against both backgrounds", () => { + const theme = clean(); + theme.base = { ...theme.base, node: "#777777" }; + const report = checkColors(theme); + expect(report.defects).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + kind: "contrast", + path: "base.mutedFg", + values: expect.objectContaining({ + background: "base.node", + minimum: 4.5, + }), + }), + expect.objectContaining({ + kind: "contrast", + path: "accent", + values: expect.objectContaining({ + background: "base.node", + minimum: 3, + }), + }), + ]), + ); + expect(checkColors(clean()).defects).toEqual([]); + expect( + report.metrics.contrasts.find( + (m) => m.path === "base.fg" && m.background === "base.bg", + )?.ratio, + ).toBeCloseTo(16.09895, 4); +}); + +test("layers require line contrast, not text contrast", () => { + const report = checkColors({ + ...clean(), + accent: "#000", + layers: { a: "#888" }, + }); + expect(report.defects).toEqual([]); + expect( + report.metrics.contrasts.find((m) => m.path === "layers.a")?.ratio, + ).toBeCloseTo(3.544886, 5); +}); + +test("equal layer colours always give a hard indistinct defect", () => { + fc.assert( + fc.property(fc.integer({ min: 0, max: 0xffffff }), (value) => { + const hex = `#${value.toString(16).padStart(6, "0")}`; + const report = checkColors({ ...clean(), layers: { a: hex, b: hex } }); + expect(report.defects).toContainEqual({ + kind: "indistinct", + severity: "hard", + path: "layers.a", + values: { other: "layers.b", distance: 0, vision: "normal" }, + }); + }), + ); +}); + +test("distance bands separate advice from hard defects", () => { + const report = checkColors({ + ...clean(), + accent: "#000", + layers: { a: "#555", b: "#646464" }, + }); + expect(report.defects.filter((d) => d.kind === "indistinct")).toEqual([ + expect.objectContaining({ + severity: "advice", + values: expect.objectContaining({ other: "layers.b" }), + }), + ]); +}); + +test("more than six layers is advice even with no strict mode", () => { + expect( + checkColors({ + ...clean(), + layers: Object.fromEntries( + Array.from({ length: 7 }, (_, i) => [`l${i}`, "#555"]), + ), + }).defects, + ).toContainEqual({ + kind: "tooManyLayers", + severity: "advice", + path: "layers", + values: { count: 7, maximum: 6 }, + }); +}); + +test.each(["red", "#abcd", "#12345678", "#12", "#ggg", " #fff", "#fff\n"])( + "rejects non-opaque-hex %j with its path", + (hex) => { + expect(() => checkColors({ ...clean(), layers: { broken: hex } })).toThrow( + ColorError, + ); + expect(() => checkColors({ ...clean(), layers: { broken: hex } })).toThrow( + /layers.broken/, + ); + }, +); + +test("validates every role including decorative borders and optional ghosts", () => { + expect(() => + checkColors({ + ...clean(), + base: { ...defaults.base, border: "transparent" }, + }), + ).toThrow(/base.border/); + expect(() => + checkColors({ ...clean(), ghost: { text: "#999", line: "rgb(0,0,0)" } }), + ).toThrow(/ghost.line/); + expect( + checkColors({ ...clean(), accent: "#ABC" }).metrics.contrasts[0], + ).toBeDefined(); +}); + +test("strict throws hard defects and preserves the complete report", () => { + try { + checkColors(defaults, { strict: true }); + expect.fail("expected a hard colour defect"); + } catch (error) { + expect(error).toBeInstanceOf(ColorError); + expect((error as ColorError).report).toEqual(checkColors(defaults)); + } + expect(() => + checkColors( + { ...clean(), accent: "#000", layers: { a: "#555", b: "#646464" } }, + { strict: true }, + ), + ).not.toThrow(); +}); + +test("ghost floors exempt inactive marks from normal contrast minima", () => { + const report = checkColors({ + ...clean(), + accent: "#000", + ghost: { text: "#aaa", line: "#ddd" }, + }); + expect(report.defects).toEqual([]); + const low = checkColors({ + ...clean(), + ghost: { text: "#eee", line: "#fff" }, + }); + expect(low.defects.filter((d) => d.kind === "ghostFloor")).toHaveLength(4); +}); + +test("ghost order checks text, each normal line, and the current accent", () => { + const equal = checkColors({ + ...clean(), + ghost: { text: "#202124", line: "#666" }, + }); + expect(equal.defects.filter((d) => d.kind === "ghostOrder")).toHaveLength(6); + const reversed = checkColors({ + ...clean(), + accent: "#888", + layers: { a: "#000" }, + ghost: { text: "#aaa", line: "#ddd" }, + }); + expect(reversed.defects).toContainEqual( + expect.objectContaining({ + kind: "ghostOrder", + path: "ghost.line", + values: expect.objectContaining({ + normalPath: "layers.a", + current: expect.any(Number), + }), + }), + ); +}); + +test("checking does not change host colours", () => { + const before = structuredClone(defaults); + checkColors(defaults); + expect(defaults).toEqual(before); +}); + +test.each([null, undefined, [], "#fff", 42])( + "malformed theme root %j stays inside the ColorError boundary", + (value) => { + expect(() => checkColors(value as unknown as Theme)).toThrow(ColorError); + }, +); diff --git a/test/unit/color-fixed-accent.test.ts b/test/unit/color-fixed-accent.test.ts new file mode 100644 index 00000000..f974f5a0 --- /dev/null +++ b/test/unit/color-fixed-accent.test.ts @@ -0,0 +1,48 @@ +import { expect, test } from "vitest"; +import { generateTheme } from "../../src/color/generate.js"; +import { checkColors } from "../../src/color/check.js"; +import { ColorError } from "../../src/color/errors.js"; + +// Ignoring a host accent would make a proposed fallback fail against its real CSS. +test.each(["light", "dark"] as const)( + "%s fallback keeps the host accent and passes all hard checks", + (mode) => { + const accent = mode === "light" ? "#285bb5" : "#65a7fa"; + const theme = generateTheme(["fallback"], mode, { accent }); + expect(theme.accent).toBe(accent); + expect( + checkColors(theme).defects.filter((d) => d.severity === "hard"), + ).toEqual([]); + expect(checkColors(theme).metrics.pairs[0].distance).toBeGreaterThanOrEqual( + 0.06, + ); + }, +); + +test("fixed accent keeps short uppercase hex spelling", () => { + expect(generateTheme(["a"], "light", { accent: "#36C" }).accent).toBe("#36C"); +}); + +test("invalid fixed accent names its path in ColorError", () => { + try { + generateTheme(["a"], "light", { accent: "red" }); + expect.fail("invalid accent must throw"); + } catch (error) { + expect(error).toBeInstanceOf(ColorError); + expect((error as ColorError).path).toBe("accent"); + } +}); + +test("a fixed accent conflict remains visible to the checker", () => { + const theme = generateTheme(["a"], "light", { + accent: "#285bb5", + fixed: { a: "#285bb5" }, + }); + expect(checkColors(theme).defects).toContainEqual( + expect.objectContaining({ + kind: "indistinct", + severity: "hard", + values: expect.objectContaining({ distance: 0 }), + }), + ); +}); diff --git a/test/unit/color-math.test.ts b/test/unit/color-math.test.ts new file mode 100644 index 00000000..261bd3ba --- /dev/null +++ b/test/unit/color-math.test.ts @@ -0,0 +1,190 @@ +import { expect, test } from "vitest"; +import fc from "fast-check"; +import { + toLinear, + fromLinear, + toOklab, + fromOklab, + toOklch, + fromOklch, + deltaE, + type Triple, +} from "../../src/color/space.js"; +import { contrast } from "../../src/color/contrast.js"; +import { simulate, worstPair } from "../../src/color/vision.js"; + +function close(actual: Triple, expected: Triple, digits = 6) { + actual.forEach((value, i) => expect(value).toBeCloseTo(expected[i], digits)); +} +const channel = fc.double({ min: 0, max: 1, noNaN: true }); +const rgb = fc.tuple(channel, channel, channel); + +// Björn Ottosson's updated linear-sRGB matrices (2021-01-25): +// https://bottosson.github.io/posts/oklab/ +test.each<[Triple, Triple]>([ + [ + [0, 0, 0], + [0, 0, 0], + ], + [ + [1, 1, 1], + [1, 0, 0], + ], + [ + [1, 0, 0], + [0.62795536, 0.22486306, 0.1258463], + ], + [ + [0, 1, 0], + [0.86643961, -0.23388757, 0.17949848], + ], + [ + [0, 0, 1], + [0.45201372, -0.03245698, -0.31152815], + ], +])("OKLab reference for %j", (input, expected) => { + close(toOklab(input), expected); + close(fromOklab(expected), input); +}); + +test("polar coordinates use degrees and normalized hue", () => { + close(toOklch([0.5, 0, -0.2]), [0.5, 0.2, 270]); + close(fromOklch([0.5, 0.2, 90]), [0.5, 0, 0.2]); + close(toOklch([0.5, 0, 0]), [0.5, 0, 0]); +}); + +test("sRGB transfer function covers both sides of its breakpoints", () => { + close(toLinear([0, 0.04045, 1]), [0, 0.04045 / 12.92, 1], 10); + close(fromLinear([0, 0.0031308, 1]), [0, 0.0031308 * 12.92, 1], 10); +}); + +test("RGB and polar round trips stay within 1e-6", () => { + fc.assert( + fc.property(rgb, (input) => { + const lab = toOklab(input); + close(fromOklab(fromOklch(toOklch(lab))), input); + close(fromLinear(toLinear(input)), input, 10); + }), + { numRuns: 1000, seed: 140 }, + ); +}); + +test("inverse conversion preserves out-of-gamut values for the generator", () => { + expect(fromOklab(fromOklch([0.6, 0.4, 30])).some((c) => c < 0 || c > 1)).toBe( + true, + ); +}); + +test("WCAG contrast reference values", () => { + expect(contrast([0, 0, 0], [1, 1, 1])).toBe(21); + expect(contrast([119 / 255, 119 / 255, 119 / 255], [1, 1, 1])).toBeCloseTo( + 4.47808945, + 7, + ); +}); + +test("contrast is symmetric and bounded", () => { + fc.assert( + fc.property(rgb, rgb, (a, b) => { + const value = contrast(a, b); + expect(value).toBe(contrast(b, a)); + expect(value).toBeGreaterThanOrEqual(1); + expect(value).toBeLessThanOrEqual(21); + expect(contrast(a, a)).toBe(1); + }), + { numRuns: 1000, seed: 141 }, + ); +}); + +test("OKLab distance is unscaled Euclidean distance", () => { + expect(deltaE([0, 0, 0], [1, 0, 0])).toBe(1); + expect(deltaE([0.2, 0.1, -0.1], [0.5, 0.5, -0.1])).toBeCloseTo(0.5, 12); + fc.assert( + fc.property(rgb, rgb, (a, b) => { + expect(deltaE(a, b)).toBe(deltaE(b, a)); + expect(deltaE(a, a)).toBe(0); + }), + ); +}); + +// Machado severity 1.0 matrices, applied to linear RGB before clamping. +test.each([ + [ + "protanopia", + [ + [0.152286, 0.114503, 0], + [1, 0.786281, 0], + [0, 0.099216, 1], + ], + ], + [ + "deuteranopia", + [ + [0.367322, 0.280085, 0], + [0.860646, 0.672501, 0.04294], + [0, 0.047413, 0.968881], + ], + ], + [ + "tritanopia", + [ + [1, 0, 0.004733], + [0, 0.930809, 0.691367], + [0, 0.147602, 0.3039], + ], + ], +] as const)( + "%s linear primary references and neutral grey", + (vision, expected) => { + const primaries: Triple[] = [ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1], + ]; + primaries.forEach((primary, i) => + close(toLinear(simulate(primary, vision)), expected[i], 10), + ); + close(simulate([0.5, 0.5, 0.5], vision), [0.5, 0.5, 0.5]); + close(simulate([0, 0, 0], vision), [0, 0, 0]); + close(simulate([1, 1, 1], vision), [1, 1, 1]); + }, +); + +test("simulation decodes sRGB before applying the matrix", () => { + close( + toLinear(simulate([0.5, 0, 0], "protanopia")), + [0.03259546911947727, 0.024508352708637073, 0], + 8, + ); +}); + +test("worst pair returns the minimum and names the vision model", () => { + fc.assert( + fc.property(rgb, rgb, (a, b) => { + const result = worstPair(a, b); + const distances = [ + "normal", + "protanopia", + "deuteranopia", + "tritanopia", + ].map((model) => { + const vision = model as Parameters[1]; + return deltaE( + toOklab(simulate(a, vision)), + toOklab(simulate(b, vision)), + ); + }); + expect(result.distance).toBe(Math.min(...distances)); + expect(result.distance).toBe(worstPair(b, a).distance); + expect(result.distance).toBe( + distances[ + ["normal", "protanopia", "deuteranopia", "tritanopia"].indexOf( + result.vision, + ) + ], + ); + expect(worstPair(a, a)).toEqual({ distance: 0, vision: "normal" }); + }), + ); + expect(worstPair([1, 0, 0], [0, 1, 0]).vision).toBe("deuteranopia"); +}); diff --git a/test/unit/color-palette.test.ts b/test/unit/color-palette.test.ts new file mode 100644 index 00000000..c5cb9f09 --- /dev/null +++ b/test/unit/color-palette.test.ts @@ -0,0 +1,95 @@ +import { expect, test } from "vitest"; +import fc from "fast-check"; +import { generateTheme } from "../../src/color/generate.js"; +import { checkColors } from "../../src/color/check.js"; +import { ColorError } from "../../src/color/errors.js"; + +const ids = (n: number) => Array.from({ length: n }, (_, i) => `layer${i + 1}`); +const worst = (theme: ReturnType) => + Math.min(...checkColors(theme).metrics.pairs.map((p) => p.distance)); + +// Removing simulations from the objective or using one lightness loses these targets. +test.each([ + [4, 0.102, 0.102], + [6, 0.063, 0.075], + [8, 0.055, 0.056], +])("%i default layers reach both prototype targets", (n, light, dark) => { + expect(worst(generateTheme(ids(n), "light"))).toBeGreaterThanOrEqual(light); + expect(worst(generateTheme(ids(n), "dark"))).toBeGreaterThanOrEqual(dark); +}); + +test("generated defaults have no hard defects for one to eight layers", () => { + for (let n = 1; n <= 8; n++) { + for (const mode of ["light", "dark"] as const) { + const theme = generateTheme(ids(n), mode); + expect(Object.keys(theme.layers)).toEqual(ids(n)); + expect( + checkColors(theme).defects.filter((d) => d.severity === "hard"), + ).toEqual([]); + for (const hex of [theme.accent, ...Object.values(theme.layers)]) + expect(hex).toMatch(/^#[0-9a-f]{6}$/); + } + } +}); + +test("search is deterministic and preserves fixed hex spelling", () => { + fc.assert( + fc.property(fc.integer({ min: 1, max: 8 }), (n) => { + for (const mode of ["light", "dark"] as const) { + const fixed = { layer1: mode === "light" ? "#753646" : "#DAA4B2" }; + const a = generateTheme(ids(n), mode, { fixed }); + expect(a).toEqual(generateTheme(ids(n), mode, { fixed })); + expect(a.layers.layer1).toBe(fixed.layer1); + expect( + checkColors(a).defects.filter((d) => d.severity === "hard"), + ).toEqual([]); + const defaults = generateTheme(ids(n), mode); + expect(defaults).toEqual(generateTheme(ids(n), mode)); + expect( + checkColors(defaults).defects.filter((d) => d.severity === "hard"), + ).toEqual([]); + } + }), + { numRuns: 8 }, + ); +}); + +test("fixed conflicts remain visible to the checker", () => { + const theme = generateTheme(["a", "b"], "light", { + fixed: { a: "#753646", b: "#753646" }, + }); + expect(theme.layers).toEqual({ a: "#753646", b: "#753646" }); + expect(checkColors(theme).defects).toContainEqual( + expect.objectContaining({ + kind: "indistinct", + severity: "hard", + path: "layers.a", + }), + ); +}); + +test("invalid fixed colours and nonfinite hues use ColorError", () => { + expect(() => generateTheme(["a"], "light", { fixed: { a: "red" } })).toThrow( + ColorError, + ); + expect(() => generateTheme(["a"], "light", { accentHue: NaN })).toThrow( + ColorError, + ); +}); + +test("accent hue wraps by whole turns and empty layers retain checked bases", () => { + for (const mode of ["light", "dark"] as const) { + const theme = generateTheme([], mode); + expect(theme.layers).toEqual({}); + expect(checkColors(theme).defects).toEqual([]); + expect(generateTheme(["a"], mode, { accentHue: -105 })).toEqual( + generateTheme(["a"], mode, { accentHue: 615 }), + ); + } +}); + +test("layer ids do not read inherited fixed colours", () => { + expect(generateTheme(["constructor"], "light", { fixed: {} })).toEqual( + generateTheme(["constructor"], "light"), + ); +}); diff --git a/test/unit/color-public.test.ts b/test/unit/color-public.test.ts new file mode 100644 index 00000000..0f0a62ec --- /dev/null +++ b/test/unit/color-public.test.ts @@ -0,0 +1,50 @@ +import { expect, test } from "vitest"; +import { palette, checkColors, ColorError } from "../../src/color/index.js"; + +test("palette keeps each theme's fixed colours and emits existing CSS properties", () => { + const p = palette(["server"], { + fixed: { light: { server: "#753646" }, dark: { server: "#DAA4B2" } }, + accent: { light: "#285bb5", dark: "#65a7fa" }, + }); + expect(p.light.layers.server).toBe("#753646"); + expect(p.dark.layers.server).toBe("#DAA4B2"); + expect(p.toCss({ light: ".map-ui", dark: "[data-theme=dark] .map-ui" })).toBe( + `.map-ui { + --cmap-bg: #ffffff; + --cmap-node: #ffffff; + --cmap-fg: #202124; + --cmap-muted-fg: #666666; + --cmap-border: #b4b8be; + --cmap-accent: #285bb5; + --cmap-layer-server: #753646; +} +[data-theme=dark] .map-ui { + --cmap-bg: #17191d; + --cmap-node: #1f2227; + --cmap-fg: #e6e7ea; + --cmap-muted-fg: #a4a8b0; + --cmap-border: #626975; + --cmap-accent: #65a7fa; + --cmap-layer-server: #DAA4B2; +}`, + ); +}); + +test("public palette produces checked themes around a requested accent hue", () => { + const p = palette(["client", "server"], { accentHue: 40 }); + for (const theme of [p.light, p.dark]) { + expect( + checkColors(theme).defects.filter((d) => d.severity === "hard"), + ).toEqual([]); + } + expect(p.light.accent).not.toBe("#0061be"); +}); + +test.each(["bad; color:red", "", "1layer", "a b"])( + "rejects a layer id that cannot become a CSS property: %s", + (id) => expect(() => palette([id])).toThrow(ColorError), +); + +test("rejects duplicate ids instead of silently losing a generated layer", () => { + expect(() => palette(["a", "a"])).toThrow(ColorError); +}); diff --git a/tsconfig.core.json b/tsconfig.core.json index 8666028b..06170d7d 100644 --- a/tsconfig.core.json +++ b/tsconfig.core.json @@ -9,6 +9,7 @@ "src/schema.ts", "src/schema/**/*.ts", "src/model/**/*.ts", + "src/color/**/*.ts", "src/render/**/*.ts", "src/layout/**/*.ts" ]