From cca79c45ee061428a8611ef9cd46873c62907d46 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:20:49 +0200 Subject: [PATCH 1/8] 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 6d3c3f632efcc3e2e66f699d6753ff92c13361c9 Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 9 Nov 2026 16:22:07 +0200 Subject: [PATCH 2/8] 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 2fc479d024bb52ef908e050834b18e376e623f9b Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Tue, 10 Nov 2026 08:55:43 +0200 Subject: [PATCH 3/8] 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 4/8] 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 5/8] 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 6/8] 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 7/8] 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 8/8] 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": [] +}