From b509c6b738f1460f10366bf5dd0ed6ea980b767e Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 14:12:24 +0200 Subject: [PATCH 01/31] fix(site-tokens): use numeric slug ladders for font sizes, radius and shadows Font sizes use 100 to 900 with body at 200, radius 0 to 700 and shadows 100 to 600. Size names stay as display names. figma-to-block-theme already maps slugs straight through from the code syntax, so it needs no change. Fixes GIT-2758 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../references/proposal-review.md | 2 +- .../references/target-structure.md | 30 ++++++++-------- .../scripts/__tests__/propose-tokens.test.ts | 35 ++++++++++++------- .../__tests__/write-token-export.test.ts | 6 ++-- .../scripts/propose-tokens.ts | 34 ++++++++++-------- 6 files changed, 63 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a87aa53a41..27996a40f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Studio Imports From Live Sites** — Live site exports now import into Studio sites that already have WordPress content; files in the wrong format are refused with a reason. ([PR #3961](https://github.com/lightspeedwp/.github/pull/3961)) - **Qodo PR-Agent Eligibility and Comment Binding** — A closed pull request is refused on every request path, and both receivers resolve the exact maintainer comment by id. ([PR #3532](https://github.com/lightspeedwp/.github/pull/3532)) diff --git a/skills/site-to-design-tokens/references/proposal-review.md b/skills/site-to-design-tokens/references/proposal-review.md index ef681bfdb6..444e2b5d54 100644 --- a/skills/site-to-design-tokens/references/proposal-review.md +++ b/skills/site-to-design-tokens/references/proposal-review.md @@ -41,7 +41,7 @@ WCAG 2.2 ratios for the semantic pairs. Text needs 4.5:1, and focus rings and in Check each scale against the site at both widths: -- The body text size should be `xSmall`. +- The body text size should be `Base`, slug `200`. - Heading sizes should shrink on mobile. - Section spacing should reflect what the eye sees. Sites that space sections with margins on unstyled wrappers can produce a smaller scale than the design intends, so say so and let the reviewer set the larger steps. - Font names come from the site's CSS (for example a web font alias such as `argesta_displayregular`). Ask the reviewer for the licensed family name and its fallback. diff --git a/skills/site-to-design-tokens/references/target-structure.md b/skills/site-to-design-tokens/references/target-structure.md index e091e04ffe..6b2c0dfca3 100644 --- a/skills/site-to-design-tokens/references/target-structure.md +++ b/skills/site-to-design-tokens/references/target-structure.md @@ -4,17 +4,17 @@ The proposal and the Figma script follow the TSP design system file (The Safari ## Collections -| Collection | Modes | Holds | Code syntax | -| ------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Theme - Colour | Value | Primitives: `Theme/base`, `Theme/contrast`, `brand/100` … `900`, `primary/…`, `cta/…`, `neutral/…`, `system//`, `custom/overlay`, `shadow/` | `--wp--preset--color--`; overlay and shadows `--wp--custom--color--…` | -| Theme - Semantic | Value | Aliases of the primitives, by role | `--wp--custom--color----` | -| Theme - Typography | Max, Min | `Sizes/`, `Font-Families/Primary` (headings) and `Secondary` (body), `Line-Heights/`, `Weights/` | `--wp--preset--font-size--`, `--wp--preset--font-family--heading` and `body`, `--wp--custom--line-height--`, `--wp--custom--font-weight--` | -| Theme - Spacing | Max, Min | `Padding/None`, `Padding/XXS`, `Padding/XS` … `Padding/Colossal` | `--wp--preset--spacing--` (`5` … `100`) | -| Theme - Radius | Mode 1 | `Radius None`, `Small`, `Base` … `Round` | `--wp--preset--border-radius--` | -| Theme - Layout | Mode 1 | `Desktop/Desktop Content Width`, `Desktop/Desktop Wide Width` | `--wp--custom--layout--content-size` and `wide-size` | -| Theme - Breakpoints | Mode 1 | `Desktop`, `Tablet`, `Mobile` | `--wp--custom--breakpoint--` | - -Shadows are effect styles named `LSX/`. Each one's description holds its slug, for example `theme.json shadow preset "small": var(--wp--preset--shadow--small).` +| Collection | Modes | Holds | Code syntax | +| ------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Theme - Colour | Value | Primitives: `Theme/base`, `Theme/contrast`, `brand/100` … `900`, `primary/…`, `cta/…`, `neutral/…`, `system//`, `custom/overlay`, `shadow/` | `--wp--preset--color--`; overlay and shadows `--wp--custom--color--…` | +| Theme - Semantic | Value | Aliases of the primitives, by role | `--wp--custom--color----` | +| Theme - Typography | Max, Min | `Sizes/`, `Font-Families/Primary` (headings) and `Secondary` (body), `Line-Heights/`, `Weights/` | `--wp--preset--font-size--` (`100` … `900`), `--wp--preset--font-family--heading` and `body`, `--wp--custom--line-height--`, `--wp--custom--font-weight--` | +| Theme - Spacing | Max, Min | `Padding/None`, `Padding/XXS`, `Padding/XS` … `Padding/Colossal` | `--wp--preset--spacing--` (`5` … `100`) | +| Theme - Radius | Mode 1 | `Radius None`, `Small`, `Base` … `Round` | `--wp--preset--border-radius--` | +| Theme - Layout | Mode 1 | `Desktop/Desktop Content Width`, `Desktop/Desktop Wide Width` | `--wp--custom--layout--content-size` and `wide-size` | +| Theme - Breakpoints | Mode 1 | `Desktop`, `Tablet`, `Mobile` | `--wp--custom--breakpoint--` | + +Shadows are effect styles named `LSX/`. Each one's description holds its slug, for example `theme.json shadow preset "200": var(--wp--preset--shadow--200).` `Max` is the 1440px desktop value and `Min` the 390px mobile value. `figma-to-block-theme` turns the pairs into fluid font sizes and spacing `clamp()` values. @@ -22,9 +22,9 @@ Line-height variables store a percentage of the font size (150 means 1.5). They ## Slugs and names -Type sizes, radius and shadows use the TSP size names, and slugs in lower kebab case: `xSmall` becomes `x-small`. +Type sizes, radius and shadows use numeric slugs, the same as the block theme scaffold and `tsp-theme`. The size names (Small, Base, Large and so on) are display names only. The slug lives in the code syntax and the effect style description, never in the variable name, and the export carries the slug straight through to `theme.json` with no renaming. -- Type: `Tiny`, `xSmall`, `Small`, `Medium`, `Large`, `xLarge`, `Huge`, `Gigantic`. The body text size is `xSmall`. +- Type, slugs `100` to `900`: `Tiny` (100), `Base` (200), `Small`, `Medium`, `Large`, `xLarge`, `Huge`, `Gigantic`, `Colossal` (900). Body text is always `Base` at `200`. When the site has no size below body text, `100` stays empty. - Spacing is the exception. The variable name carries only the size and the code syntax carries the slug, so `Padding/XS` has `var(--wp--preset--spacing--10)`. Never put the slug in the name (`Padding/10 XS`). The ladder is: | Name | XXS | XS | S | M | L | XL | XXL | XXXL | XXXXL | Gigantic | Colossal | @@ -35,8 +35,8 @@ Type sizes, radius and shadows use the TSP size names, and slugs in lower kebab Each measured value takes the step nearest its desktop size, so 40px becomes `L`. When that step is taken, the value moves up to the next free step. `Padding/None` (0) is for Figma only. It has no code syntax, because WordPress already offers a 0 spacing and importing one adds a duplicate in the editor. -- Radius: `None`, `Small`, `Base`, `Medium`, `Large`, `xLarge`, `Round`. -- Shadows: `xSmall`, `Small`, `Medium`, `Large`, `xLarge`, `Huge`. +- Radius, slugs `0` to `700`: `None` (0), `Small` (100), `Base`, `Medium`, `Large`, `xLarge`, `Huge` (600), `Round` (700, 9999px). Measured values fill 100 upward in order. +- Shadows, slugs `100` to `600`: `xSmall`, `Small`, `Medium`, `Large`, `xLarge`, `Huge`, ordered by strength (blur radius), so `100` is the softest. ## Colour families diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index fb80c948a4..c1ed94406f 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -62,12 +62,12 @@ describe('TokenProposer on a TSP-like site', () => { expect(proposal.contrast).toHaveLength(17); }); - it('builds the type scale with the body size at xSmall and mobile minimums', () => { + it('builds the type scale with the body size at slug 200 (Base) and mobile minimums', () => { const sizes = proposal.typography.sizes; expect(proposal.typography.families).toEqual({ heading: 'Moret', body: 'Lora' }); expect(sizes.map((s) => s.name)).toEqual([ 'Tiny', - 'xSmall', + 'Base', 'Small', 'Medium', 'Large', @@ -75,8 +75,18 @@ describe('TokenProposer on a TSP-like site', () => { 'Huge', 'Gigantic', ]); - expect(sizes[1]).toMatchObject({ slug: 'x-small', max: 16, min: 16, lineHeight: 1.5 }); - expect(sizes[7]).toMatchObject({ slug: 'gigantic', max: 60, min: 36, lineHeight: 1.2 }); + expect(sizes.map((s) => s.slug)).toEqual([ + '100', + '200', + '300', + '400', + '500', + '600', + '700', + '800', + ]); + expect(sizes[1]).toMatchObject({ slug: '200', max: 16, min: 16, lineHeight: 1.5 }); + expect(sizes[7]).toMatchObject({ slug: '800', max: 60, min: 36, lineHeight: 1.2 }); expect(sizes[2]).toMatchObject({ max: 20, min: 16 }); expect(proposal.typography.weights).toMatchObject({ body: 400, button: 600, h1: 400 }); expect(proposal.decisions.join(' ')).toContain('share the one Tiny slot'); @@ -93,12 +103,12 @@ describe('TokenProposer on a TSP-like site', () => { ['Colossal', '100', 100, 72], ]); expect(proposal.radius).toEqual([ - { name: 'None', slug: 'none', value: 0 }, - { name: 'Small', slug: 'small', value: 4 }, - { name: 'Base', slug: 'base', value: 8 }, - { name: 'Round', slug: 'round', value: 9999 }, + { name: 'None', slug: '0', value: 0 }, + { name: 'Small', slug: '100', value: 4 }, + { name: 'Base', slug: '200', value: 8 }, + { name: 'Round', slug: '700', value: 9999 }, ]); - expect(proposal.shadows.map((s) => s.slug)).toEqual(['x-small', 'small', 'medium']); + expect(proposal.shadows.map((s) => s.slug)).toEqual(['100', '200', '300']); expect(proposal.shadows[0].effects[0]).toMatchObject({ type: 'DROP_SHADOW', offset: { x: 0, y: 1 }, @@ -186,10 +196,10 @@ describe('TokenProposer on a sparse site', () => { expect(decisions).toContain('No repeated centred container'); expect(proposal.layout).toEqual({}); expect(proposal.breakpoints).toEqual({ mobile: 376, tablet: 768, desktop: 1240 }); - expect(proposal.radius.map((r) => r.slug)).toEqual(['none', 'round']); + expect(proposal.radius.map((r) => r.slug)).toEqual(['0', '700']); expect(proposal.shadows).toEqual([]); expect(proposal.spacing).toEqual([{ name: 'None', slug: 'none', max: 0, min: 0 }]); - expect(proposal.typography.sizes.map((s) => s.name)).toEqual(['xSmall', 'Small']); + expect(proposal.typography.sizes.map((s) => s.name)).toEqual(['Base', 'Small']); }); it('puts spacing on the nearest free ladder step and drops what does not fit', () => { @@ -243,7 +253,8 @@ describe('TokenProposer on a sparse site', () => { ); } const merged = new TokenProposer().propose(many, { now }); - expect(merged.typography.sizes).toHaveLength(7); + expect(merged.typography.sizes).toHaveLength(8); + expect(merged.typography.sizes.at(-1)).toMatchObject({ name: 'Colossal', slug: '900' }); expect(merged.decisions.join(' ')).toContain('was merged into the nearest size'); }); diff --git a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts index b2eb1cfe49..d65ef3b572 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts @@ -73,10 +73,10 @@ describe('TokenPlanBuilder', () => { it('stores fluid sizes as Max and Min, and line heights as percentages', () => { const typography = collection('Theme - Typography').variables; expect(typography.find((v) => v.name === 'Sizes/Gigantic')).toMatchObject({ - codeSyntax: 'var(--wp--preset--font-size--gigantic)', + codeSyntax: 'var(--wp--preset--font-size--800)', values: { Max: 60, Min: 36 }, }); - expect(typography.find((v) => v.name === 'Line-Heights/xSmall')!.values).toEqual({ + expect(typography.find((v) => v.name === 'Line-Heights/Base')!.values).toEqual({ Max: 150, Min: 150, }); @@ -95,7 +95,7 @@ describe('TokenPlanBuilder', () => { ]); expect(plan.effectStyles[0]).toMatchObject({ name: 'LSX/xSmall', - description: 'theme.json shadow preset "x-small": var(--wp--preset--shadow--x-small).', + description: 'theme.json shadow preset "100": var(--wp--preset--shadow--100).', }); }); diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 76424af182..eec7b9ab3f 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -76,7 +76,20 @@ export const SEMANTIC_DEFAULTS: Record = { }; export const SHADOW_ALPHAS = [5, 10, 12, 15, 20, 25, 30, 35, 40, 45, 60, 70, 85]; -const SIZE_NAMES = ['Tiny', 'xSmall', 'Small', 'Medium', 'Large', 'xLarge', 'Huge', 'Gigantic']; +/** The type ladder: slugs 100 to 900, body text at 200. Names are display names only. */ +const SIZE_NAMES = [ + 'Tiny', + 'Base', + 'Small', + 'Medium', + 'Large', + 'xLarge', + 'Huge', + 'Gigantic', + 'Colossal', +]; +/** Numeric slug for the nth step of a ladder that counts in hundreds (100, 200, ...). */ +const hundreds = (index: number) => String((index + 1) * 100); /** The LightSpeed spacing ladder: the slug is the step, the name its T-shirt size. */ export const SPACING_STEPS = [ { slug: '5', name: 'XXS' }, @@ -91,7 +104,7 @@ export const SPACING_STEPS = [ { slug: '90', name: 'Gigantic' }, { slug: '100', name: 'Colossal' }, ]; -const RADIUS_NAMES = ['Small', 'Base', 'Medium', 'Large', 'xLarge']; +const RADIUS_NAMES = ['Small', 'Base', 'Medium', 'Large', 'xLarge', 'Huge']; const SHADOW_NAMES = ['xSmall', 'Small', 'Medium', 'Large', 'xLarge', 'Huge']; export interface ColourEvidence { @@ -181,13 +194,6 @@ export interface ProposeOptions { now?: () => Date; } -const kebab = (name: string) => - name - .replace(/^x(?=[A-Z])/, 'x-') - .replace(/^xx(?=[A-Z])/, 'xx-') - .replace(/([a-z])([A-Z])/g, '$1-$2') - .toLowerCase(); - /** Weighted mode of a list of values. */ function mode(values: Array<{ value: T; weight?: number }>): T | undefined { const counts = new Map(); @@ -787,7 +793,7 @@ export class TokenProposer { const name = SIZE_NAMES[firstIndex + i]; return { name, - slug: kebab(name), + slug: hundreds(firstIndex + i), max, min: Math.min(entry.min, max), lineHeight: mode(entry.ratios.map((value) => ({ value }))), @@ -902,9 +908,9 @@ export class TokenProposer { .map(([v]) => v) .sort((a, b) => a - b); return [ - { name: 'None', slug: 'none', value: 0 }, - ...values.map((value, i) => ({ name: RADIUS_NAMES[i], slug: kebab(RADIUS_NAMES[i]), value })), - { name: 'Round', slug: 'round', value: 9999 }, + { name: 'None', slug: '0', value: 0 }, + ...values.map((value, i) => ({ name: RADIUS_NAMES[i], slug: hundreds(i), value })), + { name: 'Round', slug: '700', value: 9999 }, ]; } @@ -924,7 +930,7 @@ export class TokenProposer { (a, b) => a.effects.reduce((t, e) => t + e.radius, 0) - b.effects.reduce((t, e) => t + e.radius, 0) ); - return parsed.map((s, i) => ({ name: SHADOW_NAMES[i], slug: kebab(SHADOW_NAMES[i]), ...s })); + return parsed.map((s, i) => ({ name: SHADOW_NAMES[i], slug: hundreds(i), ...s })); } /** Parses a computed box-shadow into effects. */ From 1bcfba20a14d7248535c9d7a4e301552ba25c2b1 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 14:19:05 +0200 Subject: [PATCH 02/31] fix(site-tokens): use the whole spacing ladder before dropping a value Values that would run off the top of the ladder now shift down into free lower steps, starting at 5. A value is only left out when more than 11 are in use. Fixes GIT-2759 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../references/target-structure.md | 2 +- .../scripts/__tests__/propose-tokens.test.ts | 30 ++++++++++++++-- .../scripts/propose-tokens.ts | 35 +++++++++++++------ 4 files changed, 54 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27996a40f8..110e413e67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) - **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Studio Imports From Live Sites** — Live site exports now import into Studio sites that already have WordPress content; files in the wrong format are refused with a reason. ([PR #3961](https://github.com/lightspeedwp/.github/pull/3961)) diff --git a/skills/site-to-design-tokens/references/target-structure.md b/skills/site-to-design-tokens/references/target-structure.md index 6b2c0dfca3..a4a014c811 100644 --- a/skills/site-to-design-tokens/references/target-structure.md +++ b/skills/site-to-design-tokens/references/target-structure.md @@ -33,7 +33,7 @@ Type sizes, radius and shadows use numeric slugs, the same as the block theme sc Sizing ramps are in order. Spacing and type sizes are created in Figma smallest first, with `None` first for spacing, so the Variables panel reads as a ramp. The export JSON and the Figma script both sort by Max value, then slug, whatever order the proposal has. - Each measured value takes the step nearest its desktop size, so 40px becomes `L`. When that step is taken, the value moves up to the next free step. `Padding/None` (0) is for Figma only. It has no code syntax, because WordPress already offers a 0 spacing and importing one adds a duplicate in the editor. + Each measured value takes the step nearest its desktop size, so 40px becomes `L`. When that step is taken, the value moves up to the next free step. If that runs off the top of the ladder, values shift down into free lower steps, starting at `5`, so nothing is dropped. A value is only left out when more than 11 distinct values are in use, and then the least used go. `Padding/None` (0) is for Figma only. It has no code syntax, because WordPress already offers a 0 spacing and importing one adds a duplicate in the editor. - Radius, slugs `0` to `700`: `None` (0), `Small` (100), `Base`, `Medium`, `Large`, `xLarge`, `Huge` (600), `Round` (700, 9999px). Measured values fill 100 upward in order. - Shadows, slugs `100` to `600`: `xSmall`, `Small`, `Medium`, `Large`, `xLarge`, `Huge`, ordered by strength (blur radius), so `100` is the softest. diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index c1ed94406f..3b8fcc54fd 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -202,7 +202,7 @@ describe('TokenProposer on a sparse site', () => { expect(proposal.typography.sizes.map((s) => s.name)).toEqual(['Base', 'Small']); }); - it('puts spacing on the nearest free ladder step and drops what does not fit', () => { + it('puts spacing on the nearest free ladder step and shifts values down when the top is full', () => { const proposer = new TokenProposer(); proposer.propose(styles, { now }); const samples = [12, 16, 22, 140, 200].map((paddingBlock, i) => ({ @@ -217,8 +217,34 @@ describe('TokenProposer on a sparse site', () => { ['XS', '10', 12], ['S', '20', 16], ['M', '30', 22], - ['Colossal', '100', 140], + ['Gigantic', '90', 140], + ['Colossal', '100', 200], ]); + expect(proposer['decisions'].join(' ')).toContain('moved down to free lower steps'); + }); + + it('fills the whole 5 to 100 ladder with 11 distinct values and drops none', () => { + const proposer = new TokenProposer(); + proposer.propose(styles, { now }); + const values = [8, 10, 14, 20, 24, 32, 38, 48, 60, 70, 80]; + const samples = values.flatMap((paddingBlock, i) => + [0, 1].map((n) => ({ key: `sp:${i}:${n}`, page: '/', role: 'section', paddingBlock })) + ); + const spacing = proposer.proposeSpacing(samples as never, () => undefined); + expect(spacing.slice(1).map((s) => [s.slug, s.max])).toEqual([ + ['5', 8], + ['10', 10], + ['20', 14], + ['30', 20], + ['40', 24], + ['50', 32], + ['60', 38], + ['70', 48], + ['80', 60], + ['90', 70], + ['100', 80], + ]); + expect(proposer['decisions'].join(' ')).not.toContain('left out'); }); it('names the spacing values left out when there are more than the ladder holds', () => { diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index eec7b9ab3f..d001ea72b2 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -866,9 +866,12 @@ export class TokenProposer { ); } // Each value takes the ladder step nearest its desktop size, so 40px becomes - // L (slug 40). A taken step pushes the value to the next free step up. - const steps: ScaleEntry[] = []; - let next = 0; + // L (slug 40). A taken step pushes the value up to the next free step. If that + // runs off the top of the ladder, values shift back down into free lower steps + // (starting at 5) instead of being dropped. At most the ladder's length is kept + // above, so every kept value always gets a step. + const last = SPACING_STEPS.length - 1; + const indexes: number[] = []; for (const c of kept) { const nearest = SPACING_STEPS.reduce( (best, step, i) => @@ -877,16 +880,26 @@ export class TokenProposer { : best, 0 ); - const i = Math.max(nearest, next); - if (i >= SPACING_STEPS.length) { - this.decisions.push( - `Spacing ${c.max}px has no free step left on the ladder and was left out.` - ); - continue; + indexes.push(Math.max(nearest, indexes.length ? indexes[indexes.length - 1] + 1 : 0)); + } + let shifted = false; + for (let i = indexes.length - 1; i >= 0; i--) { + const ceiling = i === indexes.length - 1 ? last : indexes[i + 1] - 1; + if (indexes[i] > ceiling) { + indexes[i] = ceiling; + shifted = true; } - steps.push({ ...SPACING_STEPS[i], max: c.max, min: Math.min(c.min, c.max) }); - next = i + 1; } + if (shifted) { + this.decisions.push( + 'Some spacing values moved down to free lower steps so the whole 5 to 100 ladder is used and none is dropped.' + ); + } + const steps: ScaleEntry[] = kept.map((c, i) => ({ + ...SPACING_STEPS[indexes[i]], + max: c.max, + min: Math.min(c.min, c.max), + })); return [{ name: 'None', slug: 'none', max: 0, min: 0 }, ...steps]; } From da0cc700bf382881356b4a42978974297810c128 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 14:23:25 +0200 Subject: [PATCH 03/31] fix(site-tokens): measure content width from the text column and allow an override The crawler records running-text paragraph widths in the main column and the kind of page. The proposer uses single posts and pages, adds --layout content=,wide= and a reviewer decision when the content width is under 480px. Fixes GIT-2760 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + skills/site-to-design-tokens/SKILL.md | 1 + .../references/crawling.md | 2 +- .../references/proposal-review.md | 1 + .../__tests__/crawl-site-styles.test.ts | 28 + .../scripts/__tests__/propose-tokens.test.ts | 81 +- .../scripts/crawl-site-styles.ts | 33 +- .../scripts/propose-tokens.ts | 74 +- .../scripts/propose-tokens.ts.bak | 1288 +++++++++++++++++ 9 files changed, 1497 insertions(+), 12 deletions(-) create mode 100644 skills/site-to-design-tokens/scripts/propose-tokens.ts.bak diff --git a/CHANGELOG.md b/CHANGELOG.md index 110e413e67..5e5861d29e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text on single posts and pages, takes `--layout content=,wide=` to override either width, and asks the reviewer to confirm a content width under 480px. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) - **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) - **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Studio Imports From Live Sites** — Live site exports now import into Studio sites that already have WordPress content; files in the wrong format are refused with a reason. ([PR #3961](https://github.com/lightspeedwp/.github/pull/3961)) diff --git a/skills/site-to-design-tokens/SKILL.md b/skills/site-to-design-tokens/SKILL.md index 988924d060..b508f9a1e4 100644 --- a/skills/site-to-design-tokens/SKILL.md +++ b/skills/site-to-design-tokens/SKILL.md @@ -52,6 +52,7 @@ The proposal follows the structure in [references/target-structure.md](reference Present the report's summary, its **Decisions for the reviewer** list and any failing contrast pairs. [references/proposal-review.md](references/proposal-review.md) explains each section. Common changes: - **A colour in the wrong family:** re-run with `--assign brand=#hex,primary=#hex,cta=#hex`. +- **A wrong content or wide width:** re-run with `--layout content=768,wide=1240`. Content width is measured from running text on single pages, so include a long text page in the crawl. - **A failing contrast pair:** propose the nearest passing step and record the change. - **A live value with no close token:** keep the nearest token with the same role and list it for the reviewer. Don't add a raw value. diff --git a/skills/site-to-design-tokens/references/crawling.md b/skills/site-to-design-tokens/references/crawling.md index a9010ae855..330fb17183 100644 --- a/skills/site-to-design-tokens/references/crawling.md +++ b/skills/site-to-design-tokens/references/crawling.md @@ -27,7 +27,7 @@ At each viewport (390px and 1440px by default) the crawler reads computed styles | `input` | Text inputs, selects and text areas | | `section` and `surface` | Elements with a background (sections are at least half the viewport wide), and padded or centred wrappers | -For each element it keeps the text colour, background, border colour, font family, size, weight and line height, padding, bottom margin, gap, radius, shadow, and centred container width. It also records the widths in the site's same-origin `@media` rules. A DOM path key pairs the same element across the two viewports, which gives the mobile (Min) value for each desktop (Max) value. +For each element it keeps the text colour, background, border colour, font family, size, weight and line height, padding, bottom margin, gap, radius, shadow, centred container width, and the widths of running-text paragraphs in the main column (with whether the page is a single post or page, or a listing). The proposer measures the content width from the text on single pages, so include a long text page. It also records the widths in the site's same-origin `@media` rules. A DOM path key pairs the same element across the two viewports, which gives the mobile (Min) value for each desktop (Max) value. ## Politeness and limits diff --git a/skills/site-to-design-tokens/references/proposal-review.md b/skills/site-to-design-tokens/references/proposal-review.md index 444e2b5d54..e341cd92d4 100644 --- a/skills/site-to-design-tokens/references/proposal-review.md +++ b/skills/site-to-design-tokens/references/proposal-review.md @@ -45,3 +45,4 @@ Check each scale against the site at both widths: - Heading sizes should shrink on mobile. - Section spacing should reflect what the eye sees. Sites that space sections with margins on unstyled wrappers can produce a smaller scale than the design intends, so say so and let the reviewer set the larger steps. - Font names come from the site's CSS (for example a web font alias such as `argesta_displayregular`). Ask the reviewer for the licensed family name and its fallback. +- **Content width** comes from the width of running text (`p` elements with 80 or more characters in the main column) on single posts and pages, not from cards or wrappers. Include at least one long text page in the crawl. If the report says the width came from listing pages, or is under 480px, confirm it with the reviewer. Override either width with `--layout content=,wide=`. diff --git a/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts b/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts index eabca7ca9e..01d2cdd80a 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts @@ -62,6 +62,34 @@ describe('collectPageStyles', () => { expect(mediaWidths.sort()).toEqual([1240, 376, 768]); }); + it('records running-text widths from the main column and the kind of page', () => { + document.body.className = 'single single-post'; + document.body.innerHTML = ` +

${'h'.repeat(90)}

+
+

Short.

+

${'Running text of a post. '.repeat(5)}

+
  • ${'l'.repeat(90)}

+

${'w'.repeat(90)}

+
`; + const widths: Record = { text: 768, wide: 1440 }; + const spy = jest + .spyOn(window.HTMLElement.prototype, 'getBoundingClientRect') + .mockImplementation(function (this: { id: string }) { + const width = widths[this.id] ?? 0; + return { width, height: 20, left: 0, right: width, top: 0, bottom: 20 } as never; + }); + try { + const single = collectPageStyles({ requireLayout: false }); + expect(single.textWidths).toEqual([768]); + expect(single.pageKind).toBe('single'); + document.body.className = 'home page'; + expect(collectPageStyles({ requireLayout: false }).pageKind).toBe('listing'); + } finally { + spy.mockRestore(); + } + }); + it('skips elements with no layout box by default and respects the sample cap', () => { expect(collectPageStyles().samples).toHaveLength(0); expect(collectPageStyles({ requireLayout: false, maxSamples: 2 }).samples).toHaveLength(2); diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index 3b8fcc54fd..d3c6e804fa 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -193,7 +193,7 @@ describe('TokenProposer on a sparse site', () => { ).toEqual(['cta', 'primary', 'neutral']); expect(decisions).toContain('No site colour fits `primary`'); expect(decisions).toContain('No light page background was found'); - expect(decisions).toContain('No repeated centred container'); + expect(decisions).toContain('No running text or repeated centred container'); expect(proposal.layout).toEqual({}); expect(proposal.breakpoints).toEqual({ mobile: 376, tablet: 768, desktop: 1240 }); expect(proposal.radius.map((r) => r.slug)).toEqual(['0', '700']); @@ -327,6 +327,75 @@ describe('ProposalReport', () => { }); }); +describe('TokenProposer.proposeLayout', () => { + const capture = (kind: 'single' | 'listing', textWidths: number[]) => + ({ + url: `/${kind}`, + viewport: 1440, + samples: [], + mediaWidths: [], + textWidths, + pageKind: kind, + }) as never; + const wideCards = [1240, 1240, 248, 248, 248].map((containerWidth, i) => ({ + key: `c:${i}`, + role: 'surface' as const, + containerWidth, + })); + + it('measures the content width from running text on single pages, not from cards', () => { + const proposer = new TokenProposer(); + const layout = proposer.proposeLayout(wideCards, 1440, [ + capture('listing', [248, 248, 248]), + capture('single', [768, 770, 768]), + ]); + expect(layout).toEqual({ content: 768, wide: 1240 }); + expect(proposer['decisions']).toEqual([]); + }); + + it('warns when only listing pages have running text', () => { + const proposer = new TokenProposer(); + const layout = proposer.proposeLayout(wideCards, 1440, [capture('listing', [640, 640])]); + expect(layout.content).toBe(640); + expect(proposer['decisions'].join(' ')).toContain('No single post or page was captured'); + }); + + it('asks the reviewer to decide when the content width is under 480px', () => { + const proposer = new TokenProposer(); + const layout = proposer.proposeLayout(wideCards, 1440, [capture('single', [400, 400])]); + expect(layout.content).toBe(400); + expect(proposer['decisions'].join(' ')).toContain('under 480px'); + }); + + it('falls back to the centred containers when there is no running text', () => { + const proposer = new TokenProposer(); + const cards = [1240, 1240, 768, 768].map((containerWidth, i) => ({ + key: `c:${i}`, + role: 'surface' as const, + containerWidth, + })); + expect(proposer.proposeLayout(cards, 1440, [capture('single', [])])).toEqual({ + content: 768, + wide: 1240, + }); + expect(proposer['decisions'].join(' ')).toContain('No running text was found'); + }); + + it('lets the reviewer override either width', () => { + const proposer = new TokenProposer(); + const captures = [capture('single', [248, 248])]; + expect(proposer.proposeLayout(wideCards, 1440, captures, { content: 768 })).toEqual({ + content: 768, + wide: 1240, + }); + expect(proposer.proposeLayout([], 1440, [], { wide: 1200 })).toEqual({ wide: 1200 }); + expect(proposer.proposeLayout([], 1440, [], { content: 700, wide: 1200 })).toEqual({ + content: 700, + wide: 1200, + }); + }); +}); + describe('runProposeCli', () => { function io(files: Record = {}) { const out: string[] = []; @@ -369,6 +438,14 @@ describe('runProposeCli', () => { expect(run.out.join('')).toContain('Wrote p.json and p.md'); }); + it('passes --layout through to the proposal', () => { + const run = io({ 'styles.json': styles }); + expect( + runProposeCli(['styles.json', '--out', 'p.json', '--layout', 'content=700,wide=1200'], run.io) + ).toBe(0); + expect(JSON.parse(run.written['p.json']).layout).toEqual({ content: 700, wide: 1200 }); + }); + it('defaults the output path and prints help', () => { const run = io({ 'styles.json': styles }); expect(runProposeCli(['styles.json'], run.io)).toBe(0); @@ -385,6 +462,8 @@ describe('runProposeCli', () => { [['--out'], '--out needs a value'], [['--nope'], 'Unknown option --nope'], [['styles.json', '--assign', 'accent=#fff'], '--assign takes brand, primary or cta'], + [['styles.json', '--layout', 'narrow=5'], '--layout takes content and wide'], + [['styles.json', '--layout', 'content=abc'], '--layout takes content and wide'], [['missing.json'], 'ENOENT'], [['empty.json'], 'has no captures'], ])('fails cleanly for %j', (argv, message) => { diff --git a/skills/site-to-design-tokens/scripts/crawl-site-styles.ts b/skills/site-to-design-tokens/scripts/crawl-site-styles.ts index 4c21de410b..da06da3d3f 100644 --- a/skills/site-to-design-tokens/scripts/crawl-site-styles.ts +++ b/skills/site-to-design-tokens/scripts/crawl-site-styles.ts @@ -54,6 +54,14 @@ export interface ElementSample { export interface CollectedPage { samples: ElementSample[]; mediaWidths: number[]; + /** + * Widths in px of running-text paragraphs (`p` with 80 or more characters) in the main + * column, outside navigation, footers, asides, lists and figures. This is the column + * a reader sees, so it measures the content width better than any centred wrapper. + */ + textWidths?: number[]; + /** `single` for one post or page, `listing` for the home page, archives, blog and search. */ + pageKind?: 'single' | 'listing'; } export interface PageCapture extends CollectedPage { @@ -236,7 +244,30 @@ export function collectPageStyles(options: CollectOptions = {}): CollectedPage { } } - return { samples, mediaWidths }; + const textWidths: number[] = []; + const main = document.querySelector('main, [role="main"], #main, #content') ?? document.body; + const paragraphs = main ? main.querySelectorAll('p') : []; + for (let i = 0; i < paragraphs.length; i++) { + const p = paragraphs[i] as HTMLElement; + if (p.closest('nav, footer, aside, li, figure, form, blockquote, table, header')) { + continue; + } + if ((p.textContent ?? '').trim().length < 80) { + continue; + } + const box = p.getBoundingClientRect(); + if (box.width >= 1 && box.width < viewport - 16) { + textWidths.push(Math.round(box.width)); + } + } + const bodyClass = + document.body && typeof document.body.className === 'string' ? document.body.className : ''; + const pageKind: 'single' | 'listing' = + /\b(home|archive|blog|search|category|tag|post-type-archive)\b/.test(bodyClass) + ? 'listing' + : 'single'; + + return { samples, mediaWidths, textWidths, pageKind }; } export interface PageHandle { diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index d001ea72b2..4d68119007 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -6,6 +6,7 @@ * Usage: * npx tsx propose-tokens.ts site-styles.json --out proposal.json --report proposal.md * npx tsx propose-tokens.ts site-styles.json --assign brand=#8d621f,primary=#565b3d + * npx tsx propose-tokens.ts site-styles.json --layout content=768,wide=1240 */ import { readFileSync, writeFileSync } from 'node:fs'; @@ -191,6 +192,8 @@ export interface Proposal { export interface ProposeOptions { /** Force a family's anchor colour, for example { brand: '#8d621f' }. */ assign?: Partial>; + /** Force the content and wide widths in px, for example { content: 768, wide: 1240 }. */ + layout?: { content?: number; wide?: number }; now?: () => Date; } @@ -244,7 +247,7 @@ export class TokenProposer { const spacing = this.proposeSpacing(desktopSamples, pair); const radius = this.proposeRadius(desktopSamples); const shadows = this.proposeShadows(desktopSamples); - const layout = this.proposeLayout(desktopSamples, desktopWidth); + const layout = this.proposeLayout(desktopSamples, desktopWidth, desktop, options.layout); const breakpoints = this.proposeBreakpoints(styles.captures); return { @@ -993,7 +996,16 @@ export class TokenProposer { }); } - proposeLayout(samples: ElementSample[], viewport: number): Proposal['layout'] { + /** + * Content width is the width of running text (`p` in the main column) on single posts + * and pages. Wide width is the widest repeated centred container. Either can be forced. + */ + proposeLayout( + samples: ElementSample[], + viewport: number, + captures: PageCapture[] = [], + override: { content?: number; wide?: number } = {} + ): Proposal['layout'] { const counts = new Map(); for (const s of samples) { if (s.containerWidth && s.containerWidth < viewport - 16) { @@ -1002,15 +1014,47 @@ export class TokenProposer { } } const frequent = [...counts.entries()].filter(([, n]) => n >= 2).sort((a, b) => b[1] - a[1]); - if (!frequent.length) { + const wide = + override.wide ?? (frequent.length ? Math.max(...frequent.map(([w]) => w)) : undefined); + + let content = override.content; + if (content === undefined) { + const single = captures.filter((c) => c.pageKind === 'single'); + const fromSingles = single.flatMap((c) => c.textWidths ?? []); + const fromAny = captures.flatMap((c) => c.textWidths ?? []); + const widths = fromSingles.length ? fromSingles : fromAny; + if (widths.length) { + content = mode(widths.map((w) => ({ value: Math.round(w / 8) * 8 }))); + if (!fromSingles.length) { + this.decisions.push( + 'No single post or page was captured, so the content width was measured on listing pages and may be a card. Add a long text page, or set it with `--layout content=`.' + ); + } + } else if (frequent.length) { + const fallback = frequent.find(([w]) => w <= (wide ?? 0) * 0.8)?.[0]; + if (fallback) { + content = fallback; + this.decisions.push( + `No running text was found, so the content width ${fallback}px comes from the most common centred container. Check it, or set it with \`--layout content=\`.` + ); + } + } + } + if (content === undefined && wide === undefined) { this.decisions.push( - 'No repeated centred container was found; set the content and wide widths by hand.' + 'No running text or repeated centred container was found; set the content and wide widths with `--layout content=,wide=`.' ); return {}; } - const wide = Math.max(...frequent.map(([w]) => w)); - const content = frequent.find(([w]) => w <= wide * 0.8)?.[0]; - return content ? { content, wide } : { wide }; + if (content !== undefined && content < 480) { + this.decisions.push( + `The content width is ${content}px, under 480px, which is narrower than a readable text column. Confirm it, or set it with \`--layout content=\`.` + ); + } + return { + ...(content !== undefined ? { content } : {}), + ...(wide !== undefined ? { wide } : {}), + }; } proposeBreakpoints(captures: PageCapture[]): Proposal['breakpoints'] { @@ -1169,6 +1213,7 @@ export function runProposeCli(argv: string[], io: ProposeCliIo): number { let out = 'proposal.json'; let report: string | undefined; const assign: Partial> = {}; + const layout: { content?: number; wide?: number } = {}; try { for (let i = 0; i < argv.length; i++) { @@ -1182,7 +1227,7 @@ export function runProposeCli(argv: string[], io: ProposeCliIo): number { }; if (arg === '--help' || arg === '-h') { io.stdout( - 'Usage: propose-tokens [--out proposal.json] [--report proposal.md] [--assign brand=#hex,primary=#hex,cta=#hex]\n' + 'Usage: propose-tokens [--out proposal.json] [--report proposal.md] [--assign brand=#hex,primary=#hex,cta=#hex] [--layout content=,wide=]\n' ); return 0; } else if (arg === '--out') { @@ -1197,6 +1242,17 @@ export function runProposeCli(argv: string[], io: ProposeCliIo): number { } assign[family as Family] = hex; } + } else if (arg === '--layout') { + for (const part of next().split(',')) { + const [key, value] = part.split('='); + const px = Number(value); + if (!['content', 'wide'].includes(key) || !Number.isFinite(px) || px <= 0) { + throw new Error( + '--layout takes content and wide in px, for example content=768,wide=1240.' + ); + } + layout[key as 'content' | 'wide'] = Math.round(px); + } } else if (arg.startsWith('--')) { throw new Error(`Unknown option ${arg}.`); } else { @@ -1210,7 +1266,7 @@ export function runProposeCli(argv: string[], io: ProposeCliIo): number { if (!Array.isArray(styles.captures) || !styles.captures.length) { throw new Error('The styles file has no captures.'); } - const proposal = new TokenProposer().propose(styles, { assign }); + const proposal = new TokenProposer().propose(styles, { assign, layout }); io.writeFile(out, `${JSON.stringify(proposal, null, 2)}\n`); if (report) { io.writeFile(report, new ProposalReport().render(proposal)); diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts.bak b/skills/site-to-design-tokens/scripts/propose-tokens.ts.bak new file mode 100644 index 0000000000..ec82e70294 --- /dev/null +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts.bak @@ -0,0 +1,1288 @@ +/** + * Turns crawled site styles into a token proposal in the TSP structure: + * colour primitives with 100-900 ramps, semantic aliases, and type, spacing, + * radius, shadow, layout and breakpoint scales. + * + * Usage: + * npx tsx propose-tokens.ts site-styles.json --out proposal.json --report proposal.md + * npx tsx propose-tokens.ts site-styles.json --assign brand=#8d621f,primary=#565b3d + */ + +import { readFileSync, writeFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; +import { Color, RampBuilder, RAMP_STEPS, RampStep, STEP_LIGHTNESS } from './lib/color'; +import type { ElementSample, PageCapture, Role, SiteStyles } from './crawl-site-styles'; + +export type Family = 'brand' | 'primary' | 'cta' | 'neutral'; +export const CHROMATIC_FAMILIES: Family[] = ['brand', 'primary', 'cta']; + +export const SYSTEM_DEFAULTS: Record = { + 'error-foreground': '#cc0000', + 'error-background': '#fabcbc', + 'warning-foreground': '#8a5a00', + 'warning-background': '#ffeeb2', + 'success-foreground': '#127301', + 'success-background': '#e3ffe6', + 'information-foreground': '#0047d0', + 'information-background': '#b9d1ff', +}; + +/** Default semantic aliases, from the TSP design system. */ +export const SEMANTIC_DEFAULTS: Record = { + 'text/default': 'contrast', + 'text/muted': 'neutral-600', + 'text/inverse': 'base', + 'text/inverse-subtle': 'neutral-100', + 'text/brand': 'brand-600', + 'text/link': 'brand-600', + 'text/link-hover': 'primary-500', + 'text/disabled': 'neutral-500', + 'text/placeholder': 'neutral-600', + 'surface/default': 'base', + 'surface/subtle': 'neutral-100', + 'surface/brand': 'brand-100', + 'surface/inverse': 'contrast', + 'surface/overlay': 'overlay', + 'surface/control-checked': 'brand-600', + 'surface/control-off': 'neutral-500', + 'surface/control-disabled': 'neutral-200', + 'border/default': 'neutral-500', + 'border/subtle': 'neutral-400', + 'border/strong': 'neutral-700', + 'border/divider': 'neutral-200', + 'border/focus': 'brand-600', + 'border/focus-inverse': 'brand-500', + 'action/primary/background': 'primary-500', + 'action/primary/background-hover': 'primary-600', + 'action/primary/text': 'base', + 'action/secondary/background': 'brand-600', + 'action/secondary/background-hover': 'brand-700', + 'action/secondary/text': 'base', + 'action/cta/background': 'cta-500', + 'action/cta/background-hover': 'cta-600', + 'action/cta/text': 'base', + 'feedback/error/text': 'error-foreground', + 'feedback/error/background': 'error-background', + 'feedback/error/border': 'error-foreground', + 'feedback/warning/text': 'warning-foreground', + 'feedback/warning/background': 'warning-background', + 'feedback/warning/border': 'warning-foreground', + 'feedback/success/text': 'success-foreground', + 'feedback/success/background': 'success-background', + 'feedback/success/border': 'success-foreground', + 'feedback/info/text': 'information-foreground', + 'feedback/info/background': 'information-background', + 'feedback/info/border': 'information-foreground', +}; + +export const SHADOW_ALPHAS = [5, 10, 12, 15, 20, 25, 30, 35, 40, 45, 60, 70, 85]; +/** The type ladder: slugs 100 to 900, body text at 200. Names are display names only. */ +const SIZE_NAMES = [ + 'Tiny', + 'Base', + 'Small', + 'Medium', + 'Large', + 'xLarge', + 'Huge', + 'Gigantic', + 'Colossal', +]; +/** Numeric slug for the nth step of a ladder that counts in hundreds (100, 200, ...). */ +const hundreds = (index: number) => String((index + 1) * 100); +/** The LightSpeed spacing ladder: the slug is the step, the name its T-shirt size. */ +export const SPACING_STEPS = [ + { slug: '5', name: 'XXS' }, + { slug: '10', name: 'XS' }, + { slug: '20', name: 'S' }, + { slug: '30', name: 'M' }, + { slug: '40', name: 'L' }, + { slug: '50', name: 'XL' }, + { slug: '60', name: 'XXL' }, + { slug: '70', name: 'XXXL' }, + { slug: '80', name: 'XXXXL' }, + { slug: '90', name: 'Gigantic' }, + { slug: '100', name: 'Colossal' }, +]; +const RADIUS_NAMES = ['Small', 'Base', 'Medium', 'Large', 'xLarge', 'Huge']; +const SHADOW_NAMES = ['xSmall', 'Small', 'Medium', 'Large', 'xLarge', 'Huge']; + +export interface ColourEvidence { + hex: string; + weight: number; + uses: Partial>; +} + +export interface Anchor { + family: Family; + hex: string; + step: RampStep; + source: 'observed' | 'assigned' | 'generated'; + evidence: string; +} + +export interface MatchRow { + value: string; + weight: number; + uses: string; + token: string; + distance: number; + match: 'exact' | 'near' | 'none'; +} + +export interface ContrastRow { + pair: string; + foreground: string; + background: string; + ratio: number; + required: number; + pass: boolean; +} + +export interface ScaleEntry { + name: string; + slug: string; + max: number; + min: number; + lineHeight?: number; +} + +export interface ShadowEffect { + type: 'DROP_SHADOW' | 'INNER_SHADOW'; + color: { r: number; g: number; b: number; a: number }; + offset: { x: number; y: number }; + radius: number; + spread: number; +} + +export interface ShadowEntry { + name: string; + slug: string; + css: string; + uses: number; + effects: ShadowEffect[]; +} + +export interface Proposal { + site: string; + generatedAt: string; + colour: { + primitives: Record; + anchors: Anchor[]; + semantic: Record; + overlay: string; + shadowAlphas: number[]; + }; + matches: MatchRow[]; + contrast: ContrastRow[]; + typography: { + families: { heading: string; body: string }; + sizes: ScaleEntry[]; + weights: Record; + }; + spacing: ScaleEntry[]; + radius: Array<{ name: string; slug: string; value: number }>; + shadows: ShadowEntry[]; + layout: { content?: number; wide?: number }; + breakpoints: { mobile: number; tablet: number; desktop: number }; + decisions: string[]; +} + +export interface ProposeOptions { + /** Force a family's anchor colour, for example { brand: '#8d621f' }. */ + assign?: Partial>; + /** Force the content and wide widths in px, for example { content: 768, wide: 1240 }. */ + layout?: { content?: number; wide?: number }; + now?: () => Date; +} + +/** Weighted mode of a list of values. */ +function mode(values: Array<{ value: T; weight?: number }>): T | undefined { + const counts = new Map(); + for (const { value, weight } of values) { + counts.set(value, (counts.get(value) ?? 0) + (weight ?? 1)); + } + let best: T | undefined; + let bestCount = -1; + for (const [value, count] of counts) { + if (count > bestCount) { + best = value; + bestCount = count; + } + } + return best; +} + +/** Fit test limits for site colours placed into ramps. See `fitSiteColours`. */ +const FIT_HUE_TOLERANCE = 25; +const FIT_MIN_CHROMA = 0.025; +const FIT_NEUTRAL_CHROMA = 0.04; +const FIT_LIGHTNESS_TOLERANCE = 0.04; + +export class TokenProposer { + private readonly ramps = new RampBuilder(); + private decisions: string[] = []; + + propose(styles: SiteStyles, options: ProposeOptions = {}): Proposal { + this.decisions = []; + const desktopWidth = Math.max(...styles.viewports); + const mobileWidth = Math.min(...styles.viewports); + const desktop = styles.captures.filter((c) => c.viewport === desktopWidth); + const mobile = styles.captures.filter((c) => c.viewport === mobileWidth); + const desktopSamples = desktop.flatMap((c) => c.samples.map((s) => ({ ...s, page: c.url }))); + const mobileByKey = new Map(); + for (const capture of mobile) { + for (const sample of capture.samples) { + mobileByKey.set(`${capture.url}|${sample.key}`, sample); + } + } + const pair = (s: ElementSample & { page: string }) => mobileByKey.get(`${s.page}|${s.key}`); + + const evidence = this.colourEvidence(desktopSamples); + const colour = this.proposeColour(evidence, options.assign ?? {}); + const matches = this.matchColours(evidence, colour.primitives); + const contrast = this.checkContrast(colour.primitives, colour.semantic); + const typography = this.proposeTypography(desktopSamples, pair); + const spacing = this.proposeSpacing(desktopSamples, pair); + const radius = this.proposeRadius(desktopSamples); + const shadows = this.proposeShadows(desktopSamples); + const layout = this.proposeLayout(desktopSamples, desktopWidth, desktop, options.layout); + const breakpoints = this.proposeBreakpoints(styles.captures); + + return { + site: styles.site, + generatedAt: (options.now ?? (() => new Date()))().toISOString(), + colour, + matches, + contrast, + typography, + spacing, + radius, + shadows, + layout, + breakpoints, + decisions: this.decisions, + }; + } + + /** Counts every opaque colour by where it is used. */ + colourEvidence(samples: ElementSample[]): ColourEvidence[] { + const byHex = new Map(); + const add = (value: string | undefined, use: string, weight: number) => { + const color = value ? Color.parse(value) : null; + if (!color || color.rgb.a < 0.05) { + return; + } + const hex = color.toHex(); + const entry = byHex.get(hex) ?? { hex, weight: 0, uses: {} }; + entry.weight += weight; + entry.uses[use] = (entry.uses[use] ?? 0) + 1; + byHex.set(hex, entry); + }; + for (const s of samples) { + add(s.color, `${s.role}-text`, 1); + add(s.background, `${s.role}-background`, s.role === 'section' ? 3 : 1); + add(s.border, `${s.role}-border`, 0.5); + } + return [...byHex.values()].sort((a, b) => b.weight - a.weight); + } + + proposeColour( + evidence: ColourEvidence[], + assign: Partial> + ): Proposal['colour'] { + const opaque = evidence.filter((e) => Color.parse(e.hex)!.isOpaque); + const isNeutral = (hex: string) => Color.parse(hex)!.toOklch().c < 0.025; + const lightness = (hex: string) => Color.parse(hex)!.toOklch().l; + const usage = (e: ColourEvidence, suffix: string) => + Object.entries(e.uses) + .filter(([use]) => use.endsWith(suffix)) + .reduce((total, [, n]) => total + (n ?? 0), 0); + + const base = + opaque.find((e) => isNeutral(e.hex) && lightness(e.hex) > 0.9 && usage(e, '-background') > 0) + ?.hex ?? '#ffffff'; + const contrast = + opaque.find((e) => lightness(e.hex) < 0.4 && (e.uses['body-text'] ?? 0) > 0)?.hex ?? + opaque.find((e) => lightness(e.hex) < 0.4 && usage(e, '-text') > 0)?.hex ?? + '#1a1a1a'; + if (base === '#ffffff' && !opaque.some((e) => e.hex === '#ffffff')) { + this.decisions.push('No light page background was found, so `base` defaults to #ffffff.'); + } + + // Group chromatic colours into clusters of near-identical values. + const clusters: ColourEvidence[] = []; + for (const e of opaque.filter((x) => !isNeutral(x.hex))) { + const color = Color.parse(e.hex)!; + const home = clusters.find((c) => Color.parse(c.hex)!.distance(color) < 6); + if (home) { + home.weight += e.weight; + for (const [use, n] of Object.entries(e.uses)) { + home.uses[use] = (home.uses[use] ?? 0) + (n ?? 0); + } + } else { + clusters.push({ hex: e.hex, weight: e.weight, uses: { ...e.uses } }); + } + } + clusters.sort((a, b) => b.weight - a.weight); + + const describe = (c: ColourEvidence) => + Object.entries(c.uses) + .sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0)) + .slice(0, 3) + .map(([use, n]) => `${use} ×${n}`) + .join(', '); + + const anchors: Anchor[] = []; + const taken = new Set(); + const pick = (family: Family, chooser: (c: ColourEvidence) => number, reason: string) => { + if (assign[family]) { + const hex = Color.parse(assign[family]!)?.toHex(); + if (!hex) { + throw new Error(`--assign ${family}=${assign[family]} is not a colour.`); + } + taken.add(hex); + anchors.push({ + family, + hex, + step: this.ramps.nearestStep(lightness(hex)), + source: 'assigned', + evidence: 'Assigned by the reviewer.', + }); + return; + } + const candidates = clusters + .filter((c) => !taken.has(c.hex)) + .map((c) => ({ c, score: chooser(c) })) + .filter((x) => x.score > 0) + .sort((a, b) => b.score - a.score); + const chosen = candidates[0]?.c; + if (chosen) { + taken.add(chosen.hex); + anchors.push({ + family, + hex: chosen.hex, + step: this.ramps.nearestStep(lightness(chosen.hex)), + source: 'observed', + evidence: `${reason}: ${describe(chosen)}`, + }); + return; + } + const ref = anchors[0] ? Color.parse(anchors[0].hex)!.toOklch() : { l: 0.55, c: 0.12, h: 30 }; + const offsets: Record = { brand: 0, primary: 120, cta: 200 }; + const generated = Color.fromOklch({ + l: 0.5, + c: Math.max(ref.c, 0.1), + h: (ref.h + offsets[family]) % 360, + }).toHex(); + anchors.push({ + family, + hex: generated, + step: 600, + source: 'generated', + evidence: 'No distinct colour on the site.', + }); + this.decisions.push( + `No site colour fits \`${family}\`; ${generated} was generated as a placeholder. Choose one.` + ); + }; + + const chroma = (hex: string) => Color.parse(hex)!.toOklch().c; + // The call to action is the most saturated colour that fills a button. + pick( + 'cta', + (c) => (usage(c, 'button-background') > 0 ? chroma(c.hex) : 0), + 'Most saturated button fill' + ); + // The brand colour dresses buttons and in-text links. + pick( + 'brand', + (c) => + usage(c, 'button-background') * 2 + + usage(c, 'button-border') + + usage(c, 'button-text') + + usage(c, 'link-text') * 2, + 'Most used on buttons and in-text links' + ); + pick('primary', (c) => c.weight, 'Next most used colour'); + + const primitives: Record = { base, contrast }; + for (const anchor of anchors) { + const ramp = this.ramps.build(anchor.hex); + anchor.step = ramp.anchorStep; + for (const step of RAMP_STEPS) { + primitives[`${anchor.family}-${step}`] = ramp.steps[step]; + } + } + + // Neutral ramp: the site's mid grey if it has one, else a grey tinted like its greys. + const neutrals = opaque.filter((e) => isNeutral(e.hex) && e.hex !== base && e.hex !== contrast); + const midGrey = neutrals + .filter((e) => Math.abs(lightness(e.hex) - 0.62) < 0.12) + .sort((a, b) => Math.abs(lightness(a.hex) - 0.62) - Math.abs(lightness(b.hex) - 0.62))[0]; + let neutralAnchor = midGrey?.hex; + if (!neutralAnchor) { + const tinted = neutrals.map((e) => Color.parse(e.hex)!.toOklch()).filter((o) => o.c > 0.003); + const hue = tinted.length ? tinted.reduce((t, o) => t + o.h, 0) / tinted.length : 60; + const chroma = tinted.length + ? Math.min(0.012, tinted.reduce((t, o) => t + o.c, 0) / tinted.length) + : 0.006; + neutralAnchor = Color.fromOklch({ l: 0.62, c: chroma, h: hue }).toHex(); + } + const neutral = this.ramps.build(neutralAnchor, { maxChroma: 0.02 }); + anchors.push({ + family: 'neutral', + hex: neutralAnchor, + step: neutral.anchorStep, + source: midGrey ? 'observed' : 'generated', + evidence: midGrey + ? `Mid grey used on the site: ${describe(midGrey)}` + : 'Tinted from the site greys.', + }); + for (const step of RAMP_STEPS) { + primitives[`neutral-${step}`] = neutral.steps[step]; + } + this.fitSiteColours(opaque, primitives, anchors, [base, contrast]); + Object.assign(primitives, SYSTEM_DEFAULTS); + + const shadowBase = Color.parse(primitives['neutral-900'])!.rgb; + const overlay = Color.fromRgb({ ...shadowBase, a: 0.25 }).toHex(); + + const semantic = this.proposeSemantic(evidence, primitives); + return { primitives, anchors, semantic, overlay, shadowAlphas: SHADOW_ALPHAS }; + } + + /** + * Replaces generated ramp steps with real site colours that fit the ramp. + * + * A site colour fits a family's ramp when all of these hold: + * 1. Hue: chromatic families need the same hue family as the anchor (within + * FIT_HUE_TOLERANCE degrees) and a chroma between 0.4x and 1.6x the anchor's, + * and at least 0.025. The neutral family needs chroma of 0.04 or less. + * 2. Lightness: it sits within FIT_LIGHTNESS_TOLERANCE of the target lightness + * of its nearest step, so it reads as that step. + * 3. Monotonic: it is lighter than the step after it and darker than the step + * before it, using the ramp's current values, so lightness still falls from + * 100 to 900. + * The anchor step is never replaced. Colours are handled heaviest first, each + * goes to the family whose nearest step is closest, and a step already claimed + * by a heavier colour is not taken again. Colours that fit nowhere keep being + * matched to the nearest token. + */ + fitSiteColours( + candidates: ColourEvidence[], + primitives: Record, + anchors: Anchor[], + exclude: string[] + ): void { + const skip = new Set([...exclude, ...anchors.map((a) => a.hex), ...Object.values(primitives)]); + const claimed = new Map(); + const lightnessOf = (hex: string) => Color.parse(hex)!.toOklch().l; + const ordered = [...candidates].sort((a, b) => b.weight - a.weight); + + for (const site of ordered) { + if (skip.has(site.hex)) { + continue; + } + const color = Color.parse(site.hex)!; + const o = color.toOklch(); + const step = this.ramps.nearestStep(o.l); + if (Math.abs(STEP_LIGHTNESS[step] - o.l) > FIT_LIGHTNESS_TOLERANCE) { + continue; + } + let best: { slug: string; family: string; distance: number } | undefined; + for (const anchor of anchors) { + const slug = `${anchor.family}-${step}`; + if (step === anchor.step || !this.fitsRamp(o, anchor)) { + continue; + } + if (!this.keepsRampMonotonic(anchor.family, step, o.l, primitives, lightnessOf)) { + continue; + } + const distance = color.distance(Color.parse(primitives[slug])!); + if (!best || distance < best.distance) { + best = { slug, family: anchor.family, distance }; + } + } + if (!best) { + continue; + } + const holder = claimed.get(best.slug); + if (holder) { + this.decisions.push( + `Site colour ${site.hex} also fits ${best.slug}, but ${holder} is used more, so ${best.slug} keeps ${holder}.` + ); + continue; + } + this.decisions.push( + `Site colour ${site.hex} replaced ${best.slug} (was ${primitives[best.slug]}).` + ); + primitives[best.slug] = site.hex; + claimed.set(best.slug, site.hex); + } + } + + /** Hue and chroma part of the fits test. */ + private fitsRamp(o: { l: number; c: number; h: number }, anchor: Anchor): boolean { + const a = Color.parse(anchor.hex)!.toOklch(); + if (anchor.family === 'neutral') { + // Any site grey fits, whatever its tint: the ramp should match the site's own greys. + return o.c <= FIT_NEUTRAL_CHROMA; + } + const hueGap = Math.min(Math.abs(o.h - a.h), 360 - Math.abs(o.h - a.h)); + return ( + o.c >= FIT_MIN_CHROMA && hueGap <= FIT_HUE_TOLERANCE && o.c >= a.c * 0.4 && o.c <= a.c * 1.6 + ); + } + + /** True when `lightness` sits strictly between the ramp's neighbours of `step`. */ + private keepsRampMonotonic( + family: string, + step: RampStep, + lightness: number, + primitives: Record, + lightnessOf: (hex: string) => number + ): boolean { + const index = RAMP_STEPS.indexOf(step); + const lighter = RAMP_STEPS[index - 1]; + const darker = RAMP_STEPS[index + 1]; + const above = lighter ? lightnessOf(primitives[`${family}-${lighter}`]) : Infinity; + const below = darker ? lightnessOf(primitives[`${family}-${darker}`]) : -Infinity; + return lightness < above && lightness > below; + } + + proposeSemantic( + evidence: ColourEvidence[], + primitives: Record + ): Proposal['colour']['semantic'] { + const semantic: Proposal['colour']['semantic'] = {}; + for (const [role, token] of Object.entries(SEMANTIC_DEFAULTS)) { + semantic[role] = { token, source: 'default' }; + } + const heaviest = (use: string, chromaticOnly = false) => + evidence + .filter( + (e) => + (e.uses[use] ?? 0) > 0 && + Color.parse(e.hex)!.isOpaque && + (!chromaticOnly || Color.parse(e.hex)!.toOklch().c >= 0.025) + ) + .sort((a, b) => (b.uses[use] ?? 0) - (a.uses[use] ?? 0))[0]; + const page = Color.parse(primitives.base)!; + const observe = (role: string, use: string, family?: string, chromaticOnly = false) => { + const found = heaviest(use, chromaticOnly) ?? (chromaticOnly ? heaviest(use) : undefined); + if (!found) { + return; + } + // A text colour that can't be read on the page surface comes from photos or dark bands. + if (role.startsWith('text/') && Color.parse(found.hex)!.contrast(page) < 3) { + this.decisions.push( + `\`${role}\` kept the default \`${semantic[role].token}\`: the site's most used ${use} colour (${found.hex}) is unreadable on \`base\`, so it probably sits on photos or dark sections.` + ); + return; + } + const token = this.nearestPrimitive(found.hex, primitives, family); + semantic[role] = { + token, + source: 'observed', + evidence: `${found.hex} (${use} ×${found.uses[use]})`, + }; + return token; + }; + + observe('text/default', 'body-text'); + // Prefer a coloured link: white or black links usually sit on photos or in menus. + observe('text/link', 'link-text', undefined, true); + if (!heaviest('link-text')) { + observe('text/link', 'nav-text', undefined, true); + } + const buttonBg = observe('action/primary/background', 'button-background'); + observe('action/primary/text', 'button-text'); + observe('border/default', 'input-border'); + if (buttonBg) { + semantic['action/primary/background-hover'] = { + token: this.darker(buttonBg), + source: 'observed', + evidence: `One step darker than ${buttonBg}.`, + }; + } + + const light = evidence.filter( + (e) => + (e.uses['section-background'] ?? 0) > 0 && + Color.parse(e.hex)!.isOpaque && + e.hex !== primitives.base && + Color.parse(e.hex)!.toOklch().l > 0.85 + )[0]; + if (light) { + semantic['surface/subtle'] = { + token: this.nearestPrimitive(light.hex, primitives), + source: 'observed', + evidence: `${light.hex} (section-background ×${light.uses['section-background']})`, + }; + } + const dark = evidence.filter( + (e) => + (e.uses['section-background'] ?? 0) > 0 && + Color.parse(e.hex)!.isOpaque && + Color.parse(e.hex)!.toOklch().l < 0.35 + )[0]; + if (dark) { + semantic['surface/inverse'] = { + token: this.nearestPrimitive(dark.hex, primitives), + source: 'observed', + evidence: `${dark.hex} (section-background ×${dark.uses['section-background']})`, + }; + } + return semantic; + } + + nearestPrimitive(hex: string, primitives: Record, family?: string): string { + const color = Color.parse(hex)!; + let best = 'contrast'; + let bestDistance = Infinity; + for (const [slug, value] of Object.entries(primitives)) { + if (family && !slug.startsWith(family)) { + continue; + } + const d = color.distance(Color.parse(value)!); + if (d < bestDistance) { + best = slug; + bestDistance = d; + } + } + return best; + } + + matchColours(evidence: ColourEvidence[], primitives: Record): MatchRow[] { + return evidence.slice(0, 40).map((e) => { + const token = this.nearestPrimitive(e.hex, primitives); + const distance = + Math.round(Color.parse(e.hex)!.distance(Color.parse(primitives[token])!) * 10) / 10; + return { + value: e.hex, + weight: Math.round(e.weight * 10) / 10, + uses: Object.entries(e.uses) + .sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0)) + .slice(0, 3) + .map(([use, n]) => `${use} ×${n}`) + .join(', '), + token, + distance, + match: distance < 0.5 ? 'exact' : distance < 6 ? 'near' : 'none', + }; + }); + } + + checkContrast( + primitives: Record, + semantic: Proposal['colour']['semantic'] + ): ContrastRow[] { + const resolve = (role: string) => { + const token = semantic[role]?.token ?? role; + return primitives[token]; + }; + const pairs: Array<[string, string, number]> = [ + ['text/default', 'surface/default', 4.5], + ['text/muted', 'surface/default', 4.5], + ['text/link', 'surface/default', 4.5], + ['text/link-hover', 'surface/default', 4.5], + ['text/placeholder', 'surface/default', 4.5], + ['text/default', 'surface/subtle', 4.5], + ['text/inverse', 'surface/inverse', 4.5], + ['action/primary/text', 'action/primary/background', 4.5], + ['action/primary/text', 'action/primary/background-hover', 4.5], + ['action/secondary/text', 'action/secondary/background', 4.5], + ['action/cta/text', 'action/cta/background', 4.5], + ['border/focus', 'surface/default', 3], + ['border/default', 'surface/default', 3], + ['feedback/error/text', 'surface/default', 4.5], + ['feedback/warning/text', 'surface/default', 4.5], + ['feedback/success/text', 'surface/default', 4.5], + ['feedback/info/text', 'surface/default', 4.5], + ]; + return pairs.map(([fg, bg, required]) => { + const foreground = resolve(fg); + const background = resolve(bg); + const ratio = + Math.round(Color.parse(foreground)!.contrast(Color.parse(background)!) * 100) / 100; + return { + pair: `${fg} on ${bg}`, + foreground, + background, + ratio, + required, + pass: ratio >= required, + }; + }); + } + + proposeTypography( + samples: Array, + pair: (s: ElementSample & { page: string }) => ElementSample | undefined + ): Proposal['typography'] { + const textRoles: Role[] = [ + 'body', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'button', + 'link', + 'nav', + 'input', + ]; + const text = samples.filter((s) => textRoles.includes(s.role) && s.fontSize); + const headings = text.filter((s) => /^h[1-3]$/.test(s.role)); + const body = text.filter((s) => s.role === 'body'); + const families = { + heading: + mode(headings.map((s) => ({ value: s.fontFamily ?? '' }))) || + mode(text.map((s) => ({ value: s.fontFamily ?? '' }))) || + 'serif', + body: mode(body.map((s) => ({ value: s.fontFamily ?? '' }))) || 'sans-serif', + }; + + const bodySize = mode(body.map((s) => ({ value: Math.round(s.fontSize!) }))) ?? 16; + const pairs = new Map(); + for (const s of text) { + const max = Math.round(s.fontSize!); + const mobileSize = pair(s)?.fontSize; + const entry = pairs.get(max) ?? { min: max, weight: 0, ratios: [] }; + entry.weight += /^h/.test(s.role) ? 3 : 1; + if (mobileSize) { + entry.min = Math.min(entry.min, Math.round(mobileSize)); + } + const ratio = s.lineHeight ? Math.round((s.lineHeight / s.fontSize!) * 100) / 100 : 0; + if (ratio >= 0.9 && ratio <= 2.5) { + entry.ratios.push(ratio); // Outside this range is usually an icon or a fixed-height box. + } + pairs.set(max, entry); + } + + const below = [...pairs.keys()] + .filter((v) => v < bodySize) + .sort((a, b) => pairs.get(b)!.weight - pairs.get(a)!.weight); + let above = [...pairs.keys()].filter((v) => v > bodySize).sort((a, b) => a - b); + if (below.length > 1) { + this.decisions.push( + `Sizes smaller than body text (${below.join(', ')}px) share the one Tiny slot; ${below[0]}px was kept.` + ); + } + const slots = SIZE_NAMES.length - 2; + while (above.length > slots) { + // Merge the two closest sizes, keeping the more used one. + let closest = 0; + for (let i = 1; i < above.length - 1; i++) { + if (above[i + 1] / above[i] < above[closest + 1] / above[closest]) { + closest = i; + } + } + const [a, b] = [above[closest], above[closest + 1]]; + const drop = pairs.get(a)!.weight >= pairs.get(b)!.weight ? b : a; + this.decisions.push( + `The ${drop}px size was merged into the nearest size to fit the ${SIZE_NAMES.length}-step scale.` + ); + above = above.filter((v) => v !== drop); + } + + const scale = [...(below.length ? [below[0]] : []), bodySize, ...above]; + const firstIndex = below.length ? 0 : 1; + const sizes: ScaleEntry[] = scale.map((max, i) => { + const entry = pairs.get(max) ?? { min: max, weight: 0, ratios: [] }; + const name = SIZE_NAMES[firstIndex + i]; + return { + name, + slug: hundreds(firstIndex + i), + max, + min: Math.min(entry.min, max), + lineHeight: mode(entry.ratios.map((value) => ({ value }))), + }; + }); + + const weights: Record = {}; + for (const role of textRoles) { + const weight = mode( + text.filter((s) => s.role === role && s.fontWeight).map((s) => ({ value: s.fontWeight! })) + ); + if (weight) { + weights[role] = weight; + } + } + return { families, sizes, weights }; + } + + proposeSpacing( + samples: Array, + pair: (s: ElementSample & { page: string }) => ElementSample | undefined + ): ScaleEntry[] { + const values: Array<{ max: number; min: number; weight: number }> = []; + for (const s of samples) { + const m = pair(s); + if (s.paddingBlock && ['section', 'surface'].includes(s.role)) { + values.push({ + max: Math.round(s.paddingBlock), + min: Math.round(m?.paddingBlock ?? s.paddingBlock), + weight: s.role === 'section' ? 2 : 1, + }); + } + if (s.gap) { + values.push({ max: Math.round(s.gap), min: Math.round(m?.gap ?? s.gap), weight: 1 }); + } + if (s.marginBlock && ['section', 'surface'].includes(s.role)) { + values.push({ + max: Math.round(s.marginBlock), + min: Math.round(m?.marginBlock ?? s.marginBlock), + weight: s.role === 'section' ? 2 : 1, + }); + } + } + values.sort((a, b) => a.max - b.max); + // Values under 8px are borders and hairline offsets, not layout spacing. + const layout = values.filter((v) => v.max >= 8); + + const clusters: Array<{ start: number; items: typeof values }> = []; + for (const v of layout) { + const last = clusters[clusters.length - 1]; + if (last && v.max <= last.start * 1.12 + 1) { + last.items.push(v); + } else { + clusters.push({ start: v.max, items: [v] }); + } + } + let kept = clusters + .map((c) => ({ + max: mode(c.items.map((i) => ({ value: i.max, weight: i.weight })))!, + min: mode(c.items.map((i) => ({ value: i.min, weight: i.weight })))!, + weight: c.items.reduce((t, i) => t + i.weight, 0), + })) + .filter((c) => c.weight >= 2); + if (kept.length > SPACING_STEPS.length) { + const byUse = [...kept].sort((a, b) => b.weight - a.weight); + const dropped = byUse.slice(SPACING_STEPS.length).sort((a, b) => a.max - b.max); + kept = byUse.slice(0, SPACING_STEPS.length).sort((a, b) => a.max - b.max); + this.decisions.push( + `${dropped.length} rarely used spacing values were left out of the scale: ${dropped.map((d) => `${d.max}px`).join(', ')}.` + ); + } + // Each value takes the ladder step nearest its desktop size, so 40px becomes + // L (slug 40). A taken step pushes the value up to the next free step. If that + // runs off the top of the ladder, values shift back down into free lower steps + // (starting at 5) instead of being dropped. At most the ladder's length is kept + // above, so every kept value always gets a step. + const last = SPACING_STEPS.length - 1; + const indexes: number[] = []; + for (const c of kept) { + const nearest = SPACING_STEPS.reduce( + (best, step, i) => + Math.abs(Number(step.slug) - c.max) < Math.abs(Number(SPACING_STEPS[best].slug) - c.max) + ? i + : best, + 0 + ); + indexes.push(Math.max(nearest, indexes.length ? indexes[indexes.length - 1] + 1 : 0)); + } + let shifted = false; + for (let i = indexes.length - 1; i >= 0; i--) { + const ceiling = i === indexes.length - 1 ? last : indexes[i + 1] - 1; + if (indexes[i] > ceiling) { + indexes[i] = ceiling; + shifted = true; + } + } + if (shifted) { + this.decisions.push( + 'Some spacing values moved down to free lower steps so the whole 5 to 100 ladder is used and none is dropped.' + ); + } + const steps: ScaleEntry[] = kept.map((c, i) => ({ + ...SPACING_STEPS[indexes[i]], + max: c.max, + min: Math.min(c.min, c.max), + })); + return [{ name: 'None', slug: 'none', max: 0, min: 0 }, ...steps]; + } + + proposeRadius(samples: ElementSample[]): Proposal['radius'] { + const counts = new Map(); + for (const s of samples) { + if (!s.radius) { + continue; + } + const value = s.radius.endsWith('%') ? 9999 : Math.round(parseFloat(s.radius)); + if (value > 0) { + counts.set(value >= 999 ? 9999 : value, (counts.get(value >= 999 ? 9999 : value) ?? 0) + 1); + } + } + const values = [...counts.entries()] + .filter(([v]) => v !== 9999) + .sort((a, b) => b[1] - a[1]) + .slice(0, RADIUS_NAMES.length) + .map(([v]) => v) + .sort((a, b) => a - b); + return [ + { name: 'None', slug: '0', value: 0 }, + ...values.map((value, i) => ({ name: RADIUS_NAMES[i], slug: hundreds(i), value })), + { name: 'Round', slug: '700', value: 9999 }, + ]; + } + + proposeShadows(samples: ElementSample[]): ShadowEntry[] { + const counts = new Map(); + for (const s of samples) { + if (s.shadow) { + counts.set(s.shadow, (counts.get(s.shadow) ?? 0) + 1); + } + } + const parsed = [...counts.entries()] + .map(([css, uses]) => ({ css, uses, effects: TokenProposer.parseShadow(css) })) + .filter((s) => s.effects.length) + .sort((a, b) => b.uses - a.uses) + .slice(0, SHADOW_NAMES.length) + .sort( + (a, b) => + a.effects.reduce((t, e) => t + e.radius, 0) - b.effects.reduce((t, e) => t + e.radius, 0) + ); + return parsed.map((s, i) => ({ name: SHADOW_NAMES[i], slug: hundreds(i), ...s })); + } + + /** Parses a computed box-shadow into effects. */ + static parseShadow(css: string): ShadowEffect[] { + const layers: string[] = []; + let depth = 0; + let current = ''; + for (const ch of css) { + if (ch === '(') depth++; + if (ch === ')') depth--; + if (ch === ',' && depth === 0) { + layers.push(current); + current = ''; + } else { + current += ch; + } + } + layers.push(current); + + return layers.flatMap((layer) => { + const colorMatch = layer.match(/rgba?\([^)]*\)|#[0-9a-f]{3,8}/i); + const color = colorMatch ? Color.parse(colorMatch[0]) : null; + const numbers = layer + .replace(colorMatch?.[0] ?? '', '') + .split(/\s+/) + .filter((t) => /^-?[\d.]+(px)?$/.test(t)) + .map((t) => parseFloat(t)); + if (!color || numbers.length < 2) { + return []; + } + const [x, y, blur = 0, spread = 0] = numbers; + const round = (n: number) => Math.round(n * 1000) / 1000; + return [ + { + type: /\binset\b/.test(layer) ? 'INNER_SHADOW' : 'DROP_SHADOW', + color: { + r: round(color.rgb.r), + g: round(color.rgb.g), + b: round(color.rgb.b), + a: round(color.rgb.a), + }, + offset: { x, y }, + radius: blur, + spread, + } as ShadowEffect, + ]; + }); + } + + /** + * Content width is the width of running text (`p` in the main column) on single posts + * and pages. Wide width is the widest repeated centred container. Either can be forced. + */ + proposeLayout( + samples: ElementSample[], + viewport: number, + captures: PageCapture[] = [], + override: { content?: number; wide?: number } = {} + ): Proposal['layout'] { + const counts = new Map(); + for (const s of samples) { + if (s.containerWidth && s.containerWidth < viewport - 16) { + const width = Math.round(s.containerWidth / 8) * 8; + counts.set(width, (counts.get(width) ?? 0) + 1); + } + } + const frequent = [...counts.entries()].filter(([, n]) => n >= 2).sort((a, b) => b[1] - a[1]); + const wide = override.wide ?? (frequent.length ? Math.max(...frequent.map(([w]) => w)) : undefined); + + let content = override.content; + if (content === undefined) { + const single = captures.filter((c) => c.pageKind === 'single'); + const fromSingles = single.flatMap((c) => c.textWidths ?? []); + const fromAny = captures.flatMap((c) => c.textWidths ?? []); + const widths = fromSingles.length ? fromSingles : fromAny; + if (widths.length) { + content = mode(widths.map((w) => ({ value: Math.round(w / 8) * 8 }))); + if (!fromSingles.length) { + this.decisions.push( + 'No single post or page was captured, so the content width was measured on listing pages and may be a card. Add a long text page, or set it with `--layout content=`.' + ); + } + } else if (frequent.length) { + const fallback = frequent.find(([w]) => w <= (wide ?? 0) * 0.8)?.[0]; + if (fallback) { + content = fallback; + this.decisions.push( + `No running text was found, so the content width ${fallback}px comes from the most common centred container. Check it, or set it with \`--layout content=\`.` + ); + } + } + } + if (content === undefined && wide === undefined) { + this.decisions.push( + 'No running text or repeated centred container was found; set the content and wide widths with `--layout content=,wide=`.' + ); + return {}; + } + if (content !== undefined && content < 480) { + this.decisions.push( + `The content width is ${content}px, under 480px, which is narrower than a readable text column. Confirm it, or set it with \`--layout content=\`.` + ); + } + return { + ...(content !== undefined ? { content } : {}), + ...(wide !== undefined ? { wide } : {}), + }; + } + + proposeBreakpoints(captures: PageCapture[]): Proposal['breakpoints'] { + const widths = captures.flatMap((c) => c.mediaWidths); + const pick = (low: number, high: number, fallback: number) => + mode(widths.filter((w) => w > low && w <= high).map((value) => ({ value }))) ?? fallback; + return { + mobile: pick(300, 600, 376), + tablet: pick(600, 1024, 768), + desktop: pick(1024, 1600, 1240), + }; + } + + private darker(token: string): string { + const match = token.match(/^(.*)-(\d00)$/); + if (!match || match[2] === '900') { + return token; + } + return `${match[1]}-${Number(match[2]) + 100}`; + } +} + +/** Writes the proposal as a Markdown report for approval. */ +export class ProposalReport { + render(p: Proposal): string { + const lines: string[] = []; + const table = (head: string[], rows: Array>) => { + lines.push(`| ${head.join(' | ')} |`, `| ${head.map(() => '---').join(' | ')} |`); + for (const row of rows) { + lines.push(`| ${row.join(' | ')} |`); + } + lines.push(''); + }; + const failing = p.contrast.filter((c) => !c.pass); + + lines.push( + `# Token proposal: ${p.site}`, + '', + `Generated ${p.generatedAt.slice(0, 10)}. Nothing is written to Figma or a theme until this is approved.`, + '' + ); + lines.push('## Summary', ''); + lines.push( + `- Colour anchors: ${p.colour.anchors.map((a) => `${a.family} ${a.hex} at ${a.step}`).join('; ')}` + ); + lines.push( + `- Live colours matched: ${p.matches.filter((m) => m.match === 'exact').length} exact, ${p.matches.filter((m) => m.match === 'near').length} near, ${p.matches.filter((m) => m.match === 'none').length} no match` + ); + lines.push( + `- Contrast: ${p.contrast.length - failing.length} of ${p.contrast.length} pairs pass${failing.length ? ` (failing: ${failing.map((f) => f.pair).join('; ')})` : ''}` + ); + lines.push( + `- Fonts: headings ${p.typography.families.heading}, body ${p.typography.families.body}`, + '' + ); + + lines.push('## Decisions for the reviewer', ''); + const decisions = [...p.decisions]; + for (const anchor of p.colour.anchors) { + if (anchor.source === 'observed') { + decisions.push( + `Confirm \`${anchor.family}\`: ${anchor.hex} at step ${anchor.step} (${anchor.evidence}).` + ); + } + } + lines.push(...(decisions.length ? decisions.map((d) => `- ${d}`) : ['- None.']), ''); + + lines.push('## Colour primitives (Theme - Colour)', ''); + table( + ['Family', ...RAMP_STEPS.map(String)], + (['brand', 'primary', 'cta', 'neutral'] as Family[]).map((f) => [ + f, + ...RAMP_STEPS.map((s) => `\`${p.colour.primitives[`${f}-${s}`]}\``), + ]) + ); + lines.push( + `\`base\` ${p.colour.primitives.base}, \`contrast\` ${p.colour.primitives.contrast}, overlay ${p.colour.overlay}. System colours use the LightSpeed defaults.`, + '' + ); + + lines.push('## Semantic tokens (Theme - Semantic)', ''); + table( + ['Role', 'Token', 'Value', 'Source'], + Object.entries(p.colour.semantic).map(([role, s]) => [ + `\`${role}\``, + `\`${s.token}\``, + p.colour.primitives[s.token] ?? p.colour.overlay, + s.source === 'observed' ? `site: ${s.evidence}` : 'default', + ]) + ); + + lines.push('## Live colours to tokens', ''); + table( + ['Live value', 'Used on', 'Token', 'Distance', 'Match'], + p.matches.map((m) => [m.value, m.uses, `\`${m.token}\``, m.distance, m.match]) + ); + + lines.push('## Contrast (WCAG 2.2)', ''); + table( + ['Pair', 'Ratio', 'Needs', 'Result'], + p.contrast.map((c) => [c.pair, c.ratio, `${c.required}:1`, c.pass ? 'pass' : '**fail**']) + ); + + lines.push('## Typography (Theme - Typography)', ''); + table( + ['Size', 'Slug', 'Desktop (Max)', 'Mobile (Min)', 'Line height'], + p.typography.sizes.map((s) => [ + s.name, + `\`${s.slug}\``, + `${s.max}px`, + `${s.min}px`, + s.lineHeight ?? '-', + ]) + ); + lines.push( + `Weights by role: ${ + Object.entries(p.typography.weights) + .map(([r, w]) => `${r} ${w}`) + .join(', ') || 'none found' + }.`, + '' + ); + + lines.push('## Spacing (Theme - Spacing)', ''); + table( + ['Name', 'Slug', 'Max', 'Min'], + p.spacing.map((s) => [s.name, `\`${s.slug}\``, `${s.max}px`, `${s.min}px`]) + ); + + lines.push('## Radius, shadows and layout', ''); + table( + ['Radius', 'Slug', 'Value'], + p.radius.map((r) => [r.name, `\`${r.slug}\``, `${r.value}px`]) + ); + table( + ['Shadow', 'Slug', 'Uses', 'CSS'], + p.shadows.map((s) => [s.name, `\`${s.slug}\``, s.uses, `\`${s.css}\``]) + ); + lines.push( + `Layout: content ${p.layout.content ?? '?'}px, wide ${p.layout.wide ?? '?'}px. Breakpoints: mobile ${p.breakpoints.mobile}px, tablet ${p.breakpoints.tablet}px, desktop ${p.breakpoints.desktop}px.`, + '' + ); + return `${lines.join('\n')}\n`; + } +} + +export interface ProposeCliIo { + readFile: (path: string) => string; + writeFile: (path: string, content: string) => void; + stdout: (text: string) => void; + stderr: (text: string) => void; +} + +export function runProposeCli(argv: string[], io: ProposeCliIo): number { + let input: string | undefined; + let out = 'proposal.json'; + let report: string | undefined; + const assign: Partial> = {}; + const layout: { content?: number; wide?: number } = {}; + + try { + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + const next = () => { + const value = argv[++i]; + if (value === undefined) { + throw new Error(`${arg} needs a value.`); + } + return value; + }; + if (arg === '--help' || arg === '-h') { + io.stdout( + 'Usage: propose-tokens [--out proposal.json] [--report proposal.md] [--assign brand=#hex,primary=#hex,cta=#hex] [--layout content=,wide=]\n' + ); + return 0; + } else if (arg === '--out') { + out = next(); + } else if (arg === '--report') { + report = next(); + } else if (arg === '--assign') { + for (const part of next().split(',')) { + const [family, hex] = part.split('='); + if (!CHROMATIC_FAMILIES.includes(family as Family) || !hex) { + throw new Error(`--assign takes brand, primary or cta, for example brand=#8d621f.`); + } + assign[family as Family] = hex; + } + } else if (arg === '--layout') { + for (const part of next().split(',')) { + const [key, value] = part.split('='); + const px = Number(value); + if (!['content', 'wide'].includes(key) || !Number.isFinite(px) || px <= 0) { + throw new Error('--layout takes content and wide in px, for example content=768,wide=1240.'); + } + layout[key as 'content' | 'wide'] = Math.round(px); + } + } else if (arg.startsWith('--')) { + throw new Error(`Unknown option ${arg}.`); + } else { + input = arg; + } + } + if (!input) { + throw new Error('Pass the path to site-styles.json from crawl-site-styles.'); + } + const styles = JSON.parse(io.readFile(input)) as SiteStyles; + if (!Array.isArray(styles.captures) || !styles.captures.length) { + throw new Error('The styles file has no captures.'); + } + const proposal = new TokenProposer().propose(styles, { assign, layout }); + io.writeFile(out, `${JSON.stringify(proposal, null, 2)}\n`); + if (report) { + io.writeFile(report, new ProposalReport().render(proposal)); + } + io.stdout( + `Wrote ${out}${report ? ` and ${report}` : ''}. ${proposal.decisions.length} decisions need review.\n` + ); + return 0; + } catch (error) { + io.stderr(`propose-tokens: ${(error as Error).message}\n`); + return 1; + } +} + +/* istanbul ignore next -- thin CLI entry point */ +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exitCode = runProposeCli(process.argv.slice(2), { + readFile: (path) => readFileSync(path, 'utf8'), + writeFile: (path, content) => writeFileSync(path, content), + stdout: (text) => process.stdout.write(text), + stderr: (text) => process.stderr.write(text), + }); +} From eab237ef0edcca40fe691e2de06b9e0cccc20fbe Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 14:30:04 +0200 Subject: [PATCH 04/31] fix(site-tokens): clean font family names and output the four font roles Names drop weight and style suffixes, turn underscores into spaces and are title-cased; the exact CSS stack is kept in the variable description. The proposal now has heading, body, accent and monospace, each marked live or default. figma-to-block-theme uses a declared stack as the fontFamily. Fixes GIT-2761 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../references/tokens-typography.md | 5 +- .../figma-variables-to-theme-json.test.ts | 31 ++++ .../scripts/figma-variables-to-theme-json.ts | 19 ++- .../references/proposal-review.md | 2 +- .../references/target-structure.md | 31 ++-- .../__tests__/crawl-site-styles.test.ts | 1 + .../scripts/__tests__/fixtures.ts | 36 ++++- .../scripts/__tests__/propose-tokens.test.ts | 74 ++++++++- .../__tests__/write-token-export.test.ts | 9 ++ .../scripts/crawl-site-styles.ts | 3 + .../scripts/propose-tokens.ts | 141 ++++++++++++++++-- .../scripts/write-token-export.ts | 46 +++--- 13 files changed, 349 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e5861d29e..08b86486b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body`, `accent` and `monospace` roles, marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) - **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text on single posts and pages, takes `--layout content=,wide=` to override either width, and asks the reviewer to confirm a content width under 480px. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) - **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) - **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) diff --git a/skills/figma-to-block-theme/references/tokens-typography.md b/skills/figma-to-block-theme/references/tokens-typography.md index 128ce19642..048c4f2a49 100644 --- a/skills/figma-to-block-theme/references/tokens-typography.md +++ b/skills/figma-to-block-theme/references/tokens-typography.md @@ -19,10 +19,11 @@ After replacing the sizes, update every reference in `styles`, `styles.blocks`, ## Font families -Variables whose code syntax is `--wp--preset--font-family--` (usually `heading` and `body`) become `{ slug, name, fontFamily }`: +Variables whose code syntax is `--wp--preset--font-family--` (`heading`, `body`, `accent` and `monospace`) become `{ slug, name, fontFamily }`: - `name` is the font name (for example "Nunito Sans"), not the slug. -- `fontFamily` quotes names that contain spaces and adds a fallback: `sans-serif` by default, or `--font-fallback serif` for serif families. Confirm the fallback with the user. +- If the variable description holds a `CSS stack: ` line (written by `site-to-design-tokens`) and its first family is the font named by the value, `fontFamily` is that exact stack. +- Otherwise `fontFamily` quotes names that contain spaces and adds a fallback: `sans-serif` by default, or `--font-fallback serif` for serif families. Confirm the fallback with the user. ### Font files diff --git a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts index ffdc26e3e6..c7279f080b 100644 --- a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts +++ b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts @@ -391,6 +391,37 @@ describe('FigmaVariablesMapper', () => { ); }); + it('keeps the exact CSS stack declared in a font variable description', () => { + const font = (value: string, description?: string) => + new FigmaVariablesMapper().map({ + collections: [ + { + name: 'Typography', + modes: [{ id: 'm', name: 'Value' }], + variables: [ + { + id: 'f', + name: 'Font-Families/Primary', + type: 'STRING', + codeSyntax: { WEB: 'var(--wp--preset--font-family--heading)' }, + description, + valuesByMode: { m: value }, + }, + ], + }, + ], + } as never); + const stack = (mapped: ReturnType) => + (mapped.theme.settings as Json).typography.fontFamilies[0].fontFamily; + const description = 'Headings (live). CSS stack: moret, Georgia, serif'; + + expect(stack(font('Moret', description))).toBe('moret, Georgia, serif'); + // A stack for another font is ignored. + expect(stack(font('Lora', description))).toBe('Lora, sans-serif'); + expect(stack(font('Moret'))).toBe('Moret, sans-serif'); + expect(stack(font('Moret', 'Headings only'))).toBe('Moret, sans-serif'); + }); + it('warns when a sizing ramp is out of order', () => { const mapped = new FigmaVariablesMapper().map({ collections: [ diff --git a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts index 656412354f..e618c7a7ea 100644 --- a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts +++ b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts @@ -38,6 +38,8 @@ export interface ExportedVariable { name: string; type: 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'; codeSyntax?: { WEB?: string }; + /** A font family variable may carry its exact stack as `CSS stack: `. */ + description?: string; valuesByMode: Record; } @@ -356,7 +358,7 @@ export class FigmaVariablesMapper { return { slug: target.slug, name: value, - fontFamily: this.fontStack(value), + fontFamily: this.declaredStack(variable, value) ?? this.fontStack(value), }; case 'border-radius': if (typeof value !== 'number') { @@ -553,6 +555,21 @@ export class FigmaVariablesMapper { return (variations[this.slugify(modeName)] ??= { title: modeName, settings: {} }); } + /** + * The exact CSS stack from a `CSS stack: ...` line in the variable description, used + * only when its first family is the font the mode's value names (other modes differ). + */ + private declaredStack(variable: ExportedVariable, name: string): string | undefined { + const stack = variable.description?.match(/CSS stack:\s*(.+)$/m)?.[1].trim(); + if (!stack) { + return undefined; + } + const plain = (text: string) => text.toLowerCase().replace(/[^a-z0-9]/g, ''); + const first = plain(stack.split(',')[0]); + const wanted = plain(name); + return first.startsWith(wanted) || wanted.startsWith(first) ? stack : undefined; + } + private fontStack(family: string): string { const quoted = /\s/.test(family) ? `"${family}"` : family; return `${quoted}, ${this.options.fontFallback ?? 'sans-serif'}`; diff --git a/skills/site-to-design-tokens/references/proposal-review.md b/skills/site-to-design-tokens/references/proposal-review.md index e341cd92d4..87f579dc86 100644 --- a/skills/site-to-design-tokens/references/proposal-review.md +++ b/skills/site-to-design-tokens/references/proposal-review.md @@ -44,5 +44,5 @@ Check each scale against the site at both widths: - The body text size should be `Base`, slug `200`. - Heading sizes should shrink on mobile. - Section spacing should reflect what the eye sees. Sites that space sections with margins on unstyled wrappers can produce a smaller scale than the design intends, so say so and let the reviewer set the larger steps. -- Font names come from the site's CSS (for example a web font alias such as `argesta_displayregular`). Ask the reviewer for the licensed family name and its fallback. +- Font names are cleaned from the site's CSS (`argesta_displayregular` becomes `Argesta Display`) and the exact CSS stack is kept. The report marks each of the four roles as live or default. Check the cleaned names, the `accent` default (the heading font when the site has no third family) and the fallbacks with the reviewer. - **Content width** comes from the width of running text (`p` elements with 80 or more characters in the main column) on single posts and pages, not from cards or wrappers. Include at least one long text page in the crawl. If the report says the width came from listing pages, or is under 480px, confirm it with the reviewer. Override either width with `--layout content=,wide=`. diff --git a/skills/site-to-design-tokens/references/target-structure.md b/skills/site-to-design-tokens/references/target-structure.md index a4a014c811..7bffdcdf2e 100644 --- a/skills/site-to-design-tokens/references/target-structure.md +++ b/skills/site-to-design-tokens/references/target-structure.md @@ -4,15 +4,15 @@ The proposal and the Figma script follow the TSP design system file (The Safari ## Collections -| Collection | Modes | Holds | Code syntax | -| ------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Theme - Colour | Value | Primitives: `Theme/base`, `Theme/contrast`, `brand/100` … `900`, `primary/…`, `cta/…`, `neutral/…`, `system//`, `custom/overlay`, `shadow/` | `--wp--preset--color--`; overlay and shadows `--wp--custom--color--…` | -| Theme - Semantic | Value | Aliases of the primitives, by role | `--wp--custom--color----` | -| Theme - Typography | Max, Min | `Sizes/`, `Font-Families/Primary` (headings) and `Secondary` (body), `Line-Heights/`, `Weights/` | `--wp--preset--font-size--` (`100` … `900`), `--wp--preset--font-family--heading` and `body`, `--wp--custom--line-height--`, `--wp--custom--font-weight--` | -| Theme - Spacing | Max, Min | `Padding/None`, `Padding/XXS`, `Padding/XS` … `Padding/Colossal` | `--wp--preset--spacing--` (`5` … `100`) | -| Theme - Radius | Mode 1 | `Radius None`, `Small`, `Base` … `Round` | `--wp--preset--border-radius--` | -| Theme - Layout | Mode 1 | `Desktop/Desktop Content Width`, `Desktop/Desktop Wide Width` | `--wp--custom--layout--content-size` and `wide-size` | -| Theme - Breakpoints | Mode 1 | `Desktop`, `Tablet`, `Mobile` | `--wp--custom--breakpoint--` | +| Collection | Modes | Holds | Code syntax | +| ------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Theme - Colour | Value | Primitives: `Theme/base`, `Theme/contrast`, `brand/100` … `900`, `primary/…`, `cta/…`, `neutral/…`, `system//`, `custom/overlay`, `shadow/` | `--wp--preset--color--`; overlay and shadows `--wp--custom--color--…` | +| Theme - Semantic | Value | Aliases of the primitives, by role | `--wp--custom--color----` | +| Theme - Typography | Max, Min | `Sizes/`, `Font-Families/Primary` (heading), `Secondary` (body), `Tertiary` (accent) and `Monospace`, `Line-Heights/`, `Weights/` | `--wp--preset--font-size--` (`100` … `900`), `--wp--preset--font-family--heading`, `body`, `accent` and `monospace`, `--wp--custom--line-height--`, `--wp--custom--font-weight--` | +| Theme - Spacing | Max, Min | `Padding/None`, `Padding/XXS`, `Padding/XS` … `Padding/Colossal` | `--wp--preset--spacing--` (`5` … `100`) | +| Theme - Radius | Mode 1 | `Radius None`, `Small`, `Base` … `Round` | `--wp--preset--border-radius--` | +| Theme - Layout | Mode 1 | `Desktop/Desktop Content Width`, `Desktop/Desktop Wide Width` | `--wp--custom--layout--content-size` and `wide-size` | +| Theme - Breakpoints | Mode 1 | `Desktop`, `Tablet`, `Mobile` | `--wp--custom--breakpoint--` | Shadows are effect styles named `LSX/`. Each one's description holds its slug, for example `theme.json shadow preset "200": var(--wp--preset--shadow--200).` @@ -38,6 +38,19 @@ Type sizes, radius and shadows use numeric slugs, the same as the block theme sc - Radius, slugs `0` to `700`: `None` (0), `Small` (100), `Base`, `Medium`, `Large`, `xLarge`, `Huge` (600), `Round` (700, 9999px). Measured values fill 100 upward in order. - Shadows, slugs `100` to `600`: `xSmall`, `Small`, `Medium`, `Large`, `xLarge`, `Huge`, ordered by strength (blur radius), so `100` is the softest. +## Font families + +There are four role slugs, `heading`, `body`, `accent` and `monospace`. The slug is the role. The variable value and the `theme.json` name are the real font, cleaned from the CSS name: weight and style suffixes (`regular`, `bold`, `italic`) are dropped, underscores become spaces and lower-case words are title-cased, so `argesta_displayregular` becomes `Argesta Display`. The variable description keeps the exact CSS stack (`CSS stack: ...`), and `figma-to-block-theme` uses it as the `fontFamily`. + +| Role | Live | Default | +| ----------- | ---------------------------------------------- | ---------------------------------------------------- | +| `heading` | The most used family on `h1` to `h3` | Generic serif | +| `body` | The most used family on body text | Generic sans-serif | +| `accent` | The next most used family, if there is a third | The heading font, flagged for the reviewer | +| `monospace` | A family whose stack ends in `monospace` | `ui-monospace, SFMono-Regular, Menlo, Consolas, ...` | + +The report lists each role as live or default. + ## Colour families | Family | What it is on the live site | diff --git a/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts b/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts index 01d2cdd80a..aa732cf781 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts @@ -34,6 +34,7 @@ describe('collectPageStyles', () => { expect(byRole('h1')[0]).toMatchObject({ color: 'rgb(38, 36, 35)', fontFamily: 'Moret', + fontStack: '"Moret", serif', fontSize: 60, fontWeight: 400, lineHeight: 72, diff --git a/skills/site-to-design-tokens/scripts/__tests__/fixtures.ts b/skills/site-to-design-tokens/scripts/__tests__/fixtures.ts index 4655af4ba9..7ad88b2599 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/fixtures.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/fixtures.ts @@ -19,7 +19,8 @@ function samples(desktop: boolean): ElementSample[] { { role, color: rgb('#262423'), - fontFamily: 'Moret', + fontFamily: 'moret', + fontStack: 'moret, Georgia, serif', fontSize: desktop ? max : min, fontWeight: 400, lineHeight: (desktop ? max : min) * 1.2, @@ -33,6 +34,7 @@ function samples(desktop: boolean): ElementSample[] { role: 'body', color: rgb('#262423'), fontFamily: 'Lora', + fontStack: 'Lora, serif', fontSize: 16, fontWeight: 400, lineHeight: 24, @@ -45,6 +47,7 @@ function samples(desktop: boolean): ElementSample[] { role: 'body', color: rgb('#68645f'), fontFamily: 'Lora', + fontStack: 'Lora, serif', fontSize: 12, fontWeight: 400, lineHeight: 18, @@ -57,6 +60,7 @@ function samples(desktop: boolean): ElementSample[] { role: 'body', color: rgb('#68645f'), fontFamily: 'Lora', + fontStack: 'Lora, serif', fontSize: 14, fontWeight: 400, lineHeight: 20, @@ -69,6 +73,7 @@ function samples(desktop: boolean): ElementSample[] { role: 'link', color: rgb('#8d621f'), fontFamily: 'Lora', + fontStack: 'Lora, serif', fontSize: 16, fontWeight: 400, lineHeight: 24, @@ -82,6 +87,7 @@ function samples(desktop: boolean): ElementSample[] { color: rgb('#ffffff'), background: rgb('#565b3d'), fontFamily: 'Lora', + fontStack: 'Lora, serif', fontSize: 16, fontWeight: 600, lineHeight: 24, @@ -99,6 +105,7 @@ function samples(desktop: boolean): ElementSample[] { color: rgb('#ffffff'), background: rgb('#a31700'), fontFamily: 'Lora', + fontStack: 'Lora, serif', fontSize: 16, fontWeight: 600, lineHeight: 24, @@ -113,6 +120,7 @@ function samples(desktop: boolean): ElementSample[] { color: rgb('#262423'), border: rgb('#8a8580'), fontFamily: 'Lora', + fontStack: 'Lora, serif', fontSize: 16, fontWeight: 400, lineHeight: 24, @@ -131,6 +139,32 @@ function samples(desktop: boolean): ElementSample[] { }, 'avatar' ); + add( + 4, + { + role: 'body', + color: rgb('#262423'), + fontFamily: 'caveat_regular', + fontStack: 'caveat_regular, cursive', + fontSize: 16, + fontWeight: 400, + lineHeight: 24, + }, + 'accent' + ); + add( + 2, + { + role: 'body', + color: rgb('#262423'), + fontFamily: 'Courier New', + fontStack: '"Courier New", monospace', + fontSize: 16, + fontWeight: 400, + lineHeight: 24, + }, + 'code' + ); heading('h1', 60, 36); heading('h2', 48, 32); heading('h3', 40, 24); diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index d3c6e804fa..d558fd6e32 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -1,4 +1,11 @@ -import { ProposalReport, runProposeCli, SEMANTIC_DEFAULTS, TokenProposer } from '../propose-tokens'; +import { + cleanFontName, + MONOSPACE_STACK, + ProposalReport, + runProposeCli, + SEMANTIC_DEFAULTS, + TokenProposer, +} from '../propose-tokens'; import { Color, RAMP_STEPS, RampBuilder } from '../lib/color'; import { tspLikeStyles } from './fixtures'; @@ -64,7 +71,17 @@ describe('TokenProposer on a TSP-like site', () => { it('builds the type scale with the body size at slug 200 (Base) and mobile minimums', () => { const sizes = proposal.typography.sizes; - expect(proposal.typography.families).toEqual({ heading: 'Moret', body: 'Lora' }); + expect(proposal.typography.families).toEqual({ + heading: { name: 'Moret', stack: 'moret, Georgia, serif', source: 'live', raw: 'moret' }, + body: { name: 'Lora', stack: 'Lora, serif', source: 'live' }, + accent: { + name: 'Caveat', + stack: 'caveat_regular, cursive', + source: 'live', + raw: 'caveat_regular', + }, + monospace: { name: 'Courier New', stack: '"Courier New", monospace', source: 'live' }, + }); expect(sizes.map((s) => s.name)).toEqual([ 'Tiny', 'Base', @@ -327,6 +344,59 @@ describe('ProposalReport', () => { }); }); +describe('cleanFontName', () => { + it.each([ + ['argesta_displayregular', 'Argesta Display'], + ['Moret', 'Moret'], + ['open_sans_bold', 'Open Sans'], + ['"Playfair Display Italic"', 'Playfair Display'], + ['DM Sans', 'DM Sans'], + ['bold', 'Bold'], + ['lora', 'Lora'], + ])('turns %s into %s', (raw, clean) => { + expect(cleanFontName(raw)).toBe(clean); + }); +}); + +describe('TokenProposer font roles', () => { + it('defaults the roles the site does not show and records them', () => { + const proposer = new TokenProposer(); + const sample = (role: string, fontFamily: string, fontStack: string) => + ({ key: `${role}:0`, page: '/', role, fontSize: 16, fontFamily, fontStack }) as never; + const roles = ['h1', 'body']; + const families = proposer.proposeFamilies( + [sample('h1', 'Moret', 'Moret, serif'), sample('body', 'Lora', 'Lora, serif')], + roles + ); + expect(families.accent).toMatchObject({ name: 'Moret', source: 'default' }); + expect(families.monospace).toEqual({ + name: 'Monospace', + stack: MONOSPACE_STACK, + source: 'default', + }); + expect(proposer['decisions'].join(' ')).toContain('uses no third font'); + const empty = new TokenProposer().proposeFamilies([], roles); + expect(empty.heading).toMatchObject({ stack: 'serif', source: 'default' }); + expect(empty.body).toMatchObject({ stack: 'sans-serif', source: 'default' }); + }); + + it('falls back to the font name when the crawl has no stack', () => { + const families = new TokenProposer().proposeFamilies( + [{ key: 'h:0', page: '/', role: 'h1', fontSize: 40, fontFamily: 'Moret' } as never], + ['h1'] + ); + expect(families.heading).toEqual({ name: 'Moret', stack: 'Moret', source: 'live' }); + }); + + it('lists every role in the report', () => { + const report = new ProposalReport().render( + new TokenProposer().propose(tspLikeStyles(), { now }) + ); + expect(report).toContain('`heading`: Moret (live, CSS name `moret`)'); + expect(report).toContain('`monospace`: Courier New (live)'); + }); +}); + describe('TokenProposer.proposeLayout', () => { const capture = (kind: 'single' | 'listing', textWidths: number[]) => ({ diff --git a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts index d65ef3b572..3f95a5516a 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts @@ -83,7 +83,16 @@ describe('TokenPlanBuilder', () => { expect(typography.find((v) => v.name === 'Font-Families/Primary')).toMatchObject({ codeSyntax: 'var(--wp--preset--font-family--heading)', values: { Max: 'Moret' }, + description: 'Headings (live). CSS stack: moret, Georgia, serif', }); + expect( + typography.filter((v) => v.name.startsWith('Font-Families/')).map((v) => v.codeSyntax) + ).toEqual([ + 'var(--wp--preset--font-family--heading)', + 'var(--wp--preset--font-family--body)', + 'var(--wp--preset--font-family--accent)', + 'var(--wp--preset--font-family--monospace)', + ]); expect( collection('Theme - Spacing').variables.find((v) => v.name === 'Padding/Colossal')!.values ).toEqual({ Max: 100, Min: 72 }); diff --git a/skills/site-to-design-tokens/scripts/crawl-site-styles.ts b/skills/site-to-design-tokens/scripts/crawl-site-styles.ts index da06da3d3f..0cd5cd5365 100644 --- a/skills/site-to-design-tokens/scripts/crawl-site-styles.ts +++ b/skills/site-to-design-tokens/scripts/crawl-site-styles.ts @@ -38,6 +38,8 @@ export interface ElementSample { background?: string; border?: string; fontFamily?: string; + /** The full computed font-family stack, exactly as the CSS writes it. */ + fontStack?: string; fontSize?: number; fontWeight?: number; lineHeight?: number; @@ -181,6 +183,7 @@ export function collectPageStyles(options: CollectOptions = {}): CollectedPage { if (role && role !== 'section' && role !== 'surface') { sample.color = style.color; sample.fontFamily = style.fontFamily.split(',')[0].replace(/["']/g, '').trim(); + sample.fontStack = style.fontFamily; sample.fontSize = px(style.fontSize); sample.fontWeight = Number(style.fontWeight) || undefined; sample.lineHeight = px(style.lineHeight); diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 4d68119007..08934ead7f 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -177,7 +177,7 @@ export interface Proposal { matches: MatchRow[]; contrast: ContrastRow[]; typography: { - families: { heading: string; body: string }; + families: Record; sizes: ScaleEntry[]; weights: Record; }; @@ -189,6 +189,44 @@ export interface Proposal { decisions: string[]; } +export type FontRoleSlug = 'heading' | 'body' | 'accent' | 'monospace'; + +/** One font family role. `name` is the clean display name, `stack` the CSS stack. */ +export interface FontRole { + name: string; + stack: string; + source: 'live' | 'default'; + /** The name as the site's CSS writes it, when it differs from `name`. */ + raw?: string; +} + +export const MONOSPACE_STACK = + 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace'; +const STYLE_SUFFIX = + /(?:extralight|ultralight|semibold|demibold|extrabold|ultrabold|regular|italic|oblique|medium|light|bold|black|heavy|thin|book|roman)$/i; + +/** + * Cleans a raw `@font-face` family name: drops weight and style suffixes such as + * `regular` or `bold`, turns underscores into spaces and title-cases lower-case words. + * `argesta_displayregular` becomes `Argesta Display`. Mixed-case words (`DM`) are kept. + */ +export function cleanFontName(raw: string): string { + let name = raw.replace(/["']/g, '').replace(/_/g, ' ').replace(/\s+/g, ' ').trim(); + for (let i = 0; i < 3; i++) { + const stripped = name.replace(STYLE_SUFFIX, '').trim(); + if (stripped === name || stripped.length < 3) { + break; + } + name = stripped; + } + return name + .split(' ') + .map((word) => + word === word.toLowerCase() ? word.charAt(0).toUpperCase() + word.slice(1) : word + ) + .join(' '); +} + export interface ProposeOptions { /** Force a family's anchor colour, for example { brand: '#8d621f' }. */ assign?: Partial>; @@ -736,15 +774,8 @@ export class TokenProposer { 'input', ]; const text = samples.filter((s) => textRoles.includes(s.role) && s.fontSize); - const headings = text.filter((s) => /^h[1-3]$/.test(s.role)); const body = text.filter((s) => s.role === 'body'); - const families = { - heading: - mode(headings.map((s) => ({ value: s.fontFamily ?? '' }))) || - mode(text.map((s) => ({ value: s.fontFamily ?? '' }))) || - 'serif', - body: mode(body.map((s) => ({ value: s.fontFamily ?? '' }))) || 'sans-serif', - }; + const families = this.proposeFamilies(samples, textRoles); const bodySize = mode(body.map((s) => ({ value: Math.round(s.fontSize!) }))) ?? 16; const pairs = new Map(); @@ -815,6 +846,81 @@ export class TokenProposer { return { families, sizes, weights }; } + /** + * Heading and body come from the live site. Accent is the next most used family when + * the site has a third one. Monospace is live only where the CSS uses a monospace stack. + * Roles with no live evidence get a documented default, and the report says so. + */ + proposeFamilies( + samples: Array, + textRoles: string[] + ): Record { + const text = samples.filter((s) => textRoles.includes(s.role) && s.fontFamily); + const isMono = (s: ElementSample) => + /\bmonospace\b/i.test(s.fontStack ?? '') || + /^(courier|consolas|menlo|monaco|sf mono|roboto mono|fira (code|mono)|source code)/i.test( + s.fontFamily ?? '' + ); + const proseText = text.filter((s) => !isMono(s)); + const stackFor = (raw: string) => + mode( + text + .filter((s) => s.fontFamily === raw && s.fontStack) + .map((s) => ({ value: s.fontStack! })) + ) ?? raw; + const role = (raw: string): FontRole => { + const name = cleanFontName(raw); + return { + name, + stack: stackFor(raw), + source: 'live', + ...(name !== raw ? { raw } : {}), + }; + }; + const headings = proseText.filter((s) => /^h[1-3]$/.test(s.role)); + const body = proseText.filter((s) => s.role === 'body'); + const headingRaw = + mode(headings.map((s) => ({ value: s.fontFamily! }))) || + mode(proseText.map((s) => ({ value: s.fontFamily! }))); + const bodyRaw = mode(body.map((s) => ({ value: s.fontFamily! }))); + + const heading: FontRole = headingRaw + ? role(headingRaw) + : { name: 'Serif', stack: 'serif', source: 'default' }; + const bodyRole: FontRole = bodyRaw + ? role(bodyRaw) + : { name: 'Sans Serif', stack: 'sans-serif', source: 'default' }; + if (heading.source === 'default') { + this.decisions.push('No heading font was found; `heading` defaults to the generic serif.'); + } + if (bodyRole.source === 'default') { + this.decisions.push('No body font was found; `body` defaults to the generic sans-serif.'); + } + + const counts = new Map(); + for (const s of proseText) { + if (s.fontFamily !== headingRaw && s.fontFamily !== bodyRaw) { + counts.set(s.fontFamily!, (counts.get(s.fontFamily!) ?? 0) + (/^h/.test(s.role) ? 3 : 1)); + } + } + const accentRaw = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; + let accent: FontRole; + if (accentRaw) { + accent = role(accentRaw); + } else { + accent = { ...heading, source: 'default' }; + this.decisions.push( + `The site uses no third font, so \`accent\` defaults to the heading font (${heading.name}). Ask the reviewer if the theme should have a distinct accent font.` + ); + } + + const monoRaw = mode(text.filter(isMono).map((s) => ({ value: s.fontFamily! }))); + const monospace: FontRole = monoRaw + ? role(monoRaw) + : { name: 'Monospace', stack: MONOSPACE_STACK, source: 'default' }; + return { heading, body: bodyRole, accent, monospace }; + } + proposeSpacing( samples: Array, pair: (s: ElementSample & { page: string }) => ElementSample | undefined @@ -1079,6 +1185,18 @@ export class TokenProposer { /** Writes the proposal as a Markdown report for approval. */ export class ProposalReport { + private fontLines(p: Proposal): string[] { + const roles: FontRoleSlug[] = ['heading', 'body', 'accent', 'monospace']; + return [ + '- Fonts:', + ...roles.map((slug) => { + const f = p.typography.families[slug]; + const raw = f.raw ? `, CSS name \`${f.raw}\`` : ''; + return ` - \`${slug}\`: ${f.name} (${f.source}${raw}), stack \`${f.stack}\``; + }), + ]; + } + render(p: Proposal): string { const lines: string[] = []; const table = (head: string[], rows: Array>) => { @@ -1106,10 +1224,7 @@ export class ProposalReport { lines.push( `- Contrast: ${p.contrast.length - failing.length} of ${p.contrast.length} pairs pass${failing.length ? ` (failing: ${failing.map((f) => f.pair).join('; ')})` : ''}` ); - lines.push( - `- Fonts: headings ${p.typography.families.heading}, body ${p.typography.families.body}`, - '' - ); + lines.push(...this.fontLines(p), ''); lines.push('## Decisions for the reviewer', ''); const decisions = [...p.decisions]; diff --git a/skills/site-to-design-tokens/scripts/write-token-export.ts b/skills/site-to-design-tokens/scripts/write-token-export.ts index 5c79ae6b89..1397af9a29 100644 --- a/skills/site-to-design-tokens/scripts/write-token-export.ts +++ b/skills/site-to-design-tokens/scripts/write-token-export.ts @@ -12,7 +12,7 @@ import { readFileSync, writeFileSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; import { Color, RAMP_STEPS } from './lib/color'; -import type { Family, Proposal, ScaleEntry } from './propose-tokens'; +import type { Family, FontRoleSlug, Proposal, ScaleEntry } from './propose-tokens'; type Value = { r: number; g: number; b: number; a: number } | number | string | { alias: string }; @@ -171,26 +171,7 @@ export class TokenPlanBuilder { values: { Value: { alias: s.token } }, })); - const typography: PlannedVariable[] = [ - { - key: 'font-heading', - name: 'Font-Families/Primary', - type: 'STRING', - codeSyntax: preset('font-family', 'heading'), - scopes: ['FONT_FAMILY'], - values: { Max: p.typography.families.heading, Min: p.typography.families.heading }, - description: 'Headings.', - }, - { - key: 'font-body', - name: 'Font-Families/Secondary', - type: 'STRING', - codeSyntax: preset('font-family', 'body'), - scopes: ['FONT_FAMILY'], - values: { Max: p.typography.families.body, Min: p.typography.families.body }, - description: 'Body text.', - }, - ]; + const typography: PlannedVariable[] = [...this.fontVariables(p)]; for (const size of this.ascending(p.typography.sizes)) { typography.push({ key: `size-${size.slug}`, @@ -297,6 +278,28 @@ export class TokenPlanBuilder { return { collections, effectStyles }; } + /** One variable per role. The value is the clean name; the description keeps the exact CSS stack. */ + private fontVariables(p: Proposal): PlannedVariable[] { + const roles: Array<[FontRoleSlug, string, string]> = [ + ['heading', 'Primary', 'Headings'], + ['body', 'Secondary', 'Body text'], + ['accent', 'Tertiary', 'Accent text'], + ['monospace', 'Monospace', 'Code'], + ]; + return roles.map(([slug, name, use]) => { + const font = p.typography.families[slug]; + return { + key: `font-${slug}`, + name: `Font-Families/${name}`, + type: 'STRING' as const, + codeSyntax: `var(--wp--preset--font-family--${slug})`, + scopes: ['FONT_FAMILY'], + values: { Max: font.name, Min: font.name }, + description: `${use} (${font.source}). CSS stack: ${font.stack}`, + }; + }); + } + private semanticScopes(role: string): string[] { if (role === 'surface/overlay') return FILL; if (/^border\/|\/border$/.test(role)) return ['STROKE_COLOR']; @@ -318,6 +321,7 @@ export class ExportWriter { name: v.name, type: v.type, codeSyntax: v.codeSyntax ? { WEB: v.codeSyntax } : {}, + ...(v.description ? { description: v.description } : {}), valuesByMode: Object.fromEntries( Object.entries(v.values).map(([mode, value]) => [ `${c.name}:${mode}`, From 9b4d465860f99037ac0d3c32047b51bc63f2ec72 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 14:33:19 +0200 Subject: [PATCH 05/31] fix(site-tokens): use live action colours and pick passing defaults Action backgrounds take the anchor step when the anchor came from button fills, with hover one step darker. A default that fails its contrast pair moves to the nearest passing step and is recorded; failing live colours are listed with a passing alternative. Fixes GIT-2762 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + skills/site-to-design-tokens/SKILL.md | 2 +- .../references/target-structure.md | 4 + .../scripts/__tests__/propose-tokens.test.ts | 66 ++++++++ .../scripts/propose-tokens.ts | 146 +++++++++++++++--- 5 files changed, 197 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 08b86486b2..fd130da76d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Site Tokens Action Colours** — `site-to-design-tokens` uses the live button colour for action backgrounds (hover one step darker) and moves defaults that fail contrast to the nearest passing step, recording each move in the report. ([#4008](https://github.com/lightspeedwp/.github/issues/4008)) - **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body`, `accent` and `monospace` roles, marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) - **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text on single posts and pages, takes `--layout content=,wide=` to override either width, and asks the reviewer to confirm a content width under 480px. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) - **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) diff --git a/skills/site-to-design-tokens/SKILL.md b/skills/site-to-design-tokens/SKILL.md index b508f9a1e4..f40ce28d8d 100644 --- a/skills/site-to-design-tokens/SKILL.md +++ b/skills/site-to-design-tokens/SKILL.md @@ -53,7 +53,7 @@ Present the report's summary, its **Decisions for the reviewer** list and any fa - **A colour in the wrong family:** re-run with `--assign brand=#hex,primary=#hex,cta=#hex`. - **A wrong content or wide width:** re-run with `--layout content=768,wide=1240`. Content width is measured from running text on single pages, so include a long text page in the crawl. -- **A failing contrast pair:** propose the nearest passing step and record the change. +- **A failing contrast pair:** failing defaults already move to the nearest passing step and are recorded in the report. For a failing colour taken from the live site, the report lists a passing alternative; confirm which to use. - **A live value with no close token:** keep the nearest token with the same role and list it for the reviewer. Don't add a raw value. Repeat until the reviewer approves. Then ask: `Approve this token proposal and create the variables?` diff --git a/skills/site-to-design-tokens/references/target-structure.md b/skills/site-to-design-tokens/references/target-structure.md index 7bffdcdf2e..8134f2cd91 100644 --- a/skills/site-to-design-tokens/references/target-structure.md +++ b/skills/site-to-design-tokens/references/target-structure.md @@ -86,6 +86,10 @@ System colours (error, warning, success and information, each with a foreground | `action//*` | `background` (primary-500, brand-600, cta-500), `background-hover` (one step darker), `text` (base) | | `feedback//*` | `text` and `border` (system foreground), `background` (system background) | +When a family's anchor came from button fills (`cta` always does, `primary` and `brand` when their anchor fills a button), `action//background` is the anchor step itself (for example `cta-700`) and `background-hover` is the next step darker. This keeps the action colour the live button colour. + +A default that fails its contrast pair moves to the nearest step of the same family that passes, darker steps first, and the report records the move. A failing token taken from the live site is left in place and listed for the reviewer with a passing alternative. + The proposer replaces a default with the live value's nearest primitive for `text/default`, `text/link`, `action/primary/*`, `border/default`, `surface/subtle` and `surface/inverse` when the site shows them. A text colour that can't reach 3:1 on `base` (usually text on photos) keeps its default, and the report says so. ## Scopes diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index d558fd6e32..843912963f 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -344,6 +344,72 @@ describe('ProposalReport', () => { }); }); +describe('Action colours and passing defaults', () => { + const proposal = new TokenProposer().propose(tspLikeStyles(), { now }); + const sem = proposal.colour.semantic; + + it('uses the live anchor step when the anchor came from button fills', () => { + expect(sem['action/cta/background']).toMatchObject({ token: 'cta-700', source: 'observed' }); + expect(sem['action/cta/background-hover'].token).toBe('cta-800'); + expect(sem['action/primary/background-hover'].token).toBe('primary-800'); + // Brand did not anchor on a button fill, so it keeps its default. + expect(sem['action/secondary/background']).toMatchObject({ + token: 'brand-600', + source: 'default', + }); + expect(proposal.contrast.find((c) => c.pair.startsWith('action/cta/text'))!.pass).toBe(true); + }); + + it('moves a failing default to the nearest passing step and records it', () => { + expect(sem['text/link-hover']).toMatchObject({ token: 'primary-600', source: 'default' }); + expect(proposal.decisions.join('\n')).toContain( + '`text/link-hover` default `primary-500` failed 4.5:1' + ); + expect(proposal.contrast.filter((c) => !c.pass)).toEqual([]); + }); + + const setup = () => { + const proposer = new TokenProposer(); + const primitives = { + base: '#ffffff', + contrast: '#000000', + 'brand-500': '#7a7a7a', + 'brand-600': '#606060', + 'brand-700': '#444444', + 'neutral-100': '#f5f5f5', + }; + return { proposer, primitives }; + }; + + it('lists a failing live colour with a passing alternative and leaves it in place', () => { + const { proposer, primitives } = setup(); + const semantic = { + 'text/default': { token: 'contrast', source: 'default' as const }, + 'surface/default': { token: 'base', source: 'default' as const }, + 'text/link': { token: 'brand-500', source: 'observed' as const }, + }; + proposer['fixFailingPairs'](primitives, semantic as never); + expect(semantic['text/link'].token).toBe('brand-500'); + expect(proposer['decisions'].join(' ')).toContain( + '`text/link` (`brand-500`, from the live site) fails 4.5:1' + ); + expect(proposer['decisions'].join(' ')).toContain('`brand-600` passes'); + }); + + it('says so when no step of the family passes', () => { + const { proposer, primitives } = setup(); + const semantic = { + 'surface/default': { token: 'base', source: 'default' as const }, + 'text/link': { token: 'brand-500', source: 'default' as const }, + }; + proposer['fixFailingPairs']( + { ...primitives, 'brand-600': '#777777', 'brand-700': '#888888' }, + semantic as never + ); + expect(proposer['decisions'].join(' ')).toContain('no step of its family passes'); + }); +}); + describe('cleanFontName', () => { it.each([ ['argesta_displayregular', 'Argesta Display'], diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 08934ead7f..a8a9030d88 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -235,6 +235,26 @@ export interface ProposeOptions { now?: () => Date; } +export const CONTRAST_PAIRS: Array<[string, string, number]> = [ + ['text/default', 'surface/default', 4.5], + ['text/muted', 'surface/default', 4.5], + ['text/link', 'surface/default', 4.5], + ['text/link-hover', 'surface/default', 4.5], + ['text/placeholder', 'surface/default', 4.5], + ['text/default', 'surface/subtle', 4.5], + ['text/inverse', 'surface/inverse', 4.5], + ['action/primary/text', 'action/primary/background', 4.5], + ['action/primary/text', 'action/primary/background-hover', 4.5], + ['action/secondary/text', 'action/secondary/background', 4.5], + ['action/cta/text', 'action/cta/background', 4.5], + ['border/focus', 'surface/default', 3], + ['border/default', 'surface/default', 3], + ['feedback/error/text', 'surface/default', 4.5], + ['feedback/warning/text', 'surface/default', 4.5], + ['feedback/success/text', 'surface/default', 4.5], + ['feedback/info/text', 'surface/default', 4.5], +]; + /** Weighted mode of a list of values. */ function mode(values: Array<{ value: T; weight?: number }>): T | undefined { const counts = new Map(); @@ -487,7 +507,7 @@ export class TokenProposer { const shadowBase = Color.parse(primitives['neutral-900'])!.rgb; const overlay = Color.fromRgb({ ...shadowBase, a: 0.25 }).toHex(); - const semantic = this.proposeSemantic(evidence, primitives); + const semantic = this.proposeSemantic(evidence, primitives, anchors); return { primitives, anchors, semantic, overlay, shadowAlphas: SHADOW_ALPHAS }; } @@ -592,7 +612,8 @@ export class TokenProposer { proposeSemantic( evidence: ColourEvidence[], - primitives: Record + primitives: Record, + anchors: Anchor[] = [] ): Proposal['colour']['semantic'] { const semantic: Proposal['colour']['semantic'] = {}; for (const [role, token] of Object.entries(SEMANTIC_DEFAULTS)) { @@ -646,6 +667,34 @@ export class TokenProposer { }; } + // A family whose anchor came from button fills IS the live button colour, so the + // action background takes the anchor step itself, and hover goes one step darker. + const actions: Array<[string, string]> = [ + ['primary', 'primary'], + ['secondary', 'brand'], + ['cta', 'cta'], + ]; + for (const [action, family] of actions) { + const anchor = anchors.find((a) => a.family === family); + const onButtons = + anchor?.source === 'observed' && + evidence.some((e) => e.hex === anchor.hex && (e.uses['button-background'] ?? 0) > 0); + if (!anchor || !onButtons) { + continue; + } + const token = `${family}-${anchor.step}`; + semantic[`action/${action}/background`] = { + token, + source: 'observed', + evidence: `${anchor.hex}, the live button fill that anchors \`${family}\`.`, + }; + semantic[`action/${action}/background-hover`] = { + token: this.darker(token), + source: 'observed', + evidence: `One step darker than ${token}.`, + }; + } + const light = evidence.filter( (e) => (e.uses['section-background'] ?? 0) > 0 && @@ -673,9 +722,82 @@ export class TokenProposer { evidence: `${dark.hex} (section-background ×${dark.uses['section-background']})`, }; } + this.fixFailingPairs(primitives, semantic); return semantic; } + /** + * Moves a default token that fails its contrast pair to the nearest step of the same + * family that passes, darker steps first, and records the move. A failing token taken + * from the live site is left alone and listed for the reviewer with a passing alternative. + */ + private fixFailingPairs( + primitives: Record, + semantic: Proposal['colour']['semantic'] + ): void { + const hexOf = (role: string): string | undefined => primitives[semantic[role]?.token ?? role]; + const ratio = (fg: string, bg: string) => { + const [f, b] = [hexOf(fg), hexOf(bg)]; + return f && b ? Color.parse(f)!.contrast(Color.parse(b)!) : Infinity; + }; + for (const [fg, bg, required] of CONTRAST_PAIRS) { + const current = ratio(fg, bg); + if (current >= required) { + continue; + } + // Text on a fixed surface moves the text. Text on an action moves the action. + const role = fg.startsWith('action/') ? bg : fg; + const other = role === fg ? bg : fg; + const match = semantic[role]?.token.match(/^(.*)-(\d00)$/); + if (!match || ['text/default', 'text/inverse'].includes(role)) { + continue; + } + const index = RAMP_STEPS.indexOf(Number(match[2]) as RampStep); + const rounded = (n: number) => Math.round(n * 100) / 100; + let alternative: { token: string; ratio: number } | undefined; + for (let distance = 1; distance < RAMP_STEPS.length && !alternative; distance++) { + for (const i of [index + distance, index - distance]) { + const step = RAMP_STEPS[i]; + const token = step ? `${match[1]}-${step}` : undefined; + if (!token || !primitives[token]) { + continue; + } + const r = + role === fg + ? Color.parse(primitives[token])!.contrast( + Color.parse(primitives[semantic[other].token])! + ) + : Color.parse(primitives[semantic[other].token])!.contrast( + Color.parse(primitives[token])! + ); + if (r >= required) { + alternative = { token, ratio: rounded(r) }; + break; + } + } + } + const was = semantic[role].token; + if (!alternative) { + this.decisions.push( + `\`${role}\` (\`${was}\`) fails ${required}:1 against \`${other}\` (${rounded(current)}:1) and no step of its family passes. Choose another colour.` + ); + } else if (semantic[role].source === 'default') { + semantic[role] = { + token: alternative.token, + source: 'default', + evidence: `Default \`${was}\` failed ${required}:1 (${rounded(current)}:1), so it moved to the nearest passing step.`, + }; + this.decisions.push( + `\`${role}\` default \`${was}\` failed ${required}:1 against \`${other}\` (${rounded(current)}:1); moved to \`${alternative.token}\` (${alternative.ratio}:1).` + ); + } else { + this.decisions.push( + `\`${role}\` (\`${was}\`, from the live site) fails ${required}:1 against \`${other}\` (${rounded(current)}:1). \`${alternative.token}\` passes (${alternative.ratio}:1). Confirm which to use.` + ); + } + } + } + nearestPrimitive(hex: string, primitives: Record, family?: string): string { const color = Color.parse(hex)!; let best = 'contrast'; @@ -721,25 +843,7 @@ export class TokenProposer { const token = semantic[role]?.token ?? role; return primitives[token]; }; - const pairs: Array<[string, string, number]> = [ - ['text/default', 'surface/default', 4.5], - ['text/muted', 'surface/default', 4.5], - ['text/link', 'surface/default', 4.5], - ['text/link-hover', 'surface/default', 4.5], - ['text/placeholder', 'surface/default', 4.5], - ['text/default', 'surface/subtle', 4.5], - ['text/inverse', 'surface/inverse', 4.5], - ['action/primary/text', 'action/primary/background', 4.5], - ['action/primary/text', 'action/primary/background-hover', 4.5], - ['action/secondary/text', 'action/secondary/background', 4.5], - ['action/cta/text', 'action/cta/background', 4.5], - ['border/focus', 'surface/default', 3], - ['border/default', 'surface/default', 3], - ['feedback/error/text', 'surface/default', 4.5], - ['feedback/warning/text', 'surface/default', 4.5], - ['feedback/success/text', 'surface/default', 4.5], - ['feedback/info/text', 'surface/default', 4.5], - ]; + const pairs = CONTRAST_PAIRS; return pairs.map(([fg, bg, required]) => { const foreground = resolve(fg); const background = resolve(bg); From e961b12b41184c961d1ea2ba56a16e2f09ebc35f Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 14:35:15 +0200 Subject: [PATCH 06/31] chore(site-tokens): say which dependencies and browser the scripts need Add a Before you start section: npm ci in the .github checkout, and npx puppeteer browsers install chrome if the launch fails (npm 11 blocks Puppeteer's install script). site-to-figma-components has the same note; figma-to-block-theme only needs npm ci. Fixes GIT-2763 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + skills/figma-to-block-theme/SKILL.md | 4 ++++ skills/site-to-design-tokens/SKILL.md | 7 +++++++ skills/site-to-figma-components/SKILL.md | 7 +++++++ 4 files changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd130da76d..e390d36564 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Site Skills Setup Notes** — `site-to-design-tokens` and `site-to-figma-components` now say to run `npm ci` and, if the browser fails to launch, `npx puppeteer browsers install chrome` (npm 11 skips Puppeteer's download). `figma-to-block-theme` notes the `npm ci` step. ([#4009](https://github.com/lightspeedwp/.github/issues/4009)) - **Label inventory token** — The organisation label inventory now needs its own dedicated token, refuses the GitHub Actions token and fails when private repositories are missing. (#3734) - **Private Repositories Stay Out Of Public Reports** — The label inventory and the weekly drift report now count private repositories without naming them or listing their labels. Detail goes to a private repository when one is set. (#3734) - **Dependabot Merge Queue Fixed** — Dependabot pull requests no longer fail the Mergify queue check, because the queue now tests each pull request in place. ([PR #3817](https://github.com/lightspeedwp/.github/pull/3817)) diff --git a/skills/figma-to-block-theme/SKILL.md b/skills/figma-to-block-theme/SKILL.md index d40c6ecd26..3859636fea 100644 --- a/skills/figma-to-block-theme/SKILL.md +++ b/skills/figma-to-block-theme/SKILL.md @@ -31,6 +31,10 @@ This skill holds only the Figma-to-WordPress mapping and LightSpeed conventions. If a companion skill is not installed, say so and stop rather than calling Figma tools directly. +## Before you start + +The scripts are TypeScript run with `tsx` from the `.github` repository checkout. Run `npm ci` there first. This skill does not use a browser, so it needs no Puppeteer download. + ## Step 0: Build the theme profile Never assume paths. Read [references/theme-profile.md](references/theme-profile.md) and record: diff --git a/skills/site-to-design-tokens/SKILL.md b/skills/site-to-design-tokens/SKILL.md index f40ce28d8d..31808f1948 100644 --- a/skills/site-to-design-tokens/SKILL.md +++ b/skills/site-to-design-tokens/SKILL.md @@ -20,6 +20,13 @@ Nothing is written to Figma or a theme until the reviewer approves the proposal. - `figma-use`: required before running the generated script through `use_figma`. Creating a token library also uses `figma-generate-library`. - `figma-to-block-theme`: turns the export JSON (or the new Figma variables) into `theme.json` presets. +## Before you start + +The scripts run from the `.github` repository checkout and need its dependencies and a browser: + +- Run `npm ci` in the `.github` checkout. Without it `tsx` and Puppeteer are missing. +- If the crawler fails to launch the browser, run `npx puppeteer browsers install chrome`. npm 11 blocks Puppeteer's install script, so the browser is not downloaded automatically. + ## Workflow ### 1. Agree the pages diff --git a/skills/site-to-figma-components/SKILL.md b/skills/site-to-figma-components/SKILL.md index b21a327045..9848f255b5 100644 --- a/skills/site-to-figma-components/SKILL.md +++ b/skills/site-to-figma-components/SKILL.md @@ -26,6 +26,13 @@ It stops for approval between stages. Nothing is written to Figma before the rev If a companion skill is missing, say so and stop rather than calling Figma tools directly. +## Before you start + +The scripts run from the `.github` repository checkout and need its dependencies and a browser: + +- Run `npm ci` in the `.github` checkout. Without it `tsx` and Puppeteer are missing. +- If the crawler fails to launch the browser, run `npx puppeteer browsers install chrome`. npm 11 blocks Puppeteer's install script, so the browser is not downloaded automatically. + ## Stage 1: Inventory 1. **Agree the pages** with the reviewer: one or two public pages per template, from the site's sitemap. See [references/crawling.md](references/crawling.md). From 8ccd8ed08eb7ccfaaac32ec2aa598cbc672c4fc6 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 15:05:07 +0200 Subject: [PATCH 07/31] fix(site-tokens): name radius variables by bare size The variables live in the Radius collection, so Radius Small becomes Small. figma-to-block-theme maps bare names and strips the old Radius prefix so existing files keep working. Relates to GIT-2758 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- .../references/tokens-radius-shadow.md | 2 +- .../figma-variables-to-theme-json.test.ts | 27 +++++++++++++++++++ .../scripts/figma-variables-to-theme-json.ts | 3 ++- .../references/target-structure.md | 2 +- .../__tests__/write-token-export.test.ts | 8 +++--- .../scripts/write-token-export.ts | 3 ++- 7 files changed, 38 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27996a40f8..70d6d08f0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,7 +114,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) +- **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. Radius variables are named by bare size (`Small`, not `Radius Small`), and `figma-to-block-theme` accepts both. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Studio Imports From Live Sites** — Live site exports now import into Studio sites that already have WordPress content; files in the wrong format are refused with a reason. ([PR #3961](https://github.com/lightspeedwp/.github/pull/3961)) - **Qodo PR-Agent Eligibility and Comment Binding** — A closed pull request is refused on every request path, and both receivers resolve the exact maintainer comment by id. ([PR #3532](https://github.com/lightspeedwp/.github/pull/3532)) diff --git a/skills/figma-to-block-theme/references/tokens-radius-shadow.md b/skills/figma-to-block-theme/references/tokens-radius-shadow.md index c82e7066dd..8c7d58a90c 100644 --- a/skills/figma-to-block-theme/references/tokens-radius-shadow.md +++ b/skills/figma-to-block-theme/references/tokens-radius-shadow.md @@ -5,7 +5,7 @@ Variables whose code syntax is `--wp--preset--border-radius--` become `settings.border.radiusSizes` entries `{ slug, name, size }`: - `slug` comes from the code syntax (`--border-radius--300` becomes `300`). -- `name` is the last segment of the Figma name, unchanged. +- `name` is the bare size (`Small`, `Base`). An older `Radius Small` name loses its `Radius` prefix, because the variable already lives in the Radius collection. - `size` is `0` for zero, otherwise the value in px (`8` becomes `8px`). The mapper also sets `settings.border.radius: true`. Keep the other `settings.border` keys (`color`, `style`, `width`). diff --git a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts index ffdc26e3e6..59c6bf270f 100644 --- a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts +++ b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts @@ -391,6 +391,33 @@ describe('FigmaVariablesMapper', () => { ); }); + it('maps bare radius names and strips the old "Radius " prefix', () => { + const radius = (name: string) => + new FigmaVariablesMapper().map({ + collections: [ + { + name: 'Theme - Radius', + modes: [{ id: 'm', name: 'Mode 1' }], + variables: [ + { + id: 'r', + name, + type: 'FLOAT', + codeSyntax: { WEB: 'var(--wp--preset--border-radius--100)' }, + valuesByMode: { m: 4 }, + }, + ], + }, + ], + } as never); + const names = (mapped: ReturnType) => + (mapped.theme.settings as Json).border.radiusSizes.map((r: { name: string }) => r.name); + + expect(names(radius('Small'))).toEqual(['Small']); + expect(names(radius('Radius Small'))).toEqual(['Small']); + expect(names(radius('Radius'))).toEqual(['Radius']); + }); + it('warns when a sizing ramp is out of order', () => { const mapped = new FigmaVariablesMapper().map({ collections: [ diff --git a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts index 656412354f..94deb7a4fc 100644 --- a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts +++ b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts @@ -364,7 +364,8 @@ export class FigmaVariablesMapper { } return { slug: target.slug, - name, + // The collection is Radius, so names are bare sizes. Old files wrote "Radius Small". + name: name.replace(/^Radius\s+/i, '') || name, size: value === 0 ? '0' : `${value}px`, }; default: diff --git a/skills/site-to-design-tokens/references/target-structure.md b/skills/site-to-design-tokens/references/target-structure.md index 6b2c0dfca3..18980ddbb2 100644 --- a/skills/site-to-design-tokens/references/target-structure.md +++ b/skills/site-to-design-tokens/references/target-structure.md @@ -10,7 +10,7 @@ The proposal and the Figma script follow the TSP design system file (The Safari | Theme - Semantic | Value | Aliases of the primitives, by role | `--wp--custom--color----` | | Theme - Typography | Max, Min | `Sizes/`, `Font-Families/Primary` (headings) and `Secondary` (body), `Line-Heights/`, `Weights/` | `--wp--preset--font-size--` (`100` … `900`), `--wp--preset--font-family--heading` and `body`, `--wp--custom--line-height--`, `--wp--custom--font-weight--` | | Theme - Spacing | Max, Min | `Padding/None`, `Padding/XXS`, `Padding/XS` … `Padding/Colossal` | `--wp--preset--spacing--` (`5` … `100`) | -| Theme - Radius | Mode 1 | `Radius None`, `Small`, `Base` … `Round` | `--wp--preset--border-radius--` | +| Theme - Radius | Mode 1 | `None`, `Small`, `Base` … `Round` (bare sizes, never `Radius Small`) | `--wp--preset--border-radius--` | | Theme - Layout | Mode 1 | `Desktop/Desktop Content Width`, `Desktop/Desktop Wide Width` | `--wp--custom--layout--content-size` and `wide-size` | | Theme - Breakpoints | Mode 1 | `Desktop`, `Tablet`, `Mobile` | `--wp--custom--breakpoint--` | diff --git a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts index d65ef3b572..e487bb8c6a 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts @@ -88,10 +88,10 @@ describe('TokenPlanBuilder', () => { collection('Theme - Spacing').variables.find((v) => v.name === 'Padding/Colossal')!.values ).toEqual({ Max: 100, Min: 72 }); expect(collection('Theme - Radius').variables.map((v) => v.name)).toEqual([ - 'Radius None', - 'Radius Small', - 'Radius Base', - 'Radius Round', + 'None', + 'Small', + 'Base', + 'Round', ]); expect(plan.effectStyles[0]).toMatchObject({ name: 'LSX/xSmall', diff --git a/skills/site-to-design-tokens/scripts/write-token-export.ts b/skills/site-to-design-tokens/scripts/write-token-export.ts index 5c79ae6b89..cc8bf95a09 100644 --- a/skills/site-to-design-tokens/scripts/write-token-export.ts +++ b/skills/site-to-design-tokens/scripts/write-token-export.ts @@ -238,7 +238,8 @@ export class TokenPlanBuilder { const radius: PlannedVariable[] = p.radius.map((r) => ({ key: `radius-${r.slug}`, - name: `Radius ${r.name}`, + // The collection is already Radius, so the name is the bare size. + name: r.name, type: 'FLOAT', codeSyntax: preset('border-radius', r.slug), scopes: ['CORNER_RADIUS'], From 87c4a3a48546c73b164d0c3e84dfac77cb91da77 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 15:08:43 +0200 Subject: [PATCH 08/31] fix(site-tokens): create the accent font role only when the site has a third family With two families there is no accent variable, preset or Figma script entry, and the report says so. Monospace keeps its default. figma-to-block-theme writes only the roles that exist. Relates to GIT-2761 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- .../references/tokens-typography.md | 2 +- .../figma-variables-to-theme-json.test.ts | 27 +++++++++++++++++++ .../references/proposal-review.md | 2 +- .../references/target-structure.md | 6 ++--- .../scripts/__tests__/propose-tokens.test.ts | 11 +++++--- .../__tests__/write-token-export.test.ts | 17 ++++++++++++ .../scripts/propose-tokens.ts | 20 ++++++-------- .../scripts/write-token-export.ts | 26 +++++++++++------- 9 files changed, 82 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20f650c0c5..c29cd74839 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,7 +114,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body`, `accent` and `monospace` roles, marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) +- **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body` and `monospace` roles (plus `accent` only when the site uses a third font), marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) - **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text on single posts and pages, takes `--layout content=,wide=` to override either width, and asks the reviewer to confirm a content width under 480px. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) - **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) - **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) diff --git a/skills/figma-to-block-theme/references/tokens-typography.md b/skills/figma-to-block-theme/references/tokens-typography.md index 048c4f2a49..c76c03512b 100644 --- a/skills/figma-to-block-theme/references/tokens-typography.md +++ b/skills/figma-to-block-theme/references/tokens-typography.md @@ -19,7 +19,7 @@ After replacing the sizes, update every reference in `styles`, `styles.blocks`, ## Font families -Variables whose code syntax is `--wp--preset--font-family--` (`heading`, `body`, `accent` and `monospace`) become `{ slug, name, fontFamily }`: +Variables whose code syntax is `--wp--preset--font-family--` (`heading`, `body`, `monospace`, and `accent` only when the site has a third font) become `{ slug, name, fontFamily }`: - `name` is the font name (for example "Nunito Sans"), not the slug. - If the variable description holds a `CSS stack: ` line (written by `site-to-design-tokens`) and its first family is the font named by the value, `fontFamily` is that exact stack. diff --git a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts index 1d27b9eb5e..0510abd206 100644 --- a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts +++ b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts @@ -422,6 +422,33 @@ describe('FigmaVariablesMapper', () => { expect(stack(font('Moret', 'Headings only'))).toBe('Moret, sans-serif'); }); + it('writes only the font roles that exist, with no accent when there is none', () => { + const role = (slug: string, value: string) => ({ + id: slug, + name: `Font-Families/${slug}`, + type: 'STRING', + codeSyntax: { WEB: `var(--wp--preset--font-family--${slug})` }, + valuesByMode: { m: value }, + }); + const mapped = new FigmaVariablesMapper().map({ + collections: [ + { + name: 'Typography', + modes: [{ id: 'm', name: 'Value' }], + variables: [ + role('heading', 'Moret'), + role('body', 'Lora'), + role('monospace', 'Monospace'), + ], + }, + ], + } as never); + const slugs = (mapped.theme.settings as Json).typography.fontFamilies.map( + (f: { slug: string }) => f.slug + ); + expect(slugs).toEqual(['heading', 'body', 'monospace']); + }); + it('maps bare radius names and strips the old "Radius " prefix', () => { const radius = (name: string) => new FigmaVariablesMapper().map({ diff --git a/skills/site-to-design-tokens/references/proposal-review.md b/skills/site-to-design-tokens/references/proposal-review.md index 87f579dc86..aa519dfedb 100644 --- a/skills/site-to-design-tokens/references/proposal-review.md +++ b/skills/site-to-design-tokens/references/proposal-review.md @@ -44,5 +44,5 @@ Check each scale against the site at both widths: - The body text size should be `Base`, slug `200`. - Heading sizes should shrink on mobile. - Section spacing should reflect what the eye sees. Sites that space sections with margins on unstyled wrappers can produce a smaller scale than the design intends, so say so and let the reviewer set the larger steps. -- Font names are cleaned from the site's CSS (`argesta_displayregular` becomes `Argesta Display`) and the exact CSS stack is kept. The report marks each of the four roles as live or default. Check the cleaned names, the `accent` default (the heading font when the site has no third family) and the fallbacks with the reviewer. +- Font names are cleaned from the site's CSS (`argesta_displayregular` becomes `Argesta Display`) and the exact CSS stack is kept. The report marks each role as live or default, and says when there is no accent font because the site uses two families. Check the cleaned names and the fallbacks with the reviewer. - **Content width** comes from the width of running text (`p` elements with 80 or more characters in the main column) on single posts and pages, not from cards or wrappers. Include at least one long text page in the crawl. If the report says the width came from listing pages, or is under 480px, confirm it with the reviewer. Override either width with `--layout content=,wide=`. diff --git a/skills/site-to-design-tokens/references/target-structure.md b/skills/site-to-design-tokens/references/target-structure.md index 9db33c4c08..0f11b0855e 100644 --- a/skills/site-to-design-tokens/references/target-structure.md +++ b/skills/site-to-design-tokens/references/target-structure.md @@ -8,7 +8,7 @@ The proposal and the Figma script follow the TSP design system file (The Safari | ------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Theme - Colour | Value | Primitives: `Theme/base`, `Theme/contrast`, `brand/100` … `900`, `primary/…`, `cta/…`, `neutral/…`, `system//`, `custom/overlay`, `shadow/` | `--wp--preset--color--`; overlay and shadows `--wp--custom--color--…` | | Theme - Semantic | Value | Aliases of the primitives, by role | `--wp--custom--color----` | -| Theme - Typography | Max, Min | `Sizes/`, `Font-Families/Primary` (heading), `Secondary` (body), `Tertiary` (accent) and `Monospace`, `Line-Heights/`, `Weights/` | `--wp--preset--font-size--` (`100` … `900`), `--wp--preset--font-family--heading`, `body`, `accent` and `monospace`, `--wp--custom--line-height--`, `--wp--custom--font-weight--` | +| Theme - Typography | Max, Min | `Sizes/`, `Font-Families/Primary` (heading), `Secondary` (body), `Tertiary` (accent, only with a third family) and `Monospace`, `Line-Heights/`, `Weights/` | `--wp--preset--font-size--` (`100` … `900`), `--wp--preset--font-family--heading`, `body`, `accent` and `monospace`, `--wp--custom--line-height--`, `--wp--custom--font-weight--` | | Theme - Spacing | Max, Min | `Padding/None`, `Padding/XXS`, `Padding/XS` … `Padding/Colossal` | `--wp--preset--spacing--` (`5` … `100`) | | Theme - Radius | Mode 1 | `None`, `Small`, `Base` … `Round` (bare sizes, never `Radius Small`) | `--wp--preset--border-radius--` | | Theme - Layout | Mode 1 | `Desktop/Desktop Content Width`, `Desktop/Desktop Wide Width` | `--wp--custom--layout--content-size` and `wide-size` | @@ -40,13 +40,13 @@ Type sizes, radius and shadows use numeric slugs, the same as the block theme sc ## Font families -There are four role slugs, `heading`, `body`, `accent` and `monospace`. The slug is the role. The variable value and the `theme.json` name are the real font, cleaned from the CSS name: weight and style suffixes (`regular`, `bold`, `italic`) are dropped, underscores become spaces and lower-case words are title-cased, so `argesta_displayregular` becomes `Argesta Display`. The variable description keeps the exact CSS stack (`CSS stack: ...`), and `figma-to-block-theme` uses it as the `fontFamily`. +There are up to four role slugs, `heading`, `body`, `accent` and `monospace`. The slug is the role. `accent` exists only when the site really uses a third family: with two families there is no accent variable, no `accent` preset and no accent in the Figma script, and the report says "no accent font: the site uses two families". The variable value and the `theme.json` name are the real font, cleaned from the CSS name: weight and style suffixes (`regular`, `bold`, `italic`) are dropped, underscores become spaces and lower-case words are title-cased, so `argesta_displayregular` becomes `Argesta Display`. The variable description keeps the exact CSS stack (`CSS stack: ...`), and `figma-to-block-theme` uses it as the `fontFamily`. | Role | Live | Default | | ----------- | ---------------------------------------------- | ---------------------------------------------------- | | `heading` | The most used family on `h1` to `h3` | Generic serif | | `body` | The most used family on body text | Generic sans-serif | -| `accent` | The next most used family, if there is a third | The heading font, flagged for the reviewer | +| `accent` | The next most used family, if there is a third | None: the role is not created | | `monospace` | A family whose stack ends in `monospace` | `ui-monospace, SFMono-Regular, Menlo, Consolas, ...` | The report lists each role as live or default. diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index d558fd6e32..9d52439150 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -359,7 +359,7 @@ describe('cleanFontName', () => { }); describe('TokenProposer font roles', () => { - it('defaults the roles the site does not show and records them', () => { + it('omits the accent role without a third family and defaults monospace', () => { const proposer = new TokenProposer(); const sample = (role: string, fontFamily: string, fontStack: string) => ({ key: `${role}:0`, page: '/', role, fontSize: 16, fontFamily, fontStack }) as never; @@ -368,13 +368,13 @@ describe('TokenProposer font roles', () => { [sample('h1', 'Moret', 'Moret, serif'), sample('body', 'Lora', 'Lora, serif')], roles ); - expect(families.accent).toMatchObject({ name: 'Moret', source: 'default' }); + expect(families.accent).toBeUndefined(); + expect('accent' in families).toBe(false); expect(families.monospace).toEqual({ name: 'Monospace', stack: MONOSPACE_STACK, source: 'default', }); - expect(proposer['decisions'].join(' ')).toContain('uses no third font'); const empty = new TokenProposer().proposeFamilies([], roles); expect(empty.heading).toMatchObject({ stack: 'serif', source: 'default' }); expect(empty.body).toMatchObject({ stack: 'sans-serif', source: 'default' }); @@ -394,6 +394,11 @@ describe('TokenProposer font roles', () => { ); expect(report).toContain('`heading`: Moret (live, CSS name `moret`)'); expect(report).toContain('`monospace`: Courier New (live)'); + const two = new TokenProposer().propose(tspLikeStyles(), { now }); + delete two.typography.families.accent; + expect(new ProposalReport().render(two)).toContain( + '`accent`: none (no accent font: the site uses two families)' + ); }); }); diff --git a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts index 208ec7db27..f71257986a 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts @@ -118,6 +118,23 @@ describe('TokenPlanBuilder', () => { }); }); +describe('Without a third font', () => { + it('creates no accent variable', () => { + const two = JSON.parse(JSON.stringify(proposal)) as typeof proposal; + delete two.typography.families.accent; + const plan = new TokenPlanBuilder().build(two); + const names = plan.collections + .find((c) => c.name === 'Theme - Typography')! + .variables.filter((v) => v.name.startsWith('Font-Families/')) + .map((v) => v.name); + expect(names).toEqual([ + 'Font-Families/Primary', + 'Font-Families/Secondary', + 'Font-Families/Monospace', + ]); + }); +}); + describe('Sizing ramps are in ascending order', () => { it('orders spacing and type sizes by Max whatever the proposal order', () => { const scrambled = JSON.parse(JSON.stringify(proposal)) as typeof proposal; diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 08934ead7f..959422274a 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -177,7 +177,7 @@ export interface Proposal { matches: MatchRow[]; contrast: ContrastRow[]; typography: { - families: Record; + families: Record, FontRole> & { accent?: FontRole }; sizes: ScaleEntry[]; weights: Record; }; @@ -854,7 +854,7 @@ export class TokenProposer { proposeFamilies( samples: Array, textRoles: string[] - ): Record { + ): Proposal['typography']['families'] { const text = samples.filter((s) => textRoles.includes(s.role) && s.fontFamily); const isMono = (s: ElementSample) => /\bmonospace\b/i.test(s.fontStack ?? '') || @@ -904,21 +904,14 @@ export class TokenProposer { } } const accentRaw = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; - let accent: FontRole; - if (accentRaw) { - accent = role(accentRaw); - } else { - accent = { ...heading, source: 'default' }; - this.decisions.push( - `The site uses no third font, so \`accent\` defaults to the heading font (${heading.name}). Ask the reviewer if the theme should have a distinct accent font.` - ); - } + // The accent role exists only when the site really uses a third family. + const accent = accentRaw ? role(accentRaw) : undefined; const monoRaw = mode(text.filter(isMono).map((s) => ({ value: s.fontFamily! }))); const monospace: FontRole = monoRaw ? role(monoRaw) : { name: 'Monospace', stack: MONOSPACE_STACK, source: 'default' }; - return { heading, body: bodyRole, accent, monospace }; + return { heading, body: bodyRole, ...(accent ? { accent } : {}), monospace }; } proposeSpacing( @@ -1191,6 +1184,9 @@ export class ProposalReport { '- Fonts:', ...roles.map((slug) => { const f = p.typography.families[slug]; + if (!f) { + return ` - \`${slug}\`: none (no accent font: the site uses two families)`; + } const raw = f.raw ? `, CSS name \`${f.raw}\`` : ''; return ` - \`${slug}\`: ${f.name} (${f.source}${raw}), stack \`${f.stack}\``; }), diff --git a/skills/site-to-design-tokens/scripts/write-token-export.ts b/skills/site-to-design-tokens/scripts/write-token-export.ts index 02a4daa67f..fe789fd337 100644 --- a/skills/site-to-design-tokens/scripts/write-token-export.ts +++ b/skills/site-to-design-tokens/scripts/write-token-export.ts @@ -287,17 +287,23 @@ export class TokenPlanBuilder { ['accent', 'Tertiary', 'Accent text'], ['monospace', 'Monospace', 'Code'], ]; - return roles.map(([slug, name, use]) => { + return roles.flatMap(([slug, name, use]) => { const font = p.typography.families[slug]; - return { - key: `font-${slug}`, - name: `Font-Families/${name}`, - type: 'STRING' as const, - codeSyntax: `var(--wp--preset--font-family--${slug})`, - scopes: ['FONT_FAMILY'], - values: { Max: font.name, Min: font.name }, - description: `${use} (${font.source}). CSS stack: ${font.stack}`, - }; + // No accent variable unless the site uses a third family. + if (!font) { + return []; + } + return [ + { + key: `font-${slug}`, + name: `Font-Families/${name}`, + type: 'STRING' as const, + codeSyntax: `var(--wp--preset--font-family--${slug})`, + scopes: ['FONT_FAMILY'], + values: { Max: font.name, Min: font.name }, + description: `${use} (${font.source}). CSS stack: ${font.stack}`, + }, + ]; }); } From bcda7bfb257c499e53d3299ed70b7a664d5241ec Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 15:52:32 +0200 Subject: [PATCH 09/31] fix(site-tokens): use X-Large and X-Small as the display names Matches theme.json and the TSP Figma file. figma-to-block-theme maps both spellings (xLarge and X-Large) to X-Large for radius, font sizes and shadows. Relates to GIT-2758 Co-Authored-By: Claude Opus 5.5 --- .../references/tokens-radius-shadow.md | 2 +- .../figma-variables-to-theme-json.test.ts | 22 +++++++++++++++++++ .../scripts/figma-variables-to-theme-json.ts | 14 +++++++++--- .../references/target-structure.md | 6 ++--- .../scripts/__tests__/propose-tokens.test.ts | 2 +- .../__tests__/write-token-export.test.ts | 4 ++-- .../scripts/propose-tokens.ts | 6 ++--- 7 files changed, 43 insertions(+), 13 deletions(-) diff --git a/skills/figma-to-block-theme/references/tokens-radius-shadow.md b/skills/figma-to-block-theme/references/tokens-radius-shadow.md index 8c7d58a90c..a453d0945a 100644 --- a/skills/figma-to-block-theme/references/tokens-radius-shadow.md +++ b/skills/figma-to-block-theme/references/tokens-radius-shadow.md @@ -5,7 +5,7 @@ Variables whose code syntax is `--wp--preset--border-radius--` become `settings.border.radiusSizes` entries `{ slug, name, size }`: - `slug` comes from the code syntax (`--border-radius--300` becomes `300`). -- `name` is the bare size (`Small`, `Base`). An older `Radius Small` name loses its `Radius` prefix, because the variable already lives in the Radius collection. +- `name` is the bare size (`Small`, `Base`). An older `Radius Small` name loses its `Radius` prefix, because the variable already lives in the Radius collection. `xLarge` and `X-Large` (also `xSmall`) both map to `X-Large`, the same for font sizes and shadows. - `size` is `0` for zero, otherwise the value in px (`8` becomes `8px`). The mapper also sets `settings.border.radius: true`. Keep the other `settings.border` keys (`color`, `style`, `width`). diff --git a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts index 59c6bf270f..70d2743fe0 100644 --- a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts +++ b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts @@ -391,6 +391,28 @@ describe('FigmaVariablesMapper', () => { ); }); + it('maps both spellings of the extra sizes to X-Large and X-Small', () => { + const mapped = new FigmaVariablesMapper().map({ + collections: [ + { + name: 'Radius', + modes: [{ id: 'm', name: 'Mode 1' }], + variables: ['xLarge', 'X-Large', 'x-small'].map((name, i) => ({ + id: `r${i}`, + name, + type: 'FLOAT', + codeSyntax: { WEB: `var(--wp--preset--border-radius--${(i + 1) * 100})` }, + valuesByMode: { m: 4 }, + })), + }, + ], + } as never); + const names = (mapped.theme.settings as Json).border.radiusSizes.map( + (r: { name: string }) => r.name + ); + expect(names).toEqual(['X-Large', 'X-Large', 'X-Small']); + }); + it('maps bare radius names and strips the old "Radius " prefix', () => { const radius = (name: string) => new FigmaVariablesMapper().map({ diff --git a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts index 94deb7a4fc..15af74cfca 100644 --- a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts +++ b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts @@ -338,7 +338,7 @@ export class FigmaVariablesMapper { } const entry: JsonObject = { slug: target.slug, - name, + name: this.sizeName(name), size: this.fluid.toRem(sizes.max), }; if (sizes.min !== sizes.max) { @@ -365,7 +365,7 @@ export class FigmaVariablesMapper { return { slug: target.slug, // The collection is Radius, so names are bare sizes. Old files wrote "Radius Small". - name: name.replace(/^Radius\s+/i, '') || name, + name: this.sizeName(name.replace(/^Radius\s+/i, '') || name), size: value === 0 ? '0' : `${value}px`, }; default: @@ -451,7 +451,7 @@ export class FigmaVariablesMapper { } presets.push({ slug: syntax ? syntax[1] : this.slugify(name), - name, + name: this.sizeName(name), shadow: shadows.join(', '), }); } @@ -626,6 +626,14 @@ export class FigmaVariablesMapper { return name.split('/').pop()!.trim(); } + /** Both spellings of the extra sizes map to one: xLarge, x-large and X-Large become X-Large. */ + private sizeName(name: string): string { + return name.replace( + /^x[\s-]?(small|large)$/i, + (_m, size: string) => `X-${size[0].toUpperCase()}${size.slice(1).toLowerCase()}` + ); + } + private titleCase(slug: string): string { return slug .split('-') diff --git a/skills/site-to-design-tokens/references/target-structure.md b/skills/site-to-design-tokens/references/target-structure.md index 18980ddbb2..01e265913b 100644 --- a/skills/site-to-design-tokens/references/target-structure.md +++ b/skills/site-to-design-tokens/references/target-structure.md @@ -24,7 +24,7 @@ Line-height variables store a percentage of the font size (150 means 1.5). They Type sizes, radius and shadows use numeric slugs, the same as the block theme scaffold and `tsp-theme`. The size names (Small, Base, Large and so on) are display names only. The slug lives in the code syntax and the effect style description, never in the variable name, and the export carries the slug straight through to `theme.json` with no renaming. -- Type, slugs `100` to `900`: `Tiny` (100), `Base` (200), `Small`, `Medium`, `Large`, `xLarge`, `Huge`, `Gigantic`, `Colossal` (900). Body text is always `Base` at `200`. When the site has no size below body text, `100` stays empty. +- Type, slugs `100` to `900`: `Tiny` (100), `Base` (200), `Small`, `Medium`, `Large`, `X-Large`, `Huge`, `Gigantic`, `Colossal` (900). Body text is always `Base` at `200`. When the site has no size below body text, `100` stays empty. - Spacing is the exception. The variable name carries only the size and the code syntax carries the slug, so `Padding/XS` has `var(--wp--preset--spacing--10)`. Never put the slug in the name (`Padding/10 XS`). The ladder is: | Name | XXS | XS | S | M | L | XL | XXL | XXXL | XXXXL | Gigantic | Colossal | @@ -35,8 +35,8 @@ Type sizes, radius and shadows use numeric slugs, the same as the block theme sc Each measured value takes the step nearest its desktop size, so 40px becomes `L`. When that step is taken, the value moves up to the next free step. `Padding/None` (0) is for Figma only. It has no code syntax, because WordPress already offers a 0 spacing and importing one adds a duplicate in the editor. -- Radius, slugs `0` to `700`: `None` (0), `Small` (100), `Base`, `Medium`, `Large`, `xLarge`, `Huge` (600), `Round` (700, 9999px). Measured values fill 100 upward in order. -- Shadows, slugs `100` to `600`: `xSmall`, `Small`, `Medium`, `Large`, `xLarge`, `Huge`, ordered by strength (blur radius), so `100` is the softest. +- Radius, slugs `0` to `700`: `None` (0), `Small` (100), `Base`, `Medium`, `Large`, `X-Large`, `Huge` (600), `Round` (700, 9999px). Measured values fill 100 upward in order. +- Shadows, slugs `100` to `600`: `X-Small`, `Small`, `Medium`, `Large`, `X-Large`, `Huge`, ordered by strength (blur radius), so `100` is the softest. ## Colour families diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index c1ed94406f..175a0826f4 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -71,7 +71,7 @@ describe('TokenProposer on a TSP-like site', () => { 'Small', 'Medium', 'Large', - 'xLarge', + 'X-Large', 'Huge', 'Gigantic', ]); diff --git a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts index e487bb8c6a..4246be6c8a 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts @@ -94,7 +94,7 @@ describe('TokenPlanBuilder', () => { 'Round', ]); expect(plan.effectStyles[0]).toMatchObject({ - name: 'LSX/xSmall', + name: 'LSX/X-Small', description: 'theme.json shadow preset "100": var(--wp--preset--shadow--100).', }); }); @@ -278,7 +278,7 @@ describe('FigmaScriptWriter', () => { expect(calls.aliases).toBe(44); expect(result.variableCount).toBe(calls.variables.length); expect(result.effectStyleIds).toHaveLength(plan.effectStyles.length); - expect(calls.styles[0].name).toBe('LSX/xSmall'); + expect(calls.styles[0].name).toBe('LSX/X-Small'); const inner = calls.styles .flatMap((s) => s.effects as Array<{ type: string; showShadowBehindNode?: boolean }>) .find((e) => e.type === 'INNER_SHADOW'); diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index eec7b9ab3f..7b4fbc2c85 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -83,7 +83,7 @@ const SIZE_NAMES = [ 'Small', 'Medium', 'Large', - 'xLarge', + 'X-Large', 'Huge', 'Gigantic', 'Colossal', @@ -104,8 +104,8 @@ export const SPACING_STEPS = [ { slug: '90', name: 'Gigantic' }, { slug: '100', name: 'Colossal' }, ]; -const RADIUS_NAMES = ['Small', 'Base', 'Medium', 'Large', 'xLarge', 'Huge']; -const SHADOW_NAMES = ['xSmall', 'Small', 'Medium', 'Large', 'xLarge', 'Huge']; +const RADIUS_NAMES = ['Small', 'Base', 'Medium', 'Large', 'X-Large', 'Huge']; +const SHADOW_NAMES = ['X-Small', 'Small', 'Medium', 'Large', 'X-Large', 'Huge']; export interface ColourEvidence { hex: string; From 5c0236d3d2d1f796102869c4c42fbc721a0bf3ad Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:16:01 +0200 Subject: [PATCH 10/31] chore(site-tokens): remove the committed propose-tokens.ts.bak Refs GIT-2768. Co-Authored-By: Claude Opus 5.5 --- .../scripts/propose-tokens.ts.bak | 1288 ----------------- 1 file changed, 1288 deletions(-) delete mode 100644 skills/site-to-design-tokens/scripts/propose-tokens.ts.bak diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts.bak b/skills/site-to-design-tokens/scripts/propose-tokens.ts.bak deleted file mode 100644 index ec82e70294..0000000000 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts.bak +++ /dev/null @@ -1,1288 +0,0 @@ -/** - * Turns crawled site styles into a token proposal in the TSP structure: - * colour primitives with 100-900 ramps, semantic aliases, and type, spacing, - * radius, shadow, layout and breakpoint scales. - * - * Usage: - * npx tsx propose-tokens.ts site-styles.json --out proposal.json --report proposal.md - * npx tsx propose-tokens.ts site-styles.json --assign brand=#8d621f,primary=#565b3d - */ - -import { readFileSync, writeFileSync } from 'node:fs'; -import { pathToFileURL } from 'node:url'; -import { Color, RampBuilder, RAMP_STEPS, RampStep, STEP_LIGHTNESS } from './lib/color'; -import type { ElementSample, PageCapture, Role, SiteStyles } from './crawl-site-styles'; - -export type Family = 'brand' | 'primary' | 'cta' | 'neutral'; -export const CHROMATIC_FAMILIES: Family[] = ['brand', 'primary', 'cta']; - -export const SYSTEM_DEFAULTS: Record = { - 'error-foreground': '#cc0000', - 'error-background': '#fabcbc', - 'warning-foreground': '#8a5a00', - 'warning-background': '#ffeeb2', - 'success-foreground': '#127301', - 'success-background': '#e3ffe6', - 'information-foreground': '#0047d0', - 'information-background': '#b9d1ff', -}; - -/** Default semantic aliases, from the TSP design system. */ -export const SEMANTIC_DEFAULTS: Record = { - 'text/default': 'contrast', - 'text/muted': 'neutral-600', - 'text/inverse': 'base', - 'text/inverse-subtle': 'neutral-100', - 'text/brand': 'brand-600', - 'text/link': 'brand-600', - 'text/link-hover': 'primary-500', - 'text/disabled': 'neutral-500', - 'text/placeholder': 'neutral-600', - 'surface/default': 'base', - 'surface/subtle': 'neutral-100', - 'surface/brand': 'brand-100', - 'surface/inverse': 'contrast', - 'surface/overlay': 'overlay', - 'surface/control-checked': 'brand-600', - 'surface/control-off': 'neutral-500', - 'surface/control-disabled': 'neutral-200', - 'border/default': 'neutral-500', - 'border/subtle': 'neutral-400', - 'border/strong': 'neutral-700', - 'border/divider': 'neutral-200', - 'border/focus': 'brand-600', - 'border/focus-inverse': 'brand-500', - 'action/primary/background': 'primary-500', - 'action/primary/background-hover': 'primary-600', - 'action/primary/text': 'base', - 'action/secondary/background': 'brand-600', - 'action/secondary/background-hover': 'brand-700', - 'action/secondary/text': 'base', - 'action/cta/background': 'cta-500', - 'action/cta/background-hover': 'cta-600', - 'action/cta/text': 'base', - 'feedback/error/text': 'error-foreground', - 'feedback/error/background': 'error-background', - 'feedback/error/border': 'error-foreground', - 'feedback/warning/text': 'warning-foreground', - 'feedback/warning/background': 'warning-background', - 'feedback/warning/border': 'warning-foreground', - 'feedback/success/text': 'success-foreground', - 'feedback/success/background': 'success-background', - 'feedback/success/border': 'success-foreground', - 'feedback/info/text': 'information-foreground', - 'feedback/info/background': 'information-background', - 'feedback/info/border': 'information-foreground', -}; - -export const SHADOW_ALPHAS = [5, 10, 12, 15, 20, 25, 30, 35, 40, 45, 60, 70, 85]; -/** The type ladder: slugs 100 to 900, body text at 200. Names are display names only. */ -const SIZE_NAMES = [ - 'Tiny', - 'Base', - 'Small', - 'Medium', - 'Large', - 'xLarge', - 'Huge', - 'Gigantic', - 'Colossal', -]; -/** Numeric slug for the nth step of a ladder that counts in hundreds (100, 200, ...). */ -const hundreds = (index: number) => String((index + 1) * 100); -/** The LightSpeed spacing ladder: the slug is the step, the name its T-shirt size. */ -export const SPACING_STEPS = [ - { slug: '5', name: 'XXS' }, - { slug: '10', name: 'XS' }, - { slug: '20', name: 'S' }, - { slug: '30', name: 'M' }, - { slug: '40', name: 'L' }, - { slug: '50', name: 'XL' }, - { slug: '60', name: 'XXL' }, - { slug: '70', name: 'XXXL' }, - { slug: '80', name: 'XXXXL' }, - { slug: '90', name: 'Gigantic' }, - { slug: '100', name: 'Colossal' }, -]; -const RADIUS_NAMES = ['Small', 'Base', 'Medium', 'Large', 'xLarge', 'Huge']; -const SHADOW_NAMES = ['xSmall', 'Small', 'Medium', 'Large', 'xLarge', 'Huge']; - -export interface ColourEvidence { - hex: string; - weight: number; - uses: Partial>; -} - -export interface Anchor { - family: Family; - hex: string; - step: RampStep; - source: 'observed' | 'assigned' | 'generated'; - evidence: string; -} - -export interface MatchRow { - value: string; - weight: number; - uses: string; - token: string; - distance: number; - match: 'exact' | 'near' | 'none'; -} - -export interface ContrastRow { - pair: string; - foreground: string; - background: string; - ratio: number; - required: number; - pass: boolean; -} - -export interface ScaleEntry { - name: string; - slug: string; - max: number; - min: number; - lineHeight?: number; -} - -export interface ShadowEffect { - type: 'DROP_SHADOW' | 'INNER_SHADOW'; - color: { r: number; g: number; b: number; a: number }; - offset: { x: number; y: number }; - radius: number; - spread: number; -} - -export interface ShadowEntry { - name: string; - slug: string; - css: string; - uses: number; - effects: ShadowEffect[]; -} - -export interface Proposal { - site: string; - generatedAt: string; - colour: { - primitives: Record; - anchors: Anchor[]; - semantic: Record; - overlay: string; - shadowAlphas: number[]; - }; - matches: MatchRow[]; - contrast: ContrastRow[]; - typography: { - families: { heading: string; body: string }; - sizes: ScaleEntry[]; - weights: Record; - }; - spacing: ScaleEntry[]; - radius: Array<{ name: string; slug: string; value: number }>; - shadows: ShadowEntry[]; - layout: { content?: number; wide?: number }; - breakpoints: { mobile: number; tablet: number; desktop: number }; - decisions: string[]; -} - -export interface ProposeOptions { - /** Force a family's anchor colour, for example { brand: '#8d621f' }. */ - assign?: Partial>; - /** Force the content and wide widths in px, for example { content: 768, wide: 1240 }. */ - layout?: { content?: number; wide?: number }; - now?: () => Date; -} - -/** Weighted mode of a list of values. */ -function mode(values: Array<{ value: T; weight?: number }>): T | undefined { - const counts = new Map(); - for (const { value, weight } of values) { - counts.set(value, (counts.get(value) ?? 0) + (weight ?? 1)); - } - let best: T | undefined; - let bestCount = -1; - for (const [value, count] of counts) { - if (count > bestCount) { - best = value; - bestCount = count; - } - } - return best; -} - -/** Fit test limits for site colours placed into ramps. See `fitSiteColours`. */ -const FIT_HUE_TOLERANCE = 25; -const FIT_MIN_CHROMA = 0.025; -const FIT_NEUTRAL_CHROMA = 0.04; -const FIT_LIGHTNESS_TOLERANCE = 0.04; - -export class TokenProposer { - private readonly ramps = new RampBuilder(); - private decisions: string[] = []; - - propose(styles: SiteStyles, options: ProposeOptions = {}): Proposal { - this.decisions = []; - const desktopWidth = Math.max(...styles.viewports); - const mobileWidth = Math.min(...styles.viewports); - const desktop = styles.captures.filter((c) => c.viewport === desktopWidth); - const mobile = styles.captures.filter((c) => c.viewport === mobileWidth); - const desktopSamples = desktop.flatMap((c) => c.samples.map((s) => ({ ...s, page: c.url }))); - const mobileByKey = new Map(); - for (const capture of mobile) { - for (const sample of capture.samples) { - mobileByKey.set(`${capture.url}|${sample.key}`, sample); - } - } - const pair = (s: ElementSample & { page: string }) => mobileByKey.get(`${s.page}|${s.key}`); - - const evidence = this.colourEvidence(desktopSamples); - const colour = this.proposeColour(evidence, options.assign ?? {}); - const matches = this.matchColours(evidence, colour.primitives); - const contrast = this.checkContrast(colour.primitives, colour.semantic); - const typography = this.proposeTypography(desktopSamples, pair); - const spacing = this.proposeSpacing(desktopSamples, pair); - const radius = this.proposeRadius(desktopSamples); - const shadows = this.proposeShadows(desktopSamples); - const layout = this.proposeLayout(desktopSamples, desktopWidth, desktop, options.layout); - const breakpoints = this.proposeBreakpoints(styles.captures); - - return { - site: styles.site, - generatedAt: (options.now ?? (() => new Date()))().toISOString(), - colour, - matches, - contrast, - typography, - spacing, - radius, - shadows, - layout, - breakpoints, - decisions: this.decisions, - }; - } - - /** Counts every opaque colour by where it is used. */ - colourEvidence(samples: ElementSample[]): ColourEvidence[] { - const byHex = new Map(); - const add = (value: string | undefined, use: string, weight: number) => { - const color = value ? Color.parse(value) : null; - if (!color || color.rgb.a < 0.05) { - return; - } - const hex = color.toHex(); - const entry = byHex.get(hex) ?? { hex, weight: 0, uses: {} }; - entry.weight += weight; - entry.uses[use] = (entry.uses[use] ?? 0) + 1; - byHex.set(hex, entry); - }; - for (const s of samples) { - add(s.color, `${s.role}-text`, 1); - add(s.background, `${s.role}-background`, s.role === 'section' ? 3 : 1); - add(s.border, `${s.role}-border`, 0.5); - } - return [...byHex.values()].sort((a, b) => b.weight - a.weight); - } - - proposeColour( - evidence: ColourEvidence[], - assign: Partial> - ): Proposal['colour'] { - const opaque = evidence.filter((e) => Color.parse(e.hex)!.isOpaque); - const isNeutral = (hex: string) => Color.parse(hex)!.toOklch().c < 0.025; - const lightness = (hex: string) => Color.parse(hex)!.toOklch().l; - const usage = (e: ColourEvidence, suffix: string) => - Object.entries(e.uses) - .filter(([use]) => use.endsWith(suffix)) - .reduce((total, [, n]) => total + (n ?? 0), 0); - - const base = - opaque.find((e) => isNeutral(e.hex) && lightness(e.hex) > 0.9 && usage(e, '-background') > 0) - ?.hex ?? '#ffffff'; - const contrast = - opaque.find((e) => lightness(e.hex) < 0.4 && (e.uses['body-text'] ?? 0) > 0)?.hex ?? - opaque.find((e) => lightness(e.hex) < 0.4 && usage(e, '-text') > 0)?.hex ?? - '#1a1a1a'; - if (base === '#ffffff' && !opaque.some((e) => e.hex === '#ffffff')) { - this.decisions.push('No light page background was found, so `base` defaults to #ffffff.'); - } - - // Group chromatic colours into clusters of near-identical values. - const clusters: ColourEvidence[] = []; - for (const e of opaque.filter((x) => !isNeutral(x.hex))) { - const color = Color.parse(e.hex)!; - const home = clusters.find((c) => Color.parse(c.hex)!.distance(color) < 6); - if (home) { - home.weight += e.weight; - for (const [use, n] of Object.entries(e.uses)) { - home.uses[use] = (home.uses[use] ?? 0) + (n ?? 0); - } - } else { - clusters.push({ hex: e.hex, weight: e.weight, uses: { ...e.uses } }); - } - } - clusters.sort((a, b) => b.weight - a.weight); - - const describe = (c: ColourEvidence) => - Object.entries(c.uses) - .sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0)) - .slice(0, 3) - .map(([use, n]) => `${use} ×${n}`) - .join(', '); - - const anchors: Anchor[] = []; - const taken = new Set(); - const pick = (family: Family, chooser: (c: ColourEvidence) => number, reason: string) => { - if (assign[family]) { - const hex = Color.parse(assign[family]!)?.toHex(); - if (!hex) { - throw new Error(`--assign ${family}=${assign[family]} is not a colour.`); - } - taken.add(hex); - anchors.push({ - family, - hex, - step: this.ramps.nearestStep(lightness(hex)), - source: 'assigned', - evidence: 'Assigned by the reviewer.', - }); - return; - } - const candidates = clusters - .filter((c) => !taken.has(c.hex)) - .map((c) => ({ c, score: chooser(c) })) - .filter((x) => x.score > 0) - .sort((a, b) => b.score - a.score); - const chosen = candidates[0]?.c; - if (chosen) { - taken.add(chosen.hex); - anchors.push({ - family, - hex: chosen.hex, - step: this.ramps.nearestStep(lightness(chosen.hex)), - source: 'observed', - evidence: `${reason}: ${describe(chosen)}`, - }); - return; - } - const ref = anchors[0] ? Color.parse(anchors[0].hex)!.toOklch() : { l: 0.55, c: 0.12, h: 30 }; - const offsets: Record = { brand: 0, primary: 120, cta: 200 }; - const generated = Color.fromOklch({ - l: 0.5, - c: Math.max(ref.c, 0.1), - h: (ref.h + offsets[family]) % 360, - }).toHex(); - anchors.push({ - family, - hex: generated, - step: 600, - source: 'generated', - evidence: 'No distinct colour on the site.', - }); - this.decisions.push( - `No site colour fits \`${family}\`; ${generated} was generated as a placeholder. Choose one.` - ); - }; - - const chroma = (hex: string) => Color.parse(hex)!.toOklch().c; - // The call to action is the most saturated colour that fills a button. - pick( - 'cta', - (c) => (usage(c, 'button-background') > 0 ? chroma(c.hex) : 0), - 'Most saturated button fill' - ); - // The brand colour dresses buttons and in-text links. - pick( - 'brand', - (c) => - usage(c, 'button-background') * 2 + - usage(c, 'button-border') + - usage(c, 'button-text') + - usage(c, 'link-text') * 2, - 'Most used on buttons and in-text links' - ); - pick('primary', (c) => c.weight, 'Next most used colour'); - - const primitives: Record = { base, contrast }; - for (const anchor of anchors) { - const ramp = this.ramps.build(anchor.hex); - anchor.step = ramp.anchorStep; - for (const step of RAMP_STEPS) { - primitives[`${anchor.family}-${step}`] = ramp.steps[step]; - } - } - - // Neutral ramp: the site's mid grey if it has one, else a grey tinted like its greys. - const neutrals = opaque.filter((e) => isNeutral(e.hex) && e.hex !== base && e.hex !== contrast); - const midGrey = neutrals - .filter((e) => Math.abs(lightness(e.hex) - 0.62) < 0.12) - .sort((a, b) => Math.abs(lightness(a.hex) - 0.62) - Math.abs(lightness(b.hex) - 0.62))[0]; - let neutralAnchor = midGrey?.hex; - if (!neutralAnchor) { - const tinted = neutrals.map((e) => Color.parse(e.hex)!.toOklch()).filter((o) => o.c > 0.003); - const hue = tinted.length ? tinted.reduce((t, o) => t + o.h, 0) / tinted.length : 60; - const chroma = tinted.length - ? Math.min(0.012, tinted.reduce((t, o) => t + o.c, 0) / tinted.length) - : 0.006; - neutralAnchor = Color.fromOklch({ l: 0.62, c: chroma, h: hue }).toHex(); - } - const neutral = this.ramps.build(neutralAnchor, { maxChroma: 0.02 }); - anchors.push({ - family: 'neutral', - hex: neutralAnchor, - step: neutral.anchorStep, - source: midGrey ? 'observed' : 'generated', - evidence: midGrey - ? `Mid grey used on the site: ${describe(midGrey)}` - : 'Tinted from the site greys.', - }); - for (const step of RAMP_STEPS) { - primitives[`neutral-${step}`] = neutral.steps[step]; - } - this.fitSiteColours(opaque, primitives, anchors, [base, contrast]); - Object.assign(primitives, SYSTEM_DEFAULTS); - - const shadowBase = Color.parse(primitives['neutral-900'])!.rgb; - const overlay = Color.fromRgb({ ...shadowBase, a: 0.25 }).toHex(); - - const semantic = this.proposeSemantic(evidence, primitives); - return { primitives, anchors, semantic, overlay, shadowAlphas: SHADOW_ALPHAS }; - } - - /** - * Replaces generated ramp steps with real site colours that fit the ramp. - * - * A site colour fits a family's ramp when all of these hold: - * 1. Hue: chromatic families need the same hue family as the anchor (within - * FIT_HUE_TOLERANCE degrees) and a chroma between 0.4x and 1.6x the anchor's, - * and at least 0.025. The neutral family needs chroma of 0.04 or less. - * 2. Lightness: it sits within FIT_LIGHTNESS_TOLERANCE of the target lightness - * of its nearest step, so it reads as that step. - * 3. Monotonic: it is lighter than the step after it and darker than the step - * before it, using the ramp's current values, so lightness still falls from - * 100 to 900. - * The anchor step is never replaced. Colours are handled heaviest first, each - * goes to the family whose nearest step is closest, and a step already claimed - * by a heavier colour is not taken again. Colours that fit nowhere keep being - * matched to the nearest token. - */ - fitSiteColours( - candidates: ColourEvidence[], - primitives: Record, - anchors: Anchor[], - exclude: string[] - ): void { - const skip = new Set([...exclude, ...anchors.map((a) => a.hex), ...Object.values(primitives)]); - const claimed = new Map(); - const lightnessOf = (hex: string) => Color.parse(hex)!.toOklch().l; - const ordered = [...candidates].sort((a, b) => b.weight - a.weight); - - for (const site of ordered) { - if (skip.has(site.hex)) { - continue; - } - const color = Color.parse(site.hex)!; - const o = color.toOklch(); - const step = this.ramps.nearestStep(o.l); - if (Math.abs(STEP_LIGHTNESS[step] - o.l) > FIT_LIGHTNESS_TOLERANCE) { - continue; - } - let best: { slug: string; family: string; distance: number } | undefined; - for (const anchor of anchors) { - const slug = `${anchor.family}-${step}`; - if (step === anchor.step || !this.fitsRamp(o, anchor)) { - continue; - } - if (!this.keepsRampMonotonic(anchor.family, step, o.l, primitives, lightnessOf)) { - continue; - } - const distance = color.distance(Color.parse(primitives[slug])!); - if (!best || distance < best.distance) { - best = { slug, family: anchor.family, distance }; - } - } - if (!best) { - continue; - } - const holder = claimed.get(best.slug); - if (holder) { - this.decisions.push( - `Site colour ${site.hex} also fits ${best.slug}, but ${holder} is used more, so ${best.slug} keeps ${holder}.` - ); - continue; - } - this.decisions.push( - `Site colour ${site.hex} replaced ${best.slug} (was ${primitives[best.slug]}).` - ); - primitives[best.slug] = site.hex; - claimed.set(best.slug, site.hex); - } - } - - /** Hue and chroma part of the fits test. */ - private fitsRamp(o: { l: number; c: number; h: number }, anchor: Anchor): boolean { - const a = Color.parse(anchor.hex)!.toOklch(); - if (anchor.family === 'neutral') { - // Any site grey fits, whatever its tint: the ramp should match the site's own greys. - return o.c <= FIT_NEUTRAL_CHROMA; - } - const hueGap = Math.min(Math.abs(o.h - a.h), 360 - Math.abs(o.h - a.h)); - return ( - o.c >= FIT_MIN_CHROMA && hueGap <= FIT_HUE_TOLERANCE && o.c >= a.c * 0.4 && o.c <= a.c * 1.6 - ); - } - - /** True when `lightness` sits strictly between the ramp's neighbours of `step`. */ - private keepsRampMonotonic( - family: string, - step: RampStep, - lightness: number, - primitives: Record, - lightnessOf: (hex: string) => number - ): boolean { - const index = RAMP_STEPS.indexOf(step); - const lighter = RAMP_STEPS[index - 1]; - const darker = RAMP_STEPS[index + 1]; - const above = lighter ? lightnessOf(primitives[`${family}-${lighter}`]) : Infinity; - const below = darker ? lightnessOf(primitives[`${family}-${darker}`]) : -Infinity; - return lightness < above && lightness > below; - } - - proposeSemantic( - evidence: ColourEvidence[], - primitives: Record - ): Proposal['colour']['semantic'] { - const semantic: Proposal['colour']['semantic'] = {}; - for (const [role, token] of Object.entries(SEMANTIC_DEFAULTS)) { - semantic[role] = { token, source: 'default' }; - } - const heaviest = (use: string, chromaticOnly = false) => - evidence - .filter( - (e) => - (e.uses[use] ?? 0) > 0 && - Color.parse(e.hex)!.isOpaque && - (!chromaticOnly || Color.parse(e.hex)!.toOklch().c >= 0.025) - ) - .sort((a, b) => (b.uses[use] ?? 0) - (a.uses[use] ?? 0))[0]; - const page = Color.parse(primitives.base)!; - const observe = (role: string, use: string, family?: string, chromaticOnly = false) => { - const found = heaviest(use, chromaticOnly) ?? (chromaticOnly ? heaviest(use) : undefined); - if (!found) { - return; - } - // A text colour that can't be read on the page surface comes from photos or dark bands. - if (role.startsWith('text/') && Color.parse(found.hex)!.contrast(page) < 3) { - this.decisions.push( - `\`${role}\` kept the default \`${semantic[role].token}\`: the site's most used ${use} colour (${found.hex}) is unreadable on \`base\`, so it probably sits on photos or dark sections.` - ); - return; - } - const token = this.nearestPrimitive(found.hex, primitives, family); - semantic[role] = { - token, - source: 'observed', - evidence: `${found.hex} (${use} ×${found.uses[use]})`, - }; - return token; - }; - - observe('text/default', 'body-text'); - // Prefer a coloured link: white or black links usually sit on photos or in menus. - observe('text/link', 'link-text', undefined, true); - if (!heaviest('link-text')) { - observe('text/link', 'nav-text', undefined, true); - } - const buttonBg = observe('action/primary/background', 'button-background'); - observe('action/primary/text', 'button-text'); - observe('border/default', 'input-border'); - if (buttonBg) { - semantic['action/primary/background-hover'] = { - token: this.darker(buttonBg), - source: 'observed', - evidence: `One step darker than ${buttonBg}.`, - }; - } - - const light = evidence.filter( - (e) => - (e.uses['section-background'] ?? 0) > 0 && - Color.parse(e.hex)!.isOpaque && - e.hex !== primitives.base && - Color.parse(e.hex)!.toOklch().l > 0.85 - )[0]; - if (light) { - semantic['surface/subtle'] = { - token: this.nearestPrimitive(light.hex, primitives), - source: 'observed', - evidence: `${light.hex} (section-background ×${light.uses['section-background']})`, - }; - } - const dark = evidence.filter( - (e) => - (e.uses['section-background'] ?? 0) > 0 && - Color.parse(e.hex)!.isOpaque && - Color.parse(e.hex)!.toOklch().l < 0.35 - )[0]; - if (dark) { - semantic['surface/inverse'] = { - token: this.nearestPrimitive(dark.hex, primitives), - source: 'observed', - evidence: `${dark.hex} (section-background ×${dark.uses['section-background']})`, - }; - } - return semantic; - } - - nearestPrimitive(hex: string, primitives: Record, family?: string): string { - const color = Color.parse(hex)!; - let best = 'contrast'; - let bestDistance = Infinity; - for (const [slug, value] of Object.entries(primitives)) { - if (family && !slug.startsWith(family)) { - continue; - } - const d = color.distance(Color.parse(value)!); - if (d < bestDistance) { - best = slug; - bestDistance = d; - } - } - return best; - } - - matchColours(evidence: ColourEvidence[], primitives: Record): MatchRow[] { - return evidence.slice(0, 40).map((e) => { - const token = this.nearestPrimitive(e.hex, primitives); - const distance = - Math.round(Color.parse(e.hex)!.distance(Color.parse(primitives[token])!) * 10) / 10; - return { - value: e.hex, - weight: Math.round(e.weight * 10) / 10, - uses: Object.entries(e.uses) - .sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0)) - .slice(0, 3) - .map(([use, n]) => `${use} ×${n}`) - .join(', '), - token, - distance, - match: distance < 0.5 ? 'exact' : distance < 6 ? 'near' : 'none', - }; - }); - } - - checkContrast( - primitives: Record, - semantic: Proposal['colour']['semantic'] - ): ContrastRow[] { - const resolve = (role: string) => { - const token = semantic[role]?.token ?? role; - return primitives[token]; - }; - const pairs: Array<[string, string, number]> = [ - ['text/default', 'surface/default', 4.5], - ['text/muted', 'surface/default', 4.5], - ['text/link', 'surface/default', 4.5], - ['text/link-hover', 'surface/default', 4.5], - ['text/placeholder', 'surface/default', 4.5], - ['text/default', 'surface/subtle', 4.5], - ['text/inverse', 'surface/inverse', 4.5], - ['action/primary/text', 'action/primary/background', 4.5], - ['action/primary/text', 'action/primary/background-hover', 4.5], - ['action/secondary/text', 'action/secondary/background', 4.5], - ['action/cta/text', 'action/cta/background', 4.5], - ['border/focus', 'surface/default', 3], - ['border/default', 'surface/default', 3], - ['feedback/error/text', 'surface/default', 4.5], - ['feedback/warning/text', 'surface/default', 4.5], - ['feedback/success/text', 'surface/default', 4.5], - ['feedback/info/text', 'surface/default', 4.5], - ]; - return pairs.map(([fg, bg, required]) => { - const foreground = resolve(fg); - const background = resolve(bg); - const ratio = - Math.round(Color.parse(foreground)!.contrast(Color.parse(background)!) * 100) / 100; - return { - pair: `${fg} on ${bg}`, - foreground, - background, - ratio, - required, - pass: ratio >= required, - }; - }); - } - - proposeTypography( - samples: Array, - pair: (s: ElementSample & { page: string }) => ElementSample | undefined - ): Proposal['typography'] { - const textRoles: Role[] = [ - 'body', - 'h1', - 'h2', - 'h3', - 'h4', - 'h5', - 'h6', - 'button', - 'link', - 'nav', - 'input', - ]; - const text = samples.filter((s) => textRoles.includes(s.role) && s.fontSize); - const headings = text.filter((s) => /^h[1-3]$/.test(s.role)); - const body = text.filter((s) => s.role === 'body'); - const families = { - heading: - mode(headings.map((s) => ({ value: s.fontFamily ?? '' }))) || - mode(text.map((s) => ({ value: s.fontFamily ?? '' }))) || - 'serif', - body: mode(body.map((s) => ({ value: s.fontFamily ?? '' }))) || 'sans-serif', - }; - - const bodySize = mode(body.map((s) => ({ value: Math.round(s.fontSize!) }))) ?? 16; - const pairs = new Map(); - for (const s of text) { - const max = Math.round(s.fontSize!); - const mobileSize = pair(s)?.fontSize; - const entry = pairs.get(max) ?? { min: max, weight: 0, ratios: [] }; - entry.weight += /^h/.test(s.role) ? 3 : 1; - if (mobileSize) { - entry.min = Math.min(entry.min, Math.round(mobileSize)); - } - const ratio = s.lineHeight ? Math.round((s.lineHeight / s.fontSize!) * 100) / 100 : 0; - if (ratio >= 0.9 && ratio <= 2.5) { - entry.ratios.push(ratio); // Outside this range is usually an icon or a fixed-height box. - } - pairs.set(max, entry); - } - - const below = [...pairs.keys()] - .filter((v) => v < bodySize) - .sort((a, b) => pairs.get(b)!.weight - pairs.get(a)!.weight); - let above = [...pairs.keys()].filter((v) => v > bodySize).sort((a, b) => a - b); - if (below.length > 1) { - this.decisions.push( - `Sizes smaller than body text (${below.join(', ')}px) share the one Tiny slot; ${below[0]}px was kept.` - ); - } - const slots = SIZE_NAMES.length - 2; - while (above.length > slots) { - // Merge the two closest sizes, keeping the more used one. - let closest = 0; - for (let i = 1; i < above.length - 1; i++) { - if (above[i + 1] / above[i] < above[closest + 1] / above[closest]) { - closest = i; - } - } - const [a, b] = [above[closest], above[closest + 1]]; - const drop = pairs.get(a)!.weight >= pairs.get(b)!.weight ? b : a; - this.decisions.push( - `The ${drop}px size was merged into the nearest size to fit the ${SIZE_NAMES.length}-step scale.` - ); - above = above.filter((v) => v !== drop); - } - - const scale = [...(below.length ? [below[0]] : []), bodySize, ...above]; - const firstIndex = below.length ? 0 : 1; - const sizes: ScaleEntry[] = scale.map((max, i) => { - const entry = pairs.get(max) ?? { min: max, weight: 0, ratios: [] }; - const name = SIZE_NAMES[firstIndex + i]; - return { - name, - slug: hundreds(firstIndex + i), - max, - min: Math.min(entry.min, max), - lineHeight: mode(entry.ratios.map((value) => ({ value }))), - }; - }); - - const weights: Record = {}; - for (const role of textRoles) { - const weight = mode( - text.filter((s) => s.role === role && s.fontWeight).map((s) => ({ value: s.fontWeight! })) - ); - if (weight) { - weights[role] = weight; - } - } - return { families, sizes, weights }; - } - - proposeSpacing( - samples: Array, - pair: (s: ElementSample & { page: string }) => ElementSample | undefined - ): ScaleEntry[] { - const values: Array<{ max: number; min: number; weight: number }> = []; - for (const s of samples) { - const m = pair(s); - if (s.paddingBlock && ['section', 'surface'].includes(s.role)) { - values.push({ - max: Math.round(s.paddingBlock), - min: Math.round(m?.paddingBlock ?? s.paddingBlock), - weight: s.role === 'section' ? 2 : 1, - }); - } - if (s.gap) { - values.push({ max: Math.round(s.gap), min: Math.round(m?.gap ?? s.gap), weight: 1 }); - } - if (s.marginBlock && ['section', 'surface'].includes(s.role)) { - values.push({ - max: Math.round(s.marginBlock), - min: Math.round(m?.marginBlock ?? s.marginBlock), - weight: s.role === 'section' ? 2 : 1, - }); - } - } - values.sort((a, b) => a.max - b.max); - // Values under 8px are borders and hairline offsets, not layout spacing. - const layout = values.filter((v) => v.max >= 8); - - const clusters: Array<{ start: number; items: typeof values }> = []; - for (const v of layout) { - const last = clusters[clusters.length - 1]; - if (last && v.max <= last.start * 1.12 + 1) { - last.items.push(v); - } else { - clusters.push({ start: v.max, items: [v] }); - } - } - let kept = clusters - .map((c) => ({ - max: mode(c.items.map((i) => ({ value: i.max, weight: i.weight })))!, - min: mode(c.items.map((i) => ({ value: i.min, weight: i.weight })))!, - weight: c.items.reduce((t, i) => t + i.weight, 0), - })) - .filter((c) => c.weight >= 2); - if (kept.length > SPACING_STEPS.length) { - const byUse = [...kept].sort((a, b) => b.weight - a.weight); - const dropped = byUse.slice(SPACING_STEPS.length).sort((a, b) => a.max - b.max); - kept = byUse.slice(0, SPACING_STEPS.length).sort((a, b) => a.max - b.max); - this.decisions.push( - `${dropped.length} rarely used spacing values were left out of the scale: ${dropped.map((d) => `${d.max}px`).join(', ')}.` - ); - } - // Each value takes the ladder step nearest its desktop size, so 40px becomes - // L (slug 40). A taken step pushes the value up to the next free step. If that - // runs off the top of the ladder, values shift back down into free lower steps - // (starting at 5) instead of being dropped. At most the ladder's length is kept - // above, so every kept value always gets a step. - const last = SPACING_STEPS.length - 1; - const indexes: number[] = []; - for (const c of kept) { - const nearest = SPACING_STEPS.reduce( - (best, step, i) => - Math.abs(Number(step.slug) - c.max) < Math.abs(Number(SPACING_STEPS[best].slug) - c.max) - ? i - : best, - 0 - ); - indexes.push(Math.max(nearest, indexes.length ? indexes[indexes.length - 1] + 1 : 0)); - } - let shifted = false; - for (let i = indexes.length - 1; i >= 0; i--) { - const ceiling = i === indexes.length - 1 ? last : indexes[i + 1] - 1; - if (indexes[i] > ceiling) { - indexes[i] = ceiling; - shifted = true; - } - } - if (shifted) { - this.decisions.push( - 'Some spacing values moved down to free lower steps so the whole 5 to 100 ladder is used and none is dropped.' - ); - } - const steps: ScaleEntry[] = kept.map((c, i) => ({ - ...SPACING_STEPS[indexes[i]], - max: c.max, - min: Math.min(c.min, c.max), - })); - return [{ name: 'None', slug: 'none', max: 0, min: 0 }, ...steps]; - } - - proposeRadius(samples: ElementSample[]): Proposal['radius'] { - const counts = new Map(); - for (const s of samples) { - if (!s.radius) { - continue; - } - const value = s.radius.endsWith('%') ? 9999 : Math.round(parseFloat(s.radius)); - if (value > 0) { - counts.set(value >= 999 ? 9999 : value, (counts.get(value >= 999 ? 9999 : value) ?? 0) + 1); - } - } - const values = [...counts.entries()] - .filter(([v]) => v !== 9999) - .sort((a, b) => b[1] - a[1]) - .slice(0, RADIUS_NAMES.length) - .map(([v]) => v) - .sort((a, b) => a - b); - return [ - { name: 'None', slug: '0', value: 0 }, - ...values.map((value, i) => ({ name: RADIUS_NAMES[i], slug: hundreds(i), value })), - { name: 'Round', slug: '700', value: 9999 }, - ]; - } - - proposeShadows(samples: ElementSample[]): ShadowEntry[] { - const counts = new Map(); - for (const s of samples) { - if (s.shadow) { - counts.set(s.shadow, (counts.get(s.shadow) ?? 0) + 1); - } - } - const parsed = [...counts.entries()] - .map(([css, uses]) => ({ css, uses, effects: TokenProposer.parseShadow(css) })) - .filter((s) => s.effects.length) - .sort((a, b) => b.uses - a.uses) - .slice(0, SHADOW_NAMES.length) - .sort( - (a, b) => - a.effects.reduce((t, e) => t + e.radius, 0) - b.effects.reduce((t, e) => t + e.radius, 0) - ); - return parsed.map((s, i) => ({ name: SHADOW_NAMES[i], slug: hundreds(i), ...s })); - } - - /** Parses a computed box-shadow into effects. */ - static parseShadow(css: string): ShadowEffect[] { - const layers: string[] = []; - let depth = 0; - let current = ''; - for (const ch of css) { - if (ch === '(') depth++; - if (ch === ')') depth--; - if (ch === ',' && depth === 0) { - layers.push(current); - current = ''; - } else { - current += ch; - } - } - layers.push(current); - - return layers.flatMap((layer) => { - const colorMatch = layer.match(/rgba?\([^)]*\)|#[0-9a-f]{3,8}/i); - const color = colorMatch ? Color.parse(colorMatch[0]) : null; - const numbers = layer - .replace(colorMatch?.[0] ?? '', '') - .split(/\s+/) - .filter((t) => /^-?[\d.]+(px)?$/.test(t)) - .map((t) => parseFloat(t)); - if (!color || numbers.length < 2) { - return []; - } - const [x, y, blur = 0, spread = 0] = numbers; - const round = (n: number) => Math.round(n * 1000) / 1000; - return [ - { - type: /\binset\b/.test(layer) ? 'INNER_SHADOW' : 'DROP_SHADOW', - color: { - r: round(color.rgb.r), - g: round(color.rgb.g), - b: round(color.rgb.b), - a: round(color.rgb.a), - }, - offset: { x, y }, - radius: blur, - spread, - } as ShadowEffect, - ]; - }); - } - - /** - * Content width is the width of running text (`p` in the main column) on single posts - * and pages. Wide width is the widest repeated centred container. Either can be forced. - */ - proposeLayout( - samples: ElementSample[], - viewport: number, - captures: PageCapture[] = [], - override: { content?: number; wide?: number } = {} - ): Proposal['layout'] { - const counts = new Map(); - for (const s of samples) { - if (s.containerWidth && s.containerWidth < viewport - 16) { - const width = Math.round(s.containerWidth / 8) * 8; - counts.set(width, (counts.get(width) ?? 0) + 1); - } - } - const frequent = [...counts.entries()].filter(([, n]) => n >= 2).sort((a, b) => b[1] - a[1]); - const wide = override.wide ?? (frequent.length ? Math.max(...frequent.map(([w]) => w)) : undefined); - - let content = override.content; - if (content === undefined) { - const single = captures.filter((c) => c.pageKind === 'single'); - const fromSingles = single.flatMap((c) => c.textWidths ?? []); - const fromAny = captures.flatMap((c) => c.textWidths ?? []); - const widths = fromSingles.length ? fromSingles : fromAny; - if (widths.length) { - content = mode(widths.map((w) => ({ value: Math.round(w / 8) * 8 }))); - if (!fromSingles.length) { - this.decisions.push( - 'No single post or page was captured, so the content width was measured on listing pages and may be a card. Add a long text page, or set it with `--layout content=`.' - ); - } - } else if (frequent.length) { - const fallback = frequent.find(([w]) => w <= (wide ?? 0) * 0.8)?.[0]; - if (fallback) { - content = fallback; - this.decisions.push( - `No running text was found, so the content width ${fallback}px comes from the most common centred container. Check it, or set it with \`--layout content=\`.` - ); - } - } - } - if (content === undefined && wide === undefined) { - this.decisions.push( - 'No running text or repeated centred container was found; set the content and wide widths with `--layout content=,wide=`.' - ); - return {}; - } - if (content !== undefined && content < 480) { - this.decisions.push( - `The content width is ${content}px, under 480px, which is narrower than a readable text column. Confirm it, or set it with \`--layout content=\`.` - ); - } - return { - ...(content !== undefined ? { content } : {}), - ...(wide !== undefined ? { wide } : {}), - }; - } - - proposeBreakpoints(captures: PageCapture[]): Proposal['breakpoints'] { - const widths = captures.flatMap((c) => c.mediaWidths); - const pick = (low: number, high: number, fallback: number) => - mode(widths.filter((w) => w > low && w <= high).map((value) => ({ value }))) ?? fallback; - return { - mobile: pick(300, 600, 376), - tablet: pick(600, 1024, 768), - desktop: pick(1024, 1600, 1240), - }; - } - - private darker(token: string): string { - const match = token.match(/^(.*)-(\d00)$/); - if (!match || match[2] === '900') { - return token; - } - return `${match[1]}-${Number(match[2]) + 100}`; - } -} - -/** Writes the proposal as a Markdown report for approval. */ -export class ProposalReport { - render(p: Proposal): string { - const lines: string[] = []; - const table = (head: string[], rows: Array>) => { - lines.push(`| ${head.join(' | ')} |`, `| ${head.map(() => '---').join(' | ')} |`); - for (const row of rows) { - lines.push(`| ${row.join(' | ')} |`); - } - lines.push(''); - }; - const failing = p.contrast.filter((c) => !c.pass); - - lines.push( - `# Token proposal: ${p.site}`, - '', - `Generated ${p.generatedAt.slice(0, 10)}. Nothing is written to Figma or a theme until this is approved.`, - '' - ); - lines.push('## Summary', ''); - lines.push( - `- Colour anchors: ${p.colour.anchors.map((a) => `${a.family} ${a.hex} at ${a.step}`).join('; ')}` - ); - lines.push( - `- Live colours matched: ${p.matches.filter((m) => m.match === 'exact').length} exact, ${p.matches.filter((m) => m.match === 'near').length} near, ${p.matches.filter((m) => m.match === 'none').length} no match` - ); - lines.push( - `- Contrast: ${p.contrast.length - failing.length} of ${p.contrast.length} pairs pass${failing.length ? ` (failing: ${failing.map((f) => f.pair).join('; ')})` : ''}` - ); - lines.push( - `- Fonts: headings ${p.typography.families.heading}, body ${p.typography.families.body}`, - '' - ); - - lines.push('## Decisions for the reviewer', ''); - const decisions = [...p.decisions]; - for (const anchor of p.colour.anchors) { - if (anchor.source === 'observed') { - decisions.push( - `Confirm \`${anchor.family}\`: ${anchor.hex} at step ${anchor.step} (${anchor.evidence}).` - ); - } - } - lines.push(...(decisions.length ? decisions.map((d) => `- ${d}`) : ['- None.']), ''); - - lines.push('## Colour primitives (Theme - Colour)', ''); - table( - ['Family', ...RAMP_STEPS.map(String)], - (['brand', 'primary', 'cta', 'neutral'] as Family[]).map((f) => [ - f, - ...RAMP_STEPS.map((s) => `\`${p.colour.primitives[`${f}-${s}`]}\``), - ]) - ); - lines.push( - `\`base\` ${p.colour.primitives.base}, \`contrast\` ${p.colour.primitives.contrast}, overlay ${p.colour.overlay}. System colours use the LightSpeed defaults.`, - '' - ); - - lines.push('## Semantic tokens (Theme - Semantic)', ''); - table( - ['Role', 'Token', 'Value', 'Source'], - Object.entries(p.colour.semantic).map(([role, s]) => [ - `\`${role}\``, - `\`${s.token}\``, - p.colour.primitives[s.token] ?? p.colour.overlay, - s.source === 'observed' ? `site: ${s.evidence}` : 'default', - ]) - ); - - lines.push('## Live colours to tokens', ''); - table( - ['Live value', 'Used on', 'Token', 'Distance', 'Match'], - p.matches.map((m) => [m.value, m.uses, `\`${m.token}\``, m.distance, m.match]) - ); - - lines.push('## Contrast (WCAG 2.2)', ''); - table( - ['Pair', 'Ratio', 'Needs', 'Result'], - p.contrast.map((c) => [c.pair, c.ratio, `${c.required}:1`, c.pass ? 'pass' : '**fail**']) - ); - - lines.push('## Typography (Theme - Typography)', ''); - table( - ['Size', 'Slug', 'Desktop (Max)', 'Mobile (Min)', 'Line height'], - p.typography.sizes.map((s) => [ - s.name, - `\`${s.slug}\``, - `${s.max}px`, - `${s.min}px`, - s.lineHeight ?? '-', - ]) - ); - lines.push( - `Weights by role: ${ - Object.entries(p.typography.weights) - .map(([r, w]) => `${r} ${w}`) - .join(', ') || 'none found' - }.`, - '' - ); - - lines.push('## Spacing (Theme - Spacing)', ''); - table( - ['Name', 'Slug', 'Max', 'Min'], - p.spacing.map((s) => [s.name, `\`${s.slug}\``, `${s.max}px`, `${s.min}px`]) - ); - - lines.push('## Radius, shadows and layout', ''); - table( - ['Radius', 'Slug', 'Value'], - p.radius.map((r) => [r.name, `\`${r.slug}\``, `${r.value}px`]) - ); - table( - ['Shadow', 'Slug', 'Uses', 'CSS'], - p.shadows.map((s) => [s.name, `\`${s.slug}\``, s.uses, `\`${s.css}\``]) - ); - lines.push( - `Layout: content ${p.layout.content ?? '?'}px, wide ${p.layout.wide ?? '?'}px. Breakpoints: mobile ${p.breakpoints.mobile}px, tablet ${p.breakpoints.tablet}px, desktop ${p.breakpoints.desktop}px.`, - '' - ); - return `${lines.join('\n')}\n`; - } -} - -export interface ProposeCliIo { - readFile: (path: string) => string; - writeFile: (path: string, content: string) => void; - stdout: (text: string) => void; - stderr: (text: string) => void; -} - -export function runProposeCli(argv: string[], io: ProposeCliIo): number { - let input: string | undefined; - let out = 'proposal.json'; - let report: string | undefined; - const assign: Partial> = {}; - const layout: { content?: number; wide?: number } = {}; - - try { - for (let i = 0; i < argv.length; i++) { - const arg = argv[i]; - const next = () => { - const value = argv[++i]; - if (value === undefined) { - throw new Error(`${arg} needs a value.`); - } - return value; - }; - if (arg === '--help' || arg === '-h') { - io.stdout( - 'Usage: propose-tokens [--out proposal.json] [--report proposal.md] [--assign brand=#hex,primary=#hex,cta=#hex] [--layout content=,wide=]\n' - ); - return 0; - } else if (arg === '--out') { - out = next(); - } else if (arg === '--report') { - report = next(); - } else if (arg === '--assign') { - for (const part of next().split(',')) { - const [family, hex] = part.split('='); - if (!CHROMATIC_FAMILIES.includes(family as Family) || !hex) { - throw new Error(`--assign takes brand, primary or cta, for example brand=#8d621f.`); - } - assign[family as Family] = hex; - } - } else if (arg === '--layout') { - for (const part of next().split(',')) { - const [key, value] = part.split('='); - const px = Number(value); - if (!['content', 'wide'].includes(key) || !Number.isFinite(px) || px <= 0) { - throw new Error('--layout takes content and wide in px, for example content=768,wide=1240.'); - } - layout[key as 'content' | 'wide'] = Math.round(px); - } - } else if (arg.startsWith('--')) { - throw new Error(`Unknown option ${arg}.`); - } else { - input = arg; - } - } - if (!input) { - throw new Error('Pass the path to site-styles.json from crawl-site-styles.'); - } - const styles = JSON.parse(io.readFile(input)) as SiteStyles; - if (!Array.isArray(styles.captures) || !styles.captures.length) { - throw new Error('The styles file has no captures.'); - } - const proposal = new TokenProposer().propose(styles, { assign, layout }); - io.writeFile(out, `${JSON.stringify(proposal, null, 2)}\n`); - if (report) { - io.writeFile(report, new ProposalReport().render(proposal)); - } - io.stdout( - `Wrote ${out}${report ? ` and ${report}` : ''}. ${proposal.decisions.length} decisions need review.\n` - ); - return 0; - } catch (error) { - io.stderr(`propose-tokens: ${(error as Error).message}\n`); - return 1; - } -} - -/* istanbul ignore next -- thin CLI entry point */ -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - process.exitCode = runProposeCli(process.argv.slice(2), { - readFile: (path) => readFileSync(path, 'utf8'), - writeFile: (path, content) => writeFileSync(path, content), - stdout: (text) => process.stdout.write(text), - stderr: (text) => process.stderr.write(text), - }); -} From 3d779c38b0c2147f8478f3a7122137cadab1e728 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:16:02 +0200 Subject: [PATCH 11/31] fix(site-tokens): give each page one vote for the content width, posts first On live TSP the terms page's 26 full-width paragraphs set the content width to 1200px. Each page now votes with its most common text width, blog posts win when the crawl has any, the median vote is used, and a width within 10% of the wide width becomes a reviewer decision. Refs GIT-2760. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- skills/site-to-design-tokens/SKILL.md | 2 +- .../references/crawling.md | 2 +- .../references/proposal-review.md | 2 +- .../__tests__/crawl-site-styles.test.ts | 5 ++- .../scripts/__tests__/propose-tokens.test.ts | 31 ++++++++++++++++++- .../scripts/crawl-site-styles.ts | 6 +++- .../scripts/propose-tokens.ts | 30 +++++++++++++----- 8 files changed, 65 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f011d466d..f77cc58602 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,7 +114,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text on single posts and pages, takes `--layout content=,wide=` to override either width, and asks the reviewer to confirm a content width under 480px. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) +- **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text, one vote per page with blog posts first, takes a `--layout` override, and flags widths under 480px or near the wide width. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) - **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) - **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. Radius variables are named by bare size (`Small`, not `Radius Small`), and `figma-to-block-theme` accepts both. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) diff --git a/skills/site-to-design-tokens/SKILL.md b/skills/site-to-design-tokens/SKILL.md index b508f9a1e4..fa247f05c8 100644 --- a/skills/site-to-design-tokens/SKILL.md +++ b/skills/site-to-design-tokens/SKILL.md @@ -52,7 +52,7 @@ The proposal follows the structure in [references/target-structure.md](reference Present the report's summary, its **Decisions for the reviewer** list and any failing contrast pairs. [references/proposal-review.md](references/proposal-review.md) explains each section. Common changes: - **A colour in the wrong family:** re-run with `--assign brand=#hex,primary=#hex,cta=#hex`. -- **A wrong content or wide width:** re-run with `--layout content=768,wide=1240`. Content width is measured from running text on single pages, so include a long text page in the crawl. +- **A wrong content or wide width:** re-run with `--layout content=768,wide=1240`. Content width is measured from running text, one vote per page, preferring blog posts, so include a blog post in the crawl. - **A failing contrast pair:** propose the nearest passing step and record the change. - **A live value with no close token:** keep the nearest token with the same role and list it for the reviewer. Don't add a raw value. diff --git a/skills/site-to-design-tokens/references/crawling.md b/skills/site-to-design-tokens/references/crawling.md index 330fb17183..63a31a1c04 100644 --- a/skills/site-to-design-tokens/references/crawling.md +++ b/skills/site-to-design-tokens/references/crawling.md @@ -27,7 +27,7 @@ At each viewport (390px and 1440px by default) the crawler reads computed styles | `input` | Text inputs, selects and text areas | | `section` and `surface` | Elements with a background (sections are at least half the viewport wide), and padded or centred wrappers | -For each element it keeps the text colour, background, border colour, font family, size, weight and line height, padding, bottom margin, gap, radius, shadow, centred container width, and the widths of running-text paragraphs in the main column (with whether the page is a single post or page, or a listing). The proposer measures the content width from the text on single pages, so include a long text page. It also records the widths in the site's same-origin `@media` rules. A DOM path key pairs the same element across the two viewports, which gives the mobile (Min) value for each desktop (Max) value. +For each element it keeps the text colour, background, border colour, font family, size, weight and line height, padding, bottom margin, gap, radius, shadow, centred container width, and the widths of running-text paragraphs in the main column (with whether the page is a blog post, another single page, or a listing). The proposer measures the content width from that text, so include a blog post. It also records the widths in the site's same-origin `@media` rules. A DOM path key pairs the same element across the two viewports, which gives the mobile (Min) value for each desktop (Max) value. ## Politeness and limits diff --git a/skills/site-to-design-tokens/references/proposal-review.md b/skills/site-to-design-tokens/references/proposal-review.md index e341cd92d4..323b90b9d2 100644 --- a/skills/site-to-design-tokens/references/proposal-review.md +++ b/skills/site-to-design-tokens/references/proposal-review.md @@ -45,4 +45,4 @@ Check each scale against the site at both widths: - Heading sizes should shrink on mobile. - Section spacing should reflect what the eye sees. Sites that space sections with margins on unstyled wrappers can produce a smaller scale than the design intends, so say so and let the reviewer set the larger steps. - Font names come from the site's CSS (for example a web font alias such as `argesta_displayregular`). Ask the reviewer for the licensed family name and its fallback. -- **Content width** comes from the width of running text (`p` elements with 80 or more characters in the main column) on single posts and pages, not from cards or wrappers. Include at least one long text page in the crawl. If the report says the width came from listing pages, or is under 480px, confirm it with the reviewer. Override either width with `--layout content=,wide=`. +- **Content width** comes from the width of running text (`p` elements with 80 or more characters in the main column) on single pages, not from cards or wrappers. Each page votes with its most common width, blog posts win when the crawl has any, and the median vote is used. Include a blog post in the crawl. If the report says the width came from listing pages, is under 480px, or is within 10% of the wide width, confirm it with the reviewer. Override either width with `--layout content=,wide=`. diff --git a/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts b/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts index 01d2cdd80a..eb2ff8ab1b 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts @@ -83,8 +83,11 @@ describe('collectPageStyles', () => { const single = collectPageStyles({ requireLayout: false }); expect(single.textWidths).toEqual([768]); expect(single.pageKind).toBe('single'); + expect(single.isPost).toBe(true); document.body.className = 'home page'; - expect(collectPageStyles({ requireLayout: false }).pageKind).toBe('listing'); + const home = collectPageStyles({ requireLayout: false }); + expect(home.pageKind).toBe('listing'); + expect(home.isPost).toBe(false); } finally { spy.mockRestore(); } diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index 9606031612..7b5c659020 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -328,7 +328,7 @@ describe('ProposalReport', () => { }); describe('TokenProposer.proposeLayout', () => { - const capture = (kind: 'single' | 'listing', textWidths: number[]) => + const capture = (kind: 'single' | 'listing', textWidths: number[], isPost = false) => ({ url: `/${kind}`, viewport: 1440, @@ -336,6 +336,7 @@ describe('TokenProposer.proposeLayout', () => { mediaWidths: [], textWidths, pageKind: kind, + isPost, }) as never; const wideCards = [1240, 1240, 248, 248, 248].map((containerWidth, i) => ({ key: `c:${i}`, @@ -353,6 +354,34 @@ describe('TokenProposer.proposeLayout', () => { expect(proposer['decisions']).toEqual([]); }); + it('gives each page one vote, so a page full of paragraphs cannot outvote the rest', () => { + const proposer = new TokenProposer(); + const layout = proposer.proposeLayout(wideCards, 1440, [ + capture('single', Array(26).fill(1200)), + capture('single', [688, 688]), + capture('single', [584, 584, 584]), + ]); + expect(layout.content).toBe(688); + }); + + it('prefers blog posts over other single pages', () => { + const proposer = new TokenProposer(); + const layout = proposer.proposeLayout(wideCards, 1440, [ + capture('single', Array(26).fill(1200)), + capture('single', [848, 848], true), + capture('single', [584, 584]), + ]); + expect(layout.content).toBe(848); + expect(proposer['decisions']).toEqual([]); + }); + + it('asks the reviewer to decide when the content width is close to the wide width', () => { + const proposer = new TokenProposer(); + const layout = proposer.proposeLayout(wideCards, 1440, [capture('single', [1200, 1200])]); + expect(layout).toEqual({ content: 1200, wide: 1240 }); + expect(proposer['decisions'].join(' ')).toContain('within 10% of the wide width'); + }); + it('warns when only listing pages have running text', () => { const proposer = new TokenProposer(); const layout = proposer.proposeLayout(wideCards, 1440, [capture('listing', [640, 640])]); diff --git a/skills/site-to-design-tokens/scripts/crawl-site-styles.ts b/skills/site-to-design-tokens/scripts/crawl-site-styles.ts index da06da3d3f..59671c59fe 100644 --- a/skills/site-to-design-tokens/scripts/crawl-site-styles.ts +++ b/skills/site-to-design-tokens/scripts/crawl-site-styles.ts @@ -62,6 +62,8 @@ export interface CollectedPage { textWidths?: number[]; /** `single` for one post or page, `listing` for the home page, archives, blog and search. */ pageKind?: 'single' | 'listing'; + /** True for a single blog post (`single-post`), whose text column is the clearest content width. */ + isPost?: boolean; } export interface PageCapture extends CollectedPage { @@ -267,7 +269,9 @@ export function collectPageStyles(options: CollectOptions = {}): CollectedPage { ? 'listing' : 'single'; - return { samples, mediaWidths, textWidths, pageKind }; + const isPost = /\bsingle-post\b/.test(bodyClass); + + return { samples, mediaWidths, textWidths, pageKind, isPost }; } export interface PageHandle { diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 984b6ba7db..232829423c 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -997,8 +997,9 @@ export class TokenProposer { } /** - * Content width is the width of running text (`p` in the main column) on single posts - * and pages. Wide width is the widest repeated centred container. Either can be forced. + * Content width is the width of running text (`p` in the main column): the median of + * each blog post's most common width, or of each single page's when there are no posts. + * Wide width is the widest repeated centred container. Either can be forced. */ proposeLayout( samples: ElementSample[], @@ -1019,12 +1020,20 @@ export class TokenProposer { let content = override.content; if (content === undefined) { - const single = captures.filter((c) => c.pageKind === 'single'); - const fromSingles = single.flatMap((c) => c.textWidths ?? []); - const fromAny = captures.flatMap((c) => c.textWidths ?? []); - const widths = fromSingles.length ? fromSingles : fromAny; - if (widths.length) { - content = mode(widths.map((w) => ({ value: Math.round(w / 8) * 8 }))); + // Each page gets one vote, its most common text width, so one long page full of + // paragraphs (a legal page, say) can't outvote the rest. Blog posts are the + // clearest reading column, so their votes win when the crawl has any. + const vote = (c: PageCapture) => + mode((c.textWidths ?? []).map((w) => ({ value: Math.round(w / 8) * 8 }))); + const votesFrom = (list: PageCapture[]) => + list.map(vote).filter((w): w is number => w !== undefined); + const fromPosts = votesFrom(captures.filter((c) => c.pageKind === 'single' && c.isPost)); + const fromSingles = votesFrom(captures.filter((c) => c.pageKind === 'single')); + const fromAny = votesFrom(captures); + const votes = fromPosts.length ? fromPosts : fromSingles.length ? fromSingles : fromAny; + if (votes.length) { + const sorted = [...votes].sort((a, b) => a - b); + content = sorted[Math.floor((sorted.length - 1) / 2)]; if (!fromSingles.length) { this.decisions.push( 'No single post or page was captured, so the content width was measured on listing pages and may be a card. Add a long text page, or set it with `--layout content=`.' @@ -1051,6 +1060,11 @@ export class TokenProposer { `The content width is ${content}px, under 480px, which is narrower than a readable text column. Confirm it, or set it with \`--layout content=\`.` ); } + if (content !== undefined && wide !== undefined && content >= wide * 0.9) { + this.decisions.push( + `The content width (${content}px) is within 10% of the wide width (${wide}px), so the text column may be a full-width section. Confirm it, or set it with \`--layout content=\`.` + ); + } return { ...(content !== undefined ? { content } : {}), ...(wide !== undefined ? { wide } : {}), From a691cd80a36ec97e0ec4355bd6620bfc1b70a14e Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:17:10 +0200 Subject: [PATCH 12/31] fix(site-tokens): compare font family names without case Live TSP writes Moret on 88 links and moret everywhere else, so the proposal added Moret as an accent. CSS family names are not case-sensitive; roles are now picked by lower-case name and named after the most common spelling. Refs GIT-2761. Co-Authored-By: Claude Opus 5.5 --- .../scripts/__tests__/propose-tokens.test.ts | 21 +++++++++ .../scripts/propose-tokens.ts | 43 +++++++++++-------- 2 files changed, 45 insertions(+), 19 deletions(-) diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index d9a9c42e4a..825708304c 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -380,6 +380,27 @@ describe('TokenProposer font roles', () => { expect(empty.body).toMatchObject({ stack: 'sans-serif', source: 'default' }); }); + it('treats one family written in two cases as one family, not an accent', () => { + const sample = (role: string, fontFamily: string, fontStack: string) => + ({ key: `${role}:0`, page: '/', role, fontSize: 16, fontFamily, fontStack }) as never; + const families = new TokenProposer().proposeFamilies( + [ + sample('h1', 'moret', 'moret, serif'), + sample('h2', 'moret', 'moret, serif'), + sample('link', 'Moret', 'Moret'), + sample('body', 'argesta_displayregular', 'argesta_displayregular, serif'), + ], + ['h1', 'h2', 'link', 'body'] + ); + expect('accent' in families).toBe(false); + expect(families.heading).toEqual({ + name: 'Moret', + stack: 'moret, serif', + source: 'live', + raw: 'moret', + }); + }); + it('falls back to the font name when the crawl has no stack', () => { const families = new TokenProposer().proposeFamilies( [{ key: 'h:0', page: '/', role: 'h1', fontSize: 40, fontFamily: 'Moret' } as never], diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 24b9ad0f27..b56879d323 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -862,33 +862,38 @@ export class TokenProposer { s.fontFamily ?? '' ); const proseText = text.filter((s) => !isMono(s)); - const stackFor = (raw: string) => + // CSS family names are not case-sensitive: `Moret` and `moret` are one family. + const fam = (s: ElementSample) => s.fontFamily!.toLowerCase(); + const spelling = (key: string) => + mode(text.filter((s) => fam(s) === key).map((s) => ({ value: s.fontFamily! }))) ?? key; + const stackFor = (key: string, raw: string) => mode( text - .filter((s) => s.fontFamily === raw && s.fontStack) + .filter((s) => fam(s) === key && s.fontStack) .map((s) => ({ value: s.fontStack! })) ) ?? raw; - const role = (raw: string): FontRole => { + const role = (key: string): FontRole => { + const raw = spelling(key); const name = cleanFontName(raw); return { name, - stack: stackFor(raw), + stack: stackFor(key, raw), source: 'live', ...(name !== raw ? { raw } : {}), }; }; const headings = proseText.filter((s) => /^h[1-3]$/.test(s.role)); const body = proseText.filter((s) => s.role === 'body'); - const headingRaw = - mode(headings.map((s) => ({ value: s.fontFamily! }))) || - mode(proseText.map((s) => ({ value: s.fontFamily! }))); - const bodyRaw = mode(body.map((s) => ({ value: s.fontFamily! }))); + const headingKey = + mode(headings.map((s) => ({ value: fam(s) }))) || + mode(proseText.map((s) => ({ value: fam(s) }))); + const bodyKey = mode(body.map((s) => ({ value: fam(s) }))); - const heading: FontRole = headingRaw - ? role(headingRaw) + const heading: FontRole = headingKey + ? role(headingKey) : { name: 'Serif', stack: 'serif', source: 'default' }; - const bodyRole: FontRole = bodyRaw - ? role(bodyRaw) + const bodyRole: FontRole = bodyKey + ? role(bodyKey) : { name: 'Sans Serif', stack: 'sans-serif', source: 'default' }; if (heading.source === 'default') { this.decisions.push('No heading font was found; `heading` defaults to the generic serif.'); @@ -899,17 +904,17 @@ export class TokenProposer { const counts = new Map(); for (const s of proseText) { - if (s.fontFamily !== headingRaw && s.fontFamily !== bodyRaw) { - counts.set(s.fontFamily!, (counts.get(s.fontFamily!) ?? 0) + (/^h/.test(s.role) ? 3 : 1)); + if (fam(s) !== headingKey && fam(s) !== bodyKey) { + counts.set(fam(s), (counts.get(fam(s)) ?? 0) + (/^h/.test(s.role) ? 3 : 1)); } } - const accentRaw = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; + const accentKey = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; // The accent role exists only when the site really uses a third family. - const accent = accentRaw ? role(accentRaw) : undefined; + const accent = accentKey ? role(accentKey) : undefined; - const monoRaw = mode(text.filter(isMono).map((s) => ({ value: s.fontFamily! }))); - const monospace: FontRole = monoRaw - ? role(monoRaw) + const monoKey = mode(text.filter(isMono).map((s) => ({ value: fam(s) }))); + const monospace: FontRole = monoKey + ? role(monoKey) : { name: 'Monospace', stack: MONOSPACE_STACK, source: 'default' }; return { heading, body: bodyRole, ...(accent ? { accent } : {}), monospace }; } From b628bab60b08deb64c14bd70e51c508123d7fd69 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:19:02 +0200 Subject: [PATCH 13/31] chore(changelog): drop the entry a stack merge duplicated Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fdd454f62d..ee54156bd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,7 +115,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) -- **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. Radius variables are named by bare size (`Small`, not `Radius Small`), and `figma-to-block-theme` accepts both. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Studio Imports From Live Sites** — Live site exports now import into Studio sites that already have WordPress content; files in the wrong format are refused with a reason. ([PR #3961](https://github.com/lightspeedwp/.github/pull/3961)) From 7b06408ecd28c047af72a6c582ca7f7a6ad1d4d3 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:19:03 +0200 Subject: [PATCH 14/31] chore(changelog): drop the entry a stack merge duplicated Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e0c16053e..eaa93df1e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,7 +115,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body` and `monospace` roles (plus `accent` only when the site uses a third font), marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) -- **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text on single posts and pages, takes `--layout content=,wide=` to override either width, and asks the reviewer to confirm a content width under 480px. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) - **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text, one vote per page with blog posts first, takes a `--layout` override, and flags widths under 480px or near the wide width. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) - **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) - **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. Radius variables are named by bare size (`Small`, not `Radius Small`), and `figma-to-block-theme` accepts both. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) From f8d5b1b1cf4a674f5bdf129c71e8e855a148ea73 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:19:03 +0200 Subject: [PATCH 15/31] chore(changelog): drop the entry a stack merge duplicated Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ae4546219..650cf7df66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,7 +115,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - **Site Tokens Action Colours** — `site-to-design-tokens` uses the live button colour for action backgrounds (hover one step darker) and moves defaults that fail contrast to the nearest passing step, recording each move in the report. ([#4008](https://github.com/lightspeedwp/.github/issues/4008)) -- **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body`, `accent` and `monospace` roles, marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) - **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body` and `monospace` roles (plus `accent` only when the site uses a third font), marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) - **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text, one vote per page with blog posts first, takes a `--layout` override, and flags widths under 480px or near the wide width. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) - **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) From a6264f41f3aa83c2f73f57a28d260f965ad21571 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:19:22 +0200 Subject: [PATCH 16/31] fix(site-tokens): record redirects and skip pages that land on one already captured On live TSP, /tours/, /accommodation/ and every accommodation page redirect to the home page, so runs 1 and 2 captured the home page four times without noticing. The crawler now keeps each page's final URL, warns about redirects, leaves out duplicates, and the proposal lists them as reviewer decisions. Refs GIT-2767. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + skills/site-to-design-tokens/SKILL.md | 2 +- .../references/crawling.md | 1 + .../__tests__/crawl-site-styles.test.ts | 74 ++++++++++++++++++- .../scripts/__tests__/propose-tokens.test.ts | 21 ++++++ .../scripts/crawl-site-styles.ts | 41 +++++++++- .../scripts/propose-tokens.ts | 7 ++ 7 files changed, 142 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cd9255bac..f3269c66af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Site Tokens Crawl Redirects** — `site-to-design-tokens` records where each page landed, warns about redirects, and leaves out pages that land on one already captured. ([GIT-2767](https://linear.app/lightspeedwp/issue/GIT-2767)) - **Site Tokens Action Colours** — `site-to-design-tokens` uses the live button colour for action backgrounds (hover one step darker) and moves defaults that fail contrast to the nearest passing step, recording each move in the report. ([#4008](https://github.com/lightspeedwp/.github/issues/4008)) - **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body` and `monospace` roles (plus `accent` only when the site uses a third font), marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) - **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text, one vote per page with blog posts first, takes a `--layout` override, and flags widths under 480px or near the wide width. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) diff --git a/skills/site-to-design-tokens/SKILL.md b/skills/site-to-design-tokens/SKILL.md index c6c0bb2839..4671e028f5 100644 --- a/skills/site-to-design-tokens/SKILL.md +++ b/skills/site-to-design-tokens/SKILL.md @@ -40,7 +40,7 @@ npx tsx ${CLAUDE_SKILL_DIR}/scripts/crawl-site-styles.ts --url https://www.examp --pages /,/about/,/tours/,/contact/ --out site-styles.json ``` -Save the output to a scratch folder outside the repository. The crawler reads public pages one at a time, with a 1.5 second pause between requests. +Save the output to a scratch folder outside the repository. The crawler reads public pages one at a time, with a 1.5 second pause between requests. It warns when a page redirects, and leaves out a page that lands on one already captured: replace it with a page that still exists and crawl again. ### 3. Propose diff --git a/skills/site-to-design-tokens/references/crawling.md b/skills/site-to-design-tokens/references/crawling.md index 63a31a1c04..ffc13138d2 100644 --- a/skills/site-to-design-tokens/references/crawling.md +++ b/skills/site-to-design-tokens/references/crawling.md @@ -32,6 +32,7 @@ For each element it keeps the text colour, background, border colour, font famil ## Politeness and limits - One page at a time, with a 1.5 second pause between requests (`--delay`), and at most 10 pages (`--max-pages`). +- Redirects are recorded in `redirects` in the output, with a warning for each. A page that lands on a page already captured is left out, so retired pages that redirect to the home page don't count twice. Sitemaps often still list them. - Only pages on the `--url` origin. - Cookie banners and pop-ups are measured like any other element. If one dominates the results, list the affected values for the reviewer. - Cross-origin stylesheets can't be read, so breakpoints from them are missed and the defaults (376px, 768px and 1240px) fill the gaps. diff --git a/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts b/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts index 26d017f251..38b5fd2b0c 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/crawl-site-styles.test.ts @@ -110,7 +110,7 @@ describe('collectPageStyles', () => { }); }); -function fakeDriver(failOn?: string) { +function fakeDriver(failOn?: string, redirects: Record = {}) { const opened: string[] = []; let closed = 0; let browserClosed = false; @@ -118,6 +118,7 @@ function fakeDriver(failOn?: string) { open: async (url, viewport) => { opened.push(`${url}@${viewport}`); return { + ...(redirects[url] ? { finalUrl: redirects[url] } : {}), collect: async () => { if (failOn && url.endsWith(failOn)) { throw new Error('page crashed'); @@ -171,6 +172,53 @@ describe('SiteCrawler', () => { expect(fake.browserClosed()).toBe(true); }); + it('records redirects and leaves out pages that land on a page already captured', async () => { + const home = 'https://www.example.com/'; + const fake = fakeDriver(undefined, { + 'https://www.example.com/tours/': home, + 'https://www.example.com/old/': 'https://www.example.com/new/', + }); + const crawler = new SiteCrawler(fake.driver, async () => undefined); + + const result = await crawler.crawl({ + site: 'https://www.example.com', + pages: ['/', '/tours/', '/old/'], + }); + + expect(fake.opened).toEqual([ + `${home}@390`, + `${home}@1440`, + 'https://www.example.com/tours/@390', + 'https://www.example.com/old/@390', + 'https://www.example.com/old/@1440', + ]); + expect(result.captures.map((c) => c.url)).toEqual([ + home, + home, + 'https://www.example.com/old/', + 'https://www.example.com/old/', + ]); + expect(result.captures[2].finalUrl).toBe('https://www.example.com/new/'); + expect(result.captures[0]).not.toHaveProperty('finalUrl'); + expect(result.redirects).toEqual([ + { url: 'https://www.example.com/tours/', finalUrl: home, skipped: true }, + { + url: 'https://www.example.com/old/', + finalUrl: 'https://www.example.com/new/', + skipped: false, + }, + ]); + expect(fake.closedCount()).toBe(5); + }); + + it('leaves redirects out of the result when no page redirected', async () => { + const result = await new SiteCrawler(fakeDriver().driver, async () => undefined).crawl({ + site: 'https://www.example.com', + pages: ['/'], + }); + expect(result).not.toHaveProperty('redirects'); + }); + it('closes pages and the browser when a page fails', async () => { const fake = fakeDriver('/broken'); const crawler = new SiteCrawler(fake.driver, async () => undefined); @@ -195,7 +243,7 @@ describe('SiteCrawler', () => { }); describe('runCrawlCli', () => { - function deps() { + function deps(redirects: Record = {}) { const out: string[] = []; const err: string[] = []; const written: Record = {}; @@ -204,7 +252,7 @@ describe('runCrawlCli', () => { err, written, deps: { - createDriver: async () => fakeDriver().driver, + createDriver: async () => fakeDriver(undefined, redirects).driver, sleep: async () => undefined, writeFile: (path: string, content: string) => { written[path] = content; @@ -241,6 +289,26 @@ describe('runCrawlCli', () => { expect(run.out.join('')).toContain('Captured 4 page views and 4 elements into styles.json'); }); + it('warns about each redirect', async () => { + const run = deps({ + 'https://www.example.com/tours/': 'https://www.example.com/', + 'https://www.example.com/old/': 'https://www.example.com/new/', + }); + + const code = await runCrawlCli( + ['--url', 'https://www.example.com', '--pages', '/,/tours/,/old/', '--delay', '0'], + run.deps + ); + + expect(code).toBe(0); + expect(run.err.join('')).toContain( + 'Warning: https://www.example.com/tours/ redirected to https://www.example.com/, which was already captured, so it was left out.' + ); + expect(run.err.join('')).toContain( + 'Warning: https://www.example.com/old/ redirected to https://www.example.com/new/.' + ); + }); + it('prints help', async () => { const run = deps(); diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index 3c14082d7e..a399eeb002 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -489,6 +489,27 @@ describe('TokenProposer font roles', () => { }); }); +describe('TokenProposer redirects', () => { + it('lists redirected and left-out pages for the reviewer', () => { + const styles = { + ...tspLikeStyles(), + redirects: [ + { url: 'https://x.com/tours/', finalUrl: 'https://x.com/', skipped: true }, + { url: 'https://x.com/old/', finalUrl: 'https://x.com/new/', skipped: false }, + ], + }; + const proposer = new TokenProposer(); + proposer.propose(styles, { now }); + const decisions = proposer['decisions'].join(' '); + expect(decisions).toContain( + 'https://x.com/tours/ redirected to https://x.com/, which was already captured, so it was left out.' + ); + expect(decisions).toContain( + 'https://x.com/old/ redirected to https://x.com/new/; the tokens use the page it landed on.' + ); + }); +}); + describe('TokenProposer.proposeLayout', () => { const capture = (kind: 'single' | 'listing', textWidths: number[], isPost = false) => ({ diff --git a/skills/site-to-design-tokens/scripts/crawl-site-styles.ts b/skills/site-to-design-tokens/scripts/crawl-site-styles.ts index db4d837a78..00ae7c91be 100644 --- a/skills/site-to-design-tokens/scripts/crawl-site-styles.ts +++ b/skills/site-to-design-tokens/scripts/crawl-site-styles.ts @@ -70,14 +70,27 @@ export interface CollectedPage { export interface PageCapture extends CollectedPage { url: string; + /** Set when the page redirected: where it landed. */ + finalUrl?: string; viewport: number; } +export interface PageRedirect { + /** The page asked for. */ + url: string; + /** Where the browser ended up. */ + finalUrl: string; + /** True when that final URL had already been captured, so the page was left out. */ + skipped: boolean; +} + export interface SiteStyles { site: string; capturedAt: string; viewports: number[]; captures: PageCapture[]; + /** Pages that redirected. Live sites redirect retired pages, often to the home page. */ + redirects?: PageRedirect[]; } export interface CollectOptions { @@ -278,6 +291,8 @@ export function collectPageStyles(options: CollectOptions = {}): CollectedPage { } export interface PageHandle { + /** The URL the page landed on after any redirects. */ + finalUrl?: string; collect: () => Promise; close: () => Promise; } @@ -307,6 +322,8 @@ export class SiteCrawler { const viewports = options.viewports ?? [390, 1440]; const urls = this.resolvePages(site, options.pages, options.maxPages ?? 10); const captures: PageCapture[] = []; + const redirects: PageRedirect[] = []; + const captured = new Set(); let first = true; try { @@ -318,7 +335,22 @@ export class SiteCrawler { first = false; const page = await this.driver.open(url, viewport); try { - captures.push({ url, viewport, ...(await page.collect()) }); + const finalUrl = page.finalUrl ?? url; + if (finalUrl !== url && !redirects.some((r) => r.url === url)) { + const skipped = captured.has(`${finalUrl}@${viewport}`); + redirects.push({ url, finalUrl, skipped }); + } + if (captured.has(`${finalUrl}@${viewport}`)) { + // Already captured under another address: one page, one set of votes. + break; + } + captured.add(`${finalUrl}@${viewport}`); + captures.push({ + url, + viewport, + ...(finalUrl !== url ? { finalUrl } : {}), + ...(await page.collect()), + }); } finally { await page.close(); } @@ -333,6 +365,7 @@ export class SiteCrawler { capturedAt: this.now().toISOString(), viewports, captures, + ...(redirects.length ? { redirects } : {}), }; } @@ -432,6 +465,11 @@ export async function runCrawlCli(argv: string[], deps: CrawlCliDeps): Promise total + c.samples.length, 0); + for (const r of result.redirects ?? []) { + deps.stderr( + `Warning: ${r.url} redirected to ${r.finalUrl}${r.skipped ? ', which was already captured, so it was left out' : ''}.\n` + ); + } deps.stdout( `Captured ${result.captures.length} page views and ${samples} elements into ${values.out}\n` ); @@ -472,6 +510,7 @@ export async function createPuppeteerDriver(): Promise { throw error; } return { + finalUrl: page.url(), collect: async () => { // tsx (esbuild) can add __name() helpers to function source; define it in the page. await page.evaluate('globalThis.__name = (f) => f'); diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 5931e803eb..7a77a1d287 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -284,6 +284,13 @@ export class TokenProposer { propose(styles: SiteStyles, options: ProposeOptions = {}): Proposal { this.decisions = []; + for (const r of styles.redirects ?? []) { + this.decisions.push( + r.skipped + ? `${r.url} redirected to ${r.finalUrl}, which was already captured, so it was left out. Replace it with a page that still exists, or drop it.` + : `${r.url} redirected to ${r.finalUrl}; the tokens use the page it landed on.` + ); + } const desktopWidth = Math.max(...styles.viewports); const mobileWidth = Math.min(...styles.viewports); const desktop = styles.captures.filter((c) => c.viewport === desktopWidth); From cca79c45ee061428a8611ef9cd46873c62907d46 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:20:49 +0200 Subject: [PATCH 17/31] fix(site-tokens): pair each action's text with the buttons that have its fill On live TSP the primary action took its fill from #6a6d5b buttons (white text) but its text from the 112 light #f7f3f1 buttons with brown text, which gave 1.01:1. Button text is now grouped by fill, and each action's text comes from the buttons whose fill matches its background. Refs GIT-2765. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../scripts/__tests__/propose-tokens.test.ts | 34 ++++++++++ .../scripts/propose-tokens.ts | 63 +++++++++++++++++-- 3 files changed, 93 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3269c66af..d05fbb3fac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Site Tokens Action Text** — `site-to-design-tokens` takes each action's text colour from the buttons that have its fill, so text and fill are a pair the site really shows. ([GIT-2765](https://linear.app/lightspeedwp/issue/GIT-2765)) - **Site Tokens Crawl Redirects** — `site-to-design-tokens` records where each page landed, warns about redirects, and leaves out pages that land on one already captured. ([GIT-2767](https://linear.app/lightspeedwp/issue/GIT-2767)) - **Site Tokens Action Colours** — `site-to-design-tokens` uses the live button colour for action backgrounds (hover one step darker) and moves defaults that fail contrast to the nearest passing step, recording each move in the report. ([#4008](https://github.com/lightspeedwp/.github/issues/4008)) - **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body` and `monospace` roles (plus `accent` only when the site uses a third font), marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index a399eeb002..06ea1bd47f 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -489,6 +489,40 @@ describe('TokenProposer font roles', () => { }); }); +describe('TokenProposer action text', () => { + it('takes each action text colour from the buttons that have its fill', () => { + const styles = tspLikeStyles(); + const desktop = styles.captures.find((c) => c.viewport === 1440)!; + // Many light buttons with brown text, as on live TSP, must not set the primary text. + for (let i = 0; i < 30; i++) { + desktop.samples.push({ + key: `ghost:${i}`, + role: 'button', + color: 'rgb(155, 106, 34)', + background: 'rgb(247, 243, 241)', + }); + } + const proposer = new TokenProposer(); + const sem = proposer.propose(styles, { now }).colour.semantic; + expect(sem['action/primary/text']).toMatchObject({ token: 'base', source: 'observed' }); + expect(sem['action/primary/text'].evidence).toMatch(/^#ffffff on #565b3d buttons/); + expect(sem['action/cta/text'].evidence).toMatch(/^#ffffff on #a31700 buttons/); + }); + + it('pairs only opaque button text with opaque button fills', () => { + const pairs = new TokenProposer().buttonTextByFill([ + { key: 'a', role: 'button', color: 'rgb(255, 255, 255)', background: 'rgb(0, 0, 0)' }, + { key: 'b', role: 'button', color: 'rgb(255, 255, 255)', background: 'rgb(0, 0, 0)' }, + { key: 'c', role: 'button', color: 'rgb(0, 0, 0)', background: 'rgba(0, 0, 0, 0.5)' }, + { key: 'd', role: 'button', color: 'rgb(0, 0, 0)' }, + { key: 'e', role: 'link', color: 'rgb(0, 0, 0)', background: 'rgb(255, 255, 255)' }, + ]); + expect([...pairs.entries()].map(([fill, texts]) => [fill, [...texts.entries()]])).toEqual([ + ['#000000', [['#ffffff', 2]]], + ]); + }); +}); + describe('TokenProposer redirects', () => { it('lists redirected and left-out pages for the reviewer', () => { const styles = { diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 7a77a1d287..46c0d06468 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -108,6 +108,9 @@ export const SPACING_STEPS = [ const RADIUS_NAMES = ['Small', 'Base', 'Medium', 'Large', 'X-Large', 'Huge']; const SHADOW_NAMES = ['X-Small', 'Small', 'Medium', 'Large', 'X-Large', 'Huge']; +/** For each button fill (hex), how often each text colour (hex) sits on it. */ +export type ButtonTextByFill = Map>; + export interface ColourEvidence { hex: string; weight: number; @@ -305,7 +308,11 @@ export class TokenProposer { const pair = (s: ElementSample & { page: string }) => mobileByKey.get(`${s.page}|${s.key}`); const evidence = this.colourEvidence(desktopSamples); - const colour = this.proposeColour(evidence, options.assign ?? {}); + const colour = this.proposeColour( + evidence, + options.assign ?? {}, + this.buttonTextByFill(desktopSamples) + ); const matches = this.matchColours(evidence, colour.primitives); const contrast = this.checkContrast(colour.primitives, colour.semantic); const typography = this.proposeTypography(desktopSamples, pair); @@ -332,6 +339,22 @@ export class TokenProposer { } /** Counts every opaque colour by where it is used. */ + /** Pairs each button's text colour with its own fill, so action text and fill match. */ + buttonTextByFill(samples: ElementSample[]): ButtonTextByFill { + const pairs: ButtonTextByFill = new Map(); + for (const s of samples) { + const fill = s.role === 'button' && s.background ? Color.parse(s.background) : null; + const text = fill && s.color ? Color.parse(s.color) : null; + if (!fill || !text || !fill.isOpaque || !text.isOpaque) { + continue; + } + const texts = pairs.get(fill.toHex()) ?? new Map(); + texts.set(text.toHex(), (texts.get(text.toHex()) ?? 0) + 1); + pairs.set(fill.toHex(), texts); + } + return pairs; + } + colourEvidence(samples: ElementSample[]): ColourEvidence[] { const byHex = new Map(); const add = (value: string | undefined, use: string, weight: number) => { @@ -355,7 +378,8 @@ export class TokenProposer { proposeColour( evidence: ColourEvidence[], - assign: Partial> + assign: Partial>, + buttonText: ButtonTextByFill = new Map() ): Proposal['colour'] { const opaque = evidence.filter((e) => Color.parse(e.hex)!.isOpaque); const isNeutral = (hex: string) => Color.parse(hex)!.toOklch().c < 0.025; @@ -514,7 +538,7 @@ export class TokenProposer { const shadowBase = Color.parse(primitives['neutral-900'])!.rgb; const overlay = Color.fromRgb({ ...shadowBase, a: 0.25 }).toHex(); - const semantic = this.proposeSemantic(evidence, primitives, anchors); + const semantic = this.proposeSemantic(evidence, primitives, anchors, buttonText); return { primitives, anchors, semantic, overlay, shadowAlphas: SHADOW_ALPHAS }; } @@ -620,7 +644,8 @@ export class TokenProposer { proposeSemantic( evidence: ColourEvidence[], primitives: Record, - anchors: Anchor[] = [] + anchors: Anchor[] = [], + buttonText: ButtonTextByFill = new Map() ): Proposal['colour']['semantic'] { const semantic: Proposal['colour']['semantic'] = {}; for (const [role, token] of Object.entries(SEMANTIC_DEFAULTS)) { @@ -664,7 +689,6 @@ export class TokenProposer { observe('text/link', 'nav-text', undefined, true); } const buttonBg = observe('action/primary/background', 'button-background'); - observe('action/primary/text', 'button-text'); observe('border/default', 'input-border'); if (buttonBg) { semantic['action/primary/background-hover'] = { @@ -702,6 +726,35 @@ export class TokenProposer { }; } + // Each action's text comes from the buttons that have its fill, never from other + // buttons, so the pair is one the site really shows. + for (const action of ['primary', 'secondary', 'cta']) { + const fill = semantic[`action/${action}/background`]; + if (fill.source !== 'observed') { + continue; + } + const texts = new Map(); + const fills: string[] = []; + for (const [fillHex, onFill] of buttonText) { + if (this.nearestPrimitive(fillHex, primitives) !== fill.token) { + continue; + } + fills.push(fillHex); + for (const [hex, n] of onFill) { + texts.set(hex, (texts.get(hex) ?? 0) + n); + } + } + const [textHex, count] = [...texts.entries()].sort((a, b) => b[1] - a[1])[0] ?? []; + if (!textHex) { + continue; + } + semantic[`action/${action}/text`] = { + token: this.nearestPrimitive(textHex, primitives), + source: 'observed', + evidence: `${textHex} on ${fills.join(', ')} buttons (×${count})`, + }; + } + const light = evidence.filter( (e) => (e.uses['section-background'] ?? 0) > 0 && From 3d590bd8b7872c32ace07c4fec8f5eec75a1ba42 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:21:51 +0200 Subject: [PATCH 18/31] style(site-tokens): format with Prettier Co-Authored-By: Claude Opus 5.5 --- skills/site-to-design-tokens/scripts/propose-tokens.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index b56879d323..c395f0306f 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -868,9 +868,7 @@ export class TokenProposer { mode(text.filter((s) => fam(s) === key).map((s) => ({ value: s.fontFamily! }))) ?? key; const stackFor = (key: string, raw: string) => mode( - text - .filter((s) => fam(s) === key && s.fontStack) - .map((s) => ({ value: s.fontStack! })) + text.filter((s) => fam(s) === key && s.fontStack).map((s) => ({ value: s.fontStack! })) ) ?? raw; const role = (key: string): FontRole => { const raw = spelling(key); From 6d3c3f632efcc3e2e66f699d6753ff92c13361c9 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:22:07 +0200 Subject: [PATCH 19/31] fix(site-tokens): keep mobile spacing values in order up the ladder On live TSP, Gigantic (90) was 70px on desktop but 24px on mobile, below every step from 40 up. A step's mobile value is now raised to the one before it, and the change is listed for the reviewer. Refs GIT-2766. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../scripts/__tests__/propose-tokens.test.ts | 31 +++++++++++++++++++ .../scripts/propose-tokens.ts | 9 ++++++ 3 files changed, 41 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d05fbb3fac..4006e5307e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Site Tokens Spacing Minimums** — `site-to-design-tokens` keeps mobile spacing values in order up the ladder, raising a step that would shrink below the one before and listing it for the reviewer. ([GIT-2766](https://linear.app/lightspeedwp/issue/GIT-2766)) - **Site Tokens Action Text** — `site-to-design-tokens` takes each action's text colour from the buttons that have its fill, so text and fill are a pair the site really shows. ([GIT-2765](https://linear.app/lightspeedwp/issue/GIT-2765)) - **Site Tokens Crawl Redirects** — `site-to-design-tokens` records where each page landed, warns about redirects, and leaves out pages that land on one already captured. ([GIT-2767](https://linear.app/lightspeedwp/issue/GIT-2767)) - **Site Tokens Action Colours** — `site-to-design-tokens` uses the live button colour for action backgrounds (hover one step darker) and moves defaults that fail contrast to the nearest passing step, recording each move in the report. ([#4008](https://github.com/lightspeedwp/.github/issues/4008)) diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index 06ea1bd47f..0481cc82f5 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -264,6 +264,37 @@ describe('TokenProposer on a sparse site', () => { expect(proposer['decisions'].join(' ')).not.toContain('left out'); }); + it('keeps the mobile values in order up the ladder', () => { + const proposer = new TokenProposer(); + proposer.propose(styles, { now }); + const mobile: Record = { 20: 16, 48: 40, 70: 24, 80: 80 }; + const samples = [20, 48, 70, 80].flatMap((paddingBlock) => + [0, 1].map((n) => ({ + key: `sp:${paddingBlock}:${n}`, + page: '/', + role: 'section', + paddingBlock, + })) + ); + const spacing = proposer.proposeSpacing( + samples as never, + (s) => + ({ + ...(s as object), + paddingBlock: mobile[(s as { paddingBlock: number }).paddingBlock], + }) as never + ); + expect(spacing.slice(1).map((s) => [s.max, s.min])).toEqual([ + [20, 16], + [48, 40], + [70, 40], + [80, 80], + ]); + expect(proposer['decisions'].join(' ')).toContain( + 'Spacing XXXL (`70`) shrinks to 24px on mobile, below XL; its mobile value was raised to 40px.' + ); + }); + it('names the spacing values left out when there are more than the ladder holds', () => { const proposer = new TokenProposer(); proposer.propose(styles, { now }); diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 7c0825588e..50951973f5 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -1169,6 +1169,15 @@ export class TokenProposer { max: c.max, min: Math.min(c.min, c.max), })); + // Mobile values rise with the ladder too: a step never shrinks below the one before. + for (let i = 1; i < steps.length; i++) { + if (steps[i].min < steps[i - 1].min) { + this.decisions.push( + `Spacing ${steps[i].name} (\`${steps[i].slug}\`) shrinks to ${steps[i].min}px on mobile, below ${steps[i - 1].name}; its mobile value was raised to ${steps[i - 1].min}px.` + ); + steps[i].min = steps[i - 1].min; + } + } return [{ name: 'None', slug: 'none', max: 0, min: 0 }, ...steps]; } From 6844cc04501a09ad4a6bb1f6ad67f0e27b9b39a1 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:36:34 +0200 Subject: [PATCH 20/31] fix(site-tokens): never take a widget's system UI font as the accent On live TSP, two widget buttons on every page use -apple-system, which became the accent once Moret stopped counting twice. System UI stacks are not design families, so they are skipped when picking the accent. Refs GIT-2761. Co-Authored-By: Claude Opus 5.5 --- .../scripts/__tests__/propose-tokens.test.ts | 16 ++++++++++++++++ .../scripts/propose-tokens.ts | 6 +++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index 825708304c..fafe457283 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -401,6 +401,22 @@ describe('TokenProposer font roles', () => { }); }); + it('never takes the system UI font of a widget as the accent', () => { + const sample = (role: string, fontFamily: string) => + ({ key: `${role}:${fontFamily}`, page: '/', role, fontSize: 16, fontFamily }) as never; + const families = new TokenProposer().proposeFamilies( + [ + sample('h1', 'moret'), + sample('body', 'lora'), + sample('button', '-apple-system'), + sample('button', 'system-ui'), + sample('button', 'Segoe UI'), + ], + ['h1', 'body', 'button'] + ); + expect('accent' in families).toBe(false); + }); + it('falls back to the font name when the crawl has no stack', () => { const families = new TokenProposer().proposeFamilies( [{ key: 'h:0', page: '/', role: 'h1', fontSize: 40, fontFamily: 'Moret' } as never], diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index c395f0306f..453471c72f 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -900,9 +900,13 @@ export class TokenProposer { this.decisions.push('No body font was found; `body` defaults to the generic sans-serif.'); } + // The operating system's UI font (used by chat, cookie and booking widgets) is not + // a design family, so it never becomes the accent. + const isSystemUi = (s: ElementSample) => + /^(-apple-system|system-ui|blinkmacsystemfont|"?segoe ui"?)$/.test(fam(s)); const counts = new Map(); for (const s of proseText) { - if (fam(s) !== headingKey && fam(s) !== bodyKey) { + if (fam(s) !== headingKey && fam(s) !== bodyKey && !isSystemUi(s)) { counts.set(fam(s), (counts.get(fam(s)) ?? 0) + (/^h/.test(s.role) ? 3 : 1)); } } From 8ab3867f4ee242e05ff4b4b7b7e921db83c48c53 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:39:17 +0200 Subject: [PATCH 21/31] fix(site-tokens): need a third family on 2% of text before it becomes the accent On live TSP, one blog link styled with font-family: a became the accent. A third family now needs at least 2% of the text elements (and at least 5) to take the accent role. Refs GIT-2761. Co-Authored-By: Claude Opus 5.5 --- .../scripts/__tests__/fixtures.ts | 2 +- .../scripts/__tests__/propose-tokens.test.ts | 17 +++++++++++++++++ .../scripts/propose-tokens.ts | 8 ++++++-- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/skills/site-to-design-tokens/scripts/__tests__/fixtures.ts b/skills/site-to-design-tokens/scripts/__tests__/fixtures.ts index 7ad88b2599..295226030a 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/fixtures.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/fixtures.ts @@ -140,7 +140,7 @@ function samples(desktop: boolean): ElementSample[] { 'avatar' ); add( - 4, + 8, { role: 'body', color: rgb('#262423'), diff --git a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts index fafe457283..9620647872 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/propose-tokens.test.ts @@ -401,6 +401,23 @@ describe('TokenProposer font roles', () => { }); }); + it('needs a third family used on enough elements before it becomes the accent', () => { + const sample = (role: string, fontFamily: string, i: number) => + ({ key: `${role}:${i}`, page: '/', role, fontSize: 16, fontFamily }) as never; + const base = [ + ...Array.from({ length: 50 }, (_, i) => sample('h1', 'moret', i)), + ...Array.from({ length: 50 }, (_, i) => sample('body', 'lora', i)), + ]; + const roles = ['h1', 'body', 'nav']; + const stray = new TokenProposer().proposeFamilies([...base, sample('nav', 'a', 0)], roles); + expect('accent' in stray).toBe(false); + const real = new TokenProposer().proposeFamilies( + [...base, ...Array.from({ length: 6 }, (_, i) => sample('nav', 'caveat', i))], + roles + ); + expect(real.accent).toMatchObject({ name: 'Caveat', source: 'live' }); + }); + it('never takes the system UI font of a widget as the accent', () => { const sample = (role: string, fontFamily: string) => ({ key: `${role}:${fontFamily}`, page: '/', role, fontSize: 16, fontFamily }) as never; diff --git a/skills/site-to-design-tokens/scripts/propose-tokens.ts b/skills/site-to-design-tokens/scripts/propose-tokens.ts index 453471c72f..caf1597408 100644 --- a/skills/site-to-design-tokens/scripts/propose-tokens.ts +++ b/skills/site-to-design-tokens/scripts/propose-tokens.ts @@ -910,8 +910,12 @@ export class TokenProposer { counts.set(fam(s), (counts.get(fam(s)) ?? 0) + (/^h/.test(s.role) ? 3 : 1)); } } - const accentKey = [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; - // The accent role exists only when the site really uses a third family. + // The accent role exists only when the site really uses a third family: at least + // 2% of the text elements (and at least 5), so one stray rule doesn't make a role. + const minUses = Math.max(5, proseText.length * 0.02); + const accentKey = [...counts.entries()] + .filter(([, n]) => n >= minUses) + .sort((a, b) => b[1] - a[1])[0]?.[0]; const accent = accentKey ? role(accentKey) : undefined; const monoKey = mode(text.filter(isMono).map((s) => ({ value: fam(s) }))); From 2fc479d024bb52ef908e050834b18e376e623f9b Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Tue, 10 Nov 2026 08:55:43 +0200 Subject: [PATCH 22/31] fix(figma-tokens): start font stacks with the clean family name The declared CSS stack starts with the live site's own @font-face name (moret, argesta_displayregular), which the theme's fontFace entries don't declare, so the fonts would not load. Keep the stack's fallbacks and lead with the family name instead. Refs GIT-2770 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../references/tokens-typography.md | 2 +- .../figma-variables-to-theme-json.test.ts | 9 ++++++-- .../scripts/figma-variables-to-theme-json.ts | 21 +++++++++++++++---- 4 files changed, 26 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4006e5307e..bdfcb22354 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Figma Tokens Font Stacks** — `figma-to-block-theme` starts each font stack with the clean family name and keeps the declared fallbacks, instead of the live site's own `@font-face` name, so the stack matches the theme's `fontFace` entries. ([GIT-2770](https://linear.app/lightspeedwp/issue/GIT-2770)) - **Site Tokens Spacing Minimums** — `site-to-design-tokens` keeps mobile spacing values in order up the ladder, raising a step that would shrink below the one before and listing it for the reviewer. ([GIT-2766](https://linear.app/lightspeedwp/issue/GIT-2766)) - **Site Tokens Action Text** — `site-to-design-tokens` takes each action's text colour from the buttons that have its fill, so text and fill are a pair the site really shows. ([GIT-2765](https://linear.app/lightspeedwp/issue/GIT-2765)) - **Site Tokens Crawl Redirects** — `site-to-design-tokens` records where each page landed, warns about redirects, and leaves out pages that land on one already captured. ([GIT-2767](https://linear.app/lightspeedwp/issue/GIT-2767)) diff --git a/skills/figma-to-block-theme/references/tokens-typography.md b/skills/figma-to-block-theme/references/tokens-typography.md index c76c03512b..4cf6da248a 100644 --- a/skills/figma-to-block-theme/references/tokens-typography.md +++ b/skills/figma-to-block-theme/references/tokens-typography.md @@ -22,7 +22,7 @@ After replacing the sizes, update every reference in `styles`, `styles.blocks`, Variables whose code syntax is `--wp--preset--font-family--` (`heading`, `body`, `monospace`, and `accent` only when the site has a third font) become `{ slug, name, fontFamily }`: - `name` is the font name (for example "Nunito Sans"), not the slug. -- If the variable description holds a `CSS stack: ` line (written by `site-to-design-tokens`) and its first family is the font named by the value, `fontFamily` is that exact stack. +- If the variable description holds a `CSS stack: ` line (written by `site-to-design-tokens`) and its first family is the font named by the value, `fontFamily` is the font name followed by that stack's fallbacks. The first family is the live site's own `@font-face` name (for example `argesta_displayregular, serif` gives `"Argesta Display", serif`), which the theme's `fontFace` entries won't declare. - Otherwise `fontFamily` quotes names that contain spaces and adds a fallback: `sans-serif` by default, or `--font-fallback serif` for serif families. Confirm the fallback with the user. ### Font files diff --git a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts index c71d8325d0..8bbca61330 100644 --- a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts +++ b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts @@ -391,7 +391,7 @@ describe('FigmaVariablesMapper', () => { ); }); - it('keeps the exact CSS stack declared in a font variable description', () => { + it('keeps the fallbacks of the CSS stack declared in a font variable description', () => { const font = (value: string, description?: string) => new FigmaVariablesMapper().map({ collections: [ @@ -415,7 +415,12 @@ describe('FigmaVariablesMapper', () => { (mapped.theme.settings as Json).typography.fontFamilies[0].fontFamily; const description = 'Headings (live). CSS stack: moret, Georgia, serif'; - expect(stack(font('Moret', description))).toBe('moret, Georgia, serif'); + // The live @font-face name gives way to the clean family name. + expect(stack(font('Moret', description))).toBe('Moret, Georgia, serif'); + expect( + stack(font('Argesta Display', 'Body text (live). CSS stack: argesta_displayregular, serif')) + ).toBe('"Argesta Display", serif'); + expect(stack(font('Moret', 'CSS stack: moret'))).toBe('Moret'); // A stack for another font is ignored. expect(stack(font('Lora', description))).toBe('Lora, sans-serif'); expect(stack(font('Moret'))).toBe('Moret, sans-serif'); diff --git a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts index 6623c39664..2dda4ea07d 100644 --- a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts +++ b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts @@ -560,20 +560,33 @@ export class FigmaVariablesMapper { * The exact CSS stack from a `CSS stack: ...` line in the variable description, used * only when its first family is the font the mode's value names (other modes differ). */ + /** + * Uses the fallbacks from a "CSS stack: …" description. The declared stack starts + * with the live site's own `@font-face` name (such as `argesta_displayregular`), + * which the new theme's `fontFace` entries won't declare, so the clean family name + * replaces it. + */ private declaredStack(variable: ExportedVariable, name: string): string | undefined { const stack = variable.description?.match(/CSS stack:\s*(.+)$/m)?.[1].trim(); if (!stack) { return undefined; } + const [first, ...fallbacks] = stack.split(',').map((part) => part.trim()); const plain = (text: string) => text.toLowerCase().replace(/[^a-z0-9]/g, ''); - const first = plain(stack.split(',')[0]); + const face = plain(first); const wanted = plain(name); - return first.startsWith(wanted) || wanted.startsWith(first) ? stack : undefined; + if (!face.startsWith(wanted) && !wanted.startsWith(face)) { + return undefined; + } + return [this.quoteFamily(name), ...fallbacks.filter(Boolean)].join(', '); } private fontStack(family: string): string { - const quoted = /\s/.test(family) ? `"${family}"` : family; - return `${quoted}, ${this.options.fontFallback ?? 'sans-serif'}`; + return `${this.quoteFamily(family)}, ${this.options.fontFallback ?? 'sans-serif'}`; + } + + private quoteFamily(family: string): string { + return /\s/.test(family) ? `"${family}"` : family; } private typeMismatch(variable: ExportedVariable, expected: string): undefined { From 79aa6e744f102a635dbbc5b09d6749072db5478d Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Tue, 10 Nov 2026 08:56:51 +0200 Subject: [PATCH 23/31] fix(figma-tokens): keep the declared system stack for a generic family The monospace variable is named Monospace and its declared stack starts with ui-monospace, so the name check failed and the mapper wrote "Monospace, sans-serif". A generic family names no font of its own, so keep its declared stack, and fall back to monospace for that role. Refs GIT-2771 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../references/tokens-typography.md | 3 +- .../figma-variables-to-theme-json.test.ts | 30 +++++++++++++++++ .../scripts/figma-variables-to-theme-json.ts | 33 +++++++++++++++++-- 4 files changed, 63 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bdfcb22354..baf4de5d1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Figma Tokens Monospace Stack** — `figma-to-block-theme` keeps the declared system stack for a generic family such as Monospace, and falls back to `monospace` for the monospace role, instead of writing `Monospace, sans-serif`. ([GIT-2771](https://linear.app/lightspeedwp/issue/GIT-2771)) - **Figma Tokens Font Stacks** — `figma-to-block-theme` starts each font stack with the clean family name and keeps the declared fallbacks, instead of the live site's own `@font-face` name, so the stack matches the theme's `fontFace` entries. ([GIT-2770](https://linear.app/lightspeedwp/issue/GIT-2770)) - **Site Tokens Spacing Minimums** — `site-to-design-tokens` keeps mobile spacing values in order up the ladder, raising a step that would shrink below the one before and listing it for the reviewer. ([GIT-2766](https://linear.app/lightspeedwp/issue/GIT-2766)) - **Site Tokens Action Text** — `site-to-design-tokens` takes each action's text colour from the buttons that have its fill, so text and fill are a pair the site really shows. ([GIT-2765](https://linear.app/lightspeedwp/issue/GIT-2765)) diff --git a/skills/figma-to-block-theme/references/tokens-typography.md b/skills/figma-to-block-theme/references/tokens-typography.md index 4cf6da248a..09fc9469b6 100644 --- a/skills/figma-to-block-theme/references/tokens-typography.md +++ b/skills/figma-to-block-theme/references/tokens-typography.md @@ -23,7 +23,8 @@ Variables whose code syntax is `--wp--preset--font-family--` (`heading`, ` - `name` is the font name (for example "Nunito Sans"), not the slug. - If the variable description holds a `CSS stack: ` line (written by `site-to-design-tokens`) and its first family is the font named by the value, `fontFamily` is the font name followed by that stack's fallbacks. The first family is the live site's own `@font-face` name (for example `argesta_displayregular, serif` gives `"Argesta Display", serif`), which the theme's `fontFace` entries won't declare. -- Otherwise `fontFamily` quotes names that contain spaces and adds a fallback: `sans-serif` by default, or `--font-fallback serif` for serif families. Confirm the fallback with the user. +- A generic family name such as "Monospace" names no font of its own, so its declared stack is kept as it is (for example `ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace`). +- Otherwise `fontFamily` quotes names that contain spaces and adds a fallback: `monospace` for the `monospace` role, otherwise `sans-serif` by default, or `--font-fallback serif` for serif families. Confirm the fallback with the user. ### Font files diff --git a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts index 8bbca61330..c808e39c4a 100644 --- a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts +++ b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts @@ -427,6 +427,36 @@ describe('FigmaVariablesMapper', () => { expect(stack(font('Moret', 'Headings only'))).toBe('Moret, sans-serif'); }); + it('keeps the system stack of a generic family such as Monospace', () => { + const family = (slug: string, value: string, description?: string) => + ( + new FigmaVariablesMapper().map({ + collections: [ + { + name: 'Typography', + modes: [{ id: 'm', name: 'Value' }], + variables: [ + { + id: slug, + name: `Font-Families/${value}`, + type: 'STRING', + codeSyntax: { WEB: `var(--wp--preset--font-family--${slug})` }, + description, + valuesByMode: { m: value }, + }, + ], + }, + ], + } as never).theme.settings as Json + ).typography.fontFamilies[0].fontFamily; + const system = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace'; + + expect(family('monospace', 'Monospace', `Code (default). CSS stack: ${system}`)).toBe(system); + // With no declared stack, a generic name is the stack, and a named mono font falls back to monospace. + expect(family('monospace', 'Monospace')).toBe('monospace'); + expect(family('monospace', 'Fira Code')).toBe('"Fira Code", monospace'); + }); + it('writes only the font roles that exist, with no accent when there is none', () => { const role = (slug: string, value: string) => ({ id: slug, diff --git a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts index 2dda4ea07d..8eb90af77c 100644 --- a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts +++ b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts @@ -105,6 +105,22 @@ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']); const PRESET_PATTERN = /--wp--preset--(color|spacing|font-size|font-family|border-radius|shadow)--([a-z0-9-]+)/; const CUSTOM_PATTERN = /--wp--custom--([a-z0-9-]+(?:--[a-z0-9-]+)*)/; +/** CSS generic font families, which name no font of their own. */ +const GENERIC_FAMILIES = new Set([ + 'serif', + 'sans-serif', + 'monospace', + 'cursive', + 'fantasy', + 'system-ui', + 'ui-serif', + 'ui-sans-serif', + 'ui-monospace', + 'ui-rounded', + 'math', + 'emoji', + 'fangsong', +]); const MIN_MODE_PATTERN = /^(mobile|min|small|sm)$/i; const MAX_MODE_PATTERN = /^(desktop|max|large|lg)$/i; @@ -358,7 +374,7 @@ export class FigmaVariablesMapper { return { slug: target.slug, name: value, - fontFamily: this.declaredStack(variable, value) ?? this.fontStack(value), + fontFamily: this.declaredStack(variable, value) ?? this.fontStack(value, target.slug), }; case 'border-radius': if (typeof value !== 'number') { @@ -571,6 +587,10 @@ export class FigmaVariablesMapper { if (!stack) { return undefined; } + // A generic name such as "Monospace" has no font of its own: the declared system stack is the font. + if (GENERIC_FAMILIES.has(name.trim().toLowerCase())) { + return stack; + } const [first, ...fallbacks] = stack.split(',').map((part) => part.trim()); const plain = (text: string) => text.toLowerCase().replace(/[^a-z0-9]/g, ''); const face = plain(first); @@ -581,8 +601,15 @@ export class FigmaVariablesMapper { return [this.quoteFamily(name), ...fallbacks.filter(Boolean)].join(', '); } - private fontStack(family: string): string { - return `${this.quoteFamily(family)}, ${this.options.fontFallback ?? 'sans-serif'}`; + /** A stack with no declaration: the family, then the generic family for its role. */ + private fontStack(family: string, slug: string): string { + const generic = family.trim().toLowerCase(); + if (GENERIC_FAMILIES.has(generic)) { + return generic; + } + const fallback = + slug === 'monospace' ? 'monospace' : (this.options.fontFallback ?? 'sans-serif'); + return `${this.quoteFamily(family)}, ${fallback}`; } private quoteFamily(family: string): string { From ce00aa6e782689005ecd9f1b5957d8feb2f2d002 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Tue, 10 Nov 2026 08:58:18 +0200 Subject: [PATCH 24/31] fix(figma-tokens): map content and wide width to settings.layout The Layout collection's --wp--custom--layout--content-size and wide-size variables landed in settings.custom.layout with no unit, and settings.layout was never set, so the theme kept the scaffold's widths. Map them, and core's --wp--style--global-- names, to contentSize and wideSize in px. Refs GIT-2772 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../references/tokens-spacing.md | 4 ++ .../figma-variables-to-theme-json.test.ts | 50 +++++++++++++++++++ .../scripts/figma-variables-to-theme-json.ts | 48 ++++++++++++++++-- 4 files changed, 99 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index baf4de5d1f..8b1bab091f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Figma Tokens Layout Widths** — `figma-to-block-theme` maps the content and wide width variables to `settings.layout` in px, instead of unitless values in `settings.custom.layout`, so the theme gets the design's widths. ([GIT-2772](https://linear.app/lightspeedwp/issue/GIT-2772)) - **Figma Tokens Monospace Stack** — `figma-to-block-theme` keeps the declared system stack for a generic family such as Monospace, and falls back to `monospace` for the monospace role, instead of writing `Monospace, sans-serif`. ([GIT-2771](https://linear.app/lightspeedwp/issue/GIT-2771)) - **Figma Tokens Font Stacks** — `figma-to-block-theme` starts each font stack with the clean family name and keeps the declared fallbacks, instead of the live site's own `@font-face` name, so the stack matches the theme's `fontFace` entries. ([GIT-2770](https://linear.app/lightspeedwp/issue/GIT-2770)) - **Site Tokens Spacing Minimums** — `site-to-design-tokens` keeps mobile spacing values in order up the ladder, raising a step that would shrink below the one before and listing it for the reviewer. ([GIT-2766](https://linear.app/lightspeedwp/issue/GIT-2766)) diff --git a/skills/figma-to-block-theme/references/tokens-spacing.md b/skills/figma-to-block-theme/references/tokens-spacing.md index f02dbe14eb..6e5b0ec827 100644 --- a/skills/figma-to-block-theme/references/tokens-spacing.md +++ b/skills/figma-to-block-theme/references/tokens-spacing.md @@ -44,3 +44,7 @@ Use `--min-viewport` and `--max-viewport` only when the design's frames differ f - Replace `settings.spacing.spacingSizes`, and set `defaultSpacingSizes: false`. Core's default sizes use the slugs `20` to `80`, and when they are on they override theme sizes with the same slugs, so the theme's values never reach the page. Keep `units`, `padding`, `margin` and `blockGap`. - Compare the count with the mapper's `counts.spacing`. - Slugs used in `styles` and patterns (`var:preset|spacing|`) must still exist. `theme-orphaned-refs` checks this. + +## Layout widths + +Variables whose code syntax is `--wp--custom--layout--content-size` or `--wp--custom--layout--wide-size` (the form `site-to-design-tokens` writes), or core's `--wp--style--global--content-size` and `--wide-size`, go to `settings.layout.contentSize` and `wideSize`, not to `settings.custom`. Numbers become px (`848` gives `"848px"`), and a string keeps its unit. Compare the widths with the theme's current `settings.layout` in the plan, and note `counts.layout` in the report. diff --git a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts index c808e39c4a..f14a2edddf 100644 --- a/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts +++ b/skills/figma-to-block-theme/scripts/__tests__/figma-variables-to-theme-json.test.ts @@ -554,6 +554,56 @@ describe('FigmaVariablesMapper', () => { ); }); + it('maps content and wide width to settings.layout in px', () => { + const width = (id: string, syntax: string, value: unknown, type = 'FLOAT') => ({ + id, + name: `Desktop/${id}`, + type, + codeSyntax: { WEB: `var(${syntax})` }, + valuesByMode: { m: value }, + }); + const layout = (...variables: ReturnType[]) => + new FigmaVariablesMapper().map({ + collections: [{ name: 'Theme - Layout', modes: [{ id: 'm', name: 'Mode 1' }], variables }], + } as never); + + // The form site-to-design-tokens writes. + const custom = layout( + width('content', '--wp--custom--layout--content-size', 848), + width('wide', '--wp--custom--layout--wide-size', 1232) + ); + expect((custom.theme.settings as Json).layout).toEqual({ + contentSize: '848px', + wideSize: '1232px', + }); + expect((custom.theme.settings as Json).custom).toBeUndefined(); + expect(custom.report.counts.layout).toBe(2); + + // Core's own variable names, and string values with and without a unit. + const core = layout( + width('content', '--wp--style--global--content-size', '48rem', 'STRING'), + width('wide', '--wp--style--global--wide-size', '1200', 'STRING') + ); + expect((core.theme.settings as Json).layout).toEqual({ + contentSize: '48rem', + wideSize: '1200px', + }); + + // A layout width that isn't a length is reported, not written. + const bad = layout(width('content', '--wp--custom--layout--content-size', true, 'BOOLEAN')); + expect((bad.theme.settings as Json).layout).toBeUndefined(); + expect(bad.report.warnings.join('\n')).toContain('"Desktop/content" is BOOLEAN'); + + // A custom value that aliases a width refers to core's variable. + const alias = layout(width('content', '--wp--custom--layout--content-size', 848), { + ...width('gutter', '--wp--custom--max-text', 0), + valuesByMode: { m: { type: 'VARIABLE_ALIAS', id: 'content' } }, + }); + expect((alias.theme.settings as Json).custom['max-text']).toBe( + 'var(--wp--style--global--content-size)' + ); + }); + it('gives custom lengths a unit and refuses unsafe or clashing paths', () => { const variable = (id: string, syntax: string, value: number) => ({ id, diff --git a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts index 8eb90af77c..a0021ffda0 100644 --- a/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts +++ b/skills/figma-to-block-theme/scripts/figma-variables-to-theme-json.ts @@ -99,12 +99,22 @@ interface CustomTarget { path: string[]; } +/** Content and wide width, which belong in `settings.layout`. */ +interface LayoutTarget { + kind: 'layout'; + key: 'contentSize' | 'wideSize'; +} + +type Target = PresetTarget | CustomTarget | LayoutTarget; + /** Keys that would reach Object.prototype if written as plain properties. */ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']); const PRESET_PATTERN = /--wp--preset--(color|spacing|font-size|font-family|border-radius|shadow)--([a-z0-9-]+)/; const CUSTOM_PATTERN = /--wp--custom--([a-z0-9-]+(?:--[a-z0-9-]+)*)/; +/** `site-to-design-tokens` writes the custom form; core's own variables are the style form. */ +const LAYOUT_PATTERN = /--wp--(?:custom--layout|style--global)--(content|wide)-size(?![a-z0-9-])/; /** CSS generic font families, which name no font of their own. */ const GENERIC_FAMILIES = new Set([ 'serif', @@ -150,6 +160,8 @@ export class FigmaVariablesMapper { private warnings: string[] = []; /** Variation keys that come from colour modes. */ private readonly colourModes = new Set(); + /** `settings.layout` widths found while mapping. */ + private layout: JsonObject = {}; constructor(options: MapperOptions = {}) { this.options = options; @@ -158,6 +170,7 @@ export class FigmaVariablesMapper { map(data: VariablesExport): MappingResult { this.warnings = []; + this.layout = {}; this.colourModes.clear(); this.byId.clear(); for (const collection of data.collections) { @@ -216,6 +229,9 @@ export class FigmaVariablesMapper { this.assign(settings, ['shadow', 'defaultPresets'], false); this.assign(settings, ['shadow', 'presets'], presets.shadow); } + if (Object.keys(this.layout).length) { + settings.layout = this.layout; + } if (Object.keys(custom).length) { settings.custom = custom; } @@ -223,6 +239,7 @@ export class FigmaVariablesMapper { for (const [family, entries] of Object.entries(presets)) { counts[family] = entries.length; } + counts.layout = Object.keys(this.layout).length; counts.custom = this.countLeaves(custom); counts.variations = Object.keys(variations).length; @@ -261,6 +278,11 @@ export class FigmaVariablesMapper { continue; } + if (target.kind === 'layout') { + this.mapLayout(variable, target, baseMode.id); + continue; + } + if (target.kind === 'custom') { this.assign(custom, target.path, this.customValue(variable, baseMode.id, target.path)); if (target.path[0] === 'color') { @@ -394,6 +416,19 @@ export class FigmaVariablesMapper { } } + /** Content and wide width go to `settings.layout` as CSS lengths. */ + private mapLayout(variable: ExportedVariable, target: LayoutTarget, modeId: string): void { + const value = this.resolve(variable, modeId); + if (typeof value === 'number') { + this.layout[target.key] = this.px(value); + } else if (typeof value === 'string' && value.trim()) { + // A string such as "48rem" already has its unit; a bare number gets px. + this.layout[target.key] = /^\d+(\.\d+)?$/.test(value.trim()) ? `${value.trim()}px` : value; + } else { + this.typeMismatch(variable, 'FLOAT'); + } + } + private customValue(variable: ExportedVariable, modeId: string, path: string[]): unknown { const raw = variable.valuesByMode[modeId]; @@ -406,6 +441,10 @@ export class FigmaVariablesMapper { if (presetTarget && presetTarget.kind === 'custom') { return `var(--wp--custom--${presetTarget.path.join('--')})`; } + if (presetTarget && presetTarget.kind === 'layout') { + const width = presetTarget.key === 'contentSize' ? 'content' : 'wide'; + return `var(--wp--style--global--${width}-size)`; + } } const value = this.resolve(variable, modeId); @@ -477,15 +516,16 @@ export class FigmaVariablesMapper { return presets; } - private parseTarget( - variable: ExportedVariable, - report = true - ): PresetTarget | CustomTarget | undefined { + private parseTarget(variable: ExportedVariable, report = true): Target | undefined { const syntax = variable.codeSyntax?.WEB; const preset = syntax?.match(PRESET_PATTERN); if (preset) { return { kind: 'preset', family: preset[1], slug: preset[2] }; } + const layout = syntax?.match(LAYOUT_PATTERN); + if (layout) { + return { kind: 'layout', key: layout[1] === 'content' ? 'contentSize' : 'wideSize' }; + } const customMatch = syntax?.match(CUSTOM_PATTERN); if (customMatch) { return { kind: 'custom', path: customMatch[1].split('--') }; From 5fc2814ecbc8729a105494fcd51e80605bbe530a Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Tue, 10 Nov 2026 08:59:08 +0200 Subject: [PATCH 25/31] fix(site-tokens): export the palette ramps in the LightSpeed order The export created brand, primary, cta, neutral, and figma-to-block-theme keeps the Figma order, so the theme palette was out of convention. Create neutral, primary, brand, cta instead. Refs GIT-2773 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + skills/site-to-design-tokens/SKILL.md | 2 +- .../site-to-design-tokens/references/target-structure.md | 2 +- .../scripts/__tests__/write-token-export.test.ts | 7 +++++++ skills/site-to-design-tokens/scripts/write-token-export.ts | 3 ++- 5 files changed, 12 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b1bab091f..c11282a4d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Site Tokens Palette Order** — `site-to-design-tokens` exports the colour ramps in the LightSpeed order (neutral, primary, brand, cta), so the theme palette follows the convention. ([GIT-2773](https://linear.app/lightspeedwp/issue/GIT-2773)) - **Figma Tokens Layout Widths** — `figma-to-block-theme` maps the content and wide width variables to `settings.layout` in px, instead of unitless values in `settings.custom.layout`, so the theme gets the design's widths. ([GIT-2772](https://linear.app/lightspeedwp/issue/GIT-2772)) - **Figma Tokens Monospace Stack** — `figma-to-block-theme` keeps the declared system stack for a generic family such as Monospace, and falls back to `monospace` for the monospace role, instead of writing `Monospace, sans-serif`. ([GIT-2771](https://linear.app/lightspeedwp/issue/GIT-2771)) - **Figma Tokens Font Stacks** — `figma-to-block-theme` starts each font stack with the clean family name and keeps the declared fallbacks, instead of the live site's own `@font-face` name, so the stack matches the theme's `fontFace` entries. ([GIT-2770](https://linear.app/lightspeedwp/issue/GIT-2770)) diff --git a/skills/site-to-design-tokens/SKILL.md b/skills/site-to-design-tokens/SKILL.md index 4671e028f5..b5dfea3818 100644 --- a/skills/site-to-design-tokens/SKILL.md +++ b/skills/site-to-design-tokens/SKILL.md @@ -50,7 +50,7 @@ npx tsx ${CLAUDE_SKILL_DIR}/scripts/propose-tokens.ts site-styles.json --out pro The proposal follows the structure in [references/target-structure.md](references/target-structure.md): -- `base`, `contrast`, and `brand`, `primary`, `cta` and `neutral` ramps from 100 to 900, each built around a live colour that keeps its exact value +- `base`, `contrast`, and `neutral`, `primary`, `brand` and `cta` ramps from 100 to 900 (in that order), each built around a live colour that keeps its exact value - the 44 semantic roles, taken from what elements use where the site shows it, and from the TSP defaults otherwise - type, spacing, radius, shadow, layout and breakpoint scales, with Max (1440px) and Min (390px) values diff --git a/skills/site-to-design-tokens/references/target-structure.md b/skills/site-to-design-tokens/references/target-structure.md index de036ed239..58f0d1fa34 100644 --- a/skills/site-to-design-tokens/references/target-structure.md +++ b/skills/site-to-design-tokens/references/target-structure.md @@ -6,7 +6,7 @@ The proposal and the Figma script follow the TSP design system file (The Safari | Collection | Modes | Holds | Code syntax | | ------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Theme - Colour | Value | Primitives: `Theme/base`, `Theme/contrast`, `brand/100` … `900`, `primary/…`, `cta/…`, `neutral/…`, `system//`, `custom/overlay`, `shadow/` | `--wp--preset--color--`; overlay and shadows `--wp--custom--color--…` | +| Theme - Colour | Value | Primitives: `Theme/base`, `Theme/contrast`, `neutral/100` … `900`, `primary/…`, `brand/…`, `cta/…` (in that order), `system//`, `custom/overlay`, `shadow/` | `--wp--preset--color--`; overlay and shadows `--wp--custom--color--…` | | Theme - Semantic | Value | Aliases of the primitives, by role | `--wp--custom--color----` | | Theme - Typography | Max, Min | `Sizes/`, `Font-Families/Primary` (heading), `Secondary` (body), `Tertiary` (accent, only with a third family) and `Monospace`, `Line-Heights/`, `Weights/` | `--wp--preset--font-size--` (`100` … `900`), `--wp--preset--font-family--heading`, `body`, `accent` and `monospace`, `--wp--custom--line-height--`, `--wp--custom--font-weight--` | | Theme - Spacing | Max, Min | `Padding/None`, `Padding/XXS`, `Padding/XS` … `Padding/Colossal` | `--wp--preset--spacing--` (`5` … `100`) | diff --git a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts index 943b65127e..ae0842485e 100644 --- a/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts +++ b/skills/site-to-design-tokens/scripts/__tests__/write-token-export.test.ts @@ -34,6 +34,13 @@ describe('TokenPlanBuilder', () => { expect(collection('Theme - Semantic').variables).toHaveLength(44); }); + it('creates the ramps in the LightSpeed palette order', () => { + const families = collection('Theme - Colour') + .variables.map((v) => v.name.split('/')[0]) + .filter((family, i, all) => all.indexOf(family) === i); + expect(families.slice(0, 5)).toEqual(['Theme', 'neutral', 'primary', 'brand', 'cta']); + }); + it('names and code syntax match the TSP file and the mapper', () => { const colour = collection('Theme - Colour').variables; expect(colour.find((v) => v.key === 'brand-600')).toMatchObject({ diff --git a/skills/site-to-design-tokens/scripts/write-token-export.ts b/skills/site-to-design-tokens/scripts/write-token-export.ts index fe789fd337..db61004bc5 100644 --- a/skills/site-to-design-tokens/scripts/write-token-export.ts +++ b/skills/site-to-design-tokens/scripts/write-token-export.ts @@ -116,7 +116,8 @@ export class TokenPlanBuilder { values: { Value: rgba(p.colour.primitives.contrast) }, }, ]; - for (const family of ['brand', 'primary', 'cta', 'neutral'] as Family[]) { + // The LightSpeed palette order: neutral, primary, brand, cta. + for (const family of ['neutral', 'primary', 'brand', 'cta'] as Family[]) { for (const step of RAMP_STEPS) { const slug = `${family}-${step}`; colour.push({ From 39aab34869157fa1fac8c09ee9a7f20dceb805e2 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Tue, 10 Nov 2026 09:57:48 +0200 Subject: [PATCH 26/31] fix(orphaned-refs): skip dependency folders and check border-radius presets The scan walked node_modules, vendor, build and .agents, so on a scaffold-generated theme it took over 2 minutes and its report was almost all false hits. Skip those folders (with --exclude for more), add border-radius to the preset types, suggest the nearest step for bare numeric ladders, and add unit tests. Refs GIT-2774 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + skills/theme-orphaned-refs/SKILL.md | 11 +- .../__tests__/test_find_orphaned_presets.py | 110 ++++++++++++++++++ .../scripts/find_orphaned_presets.py | 58 +++++++-- 4 files changed, 168 insertions(+), 12 deletions(-) create mode 100644 skills/theme-orphaned-refs/scripts/__tests__/test_find_orphaned_presets.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c11282a4d3..252821ab04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Orphaned Refs Scan Scope** — `theme-orphaned-refs` skips dependency, build and agent folders (with `--exclude` for more), checks `border-radius` presets, and suggests the nearest step for numeric ladders. ([GIT-2774](https://linear.app/lightspeedwp/issue/GIT-2774)) - **Site Tokens Palette Order** — `site-to-design-tokens` exports the colour ramps in the LightSpeed order (neutral, primary, brand, cta), so the theme palette follows the convention. ([GIT-2773](https://linear.app/lightspeedwp/issue/GIT-2773)) - **Figma Tokens Layout Widths** — `figma-to-block-theme` maps the content and wide width variables to `settings.layout` in px, instead of unitless values in `settings.custom.layout`, so the theme gets the design's widths. ([GIT-2772](https://linear.app/lightspeedwp/issue/GIT-2772)) - **Figma Tokens Monospace Stack** — `figma-to-block-theme` keeps the declared system stack for a generic family such as Monospace, and falls back to `monospace` for the monospace role, instead of writing `Monospace, sans-serif`. ([GIT-2771](https://linear.app/lightspeedwp/issue/GIT-2771)) diff --git a/skills/theme-orphaned-refs/SKILL.md b/skills/theme-orphaned-refs/SKILL.md index 7911f4217a..10571ebf1b 100644 --- a/skills/theme-orphaned-refs/SKILL.md +++ b/skills/theme-orphaned-refs/SKILL.md @@ -11,8 +11,8 @@ This skill guides an agent to walk a WordPress block theme sequentially, detect ## Workflow (sequential) -1. Load theme.json and build the preset registry for `color`, `font-family`, `font-size`, `spacing`, `shadow`, `gradient`, `duotone`. -2. Scan the theme in path order (root → subfolders) for: +1. Load theme.json and build the preset registry for `color`, `font-family`, `font-size`, `spacing`, `shadow`, `border-radius`, `gradient`, `duotone`. +2. Scan the theme's own files in path order (root → subfolders), skipping `node_modules`, `vendor`, `build`, `dist`, `coverage`, `.git`, `.agents`, `.claude` and `.github`, for: - `var:preset||` - `--wp--preset----` 3. For each reference whose slug is not defined in theme.json, replace it with the closest match. @@ -24,6 +24,7 @@ This skill guides an agent to walk a WordPress block theme sequentially, detect - **Exact match**: keep as-is. - **Numeric slugs** (e.g., `accent-4`): choose the nearest numeric slug with the same prefix from theme.json. +- **Bare numeric ladders** (font sizes `100`–`900`, radius `0`–`700`, spacing `5`–`100`): choose the nearest step. Check what the old value was for: a pill button radius belongs on `Round`, even when another step is nearer by size. - **Accent/CTA/Brand 1–9**: map to `*-100`, `*-200`, etc. when present. - **Font sizes by name**: - `small` → `300`, `medium` → `400`, `large` → `500`, `x-large` → `600`, `xx-large` → `700` (fallback to nearest numeric). @@ -36,9 +37,11 @@ This skill guides an agent to walk a WordPress block theme sequentially, detect Use the bundled script to find orphaned references and suggested replacements: +```bash +python3 scripts/find_orphaned_presets.py --root --report ``` -python scripts/find_orphaned_presets.py --root -``` + +Add `--exclude ` (repeatable) to skip another folder. Tests: `python3 -m unittest discover -s skills/theme-orphaned-refs/scripts/__tests__` from the repository root. Then apply replacements with minimal, localized edits. diff --git a/skills/theme-orphaned-refs/scripts/__tests__/test_find_orphaned_presets.py b/skills/theme-orphaned-refs/scripts/__tests__/test_find_orphaned_presets.py new file mode 100644 index 0000000000..9e94286651 --- /dev/null +++ b/skills/theme-orphaned-refs/scripts/__tests__/test_find_orphaned_presets.py @@ -0,0 +1,110 @@ +"""Tests for find_orphaned_presets.py. Run: python3 -m unittest discover -s skills/theme-orphaned-refs/scripts/__tests__""" +import json +import pathlib +import sys +import tempfile +import unittest +from unittest import mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +import find_orphaned_presets as fop # noqa: E402 + +THEME = { + "settings": { + "color": {"palette": [{"slug": "base"}, {"slug": "brand-600"}]}, + "typography": {"fontSizes": [{"slug": "200"}, {"slug": "300"}], "fontFamilies": [{"slug": "body"}]}, + "spacing": {"spacingSizes": [{"slug": "5"}, {"slug": "10"}]}, + "shadow": {"presets": [{"slug": "100"}]}, + "border": {"radiusSizes": [{"slug": "0"}, {"slug": "400"}, {"slug": "700"}]}, + } +} + + +class ThemeFixture: + def __init__(self) -> None: + self.tmp = tempfile.TemporaryDirectory() + self.root = pathlib.Path(self.tmp.name) + self.write("theme.json", json.dumps(THEME)) + + def write(self, relative: str, text: str) -> None: + path = self.root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +class FindOrphansTest(unittest.TestCase): + def setUp(self) -> None: + self.theme = ThemeFixture() + self.addCleanup(self.theme.tmp.cleanup) + + def orphans(self, **kwargs): + presets = fop.load_theme_presets(self.theme.root / "theme.json") + return [(p.relative_to(self.theme.root).as_posix(), t, s, g) for p, t, s, g in fop.find_orphans(self.theme.root, presets, **kwargs)] + + def test_reports_orphans_in_the_theme_files(self) -> None: + self.theme.write("patterns/hero.php", 'style="color:var(--wp--preset--color--brand-500)" {"fontSize":"var:preset|font-size|small"}') + self.assertEqual( + self.orphans(), + [ + ("patterns/hero.php", "font-size", "small", "300"), + ("patterns/hero.php", "color", "brand-500", "brand-600"), + ], + ) + + def test_checks_border_radius_presets(self) -> None: + self.theme.write( + "styles/blocks/button/rounded.json", + '{"radius": "var(--wp--preset--border-radius--600)", "r2": "var:preset|border-radius|400"}', + ) + # Bare numeric slugs suggest the nearest step on the ladder. + self.assertEqual(self.orphans(), [("styles/blocks/button/rounded.json", "border-radius", "600", "700")]) + + def test_skips_dependency_build_and_agent_folders(self) -> None: + bad = "var(--wp--preset--color--vivid-purple)" + for folder in ("node_modules/pkg", "vendor/lib", "build", ".agents/skills", ".git", "coverage"): + self.theme.write(f"{folder}/file.js", bad) + self.theme.write("templates/index.html", bad) + self.assertEqual([o[0] for o in self.orphans()], ["templates/index.html"]) + + def test_extra_excludes_and_binary_files(self) -> None: + bad = "var(--wp--preset--color--vivid-purple)" + self.theme.write("tmp/file.css", bad) + self.theme.write("assets/logo.svg", bad) + self.assertEqual([o[0] for o in self.orphans(skip_dirs=fop.SKIP_DIRS | {"tmp"})], []) + + def test_unreadable_files_and_unknown_types_are_ignored(self) -> None: + (self.theme.root / "blob.bin").write_bytes(b"\xff\xfe\x00var(--wp--preset--color--x)") + self.theme.write("parts/header.html", "var(--wp--preset--aspect-ratio--wide)") + self.assertEqual(self.orphans(), []) + + +class ClosestSlugTest(unittest.TestCase): + def test_suggestions(self) -> None: + self.assertEqual(fop.closest_slug("x", "color", []), "x") + self.assertEqual(fop.closest_slug("base", "color", ["base"]), "base") + self.assertEqual(fop.closest_slug("medium", "font-size", ["300", "400"]), "400") + self.assertEqual(fop.closest_slug("brand-6", "color", ["brand-600", "brand-100"]), "brand-600") + self.assertEqual(fop.closest_slug("cta-450", "color", ["cta-400", "cta-900"]), "cta-400") + self.assertEqual(fop.closest_slug("contrast", "color", ["contrast-alt", "base"]), "contrast-alt") + self.assertEqual(fop.closest_slug("50", "spacing", ["40", "60", "base"]), "40") + self.assertEqual(fop.closest_slug("600", "border-radius", ["none"]), "none") + + +class MainTest(unittest.TestCase): + def test_writes_report_with_excludes(self) -> None: + theme = ThemeFixture() + self.addCleanup(theme.tmp.cleanup) + theme.write("patterns/a.php", "var(--wp--preset--shadow--600)") + theme.write("scratch/b.php", "var(--wp--preset--shadow--600)") + argv = ["prog", "--root", str(theme.root), "--report", "report.txt", "--exclude", "scratch"] + with mock.patch.object(sys, "argv", argv), mock.patch("builtins.print") as printed: + self.assertEqual(fop.main(), 0) + report = (theme.root / "report.txt").read_text(encoding="utf-8").strip().splitlines() + self.assertEqual(len(report), 1) + self.assertIn("patterns/a.php\tshadow\t600\t100", report[0]) + printed.assert_any_call("Orphaned count: 1") + + +if __name__ == "__main__": + unittest.main() diff --git a/skills/theme-orphaned-refs/scripts/find_orphaned_presets.py b/skills/theme-orphaned-refs/scripts/find_orphaned_presets.py index 541e3e36c2..08f46910fe 100644 --- a/skills/theme-orphaned-refs/scripts/find_orphaned_presets.py +++ b/skills/theme-orphaned-refs/scripts/find_orphaned_presets.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import argparse import json +import os import pathlib import re from difflib import get_close_matches @@ -10,6 +11,7 @@ "color", "font-family", "font-size", + "border-radius", "spacing", "shadow", "gradient", @@ -29,6 +31,21 @@ "colossal": "900", } +# Dependency, build, VCS and agent folders hold other projects' preset references. +SKIP_DIRS = { + "node_modules", + "vendor", + "build", + "dist", + "coverage", + ".git", + ".agents", + ".claude", + ".github", +} + +BINARY_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".woff", ".woff2", ".ttf", ".otf", ".eot"} + COLOR_STEP_PREFIXES = { "accent", "cta", @@ -48,6 +65,7 @@ def load_theme_presets(theme_path: pathlib.Path) -> Dict[str, List[str]]: presets["font-size"] = [f.get("slug") for f in settings.get("typography", {}).get("fontSizes", []) if f.get("slug")] presets["spacing"] = [s.get("slug") for s in settings.get("spacing", {}).get("spacingSizes", []) if s.get("slug")] presets["shadow"] = [s.get("slug") for s in settings.get("shadow", {}).get("presets", []) if s.get("slug")] + presets["border-radius"] = [r.get("slug") for r in settings.get("border", {}).get("radiusSizes", []) if r.get("slug")] for key in list(presets.keys()): presets[key] = [s for s in presets[key] if s] @@ -75,6 +93,12 @@ def closest_slug(slug: str, preset_type: str, candidates: Iterable[str]) -> str: if mapped and mapped in candidates: return mapped + # Numeric ladders (font sizes 100-900, radius 0-700, spacing 5-100): suggest the nearest step. + if slug.isdigit(): + steps = [c for c in candidates if c.isdigit()] + if steps: + return min(steps, key=lambda c: (abs(int(c) - int(slug)), int(c))) + prefix, number = _numeric_slug(slug) if number != -1: if prefix in COLOR_STEP_PREFIXES and number < 100: @@ -95,16 +119,28 @@ def closest_slug(slug: str, preset_type: str, candidates: Iterable[str]) -> str: return close[0] if close else candidates[0] -def find_orphans(root: pathlib.Path, presets: Dict[str, List[str]]) -> List[Tuple[pathlib.Path, str, str, str]]: +def theme_files(root: pathlib.Path, skip_dirs: Iterable[str] = SKIP_DIRS) -> List[pathlib.Path]: + """Lists the theme's own text files, without walking into skipped folders.""" + skip = set(skip_dirs) + files = [] + for folder, dirs, names in os.walk(root): + dirs[:] = [d for d in dirs if d not in skip] + for name in names: + path = pathlib.Path(folder) / name + if path.suffix.lower() not in BINARY_SUFFIXES: + files.append(path) + return sorted(files) + + +def find_orphans( + root: pathlib.Path, presets: Dict[str, List[str]], skip_dirs: Iterable[str] = SKIP_DIRS +) -> List[Tuple[pathlib.Path, str, str, str]]: pattern_json = re.compile(r"var:preset\|([a-z-]+)\|([a-zA-Z0-9-]+)") - pattern_css = re.compile(r"--wp--preset--([a-z-]+)--([a-zA-Z0-9-]+)") + # A type has single hyphens only, so "border-radius--600" reads as type "border-radius", slug "600". + pattern_css = re.compile(r"--wp--preset--([a-z]+(?:-[a-z]+)*)--([a-zA-Z0-9-]+)") results = [] - for path in sorted(root.rglob("*")): - if path.is_dir(): - continue - if path.suffix.lower() in {".png", ".jpg", ".jpeg", ".gif", ".svg", ".woff", ".woff2", ".ttf", ".otf", ".eot"}: - continue + for path in theme_files(root, skip_dirs): try: text = path.read_text(encoding="utf-8") except Exception: @@ -128,13 +164,19 @@ def main() -> int: parser.add_argument("--root", default=".", help="Theme root directory.") parser.add_argument("--theme", default="theme.json", help="Path to theme.json relative to root.") parser.add_argument("--report", default="_orphaned_preset_refs.txt", help="Report filename.") + parser.add_argument( + "--exclude", + action="append", + default=[], + help="Another folder name to skip (repeatable). node_modules, vendor, build and agent folders are always skipped.", + ) args = parser.parse_args() root = pathlib.Path(args.root).resolve() theme_path = (root / args.theme).resolve() presets = load_theme_presets(theme_path) - orphans = find_orphans(root, presets) + orphans = find_orphans(root, presets, SKIP_DIRS | set(args.exclude)) report_path = root / args.report with report_path.open("w", encoding="utf-8") as f: From c3770023217415064799d0060cf74c179baa2f32 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Tue, 10 Nov 2026 10:09:04 +0200 Subject: [PATCH 27/31] refactor(orphaned-refs): convert the scan script and its tests to TypeScript Agent tooling is TypeScript with Jest tests beside the script. Replace find_orphaned_presets.py and its unittest tests with find-orphaned-presets.ts (registry loader, slug suggester and scanner classes, file system injected) and Jest tests at 80% thresholds. Add npm run test:theme-orphaned-refs. Behaviour matches the previous commit. Refs GIT-2774 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- package.json | 2 + skills/theme-orphaned-refs/SKILL.md | 4 +- .../__tests__/find-orphaned-presets.test.ts | 197 ++++++++++ .../__tests__/test_find_orphaned_presets.py | 110 ------ .../scripts/find-orphaned-presets.ts | 335 ++++++++++++++++++ .../scripts/find_orphaned_presets.py | 192 ---------- .../scripts/jest.config.cjs | 28 ++ .../theme-orphaned-refs/scripts/tsconfig.json | 9 + 9 files changed, 574 insertions(+), 305 deletions(-) create mode 100644 skills/theme-orphaned-refs/scripts/__tests__/find-orphaned-presets.test.ts delete mode 100644 skills/theme-orphaned-refs/scripts/__tests__/test_find_orphaned_presets.py create mode 100644 skills/theme-orphaned-refs/scripts/find-orphaned-presets.ts delete mode 100644 skills/theme-orphaned-refs/scripts/find_orphaned_presets.py create mode 100644 skills/theme-orphaned-refs/scripts/jest.config.cjs create mode 100644 skills/theme-orphaned-refs/scripts/tsconfig.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 252821ab04..9effa58610 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,7 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- **Orphaned Refs Scan Scope** — `theme-orphaned-refs` skips dependency, build and agent folders (with `--exclude` for more), checks `border-radius` presets, and suggests the nearest step for numeric ladders. ([GIT-2774](https://linear.app/lightspeedwp/issue/GIT-2774)) +- **Orphaned Refs Scan Scope** — `theme-orphaned-refs` skips dependency, build and agent folders (with `--exclude` for more), checks `border-radius` presets, suggests the nearest step for numeric ladders, and is now TypeScript with Jest tests (`find-orphaned-presets.ts`). ([GIT-2774](https://linear.app/lightspeedwp/issue/GIT-2774)) - **Site Tokens Palette Order** — `site-to-design-tokens` exports the colour ramps in the LightSpeed order (neutral, primary, brand, cta), so the theme palette follows the convention. ([GIT-2773](https://linear.app/lightspeedwp/issue/GIT-2773)) - **Figma Tokens Layout Widths** — `figma-to-block-theme` maps the content and wide width variables to `settings.layout` in px, instead of unitless values in `settings.custom.layout`, so the theme gets the design's widths. ([GIT-2772](https://linear.app/lightspeedwp/issue/GIT-2772)) - **Figma Tokens Monospace Stack** — `figma-to-block-theme` keeps the declared system stack for a generic family such as Monospace, and falls back to `monospace` for the monospace role, instead of writing `Monospace, sans-serif`. ([GIT-2771](https://linear.app/lightspeedwp/issue/GIT-2771)) diff --git a/package.json b/package.json index ae35ff9ef8..9b0d0c57ad 100644 --- a/package.json +++ b/package.json @@ -156,6 +156,8 @@ "test:js": "jest --config .jest.config.cjs --coverage --forceExit --detectOpenHandles", "test:figma-to-block-theme": "jest --config skills/figma-to-block-theme/scripts/jest.config.cjs", "test:site-to-design-tokens": "jest --config skills/site-to-design-tokens/scripts/jest.config.cjs", + "test:theme-orphaned-refs": "jest --config skills/theme-orphaned-refs/scripts/jest.config.cjs", + "test:theme-orphaned-refs": "jest --config skills/theme-orphaned-refs/scripts/jest.config.cjs", "test:site-to-figma-components": "jest --config skills/site-to-figma-components/scripts/jest.config.cjs", "test:agent-spec-validation": "node .github/scripts/__tests__/validate-agent-specs.test.js", "test:index-generator": "node .github/scripts/__tests__/generate-agent-index.test.js", diff --git a/skills/theme-orphaned-refs/SKILL.md b/skills/theme-orphaned-refs/SKILL.md index 10571ebf1b..800ecbb617 100644 --- a/skills/theme-orphaned-refs/SKILL.md +++ b/skills/theme-orphaned-refs/SKILL.md @@ -38,10 +38,10 @@ This skill guides an agent to walk a WordPress block theme sequentially, detect Use the bundled script to find orphaned references and suggested replacements: ```bash -python3 scripts/find_orphaned_presets.py --root --report +npx tsx ${CLAUDE_SKILL_DIR}/scripts/find-orphaned-presets.ts --root --report ``` -Add `--exclude ` (repeatable) to skip another folder. Tests: `python3 -m unittest discover -s skills/theme-orphaned-refs/scripts/__tests__` from the repository root. +Add `--exclude ` (repeatable) to skip another folder. Run `npm ci` in the `.github` checkout first. Tests: `npm run test:theme-orphaned-refs` from the repository root. Then apply replacements with minimal, localized edits. diff --git a/skills/theme-orphaned-refs/scripts/__tests__/find-orphaned-presets.test.ts b/skills/theme-orphaned-refs/scripts/__tests__/find-orphaned-presets.test.ts new file mode 100644 index 0000000000..8dbbe224cc --- /dev/null +++ b/skills/theme-orphaned-refs/scripts/__tests__/find-orphaned-presets.test.ts @@ -0,0 +1,197 @@ +import { join } from 'node:path'; +import { + FileSystem, + OrphanScanner, + PresetRegistryLoader, + runOrphanedRefsCli, + SKIP_DIRS, + SlugSuggester, +} from '../find-orphaned-presets'; + +const ROOT = '/theme'; + +const THEME = JSON.stringify({ + settings: { + color: { palette: [{ slug: 'base' }, { slug: 'brand-600' }, {}], gradients: [{ slug: 'g' }] }, + typography: { fontSizes: [{ slug: '200' }, { slug: '300' }], fontFamilies: [{ slug: 'body' }] }, + spacing: { spacingSizes: [{ slug: '5' }, { slug: '10' }] }, + shadow: { presets: [{ slug: '100' }] }, + border: { radiusSizes: [{ slug: '0' }, { slug: '400' }, { slug: '700' }] }, + }, +}); + +/** An in-memory theme folder. Keys are paths relative to ROOT. */ +class MemoryFileSystem implements FileSystem { + readonly written = new Map(); + readonly listed: string[] = []; + + constructor(private readonly files: Record) {} + + readText(path: string): string | undefined { + const key = path.slice(ROOT.length + 1); + return key in this.files ? this.files[key] : undefined; + } + + listDir(path: string): { name: string; isDirectory: boolean }[] { + this.listed.push(path); + const prefix = path === ROOT ? '' : `${path.slice(ROOT.length + 1)}/`; + const entries = new Map(); + for (const file of Object.keys(this.files)) { + if (file.startsWith(prefix)) { + const [name, ...rest] = file.slice(prefix.length).split('/'); + entries.set(name, rest.length > 0); + } + } + return [...entries].map(([name, isDirectory]) => ({ name, isDirectory })); + } + + writeText(path: string, content: string): void { + this.written.set(path, content); + } +} + +function scan(files: Record, skip?: string[]) { + const fs = new MemoryFileSystem({ 'theme.json': THEME, ...files }); + const presets = new PresetRegistryLoader().load(THEME); + const orphans = new OrphanScanner(fs).scan(ROOT, presets, skip).map((o) => ({ + ...o, + file: o.file.slice(ROOT.length + 1), + })); + return { orphans, fs }; +} + +describe('PresetRegistryLoader', () => { + it('reads every preset type, including radius, and drops entries without a slug', () => { + const presets = new PresetRegistryLoader().load(THEME); + expect(presets.color).toEqual(['base', 'brand-600']); + expect(presets['border-radius']).toEqual(['0', '400', '700']); + expect(presets.duotone).toEqual([]); + }); + + it('copes with a theme.json that has no settings', () => { + expect(new PresetRegistryLoader().load('{}').spacing).toEqual([]); + }); +}); + +describe('OrphanScanner', () => { + it('reports orphans in the theme files with suggestions', () => { + const { orphans } = scan({ + 'patterns/hero.php': + 'style="color:var(--wp--preset--color--brand-500)" {"fontSize":"var:preset|font-size|small"}', + }); + expect(orphans).toEqual([ + { file: 'patterns/hero.php', type: 'font-size', slug: 'small', suggestion: '300' }, + { file: 'patterns/hero.php', type: 'color', slug: 'brand-500', suggestion: 'brand-600' }, + ]); + }); + + it('checks border-radius presets and suggests the nearest step', () => { + const { orphans } = scan({ + 'styles/blocks/button/rounded.json': + '{"radius":"var(--wp--preset--border-radius--600)","r2":"var:preset|border-radius|400"}', + }); + expect(orphans).toEqual([ + { + file: 'styles/blocks/button/rounded.json', + type: 'border-radius', + slug: '600', + suggestion: '700', + }, + ]); + }); + + it('never enters dependency, build or agent folders', () => { + const bad = 'var(--wp--preset--color--vivid-purple)'; + const files: Record = { 'templates/index.html': bad }; + for (const folder of SKIP_DIRS) { + files[`${folder}/deep/file.js`] = bad; + } + const { orphans, fs } = scan(files); + expect(orphans.map((o) => o.file)).toEqual(['templates/index.html']); + expect(fs.listed).not.toContain(join(ROOT, 'node_modules')); + }); + + it('honours extra excludes and skips binary and unreadable files', () => { + const bad = 'var(--wp--preset--color--vivid-purple)'; + const { orphans } = scan( + { 'tmp/file.css': bad, 'assets/logo.SVG': bad, 'parts/gone.html': undefined }, + [...SKIP_DIRS, 'tmp'] + ); + expect(orphans).toEqual([]); + }); + + it('ignores preset types it does not know', () => { + expect(scan({ 'parts/header.html': 'var(--wp--preset--aspect-ratio--wide)' }).orphans).toEqual( + [] + ); + }); +}); + +describe('SlugSuggester', () => { + const suggester = new SlugSuggester(); + + it.each([ + ['x', 'color', [], 'x'], + ['base', 'color', ['base'], 'base'], + ['medium', 'font-size', ['300', '400'], '400'], + ['huge', 'font-size', ['300', '400'], '300'], + ['brand-6', 'color', ['brand-600', 'brand-100'], 'brand-600'], + ['cta-450', 'color', ['cta-400', 'cta-900'], 'cta-400'], + ['primary-450', 'color', ['primary-500', 'primary-400'], 'primary-400'], + ['50', 'spacing', ['40', '60', 'base'], '40'], + ['600', 'border-radius', ['none'], 'none'], + ['contrast', 'color', ['base', 'contrast-alt'], 'contrast-alt'], + ['zzz', 'color', ['base', 'brand'], 'base'], + ] as const)('suggests for %s (%s)', (slug, type, candidates, expected) => { + expect(suggester.suggest(slug, type, [...candidates])).toBe(expected); + }); +}); + +describe('runOrphanedRefsCli', () => { + function run(argv: string[], files: Record = {}) { + const fs = new MemoryFileSystem({ 'theme.json': THEME, ...files }); + const out: string[] = []; + const err: string[] = []; + const code = runOrphanedRefsCli(argv, { + fs, + stdout: (t) => out.push(t), + stderr: (t) => err.push(t), + }); + return { code, fs, out: out.join(''), err: err.join('') }; + } + + it('writes a report of the orphans, relative to the theme', () => { + const { code, fs, out } = run( + ['--root', ROOT, '--report', 'report.txt', '--exclude', 'scratch'], + { + 'patterns/a.php': 'var(--wp--preset--shadow--600)', + 'scratch/b.php': 'var(--wp--preset--shadow--600)', + } + ); + expect(code).toBe(0); + expect(fs.written.get(join(ROOT, 'report.txt'))).toBe('patterns/a.php\tshadow\t600\t100\n'); + expect(out).toContain('Orphaned count: 1'); + }); + + it('writes an absolute report path as given', () => { + const { fs } = run(['--root', ROOT, '--report', '/tmp/out.txt', '--theme', 'theme.json']); + expect(fs.written.get('/tmp/out.txt')).toBe(''); + }); + + it('prints help', () => { + const { code, out } = run(['--help']); + expect(code).toBe(0); + expect(out).toContain('Always skips: node_modules'); + }); + + it('rejects unknown or incomplete arguments', () => { + expect(run(['--nope', 'x']).code).toBe(1); + expect(run(['--root']).err).toContain('Unknown or incomplete argument: --root'); + }); + + it('fails when theme.json cannot be read', () => { + const { code, err } = run(['--root', ROOT, '--theme', 'missing.json']); + expect(code).toBe(1); + expect(err).toContain('Cannot read'); + }); +}); diff --git a/skills/theme-orphaned-refs/scripts/__tests__/test_find_orphaned_presets.py b/skills/theme-orphaned-refs/scripts/__tests__/test_find_orphaned_presets.py deleted file mode 100644 index 9e94286651..0000000000 --- a/skills/theme-orphaned-refs/scripts/__tests__/test_find_orphaned_presets.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Tests for find_orphaned_presets.py. Run: python3 -m unittest discover -s skills/theme-orphaned-refs/scripts/__tests__""" -import json -import pathlib -import sys -import tempfile -import unittest -from unittest import mock - -sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) - -import find_orphaned_presets as fop # noqa: E402 - -THEME = { - "settings": { - "color": {"palette": [{"slug": "base"}, {"slug": "brand-600"}]}, - "typography": {"fontSizes": [{"slug": "200"}, {"slug": "300"}], "fontFamilies": [{"slug": "body"}]}, - "spacing": {"spacingSizes": [{"slug": "5"}, {"slug": "10"}]}, - "shadow": {"presets": [{"slug": "100"}]}, - "border": {"radiusSizes": [{"slug": "0"}, {"slug": "400"}, {"slug": "700"}]}, - } -} - - -class ThemeFixture: - def __init__(self) -> None: - self.tmp = tempfile.TemporaryDirectory() - self.root = pathlib.Path(self.tmp.name) - self.write("theme.json", json.dumps(THEME)) - - def write(self, relative: str, text: str) -> None: - path = self.root / relative - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding="utf-8") - - -class FindOrphansTest(unittest.TestCase): - def setUp(self) -> None: - self.theme = ThemeFixture() - self.addCleanup(self.theme.tmp.cleanup) - - def orphans(self, **kwargs): - presets = fop.load_theme_presets(self.theme.root / "theme.json") - return [(p.relative_to(self.theme.root).as_posix(), t, s, g) for p, t, s, g in fop.find_orphans(self.theme.root, presets, **kwargs)] - - def test_reports_orphans_in_the_theme_files(self) -> None: - self.theme.write("patterns/hero.php", 'style="color:var(--wp--preset--color--brand-500)" {"fontSize":"var:preset|font-size|small"}') - self.assertEqual( - self.orphans(), - [ - ("patterns/hero.php", "font-size", "small", "300"), - ("patterns/hero.php", "color", "brand-500", "brand-600"), - ], - ) - - def test_checks_border_radius_presets(self) -> None: - self.theme.write( - "styles/blocks/button/rounded.json", - '{"radius": "var(--wp--preset--border-radius--600)", "r2": "var:preset|border-radius|400"}', - ) - # Bare numeric slugs suggest the nearest step on the ladder. - self.assertEqual(self.orphans(), [("styles/blocks/button/rounded.json", "border-radius", "600", "700")]) - - def test_skips_dependency_build_and_agent_folders(self) -> None: - bad = "var(--wp--preset--color--vivid-purple)" - for folder in ("node_modules/pkg", "vendor/lib", "build", ".agents/skills", ".git", "coverage"): - self.theme.write(f"{folder}/file.js", bad) - self.theme.write("templates/index.html", bad) - self.assertEqual([o[0] for o in self.orphans()], ["templates/index.html"]) - - def test_extra_excludes_and_binary_files(self) -> None: - bad = "var(--wp--preset--color--vivid-purple)" - self.theme.write("tmp/file.css", bad) - self.theme.write("assets/logo.svg", bad) - self.assertEqual([o[0] for o in self.orphans(skip_dirs=fop.SKIP_DIRS | {"tmp"})], []) - - def test_unreadable_files_and_unknown_types_are_ignored(self) -> None: - (self.theme.root / "blob.bin").write_bytes(b"\xff\xfe\x00var(--wp--preset--color--x)") - self.theme.write("parts/header.html", "var(--wp--preset--aspect-ratio--wide)") - self.assertEqual(self.orphans(), []) - - -class ClosestSlugTest(unittest.TestCase): - def test_suggestions(self) -> None: - self.assertEqual(fop.closest_slug("x", "color", []), "x") - self.assertEqual(fop.closest_slug("base", "color", ["base"]), "base") - self.assertEqual(fop.closest_slug("medium", "font-size", ["300", "400"]), "400") - self.assertEqual(fop.closest_slug("brand-6", "color", ["brand-600", "brand-100"]), "brand-600") - self.assertEqual(fop.closest_slug("cta-450", "color", ["cta-400", "cta-900"]), "cta-400") - self.assertEqual(fop.closest_slug("contrast", "color", ["contrast-alt", "base"]), "contrast-alt") - self.assertEqual(fop.closest_slug("50", "spacing", ["40", "60", "base"]), "40") - self.assertEqual(fop.closest_slug("600", "border-radius", ["none"]), "none") - - -class MainTest(unittest.TestCase): - def test_writes_report_with_excludes(self) -> None: - theme = ThemeFixture() - self.addCleanup(theme.tmp.cleanup) - theme.write("patterns/a.php", "var(--wp--preset--shadow--600)") - theme.write("scratch/b.php", "var(--wp--preset--shadow--600)") - argv = ["prog", "--root", str(theme.root), "--report", "report.txt", "--exclude", "scratch"] - with mock.patch.object(sys, "argv", argv), mock.patch("builtins.print") as printed: - self.assertEqual(fop.main(), 0) - report = (theme.root / "report.txt").read_text(encoding="utf-8").strip().splitlines() - self.assertEqual(len(report), 1) - self.assertIn("patterns/a.php\tshadow\t600\t100", report[0]) - printed.assert_any_call("Orphaned count: 1") - - -if __name__ == "__main__": - unittest.main() diff --git a/skills/theme-orphaned-refs/scripts/find-orphaned-presets.ts b/skills/theme-orphaned-refs/scripts/find-orphaned-presets.ts new file mode 100644 index 0000000000..d45abceb4b --- /dev/null +++ b/skills/theme-orphaned-refs/scripts/find-orphaned-presets.ts @@ -0,0 +1,335 @@ +/** + * Finds preset references in a block theme that theme.json no longer defines, + * and suggests the closest defined slug for each. + * + * Usage (from the repository root): + * npx tsx skills/theme-orphaned-refs/scripts/find-orphaned-presets.ts --root [--report ] [--exclude ] + */ +import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { extname, isAbsolute, join, relative, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +export type PresetType = + | 'color' + | 'font-family' + | 'font-size' + | 'spacing' + | 'shadow' + | 'border-radius' + | 'gradient' + | 'duotone'; + +export const PRESET_TYPES: readonly PresetType[] = [ + 'color', + 'font-family', + 'font-size', + 'spacing', + 'shadow', + 'border-radius', + 'gradient', + 'duotone', +]; + +/** Dependency, build, VCS and agent folders hold other projects' preset references. */ +export const SKIP_DIRS: readonly string[] = [ + 'node_modules', + 'vendor', + 'build', + 'dist', + 'coverage', + '.git', + '.agents', + '.claude', + '.github', +]; + +const BINARY_EXTENSIONS = new Set([ + '.png', + '.jpg', + '.jpeg', + '.gif', + '.webp', + '.svg', + '.woff', + '.woff2', + '.ttf', + '.otf', + '.eot', +]); + +const NAME_TO_FONT_SIZE: Record = { + tiny: '100', + base: '200', + small: '300', + medium: '400', + large: '500', + 'x-large': '600', + 'xx-large': '700', + 'xxx-large': '800', + gigantic: '800', + colossal: '900', +}; + +const COLOR_STEP_PREFIXES = new Set(['accent', 'cta', 'brand']); + +const JSON_REFERENCE = /var:preset\|([a-z-]+)\|([a-zA-Z0-9-]+)/g; +// A type has single hyphens only, so "border-radius--600" reads as type "border-radius", slug "600". +const CSS_REFERENCE = /--wp--preset--([a-z]+(?:-[a-z]+)*)--([a-zA-Z0-9-]+)/g; + +export type PresetRegistry = Record; + +export interface Orphan { + file: string; + type: PresetType; + slug: string; + suggestion: string; +} + +/** File access, injected so tests never touch the disk. */ +export interface FileSystem { + readText(path: string): string | undefined; + listDir(path: string): { name: string; isDirectory: boolean }[]; + writeText(path: string, content: string): void; +} + +type JsonObject = Record; + +/** Reads the slugs theme.json defines for each preset type. */ +export class PresetRegistryLoader { + load(themeJson: string): PresetRegistry { + const settings = ((JSON.parse(themeJson) as JsonObject).settings ?? {}) as JsonObject; + const slugs = (group: string, key: string): string[] => { + const list = ((settings[group] ?? {}) as JsonObject)[key]; + return Array.isArray(list) + ? list + .map((entry) => (entry as JsonObject | null)?.slug) + .filter((slug): slug is string => typeof slug === 'string' && slug !== '') + : []; + }; + return { + color: slugs('color', 'palette'), + gradient: slugs('color', 'gradients'), + duotone: slugs('color', 'duotone'), + 'font-family': slugs('typography', 'fontFamilies'), + 'font-size': slugs('typography', 'fontSizes'), + spacing: slugs('spacing', 'spacingSizes'), + shadow: slugs('shadow', 'presets'), + 'border-radius': slugs('border', 'radiusSizes'), + }; + } +} + +/** Suggests the closest defined slug for one that no longer exists. */ +export class SlugSuggester { + suggest(slug: string, type: PresetType, candidates: string[]): string { + if (!candidates.length || candidates.includes(slug)) { + return slug; + } + + if (type === 'font-size') { + const mapped = NAME_TO_FONT_SIZE[slug]; + if (mapped && candidates.includes(mapped)) { + return mapped; + } + } + + // Numeric ladders (font sizes 100-900, radius 0-700, spacing 5-100): the nearest step. + if (/^\d+$/.test(slug)) { + const steps = candidates.filter((c) => /^\d+$/.test(c)); + if (steps.length) { + return this.nearest(steps, Number(slug), (c) => Number(c)); + } + } + + const stepped = slug.match(/^(.*?)-(\d+)$/); + if (stepped) { + const [, prefix, digits] = stepped; + const number = Number(digits); + if (COLOR_STEP_PREFIXES.has(prefix) && number < 100) { + const scaled = `${prefix}-${number * 100}`; + if (candidates.includes(scaled)) { + return scaled; + } + } + const samePrefix = candidates.filter((c) => new RegExp(`^${prefix}-\\d+$`).test(c)); + if (samePrefix.length) { + return this.nearest(samePrefix, number, (c) => Number(c.slice(prefix.length + 1))); + } + } + + return this.mostSimilar(slug, candidates); + } + + private nearest(candidates: string[], target: number, value: (c: string) => number): string { + return [...candidates].sort( + (a, b) => Math.abs(value(a) - target) - Math.abs(value(b) - target) || value(a) - value(b) + )[0]; + } + + /** Highest 2 x common-subsequence / total-length ratio; the first candidate wins ties. */ + private mostSimilar(slug: string, candidates: string[]): string { + let best = candidates[0]; + let bestScore = -1; + for (const candidate of candidates) { + const score = (2 * this.commonLength(slug, candidate)) / (slug.length + candidate.length); + if (score > bestScore) { + best = candidate; + bestScore = score; + } + } + return best; + } + + private commonLength(a: string, b: string): number { + const row = new Array(b.length + 1).fill(0); + for (let i = 1; i <= a.length; i++) { + let diagonal = 0; + for (let j = 1; j <= b.length; j++) { + const above = row[j]; + row[j] = a[i - 1] === b[j - 1] ? diagonal + 1 : Math.max(row[j], row[j - 1]); + diagonal = above; + } + } + return row[b.length]; + } +} + +/** Walks the theme's own files and reports references to undefined presets. */ +export class OrphanScanner { + constructor( + private readonly fs: FileSystem, + private readonly suggester = new SlugSuggester() + ) {} + + /** The theme's text files in path order, without entering skipped folders. */ + files(root: string, skipDirs: Iterable = SKIP_DIRS): string[] { + const skip = new Set(skipDirs); + const found: string[] = []; + const walk = (dir: string): void => { + for (const entry of this.fs.listDir(dir)) { + const path = join(dir, entry.name); + if (entry.isDirectory) { + if (!skip.has(entry.name)) { + walk(path); + } + } else if (!BINARY_EXTENSIONS.has(extname(entry.name).toLowerCase())) { + found.push(path); + } + } + }; + walk(root); + return found.sort(); + } + + scan(root: string, presets: PresetRegistry, skipDirs: Iterable = SKIP_DIRS): Orphan[] { + const orphans: Orphan[] = []; + for (const file of this.files(root, skipDirs)) { + const text = this.fs.readText(file); + if (text === undefined) { + continue; + } + for (const pattern of [JSON_REFERENCE, CSS_REFERENCE]) { + for (const match of text.matchAll(pattern)) { + const [, type, slug] = match; + if (!(PRESET_TYPES as readonly string[]).includes(type)) { + continue; + } + const candidates = presets[type as PresetType]; + if (!candidates.includes(slug)) { + orphans.push({ + file, + type: type as PresetType, + slug, + suggestion: this.suggester.suggest(slug, type as PresetType, candidates), + }); + } + } + } + } + return orphans; + } +} + +export interface CliIo { + fs: FileSystem; + stdout(text: string): void; + stderr(text: string): void; +} + +const USAGE = + 'Usage: find-orphaned-presets [--root ] [--theme theme.json] [--report ] [--exclude ]...\n' + + `Always skips: ${SKIP_DIRS.join(', ')}.\n`; + +/** Parses CLI arguments, scans the theme, writes the report and returns the exit code. */ +export function runOrphanedRefsCli(argv: string[], io: CliIo): number { + let root = '.'; + let theme = 'theme.json'; + let report = '_orphaned_preset_refs.txt'; + const exclude: string[] = []; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--help' || arg === '-h') { + io.stdout(USAGE); + return 0; + } + const value = argv[i + 1]; + if (!['--root', '--theme', '--report', '--exclude'].includes(arg) || value === undefined) { + io.stderr(`Unknown or incomplete argument: ${arg}\n${USAGE}`); + return 1; + } + i++; + if (arg === '--root') root = value; + else if (arg === '--theme') theme = value; + else if (arg === '--report') report = value; + else exclude.push(value); + } + + const rootPath = resolve(root); + const themeJson = io.fs.readText(join(rootPath, theme)); + if (themeJson === undefined) { + io.stderr(`Cannot read ${join(rootPath, theme)}\n`); + return 1; + } + + const presets = new PresetRegistryLoader().load(themeJson); + const orphans = new OrphanScanner(io.fs).scan(rootPath, presets, [...SKIP_DIRS, ...exclude]); + const reportPath = isAbsolute(report) ? report : join(rootPath, report); + io.fs.writeText( + reportPath, + orphans + .map((o) => `${relative(rootPath, o.file)}\t${o.type}\t${o.slug}\t${o.suggestion}\n`) + .join('') + ); + io.stdout(`Orphaned count: ${orphans.length}\nReport: ${reportPath}\n`); + return 0; +} + +/* istanbul ignore next -- the real file system, used only from the command line */ +export const nodeFileSystem: FileSystem = { + readText(path) { + try { + return readFileSync(path, 'utf8'); + } catch { + return undefined; + } + }, + listDir(path) { + return readdirSync(path, { withFileTypes: true }).map((entry) => ({ + name: entry.name, + isDirectory: entry.isDirectory(), + })); + }, + writeText(path, content) { + writeFileSync(path, content); + }, +}; + +/* istanbul ignore next -- thin CLI entry point */ +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exitCode = runOrphanedRefsCli(process.argv.slice(2), { + fs: nodeFileSystem, + stdout: (text) => process.stdout.write(text), + stderr: (text) => process.stderr.write(text), + }); +} diff --git a/skills/theme-orphaned-refs/scripts/find_orphaned_presets.py b/skills/theme-orphaned-refs/scripts/find_orphaned_presets.py deleted file mode 100644 index 08f46910fe..0000000000 --- a/skills/theme-orphaned-refs/scripts/find_orphaned_presets.py +++ /dev/null @@ -1,192 +0,0 @@ -#!/usr/bin/env python3 -import argparse -import json -import os -import pathlib -import re -from difflib import get_close_matches -from typing import Dict, Iterable, List, Tuple - -PRESET_TYPES = { - "color", - "font-family", - "font-size", - "border-radius", - "spacing", - "shadow", - "gradient", - "duotone", -} - -NAME_TO_FONT_SIZE = { - "tiny": "100", - "base": "200", - "small": "300", - "medium": "400", - "large": "500", - "x-large": "600", - "xx-large": "700", - "xxx-large": "800", - "gigantic": "800", - "colossal": "900", -} - -# Dependency, build, VCS and agent folders hold other projects' preset references. -SKIP_DIRS = { - "node_modules", - "vendor", - "build", - "dist", - "coverage", - ".git", - ".agents", - ".claude", - ".github", -} - -BINARY_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".woff", ".woff2", ".ttf", ".otf", ".eot"} - -COLOR_STEP_PREFIXES = { - "accent", - "cta", - "brand", -} - - -def load_theme_presets(theme_path: pathlib.Path) -> Dict[str, List[str]]: - data = json.loads(theme_path.read_text(encoding="utf-8")) - settings = data.get("settings", {}) - - presets: Dict[str, List[str]] = {} - presets["color"] = [c.get("slug") for c in settings.get("color", {}).get("palette", []) if c.get("slug")] - presets["gradient"] = [g.get("slug") for g in settings.get("color", {}).get("gradients", []) if g.get("slug")] - presets["duotone"] = [d.get("slug") for d in settings.get("color", {}).get("duotone", []) if d.get("slug")] - presets["font-family"] = [f.get("slug") for f in settings.get("typography", {}).get("fontFamilies", []) if f.get("slug")] - presets["font-size"] = [f.get("slug") for f in settings.get("typography", {}).get("fontSizes", []) if f.get("slug")] - presets["spacing"] = [s.get("slug") for s in settings.get("spacing", {}).get("spacingSizes", []) if s.get("slug")] - presets["shadow"] = [s.get("slug") for s in settings.get("shadow", {}).get("presets", []) if s.get("slug")] - presets["border-radius"] = [r.get("slug") for r in settings.get("border", {}).get("radiusSizes", []) if r.get("slug")] - - for key in list(presets.keys()): - presets[key] = [s for s in presets[key] if s] - - return presets - - -def _numeric_slug(slug: str) -> Tuple[str, int]: - match = re.match(r"^(.*?)-(\d+)$", slug) - if not match: - return "", -1 - return match.group(1), int(match.group(2)) - - -def closest_slug(slug: str, preset_type: str, candidates: Iterable[str]) -> str: - candidates = list(candidates) - if not candidates: - return slug - - if slug in candidates: - return slug - - if preset_type == "font-size": - mapped = NAME_TO_FONT_SIZE.get(slug) - if mapped and mapped in candidates: - return mapped - - # Numeric ladders (font sizes 100-900, radius 0-700, spacing 5-100): suggest the nearest step. - if slug.isdigit(): - steps = [c for c in candidates if c.isdigit()] - if steps: - return min(steps, key=lambda c: (abs(int(c) - int(slug)), int(c))) - - prefix, number = _numeric_slug(slug) - if number != -1: - if prefix in COLOR_STEP_PREFIXES and number < 100: - scaled = f"{prefix}-{number * 100}" - if scaled in candidates: - return scaled - same_prefix = [c for c in candidates if c.startswith(prefix + "-")] - if same_prefix: - values = [] - for c in same_prefix: - _, n = _numeric_slug(c) - if n != -1: - values.append((c, n)) - if values: - return min(values, key=lambda x: abs(x[1] - number))[0] - - close = get_close_matches(slug, candidates, n=1, cutoff=0.0) - return close[0] if close else candidates[0] - - -def theme_files(root: pathlib.Path, skip_dirs: Iterable[str] = SKIP_DIRS) -> List[pathlib.Path]: - """Lists the theme's own text files, without walking into skipped folders.""" - skip = set(skip_dirs) - files = [] - for folder, dirs, names in os.walk(root): - dirs[:] = [d for d in dirs if d not in skip] - for name in names: - path = pathlib.Path(folder) / name - if path.suffix.lower() not in BINARY_SUFFIXES: - files.append(path) - return sorted(files) - - -def find_orphans( - root: pathlib.Path, presets: Dict[str, List[str]], skip_dirs: Iterable[str] = SKIP_DIRS -) -> List[Tuple[pathlib.Path, str, str, str]]: - pattern_json = re.compile(r"var:preset\|([a-z-]+)\|([a-zA-Z0-9-]+)") - # A type has single hyphens only, so "border-radius--600" reads as type "border-radius", slug "600". - pattern_css = re.compile(r"--wp--preset--([a-z]+(?:-[a-z]+)*)--([a-zA-Z0-9-]+)") - results = [] - - for path in theme_files(root, skip_dirs): - try: - text = path.read_text(encoding="utf-8") - except Exception: - continue - - for pattern in (pattern_json, pattern_css): - for match in pattern.finditer(text): - preset_type, slug = match.group(1), match.group(2) - if preset_type not in PRESET_TYPES: - continue - candidates = presets.get(preset_type, []) - if slug not in candidates: - suggestion = closest_slug(slug, preset_type, candidates) - results.append((path, preset_type, slug, suggestion)) - - return results - - -def main() -> int: - parser = argparse.ArgumentParser(description="Find orphaned theme preset references and suggest replacements.") - parser.add_argument("--root", default=".", help="Theme root directory.") - parser.add_argument("--theme", default="theme.json", help="Path to theme.json relative to root.") - parser.add_argument("--report", default="_orphaned_preset_refs.txt", help="Report filename.") - parser.add_argument( - "--exclude", - action="append", - default=[], - help="Another folder name to skip (repeatable). node_modules, vendor, build and agent folders are always skipped.", - ) - args = parser.parse_args() - - root = pathlib.Path(args.root).resolve() - theme_path = (root / args.theme).resolve() - - presets = load_theme_presets(theme_path) - orphans = find_orphans(root, presets, SKIP_DIRS | set(args.exclude)) - - report_path = root / args.report - with report_path.open("w", encoding="utf-8") as f: - for path, preset_type, slug, suggestion in orphans: - f.write(f"{path}\t{preset_type}\t{slug}\t{suggestion}\n") - - print(f"Orphaned count: {len(orphans)}") - print(f"Report: {report_path}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/skills/theme-orphaned-refs/scripts/jest.config.cjs b/skills/theme-orphaned-refs/scripts/jest.config.cjs new file mode 100644 index 0000000000..b2160a8618 --- /dev/null +++ b/skills/theme-orphaned-refs/scripts/jest.config.cjs @@ -0,0 +1,28 @@ +/** + * Jest configuration for the theme-orphaned-refs helper scripts. + * + * Extends the repository config, scopes the run to this skill and enforces + * 80% coverage on every metric. Run from the repository root: + * npm run test:theme-orphaned-refs + */ +const base = require('../../../.jest.config.cjs'); + +const skillDir = '/skills/theme-orphaned-refs/scripts'; + +module.exports = { + ...base, + rootDir: '../../..', + testEnvironment: 'node', + testMatch: [`${skillDir}/__tests__/**/*.test.ts`], + collectCoverage: true, + collectCoverageFrom: [`${skillDir}/*.ts`], + coverageDirectory: '/coverage/theme-orphaned-refs', + coverageThreshold: { + global: { + statements: 80, + branches: 80, + functions: 80, + lines: 80, + }, + }, +}; diff --git a/skills/theme-orphaned-refs/scripts/tsconfig.json b/skills/theme-orphaned-refs/scripts/tsconfig.json new file mode 100644 index 0000000000..f902349f6b --- /dev/null +++ b/skills/theme-orphaned-refs/scripts/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "allowImportingTsExtensions": false, + "types": [ "node", "jest" ] + }, + "include": [ "*.ts", "__tests__/*.ts" ], + "exclude": [] +} From 20434ccd1b0aaf60db16f14bcbeecaedb205fc44 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Wed, 11 Nov 2026 10:15:09 +0200 Subject: [PATCH 28/31] docs(changelog): shorten the site-tokens numeric slugs entry to under 250 characters Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c82355ac01..1c01389cee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,7 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. Radius variables are named by bare size (`Small`, not `Radius Small`), and `figma-to-block-theme` accepts both. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) +- **Site Tokens Numeric Slugs** — `site-to-design-tokens` uses the scaffold's numeric slugs for font sizes, radius and shadows, so its export needs no renaming. Radius variables use bare sizes (`Small`), and `figma-to-block-theme` accepts both. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Studio Imports From Live Sites** — Live site exports now import into Studio sites that already have WordPress content; files in the wrong format are refused with a reason. ([PR #3961](https://github.com/lightspeedwp/.github/pull/3961)) - **Qodo PR-Agent Eligibility and Comment Binding** — A closed pull request is refused on every request path, and both receivers resolve the exact maintainer comment by id. ([PR #3532](https://github.com/lightspeedwp/.github/pull/3532)) From b86bd17131d41b256cca872529260333ecf62fa9 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Wed, 11 Nov 2026 10:31:02 +0200 Subject: [PATCH 29/31] docs(changelog): fit the site-tokens numeric slugs entry within 250 characters Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c01389cee..59a5a3e4d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,7 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- **Site Tokens Numeric Slugs** — `site-to-design-tokens` uses the scaffold's numeric slugs for font sizes, radius and shadows, so its export needs no renaming. Radius variables use bare sizes (`Small`), and `figma-to-block-theme` accepts both. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) +- **Site Tokens Numeric Slugs** — `site-to-design-tokens` exports the scaffold's numeric slugs for font sizes, radius and shadows, and radius uses bare size names. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Studio Imports From Live Sites** — Live site exports now import into Studio sites that already have WordPress content; files in the wrong format are refused with a reason. ([PR #3961](https://github.com/lightspeedwp/.github/pull/3961)) - **Qodo PR-Agent Eligibility and Comment Binding** — A closed pull request is refused on every request path, and both receivers resolve the exact maintainer comment by id. ([PR #3532](https://github.com/lightspeedwp/.github/pull/3532)) From 06e6eea261e2b7c37711f28593d5b9503d88a7aa Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Wed, 11 Nov 2026 10:35:03 +0200 Subject: [PATCH 30/31] docs(changelog): fit the theme token entries within 250 characters and drop a duplicate Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a88b761816..76d8813491 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,7 +73,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- **Site Skills Setup Notes** — `site-to-design-tokens` and `site-to-figma-components` now say to run `npm ci` and, if the browser fails to launch, `npx puppeteer browsers install chrome` (npm 11 skips Puppeteer's download). `figma-to-block-theme` notes the `npm ci` step. ([#4009](https://github.com/lightspeedwp/.github/issues/4009)) +- **Site Skills Setup Notes** — The site skills say to run `npm ci`, and `npx puppeteer browsers install chrome` if the browser fails to launch. ([#4009](https://github.com/lightspeedwp/.github/issues/4009)) - **Label inventory token** — The organisation label inventory now needs its own dedicated token, refuses the GitHub Actions token and fails when private repositories are missing. (#3734) - **Private Repositories Stay Out Of Public Reports** — The label inventory and the weekly drift report now count private repositories without naming them or listing their labels. Detail goes to a private repository when one is set. (#3734) - **Dependabot Merge Queue Fixed** — Dependabot pull requests no longer fail the Mergify queue check, because the queue now tests each pull request in place. ([PR #3817](https://github.com/lightspeedwp/.github/pull/3817)) @@ -117,19 +117,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - **Site Tokens Numeric Slugs** — `site-to-design-tokens` exports the scaffold's numeric slugs for font sizes, radius and shadows, and radius uses bare size names. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) -- **Orphaned Refs Scan Scope** — `theme-orphaned-refs` skips dependency, build and agent folders (with `--exclude` for more), checks `border-radius` presets, suggests the nearest step for numeric ladders, and is now TypeScript with Jest tests (`find-orphaned-presets.ts`). ([GIT-2774](https://linear.app/lightspeedwp/issue/GIT-2774)) +- **Orphaned Refs Scan Scope** — `theme-orphaned-refs` skips dependency, build and agent folders, checks radius presets, suggests numeric steps, and is now TypeScript with tests. ([GIT-2774](https://linear.app/lightspeedwp/issue/GIT-2774)) - **Site Tokens Palette Order** — `site-to-design-tokens` exports the colour ramps in the LightSpeed order (neutral, primary, brand, cta), so the theme palette follows the convention. ([GIT-2773](https://linear.app/lightspeedwp/issue/GIT-2773)) -- **Figma Tokens Layout Widths** — `figma-to-block-theme` maps the content and wide width variables to `settings.layout` in px, instead of unitless values in `settings.custom.layout`, so the theme gets the design's widths. ([GIT-2772](https://linear.app/lightspeedwp/issue/GIT-2772)) -- **Figma Tokens Monospace Stack** — `figma-to-block-theme` keeps the declared system stack for a generic family such as Monospace, and falls back to `monospace` for the monospace role, instead of writing `Monospace, sans-serif`. ([GIT-2771](https://linear.app/lightspeedwp/issue/GIT-2771)) -- **Figma Tokens Font Stacks** — `figma-to-block-theme` starts each font stack with the clean family name and keeps the declared fallbacks, instead of the live site's own `@font-face` name, so the stack matches the theme's `fontFace` entries. ([GIT-2770](https://linear.app/lightspeedwp/issue/GIT-2770)) -- **Site Tokens Spacing Minimums** — `site-to-design-tokens` keeps mobile spacing values in order up the ladder, raising a step that would shrink below the one before and listing it for the reviewer. ([GIT-2766](https://linear.app/lightspeedwp/issue/GIT-2766)) +- **Figma Tokens Layout Widths** — `figma-to-block-theme` maps content and wide width to `settings.layout` in px, not unitless custom values. ([GIT-2772](https://linear.app/lightspeedwp/issue/GIT-2772)) +- **Figma Tokens Monospace Stack** — `figma-to-block-theme` keeps the declared system stack for a generic family such as Monospace. ([GIT-2771](https://linear.app/lightspeedwp/issue/GIT-2771)) +- **Figma Tokens Font Stacks** — `figma-to-block-theme` starts font stacks with the clean family name, not the live `@font-face` name, and keeps the fallbacks. ([GIT-2770](https://linear.app/lightspeedwp/issue/GIT-2770)) +- **Site Tokens Spacing Minimums** — `site-to-design-tokens` keeps mobile spacing values in order up the ladder and lists any it raises. ([GIT-2766](https://linear.app/lightspeedwp/issue/GIT-2766)) - **Site Tokens Action Text** — `site-to-design-tokens` takes each action's text colour from the buttons that have its fill, so text and fill are a pair the site really shows. ([GIT-2765](https://linear.app/lightspeedwp/issue/GIT-2765)) - **Site Tokens Crawl Redirects** — `site-to-design-tokens` records where each page landed, warns about redirects, and leaves out pages that land on one already captured. ([GIT-2767](https://linear.app/lightspeedwp/issue/GIT-2767)) -- **Site Tokens Action Colours** — `site-to-design-tokens` uses the live button colour for action backgrounds (hover one step darker) and moves defaults that fail contrast to the nearest passing step, recording each move in the report. ([#4008](https://github.com/lightspeedwp/.github/issues/4008)) -- **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names (`argesta_displayregular` becomes Argesta Display), keeps the exact CSS stack, and outputs the `heading`, `body` and `monospace` roles (plus `accent` only when the site uses a third font), marking each as live or default. `figma-to-block-theme` uses the stack. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) -- **Site Tokens Content Width** — `site-to-design-tokens` measures the content width from running text, one vote per page with blog posts first, takes a `--layout` override, and flags widths under 480px or near the wide width. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) +- **Site Tokens Action Colours** — `site-to-design-tokens` uses the live button colour for actions and moves defaults that fail contrast to the nearest passing step. ([#4008](https://github.com/lightspeedwp/.github/issues/4008)) +- **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names, keeps the CSS stack, and outputs heading, body, monospace and (when used) accent roles. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) +- **Site Tokens Content Width** — `site-to-design-tokens` measures content width from running text, takes a `--layout` override, and flags unlikely widths. ([#4006](https://github.com/lightspeedwp/.github/issues/4006)) - **Site Tokens Spacing Ladder** — `site-to-design-tokens` fills the whole spacing ladder from `5` by shifting values down before it drops one, so 11 distinct values all get a step. ([#4005](https://github.com/lightspeedwp/.github/issues/4005)) -- **Site Tokens Numeric Slugs** — `site-to-design-tokens` now uses the scaffold's numeric slugs for font sizes (`100` to `900`), radius (`0` to `700`) and shadows (`100` to `600`), so its export needs no renaming. Radius variables are named by bare size (`Small`, not `Radius Small`), and `figma-to-block-theme` accepts both. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) - **Studio Imports From Live Sites** — Live site exports now import into Studio sites that already have WordPress content; files in the wrong format are refused with a reason. ([PR #3961](https://github.com/lightspeedwp/.github/pull/3961)) - **Qodo PR-Agent Eligibility and Comment Binding** — A closed pull request is refused on every request path, and both receivers resolve the exact maintainer comment by id. ([PR #3532](https://github.com/lightspeedwp/.github/pull/3532)) From 3d5f4f9e4d37091a5936f711ed8ebb66428e499b Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Wed, 11 Nov 2026 10:56:26 +0200 Subject: [PATCH 31/31] docs(changelog): reference the PRs instead of Linear issues and keep entries user-facing Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76d8813491..21d50715b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -117,14 +117,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - **Site Tokens Numeric Slugs** — `site-to-design-tokens` exports the scaffold's numeric slugs for font sizes, radius and shadows, and radius uses bare size names. ([#4004](https://github.com/lightspeedwp/.github/issues/4004)) -- **Orphaned Refs Scan Scope** — `theme-orphaned-refs` skips dependency, build and agent folders, checks radius presets, suggests numeric steps, and is now TypeScript with tests. ([GIT-2774](https://linear.app/lightspeedwp/issue/GIT-2774)) -- **Site Tokens Palette Order** — `site-to-design-tokens` exports the colour ramps in the LightSpeed order (neutral, primary, brand, cta), so the theme palette follows the convention. ([GIT-2773](https://linear.app/lightspeedwp/issue/GIT-2773)) -- **Figma Tokens Layout Widths** — `figma-to-block-theme` maps content and wide width to `settings.layout` in px, not unitless custom values. ([GIT-2772](https://linear.app/lightspeedwp/issue/GIT-2772)) -- **Figma Tokens Monospace Stack** — `figma-to-block-theme` keeps the declared system stack for a generic family such as Monospace. ([GIT-2771](https://linear.app/lightspeedwp/issue/GIT-2771)) -- **Figma Tokens Font Stacks** — `figma-to-block-theme` starts font stacks with the clean family name, not the live `@font-face` name, and keeps the fallbacks. ([GIT-2770](https://linear.app/lightspeedwp/issue/GIT-2770)) -- **Site Tokens Spacing Minimums** — `site-to-design-tokens` keeps mobile spacing values in order up the ladder and lists any it raises. ([GIT-2766](https://linear.app/lightspeedwp/issue/GIT-2766)) -- **Site Tokens Action Text** — `site-to-design-tokens` takes each action's text colour from the buttons that have its fill, so text and fill are a pair the site really shows. ([GIT-2765](https://linear.app/lightspeedwp/issue/GIT-2765)) -- **Site Tokens Crawl Redirects** — `site-to-design-tokens` records where each page landed, warns about redirects, and leaves out pages that land on one already captured. ([GIT-2767](https://linear.app/lightspeedwp/issue/GIT-2767)) +- **Orphaned Refs Scan Scope** — `theme-orphaned-refs` skips `node_modules`, build and agent folders, checks radius presets, suggests numeric steps, and is now TypeScript with tests. ([#4037](https://github.com/lightspeedwp/.github/pull/4037)) +- **Site Tokens Palette Order** — `site-to-design-tokens` exports the colour ramps in the LightSpeed order (neutral, primary, brand, cta), so the theme palette follows the convention. ([#4035](https://github.com/lightspeedwp/.github/pull/4035)) +- **Figma Tokens Layout Widths** — `figma-to-block-theme` maps content and wide width to `settings.layout` in px, not unitless custom values. ([#4034](https://github.com/lightspeedwp/.github/pull/4034)) +- **Figma Tokens Monospace Stack** — `figma-to-block-theme` keeps the declared system stack for a generic family such as Monospace. ([#4033](https://github.com/lightspeedwp/.github/pull/4033)) +- **Figma Tokens Font Stacks** — `figma-to-block-theme` starts font stacks with the clean family name, not the live `@font-face` name, and keeps the fallbacks. ([#4032](https://github.com/lightspeedwp/.github/pull/4032)) +- **Site Tokens Spacing Minimums** — `site-to-design-tokens` keeps mobile spacing values in order up the ladder and lists any it raises. ([#4024](https://github.com/lightspeedwp/.github/pull/4024)) +- **Site Tokens Action Text** — `site-to-design-tokens` takes each action's text colour from the buttons that have its fill, so text and fill are a pair the site really shows. ([#4023](https://github.com/lightspeedwp/.github/pull/4023)) +- **Site Tokens Crawl Redirects** — `site-to-design-tokens` records where each page landed, warns about redirects, and leaves out pages that land on one already captured. ([#4022](https://github.com/lightspeedwp/.github/pull/4022)) - **Site Tokens Action Colours** — `site-to-design-tokens` uses the live button colour for actions and moves defaults that fail contrast to the nearest passing step. ([#4008](https://github.com/lightspeedwp/.github/issues/4008)) - **Site Tokens Font Roles** — `site-to-design-tokens` cleans font names, keeps the CSS stack, and outputs heading, body, monospace and (when used) accent roles. ([#4007](https://github.com/lightspeedwp/.github/issues/4007)) - **Site Tokens Content Width** — `site-to-design-tokens` measures content width from running text, takes a `--layout` override, and flags unlikely widths. ([#4006](https://github.com/lightspeedwp/.github/issues/4006))