From fc74d353c3dd84befeaf1e7da60d74822eb2b21e Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 23 Nov 2026 11:21:24 +0200 Subject: [PATCH 1/2] feat(site-to-block-theme): add a skill that rebuilds live-site templates, parts and patterns in a block theme Adapted from tsp-theme's tsp-match-live and made generic. Measures computed styles at 390, 768 and 1440, maps each value to theme.json tokens (with WordPress fluid typography), builds with the official WordPress skills to current coding standards, and proves the match with a live vs local style diff. Links it from the sibling theme skills and the onboarding routing map. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + .../references/routing-map.yaml | 77 +-- package.json | 1 + skills/figma-to-block-theme/SKILL.md | 1 + skills/site-to-block-theme/SKILL.md | 155 ++++++ skills/site-to-block-theme/agents/openai.yaml | 4 + .../references/measuring.md | 55 +++ .../references/wordpress-standards.md | 59 +++ .../scripts/__tests__/css-length.test.ts | 85 ++++ .../scripts/__tests__/fixtures.ts | 127 +++++ .../scripts/__tests__/map-and-diff.test.ts | 200 ++++++++ .../scripts/__tests__/measure-page.test.ts | 275 +++++++++++ .../scripts/__tests__/theme-tokens.test.ts | 124 +++++ .../scripts/__tests__/token-matcher.test.ts | 150 ++++++ .../scripts/diff-measurements.ts | 228 +++++++++ .../scripts/jest.config.cjs | 28 ++ .../site-to-block-theme/scripts/lib/colour.ts | 78 +++ .../scripts/lib/css-length.ts | 260 ++++++++++ .../scripts/lib/theme-tokens.ts | 252 ++++++++++ .../scripts/lib/token-matcher.ts | 333 +++++++++++++ .../scripts/map-to-tokens.ts | 186 +++++++ .../scripts/measure-page.ts | 462 ++++++++++++++++++ .../site-to-block-theme/scripts/tsconfig.json | 9 + skills/site-to-design-tokens/SKILL.md | 1 + skills/site-to-figma-components/SKILL.md | 1 + 25 files changed, 3122 insertions(+), 30 deletions(-) create mode 100644 skills/site-to-block-theme/SKILL.md create mode 100644 skills/site-to-block-theme/agents/openai.yaml create mode 100644 skills/site-to-block-theme/references/measuring.md create mode 100644 skills/site-to-block-theme/references/wordpress-standards.md create mode 100644 skills/site-to-block-theme/scripts/__tests__/css-length.test.ts create mode 100644 skills/site-to-block-theme/scripts/__tests__/fixtures.ts create mode 100644 skills/site-to-block-theme/scripts/__tests__/map-and-diff.test.ts create mode 100644 skills/site-to-block-theme/scripts/__tests__/measure-page.test.ts create mode 100644 skills/site-to-block-theme/scripts/__tests__/theme-tokens.test.ts create mode 100644 skills/site-to-block-theme/scripts/__tests__/token-matcher.test.ts create mode 100644 skills/site-to-block-theme/scripts/diff-measurements.ts create mode 100644 skills/site-to-block-theme/scripts/jest.config.cjs create mode 100644 skills/site-to-block-theme/scripts/lib/colour.ts create mode 100644 skills/site-to-block-theme/scripts/lib/css-length.ts create mode 100644 skills/site-to-block-theme/scripts/lib/theme-tokens.ts create mode 100644 skills/site-to-block-theme/scripts/lib/token-matcher.ts create mode 100644 skills/site-to-block-theme/scripts/map-to-tokens.ts create mode 100644 skills/site-to-block-theme/scripts/measure-page.ts create mode 100644 skills/site-to-block-theme/scripts/tsconfig.json diff --git a/CHANGELOG.md b/CHANGELOG.md index bd332f2344..2fe966ce5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Site to Block Theme Skill** — Rebuilds a live site's templates, parts and patterns in a block theme to match live: measures computed styles at three widths, maps each value to theme.json tokens, builds with the official WordPress skills and proves the match with a style diff. - **Theme Screenshot Skill** — Makes a theme's 1200 by 900 `screenshot.png` from the site's logo, the theme.json palette and an industry line, rendered with Puppeteer. ([#4010](https://github.com/lightspeedwp/.github/issues/4010)) - **Site to Figma Components Skill** — Rebuilds a live site's components, patterns and templates in Figma after the reviewer approves an inventory. ([#3992](https://github.com/lightspeedwp/.github/issues/3992)) - **Site to Design Tokens Skill** — For rebuilds: proposes design tokens from a live site, then creates the Figma variables and a theme.json export once approved. ([#3990](https://github.com/lightspeedwp/.github/issues/3990)) diff --git a/agents/ai-readiness-agent/skills/lightspeed-project-onboarding/references/routing-map.yaml b/agents/ai-readiness-agent/skills/lightspeed-project-onboarding/references/routing-map.yaml index d6e6104ff6..676f40b13f 100644 --- a/agents/ai-readiness-agent/skills/lightspeed-project-onboarding/references/routing-map.yaml +++ b/agents/ai-readiness-agent/skills/lightspeed-project-onboarding/references/routing-map.yaml @@ -17,7 +17,7 @@ routes: - intake_pack primary_skill: lightspeed-project-intake-router use_when: messy or incomplete project details need a structured intake pack and workflow route before deeper planning. - prompt_starter: "Use the LightSpeed project intake router to normalise this material into an intake pack, identify blockers, and recommend the next specialist workflow." + prompt_starter: 'Use the LightSpeed project intake router to normalise this material into an intake pack, identify blockers, and recommend the next specialist workflow.' - match: intents: @@ -31,7 +31,7 @@ routes: - discovery-source-intake - design-context-synthesis use_when: source evidence must be gathered, separated, and summarised before PRD, technical brief, or task planning. - prompt_starter: "Use the LightSpeed project researcher to produce an evidence review, source inventory, assumptions, blockers, and PRD-ready notes from this material." + prompt_starter: 'Use the LightSpeed project researcher to produce an evidence review, source inventory, assumptions, blockers, and PRD-ready notes from this material.' - match: intents: @@ -45,7 +45,7 @@ routes: - lightspeed-prd-task-manager - lightspeed-prd-task-reviewer use_when: the user needs a PRD or product brief before technical planning, task breakdown, or GitHub issues. - prompt_starter: "Use the LightSpeed PRD generator to create a PRD with goals, non-goals, users, requirements, acceptance criteria, risks, assumptions, and open questions." + prompt_starter: 'Use the LightSpeed PRD generator to create a PRD with goals, non-goals, users, requirements, acceptance criteria, risks, assumptions, and open questions.' - match: intents: @@ -61,7 +61,7 @@ routes: - wordpress-block-theme-handoff - lightspeed-figma-wordpress-parity-auditor use_when: Figma design-system evidence must become WordPress architecture, theme.json, template, pattern, and implementation guidance. - prompt_starter: "Use the LightSpeed Figma-to-WordPress technical brief skill to convert the design and repo evidence into a developer-ready WordPress brief." + prompt_starter: 'Use the LightSpeed Figma-to-WordPress technical brief skill to convert the design and repo evidence into a developer-ready WordPress brief.' - match: intents: @@ -76,7 +76,7 @@ routes: - lightspeed-requirements-traceability-mapper - breakdown-plan use_when: approved or near-approved requirements need to become implementation tasks, epics, estimates, dependencies, and QA checks. - prompt_starter: "Use the LightSpeed task breakdown planner to create epics, task waves, dependencies, acceptance criteria, QA checks, and implementation sequencing." + prompt_starter: 'Use the LightSpeed task breakdown planner to create epics, task waves, dependencies, acceptance criteria, QA checks, and implementation sequencing.' - match: intents: @@ -89,7 +89,7 @@ routes: - linear-the-architect - lightspeed-task-breakdown-planner use_when: the user needs GitHub-ready markdown issue drafts without automatically creating issues. - prompt_starter: "Use the LightSpeed GitHub issue drafter to turn this plan or finding into GitHub-ready issue drafts with labels, dependencies, acceptance criteria, and QA notes." + prompt_starter: 'Use the LightSpeed GitHub issue drafter to turn this plan or finding into GitHub-ready issue drafts with labels, dependencies, acceptance criteria, and QA notes.' - match: intents: @@ -102,7 +102,7 @@ routes: - wp-figma-artifact-builder - lightspeed-acceptance-test-planner use_when: approved tasks or briefs need practical sequencing, branch strategy, testing approach, and handoff controls before coding. - prompt_starter: "Use the LightSpeed implementation plan generator to create the build sequence, dependencies, branch strategy, testing approach, and handoff notes." + prompt_starter: 'Use the LightSpeed implementation plan generator to create the build sequence, dependencies, branch strategy, testing approach, and handoff notes.' - match: intents: @@ -115,7 +115,7 @@ routes: - linear-gap-analyzer - evidence-quality-review use_when: a PRD, brief, task plan, issue set, or QA plan needs quality review before implementation. - prompt_starter: "Use the LightSpeed PRD task reviewer to check this planning pack for gaps, risks, acceptance coverage, launch alignment, and readiness." + prompt_starter: 'Use the LightSpeed PRD task reviewer to check this planning pack for gaps, risks, acceptance coverage, launch alignment, and readiness.' - match: intents: @@ -130,7 +130,7 @@ routes: - lightspeed-redirect-map-planner - technical-seo-audit use_when: launch-preparation work needs routing across QA, SEO, redirects, analytics, schema, content, policies, or approval gates. - prompt_starter: "Use the LightSpeed launch task router to sequence launch workstreams, identify blockers, and route each item to the right specialist workflow." + prompt_starter: 'Use the LightSpeed launch task router to sequence launch workstreams, identify blockers, and route each item to the right specialist workflow.' - match: intents: @@ -144,7 +144,7 @@ routes: - lightspeed-launch-readiness-auditor - lightspeed-qa-findings-router use_when: the user needs pre-launch QA scope, page/template checks, accessibility, responsive checks, conversion tracking checks, and go/no-go criteria. - prompt_starter: "Use the LightSpeed launch QA planner to create a launch QA plan, validation matrix, page checks, accessibility and responsive scope, and go/no-go gates." + prompt_starter: 'Use the LightSpeed launch QA planner to create a launch QA plan, validation matrix, page checks, accessibility and responsive scope, and go/no-go gates.' - match: intents: @@ -158,7 +158,7 @@ routes: - website-performance-assessor - lightspeed-schema-and-ai-discoverability-planner use_when: the user needs final pre-launch QA, page-by-page checks, forms, accessibility, analytics, redirects, SEO, or launch go/no-go notes. - prompt_starter: "Use the LightSpeed launch readiness auditor to produce a final pre-launch QA checklist, findings table, and go/no-go summary." + prompt_starter: 'Use the LightSpeed launch readiness auditor to produce a final pre-launch QA checklist, findings table, and go/no-go summary.' - match: intents: @@ -172,7 +172,7 @@ routes: - linear-triage-router - wordpress-block-asset-validator use_when: raw QA notes, screenshots, stakeholder feedback, launch blockers, or test failures need severity, owner routing, issue drafts, and retest steps. - prompt_starter: "Use the LightSpeed QA findings router to classify severity, separate evidence, route owners, draft issues, and define retest steps." + prompt_starter: 'Use the LightSpeed QA findings router to classify severity, separate evidence, route owners, draft issues, and define retest steps.' - match: intents: @@ -185,7 +185,7 @@ routes: - lightspeed-change-request-router - lightspeed-requirements-traceability-mapper use_when: movement to the next delivery stage depends on approval, sign-off, decision logging, or go/no-go criteria. - prompt_starter: "Use the LightSpeed approval gate manager to prepare the approval checklist, decision log, sign-off criteria, and next-stage readiness notes." + prompt_starter: 'Use the LightSpeed approval gate manager to prepare the approval checklist, decision log, sign-off criteria, and next-stage readiness notes.' - match: intents: @@ -198,7 +198,7 @@ routes: - lightspeed-approval-gate-manager - lightspeed-project-status-reporter use_when: feedback or blockers may alter scope, cost, timeline, approvals, or existing implementation plans. - prompt_starter: "Use the LightSpeed change request router to classify the change, assess impact, identify approvals, and draft updated task or decision notes." + prompt_starter: 'Use the LightSpeed change request router to classify the change, assess impact, identify approvals, and draft updated task or decision notes.' - match: intents: @@ -211,7 +211,7 @@ routes: - lightspeed-acceptance-test-planner - lightspeed-prd-task-reviewer use_when: requirements, tasks, issues, QA checks, and launch gates need coverage mapping. - prompt_starter: "Use the LightSpeed requirements traceability mapper to map requirements to tasks, acceptance criteria, QA checks, and launch gates." + prompt_starter: 'Use the LightSpeed requirements traceability mapper to map requirements to tasks, acceptance criteria, QA checks, and launch gates.' - match: intents: @@ -224,7 +224,7 @@ routes: - linear-project-pulse - lightspeed-change-request-router use_when: stakeholders need a practical progress summary, blockers, risks, decisions, and next actions. - prompt_starter: "Use the LightSpeed project status reporter to create a stakeholder-ready progress summary with blockers, risks, decisions, and next actions." + prompt_starter: 'Use the LightSpeed project status reporter to create a stakeholder-ready progress summary with blockers, risks, decisions, and next actions.' - match: intents: @@ -237,7 +237,7 @@ routes: - lightspeed-prd-task-pack-exporter - lightspeed-project-memory-manager use_when: launch, release, support transition, or delivery closure needs a clean handoff package. - prompt_starter: "Use the LightSpeed release handoff generator to create release notes, support transition notes, monitoring plan, and delivery closure summary." + prompt_starter: 'Use the LightSpeed release handoff generator to create release notes, support transition notes, monitoring plan, and delivery closure summary.' - match: intents: @@ -250,7 +250,7 @@ routes: - lightspeed-project-memory-manager - lightspeed-release-handoff-generator use_when: PRDs, task plans, briefs, issue drafts, QA plans, and notes need to be packaged into a clean handoff archive. - prompt_starter: "Use the LightSpeed PRD task pack exporter to organise these materials into a clean markdown folder structure, review checklist, and handoff pack." + prompt_starter: 'Use the LightSpeed PRD task pack exporter to organise these materials into a clean markdown folder structure, review checklist, and handoff pack.' - match: intents: @@ -263,7 +263,7 @@ routes: - lightspeed-prd-task-pack-exporter - linear-decision-logger use_when: durable project context, decisions, assumptions, progress, and handoff-ready memory files need to be created or updated. - prompt_starter: "Use the LightSpeed project memory manager to create or update the project memory bank, decision log, assumptions, active context, and progress notes." + prompt_starter: 'Use the LightSpeed project memory manager to create or update the project memory bank, decision log, assumptions, active context, and progress notes.' - match: intents: @@ -285,7 +285,7 @@ routes: - lightspeed-policy-page-generator - lightspeed-claim-register-auditor use_when: AI-readiness, governance, chatbot, source-quality, schema, policy, claims, estimate, or launch readiness work needs sequencing. - prompt_starter: "Use the LightSpeed AI-readiness router to classify this AI/chatbot/governance request, identify readiness gates, and route to the correct specialist deliverable." + prompt_starter: 'Use the LightSpeed AI-readiness router to classify this AI/chatbot/governance request, identify readiness gates, and route to the correct specialist deliverable.' - match: intents: @@ -300,7 +300,7 @@ routes: - chatbot-discovery-question-prioritiser - lightspeed-faq-and-chatbot-source-curator use_when: a bounded website chatbot needs purpose, approved sources, exclusions, behaviour rules, fallback wording, escalation, privacy notes, and tests. - prompt_starter: "Use the AI chatbot planner to define chatbot purpose, sources, exclusions, behaviour, escalation, privacy notes, launch gates, test scripts, and first draft system prompt." + prompt_starter: 'Use the AI chatbot planner to define chatbot purpose, sources, exclusions, behaviour, escalation, privacy notes, launch gates, test scripts, and first draft system prompt.' - match: intents: @@ -319,7 +319,7 @@ routes: - lightspeed-policy-page-generator - content-audit-strategist use_when: website, governance, or chatbot content needs collection, source mapping, FAQ curation, schema planning, claim safety, or policy drafting. - prompt_starter: "Use the content collection planner to create a source-aware content checklist, gap report, client request notes, and next content workflow route." + prompt_starter: 'Use the content collection planner to create a source-aware content checklist, gap report, client request notes, and next content workflow route.' - match: intents: @@ -337,7 +337,7 @@ routes: - website-security-discovery-reviewer - email-list-reviewer use_when: discovery or launch work needs SEO, redirects, performance, hosting, security, or email-list risk assessment. - prompt_starter: "Use the most specific discovery/audit skill to assess the supplied evidence, separate observed issues from assumptions, and produce a prioritised fix list." + prompt_starter: 'Use the most specific discovery/audit skill to assess the supplied evidence, separate observed issues from assumptions, and produce a prioritised fix list.' - match: intents: @@ -359,7 +359,7 @@ routes: - design-md-generator - wp-figma-artifact-builder use_when: scattered design, Figma, WordPress, repo, QA, or content inputs need a normalised execution packet or handoff route. - prompt_starter: "Use the design execution packet skill to consolidate the design and implementation inputs, separate approved from unconfirmed material, and route the next workflow." + prompt_starter: 'Use the design execution packet skill to consolidate the design and implementation inputs, separate approved from unconfirmed material, and route the next workflow.' - match: intents: @@ -384,7 +384,7 @@ routes: - figma-to-block-theme - theme-color-token-enforcer use_when: the user asks for WordPress block theme assets but the exact generator, metadata, validation, or token workflow needs routing. - prompt_starter: "Use the WordPress block theme router to identify the correct asset workflow, required parameters, validation rules, and next specialist skill." + prompt_starter: 'Use the WordPress block theme router to identify the correct asset workflow, required parameters, validation rules, and next specialist skill.' - match: intents: @@ -401,7 +401,7 @@ routes: - theme-orphaned-refs - theme-color-token-enforcer use_when: Figma variables or codebase tokens need to become WordPress theme.json settings, presets, or style variations. - prompt_starter: "Use figma-to-block-theme to extract Figma variables into theme.json palette, typography, spacing, radius, shadow presets and style variations." + prompt_starter: 'Use figma-to-block-theme to extract Figma variables into theme.json palette, typography, spacing, radius, shadow presets and style variations.' - match: intents: @@ -417,7 +417,24 @@ routes: - figma-generate-design - audit-design-system use_when: a live website is being rebuilt and its components, patterns, template parts and templates need to exist in Figma, bound to the design tokens, before the theme is built. - prompt_starter: "Use site-to-figma-components after site-to-design-tokens: crawl the live site, approve the inventory and build scope, build the approved set in Figma, then hand the manifest to figma-to-block-theme Pattern mode." + prompt_starter: 'Use site-to-figma-components after site-to-design-tokens: crawl the live site, approve the inventory and build scope, build the approved set in Figma, then hand the manifest to figma-to-block-theme Pattern mode.' + + - match: + intents: + - live_site_to_theme + - match_live_site + - port_patterns_from_live + - rebuild_templates_from_live + primary_skill: site-to-block-theme + related_skills: + - site-to-design-tokens + - figma-to-block-theme + - wp-block-themes + - wp-patterns + - wp-interactivity-api + - wp-db-override-reconciliation + use_when: a block theme rebuild copies the live site as it is, and its templates, parts, patterns or cards must be built or fixed in the theme to match live, without a Figma layout step. + prompt_starter: "Use site-to-block-theme: inventory the part of the live site to rebuild, measure it at 390, 768 and 1440, map every value to the theme's tokens, build it with the official WordPress skills, then prove it with screenshots, a style diff and an accessibility check." - match: intents: @@ -437,7 +454,7 @@ routes: - linear-momentum-auditor - linear-decision-logger use_when: Linear work needs routing, rewriting, gap analysis, sub-issue splitting, project pulse, or customer-signal synthesis. - prompt_starter: "Use the Linear triage router to classify this work, recommend owner/priority/labels/status, and route deeper work to the right Linear skill." + prompt_starter: 'Use the Linear triage router to classify this work, recommend owner/priority/labels/status, and route deeper work to the right Linear skill.' - match: intents: @@ -458,7 +475,7 @@ routes: - backlog-trend-analysis - evidence-quality-review use_when: support, customer, Zendesk, Gmail, or backlog evidence needs triage, investigation, escalation, response drafting, KB creation, or trend analysis. - prompt_starter: "Use the support triage route to classify the case, identify evidence needs, and send deeper work to the correct customer/support skill." + prompt_starter: 'Use the support triage route to classify the case, identify evidence needs, and send deeper work to the correct customer/support skill.' - match: intents: @@ -472,4 +489,4 @@ routes: - agent-creator - linear-app-skill-creator use_when: the user asks to create, update, validate, improve, package, or troubleshoot a ChatGPT skill or reusable agent workflow. - prompt_starter: "Use the skill creator workflow to update the skill instructions, resources, validation, and packaged skill.zip deliverable." + prompt_starter: 'Use the skill creator workflow to update the skill instructions, resources, validation, and packaged skill.zip deliverable.' diff --git a/package.json b/package.json index b331e402fa..7f128a0aa1 100644 --- a/package.json +++ b/package.json @@ -157,6 +157,7 @@ "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-screenshot": "jest --config skills/theme-screenshot/scripts/jest.config.cjs", + "test:site-to-block-theme": "jest --config skills/site-to-block-theme/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/figma-to-block-theme/SKILL.md b/skills/figma-to-block-theme/SKILL.md index d40c6ecd26..66a53954fe 100644 --- a/skills/figma-to-block-theme/SKILL.md +++ b/skills/figma-to-block-theme/SKILL.md @@ -28,6 +28,7 @@ This skill holds only the Figma-to-WordPress mapping and LightSpeed conventions. - `wpds`: only when building admin or editor UI. - `theme-orphaned-refs`: run after tokens change, to fix preset references. - `theme-color-token-enforcer`: run in themes that use semantic colour tokens with dark parity. +- `site-to-block-theme`: when the layout source is a live site rather than a Figma frame. It uses this skill's theme profile. If a companion skill is not installed, say so and stop rather than calling Figma tools directly. diff --git a/skills/site-to-block-theme/SKILL.md b/skills/site-to-block-theme/SKILL.md new file mode 100644 index 0000000000..54cdc6570e --- /dev/null +++ b/skills/site-to-block-theme/SKILL.md @@ -0,0 +1,155 @@ +--- +name: site-to-block-theme +description: Build or fix a WordPress block theme's templates, template parts, patterns and cards so they match an existing live site, without a Figma layout step. Use when a rebuild copies the live site directly, for example 'rebuild the homepage from live', 'match the footer to live', 'port this section from the old site into the new theme', 'why does this card look different from live' or 'compare local with live'. Measures live with computed styles at 390, 768 and 1440, maps every value to the theme's theme.json tokens, builds with the official WordPress skills to current WordPress coding standards, then proves the match with side-by-side screenshots, a style diff and an accessibility check. +--- + +# Site to Block Theme + +## Overview + +The direct route from a live site to block theme files. The live page is the source for layout, content and styles; the theme's `theme.json` is the source for tokens. + +```text +site-to-design-tokens (tokens) → site-to-block-theme: inventory → measure → map to tokens → build → check local → prove +``` + +Use the Figma route instead (`site-to-figma-components`, then `figma-to-block-theme` Pattern mode) when the design is changing and needs sign-off in Figma first. Use this skill when the rebuild matches the live site as it is. + +It stops for approval after the inventory, and again before any new token. + +## Companion skills + +This skill holds only the live-site workflow and LightSpeed conventions. WordPress mechanics come from the **official WordPress skills** ([WordPress/agent-skills](https://github.com/WordPress/agent-skills)). Load them; don't work from memory: + +| Skill | Load it for | +| --------------------------------------- | ----------------------------------------------------------------------------------------- | +| `wordpress-router`, `wp-project-triage` | Step 0: classify the repository and its tooling | +| `wp-block-themes` | `theme.json`, templates, template parts, style variations, the style hierarchy and caches | +| `wp-patterns` | Pattern registration, file headers, block markup, i18n and escaping | +| `wp-block-development` | Only if no core block can do the job (the block then belongs in the project plugin) | +| `wp-interactivity-api` | Any front-end behaviour: menus, sliders, accordions, filters | +| `wp-performance` | Images, fonts and script loading on the built page | +| `wp-wpcli-and-ops` | WP-CLI: caches, database template copies, options | +| `wp-phpstan` | Themes that run PHPStan | + +LightSpeed skills: + +- `site-to-design-tokens`: if the theme has no tokens yet, run it first. +- `figma-to-block-theme`: its [theme profile](../figma-to-block-theme/references/theme-profile.md) is step 0 here, and its Complete mode fills missing `theme.json` block settings. +- `theme-color-token-enforcer` and `theme-orphaned-refs`: run after the build in themes with semantic colour tokens. +- `wp-blockstyle-css-field`: the limits of the `css` field in block and section styles. +- `wp-pattern-runtime-pitfalls`: patterns that render nothing or stale data. +- `wp-db-override-reconciliation`: when a Site Editor copy in the database hides the theme file. +- `theme-screenshot`: the theme's `screenshot.png`. + +If an official WordPress skill is not installed, say so and install it from WordPress/agent-skills before building. + +## Current WordPress, not memory + +WordPress changes every release. Before you write code, read [references/wordpress-standards.md](references/wordpress-standards.md) and: + +1. Find the version the theme targets: the `theme.json` `$schema` and `version`, `Requires at least` and `Tested up to` in `style.css`, and `wp core version` on the local site. +2. Look up anything version-sensitive in the current documentation (Context7, the Block Editor Handbook, the Theme Handbook, the `theme.json` reference for that version and the Core dev notes), not in recalled knowledge. +3. Build to the WordPress Coding Standards with the theme's own lint, PHPCS and test commands, and leave them passing. + +## Step 0: Theme profile and project rules + +1. Read the theme's `AGENTS.md`, `CLAUDE.md`, `.claude/rules/` and `CONTRIBUTING.md`. Project rules win over this skill. +2. Build the theme profile from [figma-to-block-theme's theme-profile.md](../figma-to-block-theme/references/theme-profile.md): theme root, text domain, colour model (preset-direct or semantic), where tokens live, the pattern, part and style layouts, and the lint and test commands. +3. Note the live URL, the local URL and how to run WP-CLI locally (for example `studio wp` in WordPress Studio). + +## Step 1: Inventory before building + +1. Read the issue: acceptance criteria and comments. +2. Find every place the thing appears on live (a card may be on the homepage, an archive and a mega menu). List each variant and each state. +3. Check the theme for something that already does the job: `patterns/`, `parts/`, `templates/`, block styles and section styles. Reuse or extend it; don't add a near-copy. +4. Show the inventory and a short plan (files to add or change, blocks to use, open questions) and wait for approval. One message is enough for a small piece of work. + +## Step 2: Measure live + +Computed styles, not the site's CSS files: live CSS is overridden in many places. Write a selectors file (one name per element, with a separate live and local selector where the markup differs), then measure at 390, 768 and 1440 in default, hover and focus. See [references/measuring.md](references/measuring.md). + +```bash +npx --prefix "$SITE_TO_BLOCK_THEME_REPO_ROOT" tsx ${CLAUDE_SKILL_DIR}/scripts/measure-page.ts \ + --url https://www.example.com/ --selectors selectors.json --side live --out live.json --shots shots +``` + +Work in a scratch folder outside the theme. Also record what styles can't show: image ratios and crops, link targets, sticky and scroll-triggered behaviour, and anything that only appears at one width. + +## Step 3: Map values to tokens + +```bash +npx --prefix "$SITE_TO_BLOCK_THEME_REPO_ROOT" tsx ${CLAUDE_SKILL_DIR}/scripts/map-to-tokens.ts live.json \ + --theme-json /theme.json --out tokens.json --report tokens.md +``` + +`tokens.md` lists the values with no exact token first. For each one: + +- **Exact:** use the token. When several match, pick the semantic token whose role fits (`text`, `surface`, `border`), not the palette slug. +- **Near:** use the nearest token with the same role and list it under "Differences from live" in the pull request. +- **None:** propose a new token (name, value, role) and stop for approval. New tokens go through the design source first (Figma, or `site-to-design-tokens`). Never hardcode the value. +- Fonts always match live. + +## Step 4: Build + +Follow `wp-block-themes` and `wp-patterns`, the theme's rules and [references/wordpress-standards.md](references/wordpress-standards.md): + +- **JSON first:** `theme.json`, block styles and section styles. Use the theme's stylesheet only when JSON can't do it (see `wp-blockstyle-css-field`). +- **Core blocks first.** Query Loop and Post Template for listings; block bindings for post data where the theme already uses them. Ask before adding a binding source or a custom block. +- **Patterns** in `patterns/*.php` with the theme's namespaced slug, full header metadata, translated strings in the theme's text domain and late escaping. +- **Tokens only** in markup and styles: `var:preset|spacing|30` in block attributes and `var(--wp--custom--…)` for semantic colours, as the theme profile says. No raw hex, px or font names. +- **No plugin features in the theme:** post types, fields, cron and integrations belong in the project plugin. Output must still render sensibly when that plugin is off. +- Real content from live: headings, labels, images (with alt text) and links. + +## Step 5: Check the local site + +1. Clear caches after adding patterns or styles (`wp transient delete --all`, or the theme's documented step). +2. Look for database copies of templates and parts that would hide the theme file: + + ```bash + wp post list --post_type=wp_template,wp_template_part --fields=ID,post_name,post_type --format=table + ``` + + If one matches what you're building, follow `wp-db-override-reconciliation`: copy any wanted Site Editor changes into the file, then remove the database copy so the file renders. Ask before deleting a copy you didn't create. + +3. Open the page in the editor and confirm no block shows "unexpected or invalid content". + +## Step 6: Prove it + +1. Measure local with the same selectors file and `--side local`, then diff: + + ```bash + npx --prefix "$SITE_TO_BLOCK_THEME_REPO_ROOT" tsx ${CLAUDE_SKILL_DIR}/scripts/diff-measurements.ts live.json local.json \ + --out diff.json --report diff.md + ``` + + Fix each difference, or keep it and say why. + +2. Put the local screenshots next to live's at 390, 768 and 1440, and fix any difference you can see that the diff missed. +3. Run an accessibility check (axe, through the theme's Playwright setup where it has one) and the theme's lint, PHPCS, JSON validation and tests. +4. Hand over: the screenshots side by side, the commands you ran and their results, a commit message and a pull request description with "Differences from live" (from `diff.md` and the near tokens) and "How to test". + +## Rules + +- **Live is the only source** for layout and content: not a staging copy, and not Figma unless the project says so. +- **Approval first:** after the inventory, and before any new token. +- **Read-only on live:** public pages only. Hover and focus to read states; never log in, click through checkout, type or submit. +- **Tokens only.** Nearest token plus a note beats a hardcoded value. +- **Current standards:** look up version-sensitive APIs; leave the theme's lint and tests passing. +- **Don't commit or push** unless the project's rules and the user say so. +- **No em dashes** in visible copy. + +## Scripts + +TypeScript run with `tsx`. Install the repository's dependencies first and set `SITE_TO_BLOCK_THEME_REPO_ROOT` to the absolute path of its checkout; `--prefix` selects its pinned `tsx` and Puppeteer while output stays in your scratch folder. Every script takes `--help`. Tests are in `scripts/__tests__/`: run `npm run test:site-to-block-theme` from the repository root. + +| Script | Does | +| ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- | +| `scripts/measure-page.ts` | Computed styles of named elements per width and state, plus full-page screenshots, with Puppeteer | +| `scripts/map-to-tokens.ts` | Matches each live value to the theme's tokens (fluid sizes per width) and writes the decisions report | +| `scripts/diff-measurements.ts` | Compares live and local measurements and writes the "Differences from live" table | +| `scripts/lib/theme-tokens.ts` | Reads presets and custom tokens from `theme.json`, including WordPress fluid typography | +| `scripts/lib/token-matcher.ts`, `scripts/lib/css-length.ts`, `scripts/lib/colour.ts` | Matching, CSS length and colour helpers | + +*Built by 🧱 LightSpeedWP with ☕, 🚀, and open-source spirit!* +[Contributors](https://github.com/lightspeedwp/.github/graphs/contributors) diff --git a/skills/site-to-block-theme/agents/openai.yaml b/skills/site-to-block-theme/agents/openai.yaml new file mode 100644 index 0000000000..7a36c4c3f6 --- /dev/null +++ b/skills/site-to-block-theme/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: 'Site to Block Theme' + short_description: 'Rebuild live-site templates, parts and patterns in a block theme to match exactly' + default_prompt: "Use $site-to-block-theme to inventory the part of the live site to rebuild, measure it at 390, 768 and 1440, map every value to the theme's theme.json tokens, build it with the official WordPress skills to current coding standards, then prove the match with screenshots, a style diff and an accessibility check." diff --git a/skills/site-to-block-theme/references/measuring.md b/skills/site-to-block-theme/references/measuring.md new file mode 100644 index 0000000000..ba5dcf9937 --- /dev/null +++ b/skills/site-to-block-theme/references/measuring.md @@ -0,0 +1,55 @@ +# Measuring live and local + +## The selectors file + +One JSON object. Each key is a name you choose; the value is a CSS selector, or a live and a local selector when the old and new markup differ. The diff matches live and local by name. + +```json +{ + "header logo": "header .site-branding img", + "menu link": { "live": ".menu-item > a", "local": ".wp-block-navigation-item__content" }, + "hero heading": { "live": ".hero h1", "local": ".wp-block-cover h1" }, + "card title": { + "live": ".lsx-to-widget-item-wrap h3", + "local": ".wp-block-post-template .wp-block-post-title" + }, + "footer": "footer" +} +``` + +- The first element that matches is measured; the output records how many matched, so check that `count` is what you expect. +- Name the element, not the selector (`card title`, not `h3`), so the report reads well in a pull request. +- A name with only a `live` selector is skipped on the local side, and the reverse. Add the other selector once it exists. +- For quick checks, pass `--selector ` one or more times instead of a file. + +## Options + +| Option | Default | Notes | +| ---------- | --------------------- | ----------------------------------------------------------------------- | +| `--url` | required | One page. Run once per page. `wp-admin` and `wp-login.php` are refused. | +| `--side` | `live` | `live` or `local`: picks the selector and names the screenshots. | +| `--widths` | `390,768,1440` | Mobile, tablet and desktop. Add a width where live changes layout. | +| `--states` | `default,hover,focus` | Hover and focus entries hold only the properties that changed. | +| `--props` | the default list | A comma-separated list of computed properties, to narrow the output. | +| `--shots` | none | Folder for full-page screenshots, named `--.png`. | +| `--delay` | `1500` | Pause in ms between widths, to be gentle with live. | + +The default properties cover type, colour, spacing (longhands), borders, radius, shadow, outline (focus rings), layout (display, flex, grid columns, max width), images (aspect ratio, object fit), opacity and transition duration. + +## What the scripts can't see + +Record these by hand, from the screenshots or the page: + +- Image crops and focal points, and which image size live serves. +- Link targets, `rel` values and which links open new tabs. +- Sticky headers, scroll-triggered animation, carousels and anything that changes after load. +- Content that only appears at one width (a mobile menu, a hidden column). +- Hover and focus on elements that are covered or off-screen when measured (the script skips them). + +## Reading the reports + +- `tokens.md` (map-to-tokens) lists live values by element, width and state with their token. "Needs a decision" comes first. +- Fluid tokens are evaluated at each width, so the same token can match 18px at 390 and 20px at 1440. +- Delta is the token minus the live value: `-2px` means the token is 2px smaller than live. +- Border and outline colours are skipped when their width is 0 or style is `none`. +- `diff.md` (diff-measurements) lists every live and local difference. Lengths within `--tolerance` px (default 1) and colours within a distance of 2 count as equal; box sizes also allow 2%. diff --git a/skills/site-to-block-theme/references/wordpress-standards.md b/skills/site-to-block-theme/references/wordpress-standards.md new file mode 100644 index 0000000000..0df71eadd8 --- /dev/null +++ b/skills/site-to-block-theme/references/wordpress-standards.md @@ -0,0 +1,59 @@ +# Current WordPress coding standards + +Check these against the WordPress version the theme targets. Where this list and the current documentation differ, the documentation wins: update this file. + +## Find the target version + +- `theme.json`: `version` and the `$schema` URL (for example `https://schemas.wp.org/wp//theme.json`). +- `style.css`: `Requires at least`, `Tested up to` and `Requires PHP`. +- The local site: `wp core version` and `php -v`. +- The project's `AGENTS.md` or README, which may pin a version. + +Then read what changed: the Core dev notes and field guide for each release since the theme was last updated (make.wordpress.org/core), and the `theme.json` reference for that version. Use Context7 or developer.wordpress.org for API syntax rather than recalled knowledge. + +## Where the rules come from + +| Area | Source | Check with | +| -------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------- | +| PHP | WordPress Coding Standards (WPCS), PHPCompatibilityWP for the minimum PHP | The theme's `composer` PHPCS script and `phpcs.xml.dist` | +| JavaScript | WordPress JavaScript Coding Standards (`@wordpress/eslint-plugin`) | `npm run lint:js` (`wp-scripts lint-js`) | +| CSS and SCSS | WordPress CSS Coding Standards (`@wordpress/stylelint-config`) | `npm run lint:css` (`wp-scripts lint-style`) | +| `theme.json`, block and section styles | The `theme.json` schema for the target version | The theme's JSON lint or schema validation | +| Accessibility | WordPress Accessibility Coding Standards, WCAG 2.2 AA | axe, keyboard pass, contrast check | +| Patterns and themes | Theme Handbook, Block Editor Handbook, `wp-patterns` and `wp-block-themes` | Editor check: no invalid blocks | + +Run the theme's own scripts; their names vary. Leave every check passing, or report what fails and why. + +## Block themes + +- Use the current `theme.json` version and schema. Reference presets by slug (`var:preset|spacing|30`, `var:preset|font-size|500`), never raw values. +- Put block-level design in `theme.json` and in block style variations and section styles under `styles/`. Use the theme stylesheet only for what JSON cannot express. +- Templates and parts are block markup HTML files. Templates hold structure; repeated sections are patterns or parts. +- Fonts: declare them with `fontFace` in `theme.json` and ship the files (woff2) in the theme. No remote font CSS. +- Keep `settings.appearanceTools` and per-block settings deliberate: expose what editors need, lock what they shouldn't change. + +## Patterns + +- One pattern per file in `patterns/`, with the header fields the current Theme Handbook lists: Title, Slug (namespaced with the theme slug), Description, Categories, Keywords, Viewport Width, Block Types, Post Types, Template Types and Inserter as needed. +- Translate every visible string with the theme's text domain (`esc_html__()`, `esc_html_e()`, `esc_attr__()`), and escape at output (`esc_url()`, `esc_attr()`, `wp_kses_post()`). Image URLs come from `get_theme_file_uri()`, never a hardcoded domain. +- Block markup must be valid: comment delimiters, attributes and the saved HTML must agree. Open the pattern in the editor and confirm no block reports unexpected or invalid content. +- Pattern PHP runs when patterns register, not on each request. Put per-request data in blocks, block bindings or Query Loop, not in pattern PHP (see `wp-pattern-runtime-pitfalls`). +- No direct database queries, `query_posts()` or business logic in patterns or templates. + +## Front-end behaviour + +- Prefer core blocks and their settings. Add behaviour with the Interactivity API (`viewScriptModule`, `data-wp-*` directives) through `wp-interactivity-api`, not jQuery or inline scripts. +- Respect `prefers-reduced-motion` and keep everything keyboard operable with a visible focus. + +## PHP in the theme + +- `functions.php` and `inc/` only for theme concerns: enqueues, supports, pattern categories and block style registration. Prefix or namespace everything. +- Enqueue assets with versions from the build (`*.asset.php`), and only where needed. +- Post types, taxonomies, fields, cron, REST routes and integrations belong in a plugin. + +## Accessibility and performance + +- One `h1` per page, headings in order, landmarks (`header`, `nav`, `main`, `footer`) from the template and part `tagName`s. +- Text contrast at least 4.5:1 (3:1 for large text and UI). Check the semantic tokens you used, not just the palette. +- Images: meaningful alt text from live, or empty alt for decoration; width and height set; lazy loading left to core except for the first visible image. +- Follow `wp-performance` for image sizes, font loading and script loading. diff --git a/skills/site-to-block-theme/scripts/__tests__/css-length.test.ts b/skills/site-to-block-theme/scripts/__tests__/css-length.test.ts new file mode 100644 index 0000000000..d6c5949bed --- /dev/null +++ b/skills/site-to-block-theme/scripts/__tests__/css-length.test.ts @@ -0,0 +1,85 @@ +import { Colour } from '../lib/colour'; +import { CssLength } from '../lib/css-length'; + +describe('CssLength.toPx', () => { + const at = (expression: string | undefined, viewport = 1440, extra = {}) => + CssLength.toPx(expression, { viewport, ...extra }); + + it('converts units', () => { + expect(at('12px')).toBe(12); + expect(at('1.5rem')).toBe(24); + expect(at('2em', 1440, { fontSize: 20 })).toBe(40); + expect(at('2em')).toBe(32); + expect(at('10vw', 390)).toBe(39); + expect(at('10vh')).toBe(90); + expect(at('1rem', 1440, { rootFontSize: 10 })).toBe(10); + expect(at('0')).toBe(0); + expect(at('.5rem')).toBe(8); + }); + + it('evaluates calc, clamp, min and max', () => { + const fluid = 'clamp(1.125rem, calc(0.19vw + 1.079rem), 1.25rem)'; + expect(at(fluid, 390)).toBeCloseTo(18, 1); + expect(at(fluid, 1440)).toBe(20); + expect(at('calc(100px - 2 * 10px)')).toBe(80); + expect(at('calc((100px + 20px) / 2)')).toBe(60); + expect(at('calc(-1 * 10px)')).toBe(-10); + expect(at('calc(-(10px))')).toBe(-10); + expect(at('min(10px, 2rem)')).toBe(10); + expect(at('max(10px, 2rem)')).toBe(32); + expect(at('calc(0 + 4px)')).toBe(4); + }); + + it('returns null for what it cannot evaluate', () => { + for (const bad of [ + undefined, + '', + '50%', + 'var(--x)', + 'auto', + '2', + 'calc(10px * 2px)', + 'calc(10px / 2px)', + 'calc(10px / 0)', + 'calc(10px + 2)', + 'clamp(1px, 2px)', + 'calc(1px, 2px)', + 'calc(10px', + '10px)', + 'calc()', + '* 2', + '10px 20px', + ]) { + expect(at(bad)).toBeNull(); + } + }); + + it('splits computed pixel lists', () => { + expect(CssLength.pxList('10px 20.5px -1px')).toEqual([10, 20.5, -1]); + expect(CssLength.pxList(undefined)).toEqual([]); + expect(CssLength.pxList('auto 10px')).toEqual([10]); + }); +}); + +describe('Colour', () => { + it('parses hex, rgb, rgba and transparent', () => { + expect(Colour.hex(Colour.parse('#abc')!)).toBe('#aabbcc'); + expect(Colour.hex(Colour.parse('#ffffff80')!)).toBe('#ffffff80'); + expect(Colour.hex(Colour.parse('#0000')!)).toBe('#00000000'); + expect(Colour.hex(Colour.parse('rgb(10, 20, 30)')!)).toBe('#0a141e'); + expect(Colour.parse('rgba(0 0 0 / 50%)')!.a).toBe(0.5); + expect(Colour.parse('rgba(0, 0, 0, 0.2)')!.a).toBe(0.2); + expect(Colour.parse('transparent')!.a).toBe(0); + }); + + it('rejects anything else', () => { + for (const bad of [undefined, '', 'red', 'rgb(1, 2)', 'rgb(a, b, c)', '#12']) { + expect(Colour.parse(bad)).toBeNull(); + } + }); + + it('measures distance', () => { + expect(Colour.distance(Colour.parse('#000')!, Colour.parse('#000')!)).toBe(0); + expect(Math.round(Colour.distance(Colour.parse('#000')!, Colour.parse('#030000')!))).toBe(3); + }); +}); diff --git a/skills/site-to-block-theme/scripts/__tests__/fixtures.ts b/skills/site-to-block-theme/scripts/__tests__/fixtures.ts new file mode 100644 index 0000000000..69714d4c88 --- /dev/null +++ b/skills/site-to-block-theme/scripts/__tests__/fixtures.ts @@ -0,0 +1,127 @@ +/** + * Shared test data: a small theme.json in the LightSpeed structure and a + * measurements file factory. + */ +import type { MeasureFile, Measurement } from '../measure-page'; + +export const themeJson = { + version: 3, + settings: { + layout: { contentSize: '800px', wideSize: '1440px' }, + color: { + palette: [ + { slug: 'base', color: '#ffffff' }, + { slug: 'contrast', color: '#0a0a0a' }, + { slug: 'brand-500', color: '#c8964f' }, + { slug: 'broken', color: 'var(--nope)' }, + { color: '#123456' }, + ], + }, + spacing: { + spacingSizes: [ + { slug: '10', size: '0.625rem' }, + { slug: '20', size: 'clamp(1.125rem, calc(0.19vw + 1.079rem), 1.25rem)' }, + { slug: '40', size: '2.5rem' }, + ], + }, + typography: { + fluid: true, + fontSizes: [ + { slug: '100', size: '0.875rem' }, + { slug: '200', size: '1rem', fluid: false }, + { slug: '500', size: '2rem' }, + { slug: '600', size: '2.5rem', fluid: { min: '1.75rem', max: '2.5rem' } }, + { slug: '700', size: 'clamp(2rem, 4vw, 3rem)' }, + ], + fontFamilies: [ + { slug: 'heading', fontFamily: 'Moret, Georgia, serif' }, + { slug: 'body', fontFamily: '"Argesta Display", Georgia, serif' }, + ], + }, + border: { + radiusSizes: [ + { slug: '0', size: '0' }, + { slug: '200', size: '8px' }, + ], + }, + shadow: { + presets: [ + { slug: '100', shadow: '0 2px 4px 0 var(--wp--custom--color--shadow--20)' }, + { slug: '200', shadow: 'inset 0 1px 2px #00000033, 0 0 1px 0 rgba(0, 0, 0, 0.1)' }, + ], + }, + custom: { + color: { + text: { + default: 'var(--wp--preset--color--contrast)', + inverse: 'var(--wp--preset--color--base)', + }, + surface: { accent: 'var(--wp--preset--color--brand-500)' }, + shadow: { 20: '#09090933' }, + }, + fontWeight: { regular: 400, bold: 700 }, + lineHeight: { tight: 1.1, normal: '1.5', loose: '2rem' }, + letterSpacing: { wide: '0.05em' }, + borderWidth: { thin: '1px' }, + motion: { fast: '150ms' }, + flag: true, + }, + }, +}; + +export function measurement(partial: Partial & { name: string }): Measurement { + return { + selector: `.${partial.name.replace(/\s+/g, '-')}`, + width: 1440, + state: 'default', + found: true, + rect: { width: 300, height: 40 }, + styles: {}, + ...partial, + }; +} + +export function measureFile( + measurements: Measurement[], + partial: Partial = {} +): MeasureFile { + return { + url: 'https://www.example.com/', + side: 'live', + measuredAt: '2026-11-23T10:00:00.000Z', + widths: [1440], + properties: [], + measurements, + screenshots: [], + failures: [], + ...partial, + }; +} + +export function memoryDeps(files: Record = {}) { + const written: Record = {}; + const out: string[] = []; + const err: string[] = []; + return { + written, + out, + err, + deps: { + readFile: (path: string) => { + if (!(path in files)) { + throw new Error(`ENOENT ${path}`); + } + return files[path]; + }, + writeFile: (path: string, content: string) => { + written[path] = content; + }, + stdout: (text: string) => { + out.push(text); + }, + stderr: (text: string) => { + err.push(text); + }, + }, + }; +} diff --git a/skills/site-to-block-theme/scripts/__tests__/map-and-diff.test.ts b/skills/site-to-block-theme/scripts/__tests__/map-and-diff.test.ts new file mode 100644 index 0000000000..4f90ada82c --- /dev/null +++ b/skills/site-to-block-theme/scripts/__tests__/map-and-diff.test.ts @@ -0,0 +1,200 @@ +import { MeasurementDiff, runDiffCli } from '../diff-measurements'; +import { runMapCli, TokenMapper } from '../map-to-tokens'; +import { ThemeTokens } from '../lib/theme-tokens'; +import { TokenMatcher } from '../lib/token-matcher'; +import { measureFile, measurement, memoryDeps, themeJson } from './fixtures'; + +const live = measureFile([ + measurement({ + name: 'hero heading', + styles: { + 'font-size': '32px', + 'font-family': 'Moret, serif', + color: 'rgb(10, 10, 10)', + 'padding-top': '21px', + 'line-height': '35.2px', + display: 'block', + }, + }), + measurement({ name: 'hero heading', state: 'hover', styles: { color: 'rgb(0, 200, 0)' } }), + measurement({ name: 'gone', found: false, styles: undefined }), +]); + +describe('TokenMapper', () => { + const mapper = new TokenMapper(new TokenMatcher(ThemeTokens.fromThemeJson([themeJson]))); + + it('maps each measured value and counts the results', () => { + const mapping = mapper.map(live); + expect(mapping.counts).toEqual({ exact: 4, near: 1, none: 1, skip: 0 }); + const hover = mapping.rows.find((r) => r.state === 'hover')!; + expect(hover.match.status).toBe('none'); + const lineHeight = mapping.rows.find((r) => r.property === 'line-height')!; + expect(lineHeight.match.tokens[0].cssVar).toBe('--wp--custom--line-height--tight'); + }); + + it('writes a report with the open decisions first', () => { + const md = TokenMapper.markdown(mapper.map(live)); + expect(md.indexOf('## Needs a decision')).toBeLessThan(md.indexOf('## Exact')); + expect(md).toContain('`var:preset|spacing|20` (-1px)'); + expect(md).toContain('`var(--wp--custom--color--text--default)`'); + }); + + it('reports shorthand parts and a fully matched page', () => { + const shorthand = mapper.map( + measureFile([measurement({ name: 'box', styles: { padding: '10px 0px 13px' } })]) + ); + expect(TokenMapper.markdown(shorthand)).toContain( + '`var:preset|spacing|10` / 0 / `var:preset|spacing|10` (-3px)' + ); + const clean = mapper.map( + measureFile([measurement({ name: 'box', styles: { 'padding-top': '10px' } })]) + ); + expect(TokenMapper.markdown(clean)).toContain('Every value has an exact token.'); + const empty = mapper.map(measureFile([])); + expect(TokenMapper.markdown(empty)).toContain('None.'); + }); +}); + +describe('runMapCli', () => { + const files = { + 'live.json': JSON.stringify(live), + 'theme.json': JSON.stringify(themeJson), + 'empty.json': '{}', + }; + + it('writes the mapping and the report', () => { + const io = memoryDeps(files); + expect( + runMapCli( + ['live.json', '--theme-json', 'theme.json', '--out', 'm.json', '--report', 'm.md'], + io.deps + ) + ).toBe(0); + expect(JSON.parse(io.written['m.json']).counts.exact).toBe(4); + expect(io.written['m.md']).toContain('# Token mapping'); + expect(io.out.join('')).toContain('4 exact, 1 near, 1 with no token'); + }); + + it('prints help', () => { + const io = memoryDeps(); + expect(runMapCli(['--help'], io.deps)).toBe(0); + expect(io.out.join('')).toContain('Usage'); + }); + + it.each([ + [[], 'Give the live measurements file.'], + [['live.json'], '--theme-json is required.'], + [['live.json', 'other.json'], 'Unexpected argument other.json.'], + [['live.json', '--theme-json'], '--theme-json needs a value.'], + [['live.json', '--nope', 'x'], 'Unknown argument --nope.'], + [['live.json', '--theme-json', 'empty.json'], 'No tokens found'], + [['live.json', '--theme-json', 'missing.json'], 'ENOENT'], + ])('fails clearly for %j', (argv, message) => { + const io = memoryDeps(files); + expect(runMapCli(argv as string[], io.deps)).toBe(1); + expect(io.err.join('')).toContain(message); + }); +}); + +describe('MeasurementDiff', () => { + const local = measureFile( + [ + measurement({ + name: 'hero heading', + rect: { width: 300, height: 60 }, + styles: { + 'font-size': '32.4px', + 'font-family': '"moret", serif', + color: '#0a0a0a', + 'padding-top': '24px', + 'line-height': '35.2px', + display: 'flex', + }, + }), + measurement({ name: 'gone', found: true }), + measurement({ name: 'new', found: true }), + ], + { side: 'local', url: 'http://localhost:8881/' } + ); + + it('lists value, state, box and missing differences', () => { + const diff = new MeasurementDiff(1).compare(live, local); + const summary = diff.map((d) => `${d.name}|${d.state}|${d.kind}|${d.property ?? ''}`); + expect(summary).toEqual([ + 'gone|default|missing-live|', + 'hero heading|default|value|box height', + 'hero heading|default|value|padding-top', + 'hero heading|default|value|display', + 'hero heading|hover|value|color', + 'new|default|missing-live|', + ]); + expect(diff.find((d) => d.state === 'hover')!.local).toBe('(unchanged)'); + }); + + it('flags elements missing on local', () => { + const diff = new MeasurementDiff().compare( + local, + measureFile([measurement({ name: 'gone', found: false })]) + ); + expect(diff.filter((d) => d.kind === 'missing-local').map((d) => d.name)).toEqual([ + 'gone', + 'hero heading', + 'new', + ]); + }); + + it('compares values by kind', () => { + const diff = new MeasurementDiff(1); + expect(diff.same('color', 'rgb(0, 0, 0)', '#000')).toBe(true); + expect(diff.same('margin', '10px 20px', '10.5px 20px')).toBe(true); + expect(diff.same('margin', '10px 20px', '10px')).toBe(false); + expect(diff.same('text-transform', 'UPPERCASE', 'uppercase')).toBe(true); + expect(diff.same('display', 'block', 'flex')).toBe(false); + }); + + it('writes the differences table', () => { + const md = MeasurementDiff.markdown(live, local, new MeasurementDiff().compare(live, local)); + expect(md).toContain('| Element | Width | State | Property | Live | Local |'); + expect(md).toContain('missing on live'); + expect(MeasurementDiff.markdown(live, live, [])).toContain('No differences found'); + const missingLocal = MeasurementDiff.markdown(live, local, [ + { name: 'x', width: 390, state: 'default', kind: 'missing-local' }, + ]); + expect(missingLocal).toContain('missing on local'); + }); +}); + +describe('runDiffCli', () => { + const files = { + 'live.json': JSON.stringify(live), + 'local.json': JSON.stringify(measureFile([], { side: 'local' })), + }; + + it('writes the diff and report', () => { + const io = memoryDeps(files); + expect( + runDiffCli( + ['live.json', 'local.json', '--tolerance', '2', '--out', 'd.json', '--report', 'd.md'], + io.deps + ) + ).toBe(0); + expect(JSON.parse(io.written['d.json'])[0].kind).toBe('missing-local'); + expect(io.written['d.md']).toContain('# Differences from live'); + }); + + it('prints help', () => { + const io = memoryDeps(); + expect(runDiffCli(['-h'], io.deps)).toBe(0); + }); + + it.each([ + [['live.json'], 'Give the live and the local'], + [['live.json', 'local.json', '--nope', '1'], 'Unknown argument --nope.'], + [['live.json', 'local.json', '--out'], '--out needs a value.'], + [['live.json', 'local.json', '--tolerance', '-1'], '--tolerance must be'], + ])('fails clearly for %j', (argv, message) => { + const io = memoryDeps(files); + expect(runDiffCli(argv as string[], io.deps)).toBe(1); + expect(io.err.join('')).toContain(message); + }); +}); diff --git a/skills/site-to-block-theme/scripts/__tests__/measure-page.test.ts b/skills/site-to-block-theme/scripts/__tests__/measure-page.test.ts new file mode 100644 index 0000000000..bafc782cf9 --- /dev/null +++ b/skills/site-to-block-theme/scripts/__tests__/measure-page.test.ts @@ -0,0 +1,275 @@ +/** + * @jest-environment jsdom + */ +/* global Element, DOMRect */ +import { + BrowserDriver, + ElementReading, + MeasureState, + PageHandle, + PageMeasurer, + readElement, + runMeasureCli, +} from '../measure-page'; +import { memoryDeps } from './fixtures'; + +describe('readElement (in the browser)', () => { + beforeAll(() => { + Element.prototype.getBoundingClientRect = function () { + return { + width: 120.04, + height: 40, + top: 0, + left: 0, + right: 120, + bottom: 40, + x: 0, + y: 0, + toJSON: () => ({}), + } as DOMRect; + }; + }); + + it('reads the first match, its box and the count', () => { + document.body.innerHTML = + '

A

B

'; + const reading = readElement({ selector: '.t', properties: ['color', 'padding-top'] })!; + expect(reading.count).toBe(2); + expect(reading.rect).toEqual({ width: 120, height: 40 }); + expect(reading.styles).toEqual({ color: 'rgb(1, 2, 3)', 'padding-top': '10px' }); + }); + + it('returns null when nothing matches', () => { + document.body.innerHTML = ''; + expect(readElement({ selector: '.t', properties: ['color'] })).toBeNull(); + }); +}); + +class FakePage implements PageHandle { + closed = false; + constructor( + private readonly width: number, + private readonly fail: boolean + ) {} + + async read( + selector: string, + _properties: string[], + state: MeasureState + ): Promise { + if (selector === '.missing') { + return null; + } + if (selector === '.no-focus' && state === 'focus') { + return null; + } + const colour = state === 'hover' ? 'rgb(255, 0, 0)' : 'rgb(0, 0, 0)'; + return { + count: 1, + rect: { width: this.width / 2, height: 40 }, + styles: { color: colour, 'font-size': '16px' }, + }; + } + + async screenshot(): Promise { + return !this.fail; + } + + async close(): Promise { + this.closed = true; + } +} + +class FakeDriver implements BrowserDriver { + opened: string[] = []; + closed = false; + constructor(private readonly failWidth?: number) {} + + async open(url: string, width: number): Promise { + if (width === this.failWidth) { + throw new Error('timeout'); + } + this.opened.push(`${url}@${width}`); + return new FakePage(width, width === 768); + } + + async close(): Promise { + this.closed = true; + } +} + +const noSleep = jest.fn(async () => undefined); +const fixedNow = () => new Date('2026-11-23T10:00:00Z'); + +describe('PageMeasurer', () => { + it('measures each element per width, keeping only changed state values', async () => { + const driver = new FakeDriver(); + const result = await new PageMeasurer(driver, noSleep, fixedNow).measure({ + url: 'https://www.example.com/tours/', + side: 'live', + selectors: [ + { name: 'title', selector: '.title' }, + { name: 'missing', selector: '.missing' }, + { name: 'link', selector: '.no-focus' }, + ], + shotsDir: 'shots', + }); + expect(driver.opened).toEqual([ + 'https://www.example.com/tours/@390', + 'https://www.example.com/tours/@768', + 'https://www.example.com/tours/@1440', + ]); + expect(driver.closed).toBe(true); + expect(noSleep).toHaveBeenCalledTimes(2); + const at390 = result.measurements.filter((m) => m.width === 390); + expect(at390.map((m) => `${m.name}:${m.state}:${m.found}`)).toEqual([ + 'title:default:true', + 'title:hover:true', + 'missing:default:false', + 'link:default:true', + 'link:hover:true', + ]); + expect(at390[1].styles).toEqual({ color: 'rgb(255, 0, 0)' }); + expect(result.screenshots).toEqual(['shots/live-tours-390.png', 'shots/live-tours-1440.png']); + expect(result.measuredAt).toBe('2026-11-23T10:00:00.000Z'); + }); + + it('records a failed width and carries on', async () => { + const result = await new PageMeasurer(new FakeDriver(390), noSleep).measure({ + url: 'https://www.example.com/', + side: 'local', + selectors: [{ name: 'title', selector: '.title' }], + widths: [390, 1440], + states: ['default'], + properties: ['color'], + }); + expect(result.failures).toEqual([{ width: 390, error: 'timeout' }]); + expect(result.measurements).toHaveLength(1); + }); + + it('refuses wp-admin and login pages', async () => { + const measurer = new PageMeasurer(new FakeDriver(), noSleep); + for (const url of ['https://example.com/wp-admin/', 'https://example.com/wp-login.php?x=1']) { + await expect(measurer.measure({ url, side: 'live', selectors: [] })).rejects.toThrow( + 'Refusing' + ); + } + }); + + it('names screenshots from the path', () => { + expect(PageMeasurer.slug(new URL('https://example.com/'))).toBe('home'); + expect(PageMeasurer.slug(new URL('https://example.com/a/B_c/'))).toBe('a-b-c'); + }); + + it('reads selectors for one side', () => { + const file = { + hero: '.hero', + card: { live: '.old-card', local: '.new-card' }, + liveOnly: { live: '.x' }, + }; + expect(PageMeasurer.selectorsFrom(file, 'local')).toEqual([ + { name: 'hero', selector: '.hero' }, + { name: 'card', selector: '.new-card' }, + ]); + expect(() => PageMeasurer.selectorsFrom([], 'live')).toThrow('must be an object'); + expect(() => PageMeasurer.selectorsFrom({ a: 1 }, 'live')).toThrow('must be a string'); + expect(() => PageMeasurer.selectorsFrom({ a: { local: '.a' } }, 'live')).toThrow( + 'No selectors' + ); + }); +}); + +describe('runMeasureCli', () => { + const run = async ( + argv: string[], + files: Record = {}, + driver = new FakeDriver() + ) => { + const io = memoryDeps(files); + const dirs: string[] = []; + const code = await runMeasureCli(argv, { + ...io.deps, + createDriver: async () => driver, + sleep: noSleep, + makeDir: (path) => { + dirs.push(path); + }, + }); + return { code, io, dirs }; + }; + + it('measures from a selectors file and single selectors', async () => { + const { code, io, dirs } = await run( + [ + '--url', + 'http://localhost:8881/', + '--selectors', + 'sel.json', + '--selector', + '.missing', + '--side', + 'local', + '--widths', + '1440', + '--states', + 'default,hover', + '--props', + 'color, font-size', + '--shots', + 'shots', + '--out', + 'local.json', + ], + { 'sel.json': JSON.stringify({ card: { live: '.a', local: '.b' } }) } + ); + expect(code).toBe(0); + expect(dirs).toEqual(['shots']); + const result = JSON.parse(io.written['local.json']); + expect(result.side).toBe('local'); + expect(result.properties).toEqual(['color', 'font-size']); + expect(result.measurements.map((m: { name: string }) => m.name)).toEqual([ + 'card', + 'card', + '.missing', + ]); + expect(io.out.join('')).toContain('Measured 2 elements at 1440px'); + expect(io.err.join('')).toContain('Not found at 1440px: .missing'); + }); + + it('exits 1 when a width fails', async () => { + const { code, io } = await run( + ['--url', 'https://example.com/', '--selector', '.a', '--widths', '390'], + {}, + new FakeDriver(390) + ); + expect(code).toBe(1); + expect(io.err.join('')).toContain('Failed at 390px: timeout'); + }); + + it('prints help', async () => { + const { code, io } = await run(['--help']); + expect(code).toBe(0); + expect(io.out.join('')).toContain('Usage'); + }); + + it.each([ + [['--selector', '.a'], '--url is required.'], + [['--url', 'https://e.com/'], 'Give --selectors'], + [ + ['--url', 'https://e.com/', '--selector', '.a', '--side', 'staging'], + '--side must be live or local.', + ], + [ + ['--url', 'https://e.com/', '--selector', '.a', '--states', 'active'], + 'Unknown state active.', + ], + [['--url', 'https://e.com/', '--nope', 'x'], 'Unknown argument --nope.'], + [['url'], 'Unknown argument url.'], + [['--url'], '--url needs a value.'], + [['--url', 'https://e.com/wp-admin/', '--selector', '.a'], 'Refusing'], + ])('fails clearly for %j', async (argv, message) => { + const { code, io } = await run(argv as string[]); + expect(code).toBe(1); + expect(io.err.join('')).toContain(message); + }); +}); diff --git a/skills/site-to-block-theme/scripts/__tests__/theme-tokens.test.ts b/skills/site-to-block-theme/scripts/__tests__/theme-tokens.test.ts new file mode 100644 index 0000000000..022de9e1af --- /dev/null +++ b/skills/site-to-block-theme/scripts/__tests__/theme-tokens.test.ts @@ -0,0 +1,124 @@ +import { ThemeTokens } from '../lib/theme-tokens'; +import { themeJson } from './fixtures'; + +describe('ThemeTokens', () => { + const theme = ThemeTokens.fromThemeJson([themeJson]); + const token = (cssVar: string) => theme.tokens.find((t) => t.cssVar === cssVar)!; + + it('collects presets with block markup references', () => { + expect(token('--wp--preset--spacing--20')).toMatchObject({ + family: 'spacing', + preset: 'var:preset|spacing|20', + semantic: false, + }); + expect(token('--wp--preset--border-radius--200').preset).toBe('var:preset|border-radius|200'); + expect(token('--wp--preset--shadow--100').family).toBe('shadow'); + expect(token('--wp--preset--font-family--body').family).toBe('font-family'); + expect(theme.list('color').some((t) => t.raw === '#123456')).toBe(false); + }); + + it('flattens custom values into semantic tokens in kebab case', () => { + expect(token('--wp--custom--color--text--default')).toMatchObject({ + family: 'color', + semantic: true, + }); + expect(token('--wp--custom--font-weight--bold').raw).toBe('700'); + expect(token('--wp--custom--line-height--normal').family).toBe('line-height'); + expect(theme.tokens.some((t) => t.cssVar.includes('motion'))).toBe(false); + expect(ThemeTokens.kebab('scrollArrowSize')).toBe('scroll-arrow-size'); + }); + + it('resolves var() chains and fallbacks', () => { + expect(theme.resolve('var(--wp--custom--color--text--default)')).toBe('#0a0a0a'); + expect(theme.resolve('var(--missing, 4px)')).toBe('4px'); + expect(theme.resolve('var(--missing)')).toBe('var(--missing)'); + expect(theme.colour(token('--wp--custom--color--surface--accent'))).not.toBeNull(); + expect(theme.colour(token('--wp--preset--color--broken'))).toBeNull(); + }); + + it('stops resolving a reference loop', () => { + const looped = ThemeTokens.fromThemeJson([ + { + settings: { + custom: { color: { a: 'var(--wp--custom--color--b)', b: 'var(--wp--custom--color--a)' } }, + }, + }, + ]); + expect(looped.resolve('var(--wp--custom--color--a)')).toMatch(/var\(/); + }); + + it('evaluates lengths at the viewport', () => { + expect(theme.lengthPx(token('--wp--preset--spacing--20'), 390)).toBeCloseTo(18, 1); + expect(theme.lengthPx(token('--wp--preset--spacing--20'), 1440)).toBe(20); + expect(theme.lengthPx(token('--wp--custom--letter-spacing--wide'), 1440, 20)).toBe(1); + }); + + it('follows WordPress fluid typography', () => { + const size = (slug: string, viewport: number) => + theme.fontSizePx(token(`--wp--preset--font-size--${slug}`), viewport); + // 14px is at the minimum font size limit, so it stays static. + expect(size('100', 390)).toBe(14); + // fluid: false stays static. + expect(size('200', 390)).toBe(16); + // 32px: factor 1 - 0.075 * log2(32) = 0.625, so 20px at 320px rising to 32px at the 1440px wide size. + expect(size('500', 320)).toBe(20); + expect(size('500', 1440)).toBe(32); + expect(size('500', 880)).toBe(26); + // Explicit min and max. + expect(size('600', 320)).toBe(28); + expect(size('600', 1600)).toBe(40); + // A preset that is already a clamp() is evaluated as written. + expect(size('700', 390)).toBe(32); + expect(size('700', 1440)).toBe(48); + }); + + it('uses the fluid settings and limits', () => { + const custom = ThemeTokens.fromThemeJson([ + { + settings: { + typography: { + fluid: { minViewportWidth: '400px', maxViewportWidth: '1200px', minFontSize: '18px' }, + fontSizes: [ + { slug: 'a', size: '20px' }, + { slug: 'b', size: 'oops' }, + ], + }, + }, + }, + ]); + const a = custom.list('font-size')[0]; + // 20px * (1 - 0.075 * log2(20)) = 13.5, below the 18px limit, so the minimum is 18px. + expect(custom.fontSizePx(a, 400)).toBe(18); + expect(custom.fontSizePx(a, 1200)).toBe(20); + expect(custom.fontSizePx(custom.list('font-size')[1], 800)).toBeNull(); + }); + + it('keeps font sizes static without fluid typography', () => { + const plain = ThemeTokens.fromThemeJson([ + { settings: { typography: { fontSizes: [{ slug: 'x', size: '2rem' }] } } }, + ]); + expect(plain.fontSizePx(plain.list('font-size')[0], 390)).toBe(32); + expect(plain.lengthPx(plain.list('font-size')[0], 390)).toBe(32); + }); + + it('merges several documents, later ones replacing presets by slug', () => { + const merged = ThemeTokens.fromThemeJson([ + themeJson, + { + settings: { + spacing: { + spacingSizes: [ + { slug: '10', size: '12px' }, + { slug: '90', size: '90px' }, + ], + }, + }, + }, + 'not json', + { nope: true }, + ]); + const spacing = merged.list('spacing').filter((t) => !t.semantic); + expect(spacing.map((t) => t.slug)).toEqual(['20', '40', '10', '90']); + expect(spacing.find((t) => t.slug === '10')!.raw).toBe('12px'); + }); +}); diff --git a/skills/site-to-block-theme/scripts/__tests__/token-matcher.test.ts b/skills/site-to-block-theme/scripts/__tests__/token-matcher.test.ts new file mode 100644 index 0000000000..4390165efb --- /dev/null +++ b/skills/site-to-block-theme/scripts/__tests__/token-matcher.test.ts @@ -0,0 +1,150 @@ +import { ThemeTokens } from '../lib/theme-tokens'; +import { TokenMatcher } from '../lib/token-matcher'; +import { themeJson } from './fixtures'; + +describe('TokenMatcher', () => { + const matcher = new TokenMatcher(ThemeTokens.fromThemeJson([themeJson])); + + it('maps properties to token families', () => { + expect(TokenMatcher.familyFor('background-color')).toBe('color'); + expect(TokenMatcher.familyFor('padding-inline-start')).toBe('spacing'); + expect(TokenMatcher.familyFor('row-gap')).toBe('spacing'); + expect(TokenMatcher.familyFor('border-top-left-radius')).toBe('radius'); + expect(TokenMatcher.familyFor('border-top-width')).toBe('border-width'); + expect(TokenMatcher.familyFor('display')).toBeUndefined(); + }); + + it('skips keywords, zero and unmapped properties', () => { + expect(matcher.match('display', 'flex', 1440).status).toBe('skip'); + expect(matcher.match('margin-top', 'auto', 1440).status).toBe('skip'); + expect(matcher.match('padding-top', '0px', 1440).status).toBe('skip'); + expect(matcher.match('background-color', 'rgba(0, 0, 0, 0)', 1440).status).toBe('skip'); + expect(matcher.match('color', 'currentcolor', 1440).status).toBe('skip'); + expect(matcher.match('padding-top', '50%', 1440).status).toBe('skip'); + }); + + it('lists every exact colour token, semantic first', () => { + const match = matcher.match('color', 'rgb(10, 10, 10)', 1440); + expect(match.status).toBe('exact'); + expect(match.tokens[0]).toEqual({ + cssVar: '--wp--custom--color--text--default', + semantic: true, + }); + expect(match.tokens.map((t) => t.preset)).toContain('var:preset|color|contrast'); + }); + + it('reports the nearest colour when nothing matches', () => { + expect(matcher.match('color', 'rgb(200, 145, 80)', 1440)).toMatchObject({ status: 'near' }); + const none = matcher.match('color', 'rgb(0, 200, 0)', 1440); + expect(none.status).toBe('none'); + expect(none.delta).toMatch(/^distance \d+$/); + }); + + it('matches fluid spacing per viewport', () => { + expect(matcher.match('padding-top', '18px', 390).tokens[0].preset).toBe( + 'var:preset|spacing|20' + ); + expect(matcher.match('padding-top', '20px', 1440).tokens[0].preset).toBe( + 'var:preset|spacing|20' + ); + const near = matcher.match('padding-top', '21px', 1440); + expect(near).toMatchObject({ status: 'near', delta: '-1px' }); + expect(matcher.match('padding-top', '300px', 1440).status).toBe('none'); + }); + + it('matches each part of a shorthand', () => { + const match = matcher.match('padding', '10px 0px 40px 11px', 1440); + expect(match.status).toBe('near'); + expect(match.parts!.map((p) => p.status)).toEqual(['exact', 'skip', 'exact', 'near']); + expect(matcher.match('padding', '10px 40px', 1440).status).toBe('exact'); + }); + + it('matches fluid font sizes', () => { + expect(matcher.match('font-size', '32px', 1440).tokens[0].preset).toBe( + 'var:preset|font-size|500' + ); + expect(matcher.match('font-size', '20px', 320).tokens[0].preset).toBe( + 'var:preset|font-size|500' + ); + }); + + it('matches font families on the first family', () => { + expect(matcher.match('font-family', 'Moret, serif', 1440).tokens[0].preset).toBe( + 'var:preset|font-family|heading' + ); + expect(matcher.match('font-family', '"Argesta Display", serif', 1440).status).toBe('exact'); + expect(matcher.match('font-family', 'Arial', 1440)).toMatchObject({ status: 'none' }); + }); + + it('matches shadows whatever the order the browser writes them in', () => { + expect(matcher.match('box-shadow', 'rgba(9, 9, 9, 0.2) 0px 2px 4px 0px', 1440).status).toBe( + 'exact' + ); + expect( + matcher.match( + 'box-shadow', + 'rgba(0, 0, 0, 0.2) 0px 1px 2px 0px inset, rgba(0, 0, 0, 0.1) 0px 0px 1px 0px', + 1440 + ).status + ).toBe('exact'); + expect(matcher.match('box-shadow', 'rgb(0, 0, 0) 0px 9px 9px 0px', 1440).status).toBe('none'); + expect(matcher.normaliseShadow('2px 2px')).toBe('2 2 0 0 ?'); + }); + + it('matches web-font aliases to the family', () => { + expect(TokenMatcher.fontKey('argesta_displayregular, serif')).toBe('argestadisplay'); + expect(matcher.match('font-family', 'argesta_displayregular, serif', 1440).status).toBe( + 'exact' + ); + }); + + it('skips the colour of a border or outline that cannot be seen', () => { + const black = 'rgb(10, 10, 10)'; + expect( + matcher.match('border-top-color', black, 1440, { 'border-top-width': '0px' }).status + ).toBe('skip'); + expect(matcher.match('outline-color', black, 1440, { 'outline-style': 'none' }).status).toBe( + 'skip' + ); + expect( + matcher.match('border-top-color', black, 1440, { 'border-top-width': '1px' }).status + ).toBe('exact'); + }); + + it('matches weights, line heights and letter spacing', () => { + expect(matcher.match('font-weight', '700', 1440).tokens[0].cssVar).toBe( + '--wp--custom--font-weight--bold' + ); + expect(matcher.match('font-weight', '600', 1440)).toMatchObject({ + status: 'near', + delta: '+100', + }); + expect(matcher.match('font-weight', 'bold', 1440).status).toBe('skip'); + const styles = { 'font-size': '16px' }; + expect(matcher.match('line-height', '24px', 1440, styles).tokens[0].cssVar).toBe( + '--wp--custom--line-height--normal' + ); + expect(matcher.match('line-height', '32px', 1440, styles).tokens[0].cssVar).toBe( + '--wp--custom--line-height--loose' + ); + expect(matcher.match('line-height', '1.1', 1440).status).toBe('exact'); + expect(matcher.match('line-height', 'abc', 1440).status).toBe('skip'); + expect(matcher.match('letter-spacing', '1px', 1440, { 'font-size': '20px' }).status).toBe( + 'exact' + ); + expect(matcher.match('border-top-width', '1px', 1440).status).toBe('exact'); + expect(matcher.match('border-top-left-radius', '8px', 1440).tokens[0].preset).toBe( + 'var:preset|border-radius|200' + ); + }); + + it('says when a family has no tokens', () => { + const empty = new TokenMatcher(ThemeTokens.fromThemeJson([{ settings: {} }])); + expect(empty.match('padding-top', '10px', 1440)).toMatchObject({ status: 'none' }); + expect(empty.match('font-weight', '400', 1440)).toMatchObject({ status: 'none' }); + }); + + it('splits on top-level commas only', () => { + expect(TokenMatcher.splitTopLevel('a(1, 2), b')).toEqual(['a(1, 2)', ' b']); + }); +}); diff --git a/skills/site-to-block-theme/scripts/diff-measurements.ts b/skills/site-to-block-theme/scripts/diff-measurements.ts new file mode 100644 index 0000000000..f478f4a925 --- /dev/null +++ b/skills/site-to-block-theme/scripts/diff-measurements.ts @@ -0,0 +1,228 @@ +/** + * Compares the live and local measurements of the same named elements and + * lists every difference: elements missing on one side, box sizes, and each + * computed property per width and state. The Markdown output is the + * "Differences from live" table for the pull request; fix what you can and + * explain the rest. + * + * Usage: + * npx tsx diff-measurements.ts live.json local.json --out diff.json --report diff.md [--tolerance 1] + */ + +import { readFileSync, writeFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +import { Colour } from './lib/colour'; +import { CssLength } from './lib/css-length'; +import { TokenMatcher } from './lib/token-matcher'; +import type { MeasureFile, Measurement, MeasureState } from './measure-page'; + +export type DifferenceKind = 'missing-local' | 'missing-live' | 'value'; + +export interface Difference { + name: string; + width: number; + state: MeasureState; + kind: DifferenceKind; + property?: string; + live?: string; + local?: string; +} + +export class MeasurementDiff { + /** + * @param tolerancePx Lengths within this many px count as equal. Box sizes + * also allow 2% so content-driven widths do not flood the report. + */ + constructor(private readonly tolerancePx = 1) {} + + compare(live: MeasureFile, local: MeasureFile): Difference[] { + const index = (file: MeasureFile) => + new Map(file.measurements.map((m) => [`${m.name}|${m.width}|${m.state}`, m])); + const liveIndex = index(live); + const localIndex = index(local); + const keys = [...new Set([...liveIndex.keys(), ...localIndex.keys()])]; + const differences: Difference[] = []; + + for (const key of keys) { + const a = liveIndex.get(key); + const b = localIndex.get(key); + const ref = (a ?? b) as Measurement; + const base = { name: ref.name, width: ref.width, state: ref.state }; + if (ref.state !== 'default') { + // Hover and focus entries hold only what changed; a missing entry means no change. + differences.push(...this.compareStyles(base, a?.styles ?? {}, b?.styles ?? {})); + continue; + } + if (!a?.found || !b?.found) { + if (a?.found || b?.found) { + differences.push({ ...base, kind: a?.found ? 'missing-local' : 'missing-live' }); + } + continue; + } + if (a.rect && b.rect) { + for (const dimension of ['width', 'height'] as const) { + const x = a.rect[dimension]; + const y = b.rect[dimension]; + if (Math.abs(x - y) > Math.max(this.tolerancePx * 2, Math.max(x, y) * 0.02)) { + differences.push({ + ...base, + kind: 'value', + property: `box ${dimension}`, + live: `${x}px`, + local: `${y}px`, + }); + } + } + } + differences.push(...this.compareStyles(base, a.styles ?? {}, b.styles ?? {})); + } + return differences.sort( + (x, y) => x.name.localeCompare(y.name) || x.width - y.width || x.state.localeCompare(y.state) + ); + } + + private compareStyles( + base: { name: string; width: number; state: MeasureState }, + live: Record, + local: Record + ): Difference[] { + const out: Difference[] = []; + for (const property of new Set([...Object.keys(live), ...Object.keys(local)])) { + const x = live[property]; + const y = local[property]; + if (x === undefined || y === undefined || !this.same(property, x, y)) { + out.push({ + ...base, + kind: 'value', + property, + live: x ?? '(unchanged)', + local: y ?? '(unchanged)', + }); + } + } + return out; + } + + same(property: string, a: string, b: string): boolean { + const x = a.trim(); + const y = b.trim(); + if (x === y) { + return true; + } + const ca = Colour.parse(x); + const cb = Colour.parse(y); + if (ca && cb) { + return Colour.distance(ca, cb) <= 2; + } + if (property === 'font-family') { + return TokenMatcher.fontKey(x) === TokenMatcher.fontKey(y); + } + const la = CssLength.pxList(x); + const lb = CssLength.pxList(y); + const allLengths = (s: string, list: number[]) => + list.length > 0 && list.length === s.split(/\s+/).length; + if (allLengths(x, la) && allLengths(y, lb) && la.length === lb.length) { + return la.every((n, i) => Math.abs(n - lb[i]) <= this.tolerancePx); + } + return x.toLowerCase() === y.toLowerCase(); + } + + static markdown(live: MeasureFile, local: MeasureFile, differences: Difference[]): string { + const lines = [ + '# Differences from live', + '', + `Live: ${live.url} · Local: ${local.url}`, + '', + differences.length + ? `${differences.length} differences. Fix each one, or keep it and say why (for example, the nearest token was used).` + : 'No differences found within tolerance.', + '', + ]; + if (differences.length) { + lines.push( + '| Element | Width | State | Property | Live | Local |', + '| --- | --- | --- | --- | --- | --- |' + ); + const cell = (s?: string) => (s ? `\`${s.replace(/\|/g, '\\|')}\`` : ''); + for (const d of differences) { + const property = + d.kind === 'value' + ? d.property + : d.kind === 'missing-local' + ? 'missing on local' + : 'missing on live'; + lines.push( + `| ${d.name} | ${d.width} | ${d.state} | ${property} | ${cell(d.live)} | ${cell(d.local)} |` + ); + } + lines.push(''); + } + return lines.join('\n'); + } +} + +export interface DiffCliDeps { + readFile: (path: string) => string; + writeFile: (path: string, content: string) => void; + stdout: (text: string) => void; + stderr: (text: string) => void; +} + +const USAGE = + 'Usage: diff-measurements [--out diff.json] [--report diff.md] [--tolerance 1]\n'; + +export function runDiffCli(argv: string[], deps: DiffCliDeps): number { + const files: string[] = []; + const values: Record = { out: 'diff.json', report: 'diff.md', tolerance: '1' }; + try { + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--help' || arg === '-h') { + deps.stdout(USAGE); + return 0; + } + if (!arg.startsWith('--')) { + files.push(arg); + continue; + } + const key = arg.slice(2); + const value = argv[++i]; + if (!(key in values)) { + throw new Error(`Unknown argument ${arg}.`); + } + if (value === undefined) { + throw new Error(`${arg} needs a value.`); + } + values[key] = value; + } + if (files.length !== 2) { + throw new Error('Give the live and the local measurements files.'); + } + const tolerance = Number(values.tolerance); + if (!Number.isFinite(tolerance) || tolerance < 0) { + throw new Error('--tolerance must be a number of px, 0 or more.'); + } + const [live, local] = files.map((f) => JSON.parse(deps.readFile(f)) as MeasureFile); + const differences = new MeasurementDiff(tolerance).compare(live, local); + deps.writeFile(values.out, `${JSON.stringify(differences, null, 2)}\n`); + deps.writeFile(values.report, MeasurementDiff.markdown(live, local, differences)); + deps.stdout(`${differences.length} differences. Wrote ${values.out} and ${values.report}\n`); + return 0; + } catch (error) { + deps.stderr(`diff-measurements: ${(error as Error).message}\n`); + return 1; + } +} + +/* istanbul ignore next -- thin CLI entry point */ +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exit( + runDiffCli(process.argv.slice(2), { + readFile: (path) => readFileSync(path, 'utf8'), + writeFile: (path, content) => writeFileSync(path, content), + stdout: (text) => process.stdout.write(text), + stderr: (text) => process.stderr.write(text), + }) + ); +} diff --git a/skills/site-to-block-theme/scripts/jest.config.cjs b/skills/site-to-block-theme/scripts/jest.config.cjs new file mode 100644 index 0000000000..50ef0414c5 --- /dev/null +++ b/skills/site-to-block-theme/scripts/jest.config.cjs @@ -0,0 +1,28 @@ +/** + * Jest configuration for the site-to-block-theme 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:site-to-block-theme + */ +const base = require('../../../.jest.config.cjs'); + +const skillDir = '/skills/site-to-block-theme/scripts'; + +module.exports = { + ...base, + rootDir: '../../..', + testEnvironment: 'node', + testMatch: [`${skillDir}/__tests__/**/*.test.ts`], + collectCoverage: true, + collectCoverageFrom: [`${skillDir}/**/*.ts`, '!**/__tests__/**'], + coverageDirectory: '/coverage/site-to-block-theme', + coverageThreshold: { + global: { + statements: 80, + branches: 80, + functions: 80, + lines: 80, + }, + }, +}; diff --git a/skills/site-to-block-theme/scripts/lib/colour.ts b/skills/site-to-block-theme/scripts/lib/colour.ts new file mode 100644 index 0000000000..20f014cc6e --- /dev/null +++ b/skills/site-to-block-theme/scripts/lib/colour.ts @@ -0,0 +1,78 @@ +/** + * Colour helpers for comparing computed CSS colours with theme.json colour tokens. + */ + +export interface Rgba { + /** Channels from 0 to 1. */ + r: number; + g: number; + b: number; + a: number; +} + +export class Colour { + /** Parses #rgb, #rgba, #rrggbb, #rrggbbaa, rgb(), rgba() and `transparent`. Returns null otherwise. */ + static parse(value: string | undefined): Rgba | null { + if (!value) { + return null; + } + const text = value.trim().toLowerCase(); + if (text === 'transparent') { + return { r: 0, g: 0, b: 0, a: 0 }; + } + const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/); + if (hex) { + const digits = + hex[1].length <= 4 + ? hex[1] + .split('') + .map((d) => d + d) + .join('') + : hex[1]; + const channel = (i: number) => parseInt(digits.slice(i, i + 2), 16) / 255; + return { + r: channel(0), + g: channel(2), + b: channel(4), + a: digits.length === 8 ? channel(6) : 1, + }; + } + const fn = text.match(/^rgba?\(([^)]+)\)$/); + if (!fn) { + return null; + } + const parts = fn[1].split(/[\s,/]+/).filter(Boolean); + if (parts.length < 3) { + return null; + } + const [r, g, b] = parts.slice(0, 3).map(Number); + const alpha = + parts[3] === undefined + ? 1 + : parts[3].endsWith('%') + ? parseFloat(parts[3]) / 100 + : Number(parts[3]); + if ([r, g, b, alpha].some((n) => !Number.isFinite(n))) { + return null; + } + return { r: r / 255, g: g / 255, b: b / 255, a: alpha }; + } + + static hex(c: Rgba): string { + const byte = (n: number) => + Math.round(Math.min(1, Math.max(0, n)) * 255) + .toString(16) + .padStart(2, '0'); + return `#${byte(c.r)}${byte(c.g)}${byte(c.b)}${c.a < 1 ? byte(c.a) : ''}`; + } + + /** Distance on a 0 to 255 scale per channel, alpha included. */ + static distance(a: Rgba, b: Rgba): number { + return Math.sqrt( + ((a.r - b.r) * 255) ** 2 + + ((a.g - b.g) * 255) ** 2 + + ((a.b - b.b) * 255) ** 2 + + ((a.a - b.a) * 255) ** 2 + ); + } +} diff --git a/skills/site-to-block-theme/scripts/lib/css-length.ts b/skills/site-to-block-theme/scripts/lib/css-length.ts new file mode 100644 index 0000000000..47866e1828 --- /dev/null +++ b/skills/site-to-block-theme/scripts/lib/css-length.ts @@ -0,0 +1,260 @@ +/** + * Evaluates CSS length expressions to pixels at a given viewport width, so a + * fluid theme.json preset such as `clamp(1.5rem, calc(0.5vw + 1.4rem), 2rem)` + * can be compared with the computed pixel value a browser reports. + * + * Supports px, rem, em, vw, vh and unitless numbers, with calc(), clamp(), + * min(), max(), + - * / and parentheses. Anything else (%, var(), keywords) + * returns null. + */ + +export interface LengthContext { + /** Viewport width in px. */ + viewport: number; + /** Viewport height in px. Defaults to 900. */ + viewportHeight?: number; + /** Root font size in px. Defaults to 16. */ + rootFontSize?: number; + /** Element font size in px, for em. Defaults to the root font size. */ + fontSize?: number; +} + +interface Value { + n: number; + /** True when the value is a length (px after conversion), false for a plain number. */ + length: boolean; +} + +type Token = + | { kind: 'num'; value: number; unit: string } + | { kind: 'fn'; name: string } + | { kind: 'op'; value: string }; + +export class CssLength { + /** The pixel value of a CSS length expression, or null when it cannot be evaluated. */ + static toPx(expression: string | undefined, context: LengthContext): number | null { + if (expression === undefined) { + return null; + } + const text = expression.trim().toLowerCase(); + if (!text) { + return null; + } + try { + const tokens = CssLength.tokenize(text); + const parser = new Parser(tokens, context); + const result = parser.parseExpression(); + if (!parser.done()) { + return null; + } + if (!result.length && result.n !== 0) { + return null; + } + return Math.round(result.n * 1000) / 1000; + } catch { + return null; + } + } + + /** Splits a space-separated computed value such as `10px 20px` into its pixel numbers. */ + static pxList(value: string | undefined): number[] { + if (!value) { + return []; + } + return value + .trim() + .split(/\s+/) + .map((part) => part.match(/^(-?[\d.]+)px$/)) + .filter((m): m is RegExpMatchArray => m !== null) + .map((m) => Number(m[1])); + } + + private static tokenize(text: string): Token[] { + const tokens: Token[] = []; + let i = 0; + while (i < text.length) { + const rest = text.slice(i); + const space = rest.match(/^\s+/); + if (space) { + i += space[0].length; + continue; + } + const previous = tokens[tokens.length - 1]; + const signAllowed = + !previous || (previous.kind === 'op' && previous.value !== ')') || previous.kind === 'fn'; + const number = rest.match( + signAllowed ? /^[-+]?(\d*\.\d+|\d+\.?)([a-z%]*)/ : /^(\d*\.\d+|\d+\.?)([a-z%]*)/ + ); + if (number) { + const value = parseFloat(number[0]); + tokens.push({ kind: 'num', value, unit: number[2] }); + i += number[0].length; + continue; + } + const fn = rest.match(/^(calc|clamp|min|max)\(/); + if (fn) { + tokens.push({ kind: 'fn', name: fn[1] }); + i += fn[0].length; + continue; + } + if ('+-*/(),'.includes(rest[0])) { + tokens.push({ kind: 'op', value: rest[0] }); + i += 1; + continue; + } + throw new Error(`Unsupported CSS at "${rest}".`); + } + return tokens; + } +} + +class Parser { + private position = 0; + + constructor( + private readonly tokens: Token[], + private readonly context: LengthContext + ) {} + + done(): boolean { + return this.position === this.tokens.length; + } + + parseExpression(): Value { + let left = this.parseTerm(); + for (;;) { + const token = this.peek(); + if (token?.kind === 'op' && (token.value === '+' || token.value === '-')) { + this.position++; + const right = this.parseTerm(); + left = this.combineSum(left, right, token.value); + } else { + return left; + } + } + } + + private parseTerm(): Value { + let left = this.parseFactor(); + for (;;) { + const token = this.peek(); + if (token?.kind === 'op' && (token.value === '*' || token.value === '/')) { + this.position++; + const right = this.parseFactor(); + if (token.value === '*') { + if (left.length && right.length) { + throw new Error('Cannot multiply two lengths.'); + } + left = { n: left.n * right.n, length: left.length || right.length }; + } else { + if (right.length || right.n === 0) { + throw new Error('Can only divide by a non-zero number.'); + } + left = { n: left.n / right.n, length: left.length }; + } + } else { + return left; + } + } + } + + private parseFactor(): Value { + const token = this.next(); + if (token.kind === 'num') { + return this.convert(token.value, token.unit); + } + if (token.kind === 'fn') { + const args = [this.parseExpression()]; + while (this.peekOp(',')) { + this.position++; + args.push(this.parseExpression()); + } + this.expectOp(')'); + return this.applyFunction(token.name, args); + } + if (token.value === '(') { + const inner = this.parseExpression(); + this.expectOp(')'); + return inner; + } + if (token.value === '-') { + const inner = this.parseFactor(); + return { n: -inner.n, length: inner.length }; + } + throw new Error(`Unexpected "${token.value}".`); + } + + private applyFunction(name: string, args: Value[]): Value { + const length = args.some((a) => a.length); + const values = args.map((a) => a.n); + if (name === 'calc') { + if (args.length !== 1) { + throw new Error('calc() takes one argument.'); + } + return args[0]; + } + if (name === 'min') { + return { n: Math.min(...values), length }; + } + if (name === 'max') { + return { n: Math.max(...values), length }; + } + if (args.length !== 3) { + throw new Error('clamp() takes three arguments.'); + } + return { n: Math.min(Math.max(values[1], values[0]), values[2]), length }; + } + + private convert(value: number, unit: string): Value { + const root = this.context.rootFontSize ?? 16; + switch (unit) { + case '': + return { n: value, length: false }; + case 'px': + return { n: value, length: true }; + case 'rem': + return { n: value * root, length: true }; + case 'em': + return { n: value * (this.context.fontSize ?? root), length: true }; + case 'vw': + return { n: (value * this.context.viewport) / 100, length: true }; + case 'vh': + return { n: (value * (this.context.viewportHeight ?? 900)) / 100, length: true }; + default: + throw new Error(`Unsupported unit ${unit}.`); + } + } + + private combineSum(left: Value, right: Value, op: string): Value { + const zero = (v: Value) => !v.length && v.n === 0; + if (left.length !== right.length && !zero(left) && !zero(right)) { + throw new Error('Cannot add a length to a number.'); + } + const n = op === '+' ? left.n + right.n : left.n - right.n; + return { n, length: left.length || right.length }; + } + + private peek(): Token | undefined { + return this.tokens[this.position]; + } + + private peekOp(value: string): boolean { + const token = this.peek(); + return token?.kind === 'op' && token.value === value; + } + + private next(): Token { + const token = this.tokens[this.position++]; + if (!token) { + throw new Error('Unexpected end of expression.'); + } + return token; + } + + private expectOp(value: string): void { + if (!this.peekOp(value)) { + throw new Error(`Expected "${value}".`); + } + this.position++; + } +} diff --git a/skills/site-to-block-theme/scripts/lib/theme-tokens.ts b/skills/site-to-block-theme/scripts/lib/theme-tokens.ts new file mode 100644 index 0000000000..a00ea2ff08 --- /dev/null +++ b/skills/site-to-block-theme/scripts/lib/theme-tokens.ts @@ -0,0 +1,252 @@ +/** + * Reads the design tokens a block theme defines in theme.json (and any preset + * slices merged into it) and evaluates them at a viewport width, so computed + * values measured on a live site can be matched to them. + * + * Presets: palette colours, spacing sizes, font sizes (with WordPress fluid + * typography), font families, radius sizes and shadows. Custom values under + * settings.custom become semantic tokens (`--wp--custom--*`). + */ + +import { Colour, Rgba } from './colour'; +import { CssLength } from './css-length'; + +export type Family = + | 'color' + | 'spacing' + | 'font-size' + | 'font-family' + | 'radius' + | 'shadow' + | 'font-weight' + | 'line-height' + | 'letter-spacing' + | 'border-width'; + +export interface Token { + family: Family; + /** Preset slug, or the custom path joined with `--`. */ + slug: string; + cssVar: string; + /** Block markup reference for presets, for example `var:preset|spacing|30`. */ + preset?: string; + raw: string; + /** True for settings.custom tokens, which carry a role (text, surface, border). */ + semantic: boolean; + /** Font size presets only: the preset's own `fluid` setting. */ + fluid?: boolean | { min?: string; max?: string }; +} + +type Json = Record; + +const CUSTOM_FAMILIES: Record = { + color: 'color', + spacing: 'spacing', + 'font-weight': 'font-weight', + 'line-height': 'line-height', + 'letter-spacing': 'letter-spacing', + 'border-width': 'border-width', + radius: 'radius', +}; + +const isObject = (value: unknown): value is Json => + typeof value === 'object' && value !== null && !Array.isArray(value); + +export class ThemeTokens { + private readonly byVar = new Map(); + + private constructor( + private readonly settings: Json, + readonly tokens: Token[] + ) { + for (const token of tokens) { + this.byVar.set(token.cssVar, token); + } + } + + /** Builds the tokens from one or more theme.json documents. Later documents win. */ + static fromThemeJson(documents: unknown[]): ThemeTokens { + let settings: Json = {}; + for (const doc of documents) { + if (isObject(doc) && isObject(doc.settings)) { + settings = ThemeTokens.merge(settings, doc.settings); + } + } + return new ThemeTokens(settings, ThemeTokens.collect(settings)); + } + + static kebab(key: string): string { + return key.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase(); + } + + list(family: Family): Token[] { + return this.tokens.filter((t) => t.family === family); + } + + /** Replaces var() references with the values they point to, recursively. */ + resolve(raw: string, depth = 0): string { + if (depth > 10) { + return raw; + } + const replaced = raw.replace( + /var\(\s*(--[a-z0-9-]+)\s*(?:,\s*([^()]*(?:\([^()]*\))?[^()]*))?\)/gi, + (match, name: string, fallback?: string) => { + const token = this.byVar.get(name.toLowerCase()); + if (token) { + return token.raw; + } + return fallback !== undefined ? fallback.trim() : match; + } + ); + return replaced === raw ? raw : this.resolve(replaced, depth + 1); + } + + colour(token: Token): Rgba | null { + return Colour.parse(this.resolve(token.raw)); + } + + /** + * The token's size in px at the viewport width, or null for values that + * are not lengths. Font sizes follow WordPress fluid typography. + */ + lengthPx(token: Token, viewport: number, fontSizePx?: number): number | null { + if (token.family === 'font-size') { + return this.fontSizePx(token, viewport); + } + return CssLength.toPx(this.resolve(token.raw), { viewport, fontSize: fontSizePx }); + } + + /** + * A font size preset at a viewport width, following WordPress core's + * wp_get_typography_font_size_value() and wp_get_computed_fluid_typography_value(). + */ + fontSizePx(token: Token, viewport: number): number | null { + const size = CssLength.toPx(this.resolve(token.raw), { viewport }); + if (size === null) { + return null; + } + const typography = isObject(this.settings.typography) ? this.settings.typography : {}; + const fluid = typography.fluid; + if (!fluid || token.fluid === false || /clamp|calc|min\(|max\(|vw/.test(token.raw)) { + return size; + } + const fluidSettings = isObject(fluid) ? fluid : {}; + const layout = isObject(this.settings.layout) ? this.settings.layout : {}; + const px = (value: unknown, fallback: number) => + typeof value === 'string' ? (CssLength.toPx(value, { viewport }) ?? fallback) : fallback; + + const maxViewport = px(fluidSettings.maxViewportWidth ?? layout.wideSize, 1600); + const minViewport = px(fluidSettings.minViewportWidth, 320); + const limit = px(fluidSettings.minFontSize, 14); + const own = isObject(token.fluid) ? token.fluid : {}; + + const max = own.max ? px(own.max, size) : size; + let min: number; + if (own.min) { + min = px(own.min, size); + } else { + if (size <= limit) { + return size; + } + const factor = Math.min(Math.max(1 - 0.075 * Math.log2(size), 0.25), 0.75); + const calculated = Math.round(size * factor * 1000) / 1000; + min = calculated <= limit ? limit : calculated; + } + if (viewport <= minViewport) { + return min; + } + if (viewport >= maxViewport) { + return max; + } + const ratio = (viewport - minViewport) / (maxViewport - minViewport); + return Math.round((min + (max - min) * ratio) * 1000) / 1000; + } + + private static merge(base: Json, extra: Json): Json { + const out: Json = { ...base }; + for (const [key, value] of Object.entries(extra)) { + const current = out[key]; + if (isObject(current) && isObject(value)) { + out[key] = ThemeTokens.merge(current, value); + } else if (Array.isArray(current) && Array.isArray(value)) { + const slugOf = (item: unknown) => (isObject(item) ? item.slug : undefined); + const replaced = new Set(value.map(slugOf).filter((s) => s !== undefined)); + out[key] = [...current.filter((item) => !replaced.has(slugOf(item))), ...value]; + } else { + out[key] = value; + } + } + return out; + } + + private static collect(settings: Json): Token[] { + const tokens: Token[] = []; + const section = (key: string): Json => (isObject(settings[key]) ? settings[key] : {}); + const presets = ( + items: unknown, + family: Family, + cssGroup: string, + valueKey: string, + withFluid = false + ) => { + if (!Array.isArray(items)) { + return; + } + for (const item of items) { + if (!isObject(item) || typeof item.slug !== 'string') { + continue; + } + const raw = item[valueKey]; + if (typeof raw !== 'string' && typeof raw !== 'number') { + continue; + } + const token: Token = { + family, + slug: item.slug, + cssVar: `--wp--preset--${cssGroup}--${item.slug}`, + preset: `var:preset|${cssGroup}|${item.slug}`, + raw: String(raw), + semantic: false, + }; + if (withFluid && (typeof item.fluid === 'boolean' || isObject(item.fluid))) { + token.fluid = item.fluid as Token['fluid']; + } + tokens.push(token); + } + }; + + presets(section('color').palette, 'color', 'color', 'color'); + presets(section('spacing').spacingSizes, 'spacing', 'spacing', 'size'); + presets(section('typography').fontSizes, 'font-size', 'font-size', 'size', true); + presets(section('typography').fontFamilies, 'font-family', 'font-family', 'fontFamily'); + presets(section('border').radiusSizes, 'radius', 'border-radius', 'size'); + presets(section('shadow').presets, 'shadow', 'shadow', 'shadow'); + + const walk = (node: unknown, path: string[], family: Family) => { + if (isObject(node)) { + for (const [key, value] of Object.entries(node)) { + walk(value, [...path, ThemeTokens.kebab(key)], family); + } + return; + } + if (typeof node !== 'string' && typeof node !== 'number') { + return; + } + tokens.push({ + family, + slug: path.slice(1).join('--'), + cssVar: `--wp--custom--${path.join('--')}`, + raw: String(node), + semantic: true, + }); + }; + for (const [key, value] of Object.entries(section('custom'))) { + const name = ThemeTokens.kebab(key); + const family = CUSTOM_FAMILIES[name]; + if (family) { + walk(value, [name], family); + } + } + return tokens; + } +} diff --git a/skills/site-to-block-theme/scripts/lib/token-matcher.ts b/skills/site-to-block-theme/scripts/lib/token-matcher.ts new file mode 100644 index 0000000000..9081b3701d --- /dev/null +++ b/skills/site-to-block-theme/scripts/lib/token-matcher.ts @@ -0,0 +1,333 @@ +/** + * Matches one computed CSS value, measured at a viewport width, to the theme's + * tokens. Exact matches list every token with that value, semantic tokens + * first, so the builder picks the one whose role fits. Anything else reports + * the nearest token and how far off it is. + */ + +import { Colour, Rgba } from './colour'; +import { CssLength } from './css-length'; +import { Family, ThemeTokens, Token } from './theme-tokens'; + +export type MatchStatus = 'exact' | 'near' | 'none' | 'skip'; + +export interface TokenRef { + cssVar: string; + preset?: string; + semantic: boolean; +} + +export interface Match { + family?: Family; + status: MatchStatus; + /** Matching tokens: all exact ones, or the nearest one. */ + tokens: TokenRef[]; + /** For near and none: how far the nearest token is, for example `+2px` or `distance 12`. */ + delta?: string; + /** For values with several parts (padding shorthand, shadow layers): a match per part. */ + parts?: Match[]; +} + +const SKIP_VALUES = new Set(['', 'auto', 'normal', 'none', 'initial', 'inherit', 'unset']); + +const PROPERTY_FAMILIES: [RegExp, Family][] = [ + [/(^|-)color$/, 'color'], + [ + /^(padding|margin)(-(top|right|bottom|left|block|inline)(-(start|end))?)?$|(^|-)gap$/, + 'spacing', + ], + [/^font-size$/, 'font-size'], + [/^font-family$/, 'font-family'], + [/^font-weight$/, 'font-weight'], + [/^line-height$/, 'line-height'], + [/^letter-spacing$/, 'letter-spacing'], + [/radius$/, 'radius'], + [/^box-shadow$/, 'shadow'], + [/^border(-(top|right|bottom|left))?-width$/, 'border-width'], +]; + +export class TokenMatcher { + constructor( + private readonly theme: ThemeTokens, + private readonly colourTolerance = { exact: 1.5, near: 24 }, + private readonly lengthTolerance = { exactPx: 0.5, nearRatio: 0.12, nearMinPx: 2 } + ) {} + + static familyFor(property: string): Family | undefined { + return PROPERTY_FAMILIES.find(([pattern]) => pattern.test(property))?.[1]; + } + + /** + * @param styles All computed styles of the element, for font-size-relative values. + */ + match( + property: string, + value: string, + viewport: number, + styles: Record = {} + ): Match { + const family = TokenMatcher.familyFor(property); + const text = (value ?? '').trim(); + if ( + !family || + SKIP_VALUES.has(text.toLowerCase()) || + TokenMatcher.invisible(property, styles) + ) { + return { family, status: 'skip', tokens: [] }; + } + const fontSize = CssLength.pxList(styles['font-size'])[0]; + switch (family) { + case 'color': + return this.matchColour(text); + case 'font-family': + return this.matchFontFamily(text); + case 'shadow': + return this.matchShadow(text); + case 'font-weight': + return this.matchNumber(family, Number(text), 0, (t) => Number(this.theme.resolve(t.raw))); + case 'line-height': + return this.matchLineHeight(text, fontSize, viewport); + default: + return this.matchLengths(family, text, viewport, fontSize); + } + } + + private matchColour(text: string): Match { + const colour = Colour.parse(text); + if (!colour) { + return { family: 'color', status: 'skip', tokens: [] }; + } + if (colour.a === 0) { + return { family: 'color', status: 'skip', tokens: [] }; + } + const scored = this.theme + .list('color') + .map((token) => ({ token, rgba: this.theme.colour(token) })) + .filter((s): s is { token: Token; rgba: Rgba } => s.rgba !== null) + .map((s) => ({ token: s.token, distance: Colour.distance(colour, s.rgba) })); + return this.rank( + 'color', + scored, + this.colourTolerance.exact, + this.colourTolerance.near, + (d) => `distance ${Math.round(d)}` + ); + } + + /** A border or outline colour whose width is 0 or style is none cannot be seen. */ + static invisible(property: string, styles: Record): boolean { + const edge = property.match(/^(border-(?:top|right|bottom|left)|outline)-color$/); + if (!edge) { + return false; + } + return styles[`${edge[1]}-width`] === '0px' || styles[`${edge[1]}-style`] === 'none'; + } + + /** + * The first family in a stack, reduced to letters and digits, without a + * trailing style word, so web-font aliases such as `argesta_displayregular` + * match `"Argesta Display"`. + */ + static fontKey(stack: string): string { + return stack + .split(',')[0] + .toLowerCase() + .replace(/[^a-z0-9]/g, '') + .replace(/(regular|normal|book|roman|webfont)+$/, ''); + } + + private matchFontFamily(text: string): Match { + const wanted = TokenMatcher.fontKey(text); + const tokens = this.theme + .list('font-family') + .filter((t) => TokenMatcher.fontKey(this.theme.resolve(t.raw)) === wanted); + if (tokens.length) { + return { family: 'font-family', status: 'exact', tokens: tokens.map(TokenMatcher.ref) }; + } + return { + family: 'font-family', + status: 'none', + tokens: [], + delta: `no family "${text.split(',')[0].trim()}"`, + }; + } + + private matchShadow(text: string): Match { + const wanted = this.normaliseShadow(text); + const tokens = this.theme + .list('shadow') + .filter((t) => this.normaliseShadow(this.theme.resolve(t.raw)) === wanted); + if (tokens.length) { + return { family: 'shadow', status: 'exact', tokens: tokens.map(TokenMatcher.ref) }; + } + return { family: 'shadow', status: 'none', tokens: [], delta: 'no shadow with these layers' }; + } + + /** One string per layer: inset flag, lengths in px and the colour as hex. Order-insensitive within a layer. */ + normaliseShadow(text: string): string { + return TokenMatcher.splitTopLevel(text) + .map((layer) => { + let rest = layer.trim().toLowerCase(); + const inset = /\binset\b/.test(rest); + rest = rest.replace(/\binset\b/, ''); + const colourMatch = rest.match(/rgba?\([^)]*\)|#[0-9a-f]{3,8}\b|\btransparent\b/); + const colour = colourMatch ? Colour.parse(colourMatch[0]) : null; + if (colourMatch) { + rest = rest.replace(colourMatch[0], ''); + } + const lengths = rest + .trim() + .split(/\s+/) + .filter(Boolean) + .map((part) => CssLength.toPx(part, { viewport: 1440 }) ?? NaN); + while (lengths.length < 4) { + lengths.push(0); + } + return `${inset ? 'inset ' : ''}${lengths.map((n) => Math.round(n * 10) / 10).join(' ')} ${ + colour ? Colour.hex(colour) : '?' + }`; + }) + .join(', '); + } + + private matchLineHeight(text: string, fontSize: number | undefined, viewport: number): Match { + const px = CssLength.pxList(text)[0]; + const ratio = px !== undefined && fontSize ? px / fontSize : Number(text); + if (!Number.isFinite(ratio)) { + return { family: 'line-height', status: 'skip', tokens: [] }; + } + return this.matchNumber('line-height', ratio, 0.01, (t) => { + const raw = this.theme.resolve(t.raw); + const n = Number(raw); + if (Number.isFinite(n)) { + return n; + } + const length = CssLength.toPx(raw, { viewport, fontSize }); + return length !== null && fontSize ? length / fontSize : NaN; + }); + } + + private matchNumber( + family: Family, + wanted: number, + tolerance: number, + valueOf: (t: Token) => number + ): Match { + if (!Number.isFinite(wanted)) { + return { family, status: 'skip', tokens: [] }; + } + const scored = this.theme + .list(family) + .map((token) => ({ token, value: valueOf(token) })) + .filter((s) => Number.isFinite(s.value)) + .map((s) => ({ + token: s.token, + distance: Math.abs(s.value - wanted), + signed: s.value - wanted, + })); + const exact = scored.filter((s) => s.distance <= tolerance + 1e-9); + if (exact.length) { + return { family, status: 'exact', tokens: TokenMatcher.sorted(exact.map((s) => s.token)) }; + } + const nearest = scored.sort((a, b) => a.distance - b.distance)[0]; + if (!nearest) { + return { family, status: 'none', tokens: [], delta: 'no tokens in this family' }; + } + return { + family, + status: 'near', + tokens: [TokenMatcher.ref(nearest.token)], + delta: `${nearest.signed > 0 ? '+' : ''}${Math.round(nearest.signed * 1000) / 1000}`, + }; + } + + private matchLengths(family: Family, text: string, viewport: number, fontSize?: number): Match { + const values = CssLength.pxList(text); + if (!values.length) { + return { family, status: 'skip', tokens: [] }; + } + const parts = values.map((px) => this.matchLength(family, px, viewport, fontSize)); + if (parts.length === 1) { + return parts[0]; + } + const order: MatchStatus[] = ['none', 'near', 'exact', 'skip']; + const status = order.find((s) => parts.some((p) => p.status === s)) as MatchStatus; + return { family, status, tokens: [], parts }; + } + + private matchLength(family: Family, px: number, viewport: number, fontSize?: number): Match { + if (px === 0) { + return { family, status: 'skip', tokens: [] }; + } + const scored = this.theme + .list(family) + .map((token) => ({ token, value: this.theme.lengthPx(token, viewport, fontSize) })) + .filter((s): s is { token: Token; value: number } => s.value !== null) + .map((s) => ({ token: s.token, distance: Math.abs(s.value - px), signed: s.value - px })); + const near = Math.max(this.lengthTolerance.nearMinPx, px * this.lengthTolerance.nearRatio); + return this.rank( + family, + scored, + this.lengthTolerance.exactPx, + near, + (_d, signed) => `${signed > 0 ? '+' : ''}${Math.round(signed * 100) / 100}px` + ); + } + + private rank( + family: Family, + scored: { token: Token; distance: number; signed?: number }[], + exactWithin: number, + nearWithin: number, + describe: (distance: number, signed: number) => string + ): Match { + const exact = scored.filter((s) => s.distance <= exactWithin); + if (exact.length) { + return { family, status: 'exact', tokens: TokenMatcher.sorted(exact.map((s) => s.token)) }; + } + const nearest = [...scored].sort((a, b) => a.distance - b.distance)[0]; + if (!nearest) { + return { family, status: 'none', tokens: [], delta: 'no tokens in this family' }; + } + return { + family, + status: nearest.distance <= nearWithin ? 'near' : 'none', + tokens: [TokenMatcher.ref(nearest.token)], + delta: describe(nearest.distance, nearest.signed ?? nearest.distance), + }; + } + + private static sorted(tokens: Token[]): TokenRef[] { + return [...tokens] + .sort((a, b) => Number(b.semantic) - Number(a.semantic)) + .map(TokenMatcher.ref); + } + + private static ref(token: Token): TokenRef { + return token.preset + ? { cssVar: token.cssVar, preset: token.preset, semantic: token.semantic } + : { cssVar: token.cssVar, semantic: token.semantic }; + } + + /** Splits on commas that are not inside parentheses. */ + static splitTopLevel(text: string): string[] { + const parts: string[] = []; + let depth = 0; + let current = ''; + for (const char of text) { + if (char === '(') { + depth++; + } else if (char === ')') { + depth--; + } + if (char === ',' && depth === 0) { + parts.push(current); + current = ''; + } else { + current += char; + } + } + parts.push(current); + return parts.filter((p) => p.trim()); + } +} diff --git a/skills/site-to-block-theme/scripts/map-to-tokens.ts b/skills/site-to-block-theme/scripts/map-to-tokens.ts new file mode 100644 index 0000000000..cd3c58edfe --- /dev/null +++ b/skills/site-to-block-theme/scripts/map-to-tokens.ts @@ -0,0 +1,186 @@ +/** + * Maps every measured live value to the theme's tokens: colours to palette and + * semantic custom colours, spacing, font sizes (fluid, per viewport), radii, + * shadows, font families and the custom weight, line-height, letter-spacing + * and border-width tokens. + * + * Writes a JSON mapping and a Markdown report. The report lists the values + * with no exact token first: each needs a decision (use the nearest token and + * note it under "Differences from live", or propose a new token for approval). + * + * Usage: + * npx tsx map-to-tokens.ts live.json --theme-json path/to/theme/theme.json \ + * [--theme-json path/to/theme/styles/presets.json] --out tokens.json --report tokens.md + */ + +import { readFileSync, writeFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +import { Match, MatchStatus, TokenMatcher, TokenRef } from './lib/token-matcher'; +import { ThemeTokens } from './lib/theme-tokens'; +import type { MeasureFile, MeasureState } from './measure-page'; + +export interface MappingRow { + name: string; + width: number; + state: MeasureState; + property: string; + value: string; + match: Match; +} + +export interface Mapping { + url: string; + counts: Record; + rows: MappingRow[]; +} + +export class TokenMapper { + constructor(private readonly matcher: TokenMatcher) {} + + map(measure: MeasureFile): Mapping { + const rows: MappingRow[] = []; + const defaults = new Map>(); + for (const m of measure.measurements) { + if (!m.found || !m.styles) { + continue; + } + const key = `${m.name}|${m.width}`; + if (m.state === 'default') { + defaults.set(key, m.styles); + } + const context = { ...(defaults.get(key) ?? {}), ...m.styles }; + for (const [property, value] of Object.entries(m.styles)) { + const match = this.matcher.match(property, value, m.width, context); + if (match.status !== 'skip') { + rows.push({ name: m.name, width: m.width, state: m.state, property, value, match }); + } + } + } + const counts: Record = { exact: 0, near: 0, none: 0, skip: 0 }; + for (const row of rows) { + counts[row.match.status]++; + } + return { url: measure.url, counts, rows }; + } + + static markdown(mapping: Mapping): string { + const tokenText = (refs: TokenRef[]) => + refs.length ? refs.map((r) => `\`${r.preset ?? `var(${r.cssVar})`}\``).join(', ') : '-'; + const matchText = (match: Match): string => + match.parts + ? match.parts + .map((p) => + p.status === 'skip' ? '0' : `${tokenText(p.tokens)}${p.delta ? ` (${p.delta})` : ''}` + ) + .join(' / ') + : `${tokenText(match.tokens)}${match.delta ? ` (${match.delta})` : ''}`; + const row = (r: MappingRow) => + `| ${r.name} | ${r.width} | ${r.state} | ${r.property} | \`${r.value.replace(/\|/g, '\\|')}\` | ${r.match.status} | ${matchText(r.match)} |`; + const header = + '| Element | Width | State | Property | Live value | Match | Token |\n| --- | --- | --- | --- | --- | --- | --- |'; + const open = mapping.rows.filter((r) => r.match.status !== 'exact'); + const exact = mapping.rows.filter((r) => r.match.status === 'exact'); + const lines = [ + `# Token mapping: ${mapping.url}`, + '', + `${mapping.counts.exact} exact, ${mapping.counts.near} near, ${mapping.counts.none} with no token.`, + '', + 'Exact matches list every token with that value, semantic tokens first: pick the one whose role fits.', + '', + '## Needs a decision', + '', + ]; + if (open.length) { + lines.push( + 'Use the nearest token and list it under "Differences from live", or propose a new token for approval. Never hardcode the value.', + '', + header, + ...open.map(row) + ); + } else { + lines.push('Every value has an exact token.'); + } + lines.push('', '## Exact', '', ...(exact.length ? [header, ...exact.map(row)] : ['None.']), ''); + return lines.join('\n'); + } +} + +export interface MapCliDeps { + readFile: (path: string) => string; + writeFile: (path: string, content: string) => void; + stdout: (text: string) => void; + stderr: (text: string) => void; +} + +const USAGE = + 'Usage: map-to-tokens --theme-json theme.json [--theme-json presets.json] [--out tokens.json] [--report tokens.md]\n'; + +export function runMapCli(argv: string[], deps: MapCliDeps): number { + const themeFiles: string[] = []; + let input: string | undefined; + let out = 'tokens.json'; + let report = 'tokens.md'; + try { + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--help' || arg === '-h') { + deps.stdout(USAGE); + return 0; + } + if (!arg.startsWith('--')) { + if (input) { + throw new Error(`Unexpected argument ${arg}.`); + } + input = arg; + continue; + } + const value = argv[++i]; + if (value === undefined) { + throw new Error(`${arg} needs a value.`); + } + if (arg === '--theme-json') { + themeFiles.push(value); + } else if (arg === '--out') { + out = value; + } else if (arg === '--report') { + report = value; + } else { + throw new Error(`Unknown argument ${arg}.`); + } + } + if (!input) { + throw new Error('Give the live measurements file.'); + } + if (!themeFiles.length) { + throw new Error('--theme-json is required.'); + } + const theme = ThemeTokens.fromThemeJson(themeFiles.map((f) => JSON.parse(deps.readFile(f)))); + if (!theme.tokens.length) { + throw new Error('No tokens found in the theme.json files given.'); + } + const measure = JSON.parse(deps.readFile(input)) as MeasureFile; + const mapping = new TokenMapper(new TokenMatcher(theme)).map(measure); + deps.writeFile(out, `${JSON.stringify(mapping, null, 2)}\n`); + deps.writeFile(report, TokenMapper.markdown(mapping)); + deps.stdout( + `${mapping.counts.exact} exact, ${mapping.counts.near} near, ${mapping.counts.none} with no token. Wrote ${out} and ${report}\n` + ); + return 0; + } catch (error) { + deps.stderr(`map-to-tokens: ${(error as Error).message}\n`); + return 1; + } +} + +/* istanbul ignore next -- thin CLI entry point */ +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exit( + runMapCli(process.argv.slice(2), { + readFile: (path) => readFileSync(path, 'utf8'), + writeFile: (path, content) => writeFileSync(path, content), + stdout: (text) => process.stdout.write(text), + stderr: (text) => process.stderr.write(text), + }) + ); +} diff --git a/skills/site-to-block-theme/scripts/measure-page.ts b/skills/site-to-block-theme/scripts/measure-page.ts new file mode 100644 index 0000000000..79cd28ed7e --- /dev/null +++ b/skills/site-to-block-theme/scripts/measure-page.ts @@ -0,0 +1,462 @@ +/** + * Measures the computed styles of named elements on one page at several + * viewport widths, in their default, hover and focus states, and takes a + * full-page screenshot at each width. Run it on the live page and on the + * local build with the same selectors file, then compare the two with + * diff-measurements.ts and map the live values to tokens with map-to-tokens.ts. + * + * It reads the page only: it hovers and focuses to read states, but never + * clicks, types or submits, and it refuses wp-admin and login URLs. + * + * Usage: + * npx tsx measure-page.ts --url https://www.example.com/ --selectors selectors.json \ + * --side live --out live.json --shots shots + * npx tsx measure-page.ts --url http://localhost:8881/ --selectors selectors.json \ + * --side local --out local.json --shots shots + * + * selectors.json maps a name to a selector, or to a live and a local selector: + * { "hero heading": ".hero h1", "card title": { "live": ".lsx-tour h3", "local": ".tsp-card h3" } } + */ + +/* global HTMLElement, getComputedStyle -- collectors run in the browser */ + +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; + +export type Side = 'live' | 'local'; +export type MeasureState = 'default' | 'hover' | 'focus'; + +export const DEFAULT_PROPERTIES = [ + 'font-family', + 'font-size', + 'font-weight', + 'font-style', + 'line-height', + 'letter-spacing', + 'text-transform', + 'text-decoration-line', + 'text-align', + 'color', + 'background-color', + 'background-image', + 'padding-top', + 'padding-right', + 'padding-bottom', + 'padding-left', + 'margin-top', + 'margin-bottom', + 'row-gap', + 'column-gap', + 'border-top-width', + 'border-top-style', + 'border-top-color', + 'border-bottom-width', + 'border-bottom-color', + 'border-top-left-radius', + 'border-bottom-right-radius', + 'box-shadow', + 'outline-color', + 'outline-width', + 'outline-offset', + 'display', + 'flex-direction', + 'justify-content', + 'align-items', + 'grid-template-columns', + 'max-width', + 'aspect-ratio', + 'object-fit', + 'opacity', + 'transition-duration', +]; + +export interface ElementReading { + count: number; + rect: { width: number; height: number }; + styles: Record; +} + +export interface Measurement { + name: string; + selector: string; + width: number; + state: MeasureState; + found: boolean; + count?: number; + rect?: { width: number; height: number }; + /** Every property in the default state; only the changed ones in hover and focus. */ + styles?: Record; +} + +export interface MeasureFile { + url: string; + side: Side; + measuredAt: string; + widths: number[]; + properties: string[]; + measurements: Measurement[]; + screenshots: string[]; + failures: { width: number; error: string }[]; +} + +export interface NamedSelector { + name: string; + selector: string; +} + +/** Runs in the browser: reads the first element that matches the selector. */ +export function readElement(args: { + selector: string; + properties: string[]; +}): ElementReading | null { + const all = document.querySelectorAll(args.selector); + const element = all[0] as HTMLElement | undefined; + if (!element) { + return null; + } + const computed = getComputedStyle(element); + const styles: Record = {}; + for (const property of args.properties) { + styles[property] = computed.getPropertyValue(property).trim(); + } + const box = element.getBoundingClientRect(); + return { + count: all.length, + rect: { width: Math.round(box.width * 10) / 10, height: Math.round(box.height * 10) / 10 }, + styles, + }; +} + +export interface PageHandle { + read: ( + selector: string, + properties: string[], + state: MeasureState + ) => Promise; + screenshot: (path: string) => Promise; + close: () => Promise; +} + +export interface BrowserDriver { + open: (url: string, width: number) => Promise; + close: () => Promise; +} + +export interface MeasureOptions { + url: string; + side: Side; + selectors: NamedSelector[]; + widths?: number[]; + states?: MeasureState[]; + properties?: string[]; + shotsDir?: string; + delayMs?: number; +} + +const FORBIDDEN_PATH = /\/(wp-admin|wp-login\.php)(\/|$|\?)/i; + +export class PageMeasurer { + constructor( + private readonly driver: BrowserDriver, + private readonly sleep: (ms: number) => Promise, + private readonly now: () => Date = () => new Date() + ) {} + + async measure(options: MeasureOptions): Promise { + const url = new URL(options.url); + if (FORBIDDEN_PATH.test(url.pathname)) { + throw new Error(`Refusing ${url.href}: measure public pages only, never wp-admin or login.`); + } + const widths = options.widths ?? [390, 768, 1440]; + const states = options.states ?? ['default', 'hover', 'focus']; + const properties = options.properties ?? DEFAULT_PROPERTIES; + const result: MeasureFile = { + url: url.href, + side: options.side, + measuredAt: this.now().toISOString(), + widths, + properties, + measurements: [], + screenshots: [], + failures: [], + }; + + try { + for (const [index, width] of widths.entries()) { + if (index > 0) { + await this.sleep(options.delayMs ?? 1500); + } + let page: PageHandle | undefined; + try { + page = await this.driver.open(url.href, width); + for (const item of options.selectors) { + result.measurements.push( + ...(await this.measureOne(page, item, width, states, properties)) + ); + } + if (options.shotsDir) { + const path = join( + options.shotsDir, + `${options.side}-${PageMeasurer.slug(url)}-${width}.png` + ); + if (await page.screenshot(path)) { + result.screenshots.push(path); + } + } + } catch (error) { + result.failures.push({ width, error: (error as Error).message }); + } finally { + await page?.close(); + } + } + } finally { + await this.driver.close(); + } + return result; + } + + private async measureOne( + page: PageHandle, + item: NamedSelector, + width: number, + states: MeasureState[], + properties: string[] + ): Promise { + const base = await page.read(item.selector, properties, 'default'); + if (!base) { + return [{ name: item.name, selector: item.selector, width, state: 'default', found: false }]; + } + const out: Measurement[] = [ + { + name: item.name, + selector: item.selector, + width, + state: 'default', + found: true, + count: base.count, + rect: base.rect, + styles: base.styles, + }, + ]; + for (const state of states) { + if (state === 'default') { + continue; + } + const reading = await page.read(item.selector, properties, state); + if (!reading) { + continue; + } + const changed = Object.fromEntries( + Object.entries(reading.styles).filter(([key, value]) => base.styles[key] !== value) + ); + if (Object.keys(changed).length) { + out.push({ + name: item.name, + selector: item.selector, + width, + state, + found: true, + styles: changed, + }); + } + } + return out; + } + + static slug(url: URL): string { + const path = url.pathname.replace(/^\/|\/$/g, ''); + return path ? path.replace(/[^a-z0-9]+/gi, '-').toLowerCase() : 'home'; + } + + /** Reads a selectors file and picks the selector for one side. */ + static selectorsFrom(json: unknown, side: Side): NamedSelector[] { + if (!json || typeof json !== 'object' || Array.isArray(json)) { + throw new Error('The selectors file must be an object of name: selector.'); + } + const out: NamedSelector[] = []; + for (const [name, value] of Object.entries(json as Record)) { + if (typeof value === 'string') { + out.push({ name, selector: value }); + } else if (value && typeof value === 'object') { + const selector = (value as Record)[side]; + if (typeof selector === 'string') { + out.push({ name, selector }); + } + } else { + throw new Error(`Selector "${name}" must be a string or { live, local }.`); + } + } + if (!out.length) { + throw new Error(`No selectors for the ${side} side.`); + } + return out; + } +} + +export interface MeasureCliDeps { + createDriver: () => Promise; + sleep: (ms: number) => Promise; + readFile: (path: string) => string; + writeFile: (path: string, content: string) => void; + makeDir: (path: string) => void; + stdout: (text: string) => void; + stderr: (text: string) => void; +} + +const USAGE = + 'Usage: measure-page --url (--selectors selectors.json | --selector ...) [--side live|local]\n' + + ' [--out measure.json] [--shots shots] [--widths 390,768,1440] [--states default,hover,focus]\n' + + ' [--props font-size,color] [--delay 1500]\n'; + +export async function runMeasureCli(argv: string[], deps: MeasureCliDeps): Promise { + const values: Record = { + side: 'live', + out: 'measure.json', + widths: '390,768,1440', + states: 'default,hover,focus', + delay: '1500', + }; + const optional = ['url', 'selectors', 'shots', 'props']; + const single: string[] = []; + try { + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--help' || arg === '-h') { + deps.stdout(USAGE); + return 0; + } + const key = arg.replace(/^--/, ''); + const value = argv[i + 1]; + if ( + !arg.startsWith('--') || + ![...optional, ...Object.keys(values), 'selector'].includes(key) + ) { + throw new Error(`Unknown argument ${arg}.`); + } + if (value === undefined) { + throw new Error(`${arg} needs a value.`); + } + i++; + if (key === 'selector') { + single.push(value); + } else { + values[key] = value; + } + } + if (!values.url) { + throw new Error('--url is required.'); + } + if (values.side !== 'live' && values.side !== 'local') { + throw new Error('--side must be live or local.'); + } + const side = values.side as Side; + const selectors: NamedSelector[] = [ + ...(values.selectors + ? PageMeasurer.selectorsFrom(JSON.parse(deps.readFile(values.selectors)), side) + : []), + ...single.map((selector) => ({ name: selector, selector })), + ]; + if (!selectors.length) { + throw new Error('Give --selectors or at least one --selector.'); + } + const states = values.states.split(',').map((s) => s.trim()) as MeasureState[]; + const unknown = states.filter((s) => !['default', 'hover', 'focus'].includes(s)); + if (unknown.length) { + throw new Error(`Unknown state ${unknown.join(', ')}.`); + } + if (values.shots) { + deps.makeDir(values.shots); + } + const measurer = new PageMeasurer(await deps.createDriver(), deps.sleep); + const result = await measurer.measure({ + url: values.url, + side, + selectors, + widths: values.widths.split(',').map(Number), + states, + properties: values.props ? values.props.split(',').map((p) => p.trim()) : undefined, + shotsDir: values.shots, + delayMs: Number(values.delay), + }); + deps.writeFile(values.out, `${JSON.stringify(result, null, 2)}\n`); + const missing = result.measurements.filter((m) => !m.found); + deps.stdout( + `Measured ${selectors.length} elements at ${result.widths.join(', ')}px into ${values.out}` + + ` (${result.screenshots.length} screenshots)\n` + ); + for (const m of missing) { + deps.stderr(`Not found at ${m.width}px: ${m.name} (${m.selector})\n`); + } + for (const f of result.failures) { + deps.stderr(`Failed at ${f.width}px: ${f.error}\n`); + } + return result.failures.length ? 1 : 0; + } catch (error) { + deps.stderr(`measure-page: ${(error as Error).message}\n`); + return 1; + } +} + +/* istanbul ignore next -- Puppeteer driver, exercised by live runs */ +export async function createPuppeteerDriver(): Promise { + const puppeteer = (await import('puppeteer')).default; + const browser = await puppeteer.launch({ headless: true }); + return { + open: async (url, width) => { + const page = await browser.newPage(); + await page.setViewport({ width, height: 900 }); + await page.goto(url, { waitUntil: 'load', timeout: 60000 }); + await page.waitForNetworkIdle({ idleTime: 500, timeout: 15000 }).catch(() => undefined); + // tsx (esbuild) can add __name() helpers to function source; define it in the page. + await page.evaluate('globalThis.__name = (f) => f'); + // Lazy-loaded images and scroll-triggered sections: scroll to the end and back. + await page.evaluate(async () => { + for (let y = 0; y < document.body.scrollHeight; y += 600) { + window.scrollTo(0, y); + await new Promise((resolve) => setTimeout(resolve, 100)); + } + window.scrollTo(0, 0); + }); + return { + read: async (selector, properties, state) => { + try { + await page.mouse.move(0, 0); + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + if (state === 'hover') { + await page.hover(selector); + } else if (state === 'focus') { + await page.focus(selector); + } + return await page.evaluate(readElement, { selector, properties }); + } catch { + return null; // Covered, hidden, not focusable or detached. + } + }, + screenshot: async (path) => { + try { + await page.screenshot({ path, fullPage: true }); + return true; + } catch { + return false; + } + }, + close: () => page.close(), + }; + }, + close: () => browser.close(), + }; +} + +/* istanbul ignore next -- thin CLI entry point */ +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + runMeasureCli(process.argv.slice(2), { + createDriver: createPuppeteerDriver, + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + readFile: (path) => readFileSync(path, 'utf8'), + writeFile: (path, content) => writeFileSync(path, content), + makeDir: (path) => mkdirSync(path, { recursive: true }), + stdout: (text) => process.stdout.write(text), + stderr: (text) => process.stderr.write(text), + }).then((code) => process.exit(code)); +} diff --git a/skills/site-to-block-theme/scripts/tsconfig.json b/skills/site-to-block-theme/scripts/tsconfig.json new file mode 100644 index 0000000000..82a9dc00aa --- /dev/null +++ b/skills/site-to-block-theme/scripts/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "types": ["node", "jest"], + "lib": ["ES2022", "DOM"] + }, + "include": ["*.ts", "lib/*.ts", "__tests__/*.ts"], + "exclude": [] +} diff --git a/skills/site-to-design-tokens/SKILL.md b/skills/site-to-design-tokens/SKILL.md index 988924d060..95648eae58 100644 --- a/skills/site-to-design-tokens/SKILL.md +++ b/skills/site-to-design-tokens/SKILL.md @@ -19,6 +19,7 @@ Nothing is written to Figma or a theme until the reviewer approves the proposal. - `figma-use`: required before running the generated script through `use_figma`. Creating a token library also uses `figma-generate-library`. - `figma-to-block-theme`: turns the export JSON (or the new Figma variables) into `theme.json` presets. +- `site-to-block-theme`: once the tokens are in `theme.json`, rebuilds the live site's templates, parts and patterns in the theme directly, without a Figma layout step. ## Workflow diff --git a/skills/site-to-figma-components/SKILL.md b/skills/site-to-figma-components/SKILL.md index b21a327045..edf1782a8f 100644 --- a/skills/site-to-figma-components/SKILL.md +++ b/skills/site-to-figma-components/SKILL.md @@ -23,6 +23,7 @@ It stops for approval between stages. Nothing is written to Figma before the rev - `audit-design-system` and `fix-design-system-finding`: the design system audit (stage 4). - `site-to-design-tokens`: must have run first. Its variables export is this skill's `--tokens` input. - `figma-to-block-theme`: reads the manifest in Pattern mode. `wp-block-themes` and `wp-patterns` cover the WordPress side. +- `site-to-block-theme`: the alternative when the rebuild copies the live site as it is. It builds the theme from live directly and skips Figma. If a companion skill is missing, say so and stop rather than calling Figma tools directly. From 31d0c42b845ef4787a8a7cc9605b6c572920136c Mon Sep 17 00:00:00 2001 From: Zared Rogers Date: Mon, 23 Nov 2026 12:00:26 +0200 Subject: [PATCH 2/2] fix(site-to-block-theme): address review findings - Changelog entry: add the PR link and keep it under 250 characters. - Fluid typography: a preset's own fluid settings turn it on when the global setting is off, and an explicit min or max skips the minimum font size limit, as in core. - Name preset and custom variables with core's _wp_to_kebab_case rules (3xl is 3-xl), and resolve var() references to every custom value. - clamp() gives the minimum priority; rgb() accepts percentage channels. - Shadows are evaluated at the element's font size and the viewport. - The diff compares each side's effective hover and focus values. - map-to-tokens and diff-measurements flag incomplete captures and exit 1. - Report tables escape pipes in preset references. - measure-page validates the URL before launching a browser, closes it on refusal, and bounds the lazy-load scroll. - SKILL.md: pass every preset slice to map-to-tokens. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- skills/site-to-block-theme/SKILL.md | 6 +- .../scripts/__tests__/css-length.test.ts | 4 + .../scripts/__tests__/map-and-diff.test.ts | 76 ++++++++++++++-- .../scripts/__tests__/measure-page.test.ts | 26 +++++- .../scripts/__tests__/theme-tokens.test.ts | 51 +++++++++++ .../scripts/__tests__/token-matcher.test.ts | 14 +++ .../scripts/diff-measurements.ts | 89 ++++++++++++++++--- .../site-to-block-theme/scripts/lib/colour.ts | 9 +- .../scripts/lib/css-length.ts | 3 +- .../scripts/lib/theme-tokens.ts | 78 +++++++++------- .../scripts/lib/token-matcher.ts | 14 +-- .../scripts/map-to-tokens.ts | 31 +++++-- .../scripts/measure-page.ts | 26 +++++- 14 files changed, 351 insertions(+), 78 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fe966ce5e..8d40a7105a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- **Site to Block Theme Skill** — Rebuilds a live site's templates, parts and patterns in a block theme to match live: measures computed styles at three widths, maps each value to theme.json tokens, builds with the official WordPress skills and proves the match with a style diff. +- **Site to Block Theme Skill** — Rebuilds live-site templates, parts and patterns in a block theme: measures live, maps values to theme.json tokens and diffs live with local. ([PR #4059](https://github.com/lightspeedwp/.github/pull/4059)) - **Theme Screenshot Skill** — Makes a theme's 1200 by 900 `screenshot.png` from the site's logo, the theme.json palette and an industry line, rendered with Puppeteer. ([#4010](https://github.com/lightspeedwp/.github/issues/4010)) - **Site to Figma Components Skill** — Rebuilds a live site's components, patterns and templates in Figma after the reviewer approves an inventory. ([#3992](https://github.com/lightspeedwp/.github/issues/3992)) - **Site to Design Tokens Skill** — For rebuilds: proposes design tokens from a live site, then creates the Figma variables and a theme.json export once approved. ([#3990](https://github.com/lightspeedwp/.github/issues/3990)) diff --git a/skills/site-to-block-theme/SKILL.md b/skills/site-to-block-theme/SKILL.md index 54cdc6570e..cf73467b31 100644 --- a/skills/site-to-block-theme/SKILL.md +++ b/skills/site-to-block-theme/SKILL.md @@ -80,9 +80,13 @@ Work in a scratch folder outside the theme. Also record what styles can't show: ```bash npx --prefix "$SITE_TO_BLOCK_THEME_REPO_ROOT" tsx ${CLAUDE_SKILL_DIR}/scripts/map-to-tokens.ts live.json \ - --theme-json /theme.json --out tokens.json --report tokens.md + --theme-json /theme.json [--theme-json /.json ...] --out tokens.json --report tokens.md ``` +Pass one `--theme-json` for `theme.json` and one for each preset slice the theme profile lists, in the order the theme merges them (later files win). A token that lives only in a slice you leave out is reported as missing. + +If any width failed to measure, the report says the capture is incomplete and the script exits with an error: re-measure first. `diff-measurements.ts` does the same when either side failed or the widths don't match. + `tokens.md` lists the values with no exact token first. For each one: - **Exact:** use the token. When several match, pick the semantic token whose role fits (`text`, `surface`, `border`), not the palette slug. diff --git a/skills/site-to-block-theme/scripts/__tests__/css-length.test.ts b/skills/site-to-block-theme/scripts/__tests__/css-length.test.ts index d6c5949bed..42548cac3f 100644 --- a/skills/site-to-block-theme/scripts/__tests__/css-length.test.ts +++ b/skills/site-to-block-theme/scripts/__tests__/css-length.test.ts @@ -28,6 +28,8 @@ describe('CssLength.toPx', () => { expect(at('min(10px, 2rem)')).toBe(10); expect(at('max(10px, 2rem)')).toBe(32); expect(at('calc(0 + 4px)')).toBe(4); + // Reversed bounds: the minimum wins. + expect(at('clamp(32px, 24px, 16px)')).toBe(32); }); it('returns null for what it cannot evaluate', () => { @@ -69,6 +71,8 @@ describe('Colour', () => { expect(Colour.hex(Colour.parse('rgb(10, 20, 30)')!)).toBe('#0a141e'); expect(Colour.parse('rgba(0 0 0 / 50%)')!.a).toBe(0.5); expect(Colour.parse('rgba(0, 0, 0, 0.2)')!.a).toBe(0.2); + expect(Colour.hex(Colour.parse('rgb(100%, 0%, 50%)')!)).toBe('#ff0080'); + expect(Colour.hex(Colour.parse('rgb(100% 0% 0% / 50%)')!)).toBe('#ff000080'); expect(Colour.parse('transparent')!.a).toBe(0); }); diff --git a/skills/site-to-block-theme/scripts/__tests__/map-and-diff.test.ts b/skills/site-to-block-theme/scripts/__tests__/map-and-diff.test.ts index 4f90ada82c..b1adc62fb1 100644 --- a/skills/site-to-block-theme/scripts/__tests__/map-and-diff.test.ts +++ b/skills/site-to-block-theme/scripts/__tests__/map-and-diff.test.ts @@ -35,7 +35,7 @@ describe('TokenMapper', () => { it('writes a report with the open decisions first', () => { const md = TokenMapper.markdown(mapper.map(live)); expect(md.indexOf('## Needs a decision')).toBeLessThan(md.indexOf('## Exact')); - expect(md).toContain('`var:preset|spacing|20` (-1px)'); + expect(md).toContain('`var:preset\\|spacing\\|20` (-1px)'); expect(md).toContain('`var(--wp--custom--color--text--default)`'); }); @@ -44,7 +44,7 @@ describe('TokenMapper', () => { measureFile([measurement({ name: 'box', styles: { padding: '10px 0px 13px' } })]) ); expect(TokenMapper.markdown(shorthand)).toContain( - '`var:preset|spacing|10` / 0 / `var:preset|spacing|10` (-3px)' + '`var:preset\\|spacing\\|10` / 0 / `var:preset\\|spacing\\|10` (-3px)' ); const clean = mapper.map( measureFile([measurement({ name: 'box', styles: { 'padding-top': '10px' } })]) @@ -75,6 +75,16 @@ describe('runMapCli', () => { expect(io.out.join('')).toContain('4 exact, 1 near, 1 with no token'); }); + it('marks an incomplete capture and exits 1', () => { + const failed = measureFile([], { failures: [{ width: 390, error: 'timeout' }] }); + const io = memoryDeps({ ...files, 'failed.json': JSON.stringify(failed) }); + expect(runMapCli(['failed.json', '--theme-json', 'theme.json'], io.deps)).toBe(1); + expect(io.written['tokens.md']).toContain( + '**Incomplete capture:** measuring failed at 390px (timeout)' + ); + expect(io.err.join('')).toContain('incomplete capture'); + }); + it('prints help', () => { const io = memoryDeps(); expect(runMapCli(['--help'], io.deps)).toBe(0); @@ -128,7 +138,22 @@ describe('MeasurementDiff', () => { 'hero heading|hover|value|color', 'new|default|missing-live|', ]); - expect(diff.find((d) => d.state === 'hover')!.local).toBe('(unchanged)'); + expect(diff.find((d) => d.state === 'hover')!.local).toBe('#0a0a0a'); + }); + + it('compares the effective hover value on each side, not the sparse changes', () => { + const liveSide = measureFile([measurement({ name: 'link', styles: { 'margin-top': '10px' } })]); + const localSide = measureFile([ + measurement({ name: 'link', styles: { 'margin-top': '20px' } }), + measurement({ name: 'link', state: 'hover', styles: { 'margin-top': '10px' } }), + ]); + const diff = new MeasurementDiff().compare(liveSide, localSide); + expect(diff.map((d) => `${d.state}|${d.property}`)).toEqual(['default|margin-top']); + const onlyHoverMissing = new MeasurementDiff().compare( + liveSide, + measureFile([measurement({ name: 'other' })]) + ); + expect(onlyHoverMissing.map((d) => d.kind)).toEqual(['missing-local', 'missing-live']); }); it('flags elements missing on local', () => { @@ -164,24 +189,65 @@ describe('MeasurementDiff', () => { }); }); +describe('MeasurementDiff.gaps', () => { + it('reports failed and one-sided widths', () => { + const a = measureFile( + [measurement({ name: 'x', width: 390 }), measurement({ name: 'x', width: 1440 })], + { + widths: [390, 768, 1440], + failures: [{ width: 768, error: 'timeout' }], + } + ); + const b = measureFile([measurement({ name: 'x', width: 390 })], { widths: [390, 1440] }); + expect(MeasurementDiff.gaps(a, b)).toEqual([ + 'live failed at 768px (timeout)', + '1440px measured on live only', + ]); + expect( + MeasurementDiff.gaps(b, measureFile([], { failures: [{ width: 390, error: 'x' }] })) + ).toEqual([ + 'local failed at 390px (x)', + '390px measured on live only', + 'no measurements on local', + ]); + expect(MeasurementDiff.gaps(measureFile([]), b)).toContain('no measurements on live'); + }); +}); + describe('runDiffCli', () => { const files = { 'live.json': JSON.stringify(live), 'local.json': JSON.stringify(measureFile([], { side: 'local' })), + 'local-full.json': JSON.stringify( + measureFile([measurement({ name: 'hero heading' })], { side: 'local' }) + ), }; it('writes the diff and report', () => { const io = memoryDeps(files); expect( runDiffCli( - ['live.json', 'local.json', '--tolerance', '2', '--out', 'd.json', '--report', 'd.md'], + ['live.json', 'local-full.json', '--tolerance', '2', '--out', 'd.json', '--report', 'd.md'], io.deps ) ).toBe(0); - expect(JSON.parse(io.written['d.json'])[0].kind).toBe('missing-local'); + const written = JSON.parse(io.written['d.json']); + expect(written.gaps).toEqual([]); + expect(written.differences.map((d: { kind: string }) => d.kind)).toContain('value'); expect(io.written['d.md']).toContain('# Differences from live'); }); + it('writes an incomplete report and exits 1 when a capture is incomplete', () => { + const io = memoryDeps(files); + expect(runDiffCli(['live.json', 'local.json'], io.deps)).toBe(1); + expect(io.written['diff.md']).toContain('**Incomplete comparison:**'); + expect(io.written['diff.md']).toContain('no measurements on local'); + expect(MeasurementDiff.markdown(live, live, [], ['live failed at 390px (x)'])).toContain( + 'No differences in what was compared.' + ); + expect(io.err.join('')).toContain('incomplete comparison'); + }); + it('prints help', () => { const io = memoryDeps(); expect(runDiffCli(['-h'], io.deps)).toBe(0); diff --git a/skills/site-to-block-theme/scripts/__tests__/measure-page.test.ts b/skills/site-to-block-theme/scripts/__tests__/measure-page.test.ts index bafc782cf9..0dec6fd7d4 100644 --- a/skills/site-to-block-theme/scripts/__tests__/measure-page.test.ts +++ b/skills/site-to-block-theme/scripts/__tests__/measure-page.test.ts @@ -147,12 +147,15 @@ describe('PageMeasurer', () => { expect(result.measurements).toHaveLength(1); }); - it('refuses wp-admin and login pages', async () => { - const measurer = new PageMeasurer(new FakeDriver(), noSleep); + it('refuses wp-admin and login pages, and closes the browser', async () => { for (const url of ['https://example.com/wp-admin/', 'https://example.com/wp-login.php?x=1']) { + const driver = new FakeDriver(); + const measurer = new PageMeasurer(driver, noSleep); await expect(measurer.measure({ url, side: 'live', selectors: [] })).rejects.toThrow( 'Refusing' ); + expect(driver.closed).toBe(true); + expect(driver.opened).toEqual([]); } }); @@ -187,17 +190,32 @@ describe('runMeasureCli', () => { ) => { const io = memoryDeps(files); const dirs: string[] = []; + let launched = 0; const code = await runMeasureCli(argv, { ...io.deps, - createDriver: async () => driver, + createDriver: async () => { + launched++; + return driver; + }, sleep: noSleep, makeDir: (path) => { dirs.push(path); }, }); - return { code, io, dirs }; + return { code, io, dirs, launched }; }; + it('never launches a browser for a refused URL', async () => { + const { code, launched } = await run([ + '--url', + 'https://e.com/wp-login.php', + '--selector', + '.a', + ]); + expect(code).toBe(1); + expect(launched).toBe(0); + }); + it('measures from a selectors file and single selectors', async () => { const { code, io, dirs } = await run( [ diff --git a/skills/site-to-block-theme/scripts/__tests__/theme-tokens.test.ts b/skills/site-to-block-theme/scripts/__tests__/theme-tokens.test.ts index 022de9e1af..982bed1e8d 100644 --- a/skills/site-to-block-theme/scripts/__tests__/theme-tokens.test.ts +++ b/skills/site-to-block-theme/scripts/__tests__/theme-tokens.test.ts @@ -26,6 +26,10 @@ describe('ThemeTokens', () => { expect(token('--wp--custom--line-height--normal').family).toBe('line-height'); expect(theme.tokens.some((t) => t.cssVar.includes('motion'))).toBe(false); expect(ThemeTokens.kebab('scrollArrowSize')).toBe('scroll-arrow-size'); + expect(ThemeTokens.kebab('3xl')).toBe('3-xl'); + expect(ThemeTokens.kebab('brand-500')).toBe('brand-500'); + expect(ThemeTokens.kebab('h1')).toBe('h-1'); + expect(ThemeTokens.kebab('XLHeading')).toBe('xl-heading'); }); it('resolves var() chains and fallbacks', () => { @@ -101,6 +105,53 @@ describe('ThemeTokens', () => { expect(plain.lengthPx(plain.list('font-size')[0], 390)).toBe(32); }); + it('names preset variables the way core does', () => { + const named = ThemeTokens.fromThemeJson([ + { settings: { typography: { fontSizes: [{ slug: '3xl', size: '3rem' }] } } }, + ]); + expect(named.list('font-size')[0]).toMatchObject({ + cssVar: '--wp--preset--font-size--3-xl', + preset: 'var:preset|font-size|3xl', + }); + }); + + it('resolves references to custom values outside the token families', () => { + const custom = ThemeTokens.fromThemeJson([ + { + settings: { + custom: { sizes: { gutter: '24px' } }, + spacing: { spacingSizes: [{ slug: 'g', size: 'var(--wp--custom--sizes--gutter)' }] }, + }, + }, + ]); + expect(custom.tokens.some((t) => t.cssVar.includes('sizes'))).toBe(false); + expect(custom.lengthPx(custom.list('spacing')[0], 1440)).toBe(24); + }); + + it('honours preset fluid settings when global fluid typography is off', () => { + const preset = ThemeTokens.fromThemeJson([ + { + settings: { + typography: { + fontSizes: [ + { slug: 'a', size: '32px', fluid: { min: '20px', max: '32px' } }, + { slug: 'b', size: '12px', fluid: { max: '16px' } }, + { slug: 'c', size: '32px', fluid: {} }, + ], + }, + }, + }, + ]); + const [a, b, c] = preset.list('font-size'); + expect(preset.fontSizePx(a, 320)).toBe(20); + expect(preset.fontSizePx(a, 1600)).toBe(32); + // An explicit max skips the 14px minimum font size limit; the calculated minimum is floored at 14px. + expect(preset.fontSizePx(b, 1600)).toBe(16); + expect(preset.fontSizePx(b, 320)).toBe(14); + // An empty fluid object does not turn fluid typography on. + expect(preset.fontSizePx(c, 320)).toBe(32); + }); + it('merges several documents, later ones replacing presets by slug', () => { const merged = ThemeTokens.fromThemeJson([ themeJson, diff --git a/skills/site-to-block-theme/scripts/__tests__/token-matcher.test.ts b/skills/site-to-block-theme/scripts/__tests__/token-matcher.test.ts index 4390165efb..21cb526f53 100644 --- a/skills/site-to-block-theme/scripts/__tests__/token-matcher.test.ts +++ b/skills/site-to-block-theme/scripts/__tests__/token-matcher.test.ts @@ -144,6 +144,20 @@ describe('TokenMatcher', () => { expect(empty.match('font-weight', '400', 1440)).toMatchObject({ status: 'none' }); }); + it('evaluates shadow lengths at the element font size and viewport', () => { + const em = new TokenMatcher( + ThemeTokens.fromThemeJson([ + { settings: { shadow: { presets: [{ slug: 'a', shadow: '0 1em 0 #000' }] } } }, + ]) + ); + expect( + em.match('box-shadow', 'rgb(0, 0, 0) 0px 20px 0px 0px', 390, { 'font-size': '20px' }).status + ).toBe('exact'); + expect( + em.match('box-shadow', 'rgb(0, 0, 0) 0px 20px 0px 0px', 390, { 'font-size': '16px' }).status + ).toBe('none'); + }); + it('splits on top-level commas only', () => { expect(TokenMatcher.splitTopLevel('a(1, 2), b')).toEqual(['a(1, 2)', ' b']); }); diff --git a/skills/site-to-block-theme/scripts/diff-measurements.ts b/skills/site-to-block-theme/scripts/diff-measurements.ts index f478f4a925..687f09a3ae 100644 --- a/skills/site-to-block-theme/scripts/diff-measurements.ts +++ b/skills/site-to-block-theme/scripts/diff-measurements.ts @@ -50,8 +50,26 @@ export class MeasurementDiff { const ref = (a ?? b) as Measurement; const base = { name: ref.name, width: ref.width, state: ref.state }; if (ref.state !== 'default') { - // Hover and focus entries hold only what changed; a missing entry means no change. - differences.push(...this.compareStyles(base, a?.styles ?? {}, b?.styles ?? {})); + // Hover and focus entries hold only what changed. Compare each side's effective value: + // its own default with its own change on top. + const defaultKey = `${ref.name}|${ref.width}|default`; + const liveDefault = liveIndex.get(defaultKey); + const localDefault = localIndex.get(defaultKey); + if (!liveDefault?.found || !localDefault?.found) { + continue; // Already reported as missing. + } + const changed = [ + ...new Set([...Object.keys(a?.styles ?? {}), ...Object.keys(b?.styles ?? {})]), + ]; + const effective = (defaults: Measurement, delta?: Measurement) => + Object.fromEntries( + changed + .map((p) => [p, delta?.styles?.[p] ?? defaults.styles?.[p]]) + .filter((entry): entry is [string, string] => entry[1] !== undefined) + ); + differences.push( + ...this.compareStyles(base, effective(liveDefault, a), effective(localDefault, b)) + ); continue; } if (!a?.found || !b?.found) { @@ -128,17 +146,55 @@ export class MeasurementDiff { return x.toLowerCase() === y.toLowerCase(); } - static markdown(live: MeasureFile, local: MeasureFile, differences: Difference[]): string { - const lines = [ - '# Differences from live', - '', - `Live: ${live.url} · Local: ${local.url}`, - '', + /** + * Why the two captures can't be fully compared: widths that failed on + * either side, or widths measured on one side only. Empty when complete. + */ + static gaps(live: MeasureFile, local: MeasureFile): string[] { + const gaps: string[] = []; + for (const [side, file] of [ + ['live', live], + ['local', local], + ] as const) { + for (const f of file.failures ?? []) { + gaps.push(`${side} failed at ${f.width}px (${f.error})`); + } + } + const measured = (file: MeasureFile) => new Set(file.measurements.map((m) => m.width)); + const liveWidths = measured(live); + const localWidths = measured(local); + for (const width of [...new Set([...live.widths, ...local.widths])].sort((x, y) => x - y)) { + if (liveWidths.has(width) !== localWidths.has(width)) { + gaps.push(`${width}px measured on ${liveWidths.has(width) ? 'live' : 'local'} only`); + } + } + if (!live.measurements.length || !local.measurements.length) { + gaps.push(`no measurements on ${live.measurements.length ? 'local' : 'live'}`); + } + return gaps; + } + + static markdown( + live: MeasureFile, + local: MeasureFile, + differences: Difference[], + gaps: string[] = [] + ): string { + const lines = ['# Differences from live', '', `Live: ${live.url} · Local: ${local.url}`, '']; + if (gaps.length) { + lines.push( + `**Incomplete comparison:** ${gaps.join('; ')}. Re-measure before relying on this report.`, + '' + ); + } + lines.push( differences.length ? `${differences.length} differences. Fix each one, or keep it and say why (for example, the nearest token was used).` - : 'No differences found within tolerance.', - '', - ]; + : gaps.length + ? 'No differences in what was compared.' + : 'No differences found within tolerance.', + '' + ); if (differences.length) { lines.push( '| Element | Width | State | Property | Live | Local |', @@ -153,7 +209,7 @@ export class MeasurementDiff { ? 'missing on local' : 'missing on live'; lines.push( - `| ${d.name} | ${d.width} | ${d.state} | ${property} | ${cell(d.live)} | ${cell(d.local)} |` + `| ${d.name.replace(/\|/g, '\\|')} | ${d.width} | ${d.state} | ${property} | ${cell(d.live)} | ${cell(d.local)} |` ); } lines.push(''); @@ -205,8 +261,13 @@ export function runDiffCli(argv: string[], deps: DiffCliDeps): number { } const [live, local] = files.map((f) => JSON.parse(deps.readFile(f)) as MeasureFile); const differences = new MeasurementDiff(tolerance).compare(live, local); - deps.writeFile(values.out, `${JSON.stringify(differences, null, 2)}\n`); - deps.writeFile(values.report, MeasurementDiff.markdown(live, local, differences)); + const gaps = MeasurementDiff.gaps(live, local); + deps.writeFile(values.out, `${JSON.stringify({ gaps, differences }, null, 2)}\n`); + deps.writeFile(values.report, MeasurementDiff.markdown(live, local, differences, gaps)); + if (gaps.length) { + deps.stderr(`diff-measurements: incomplete comparison: ${gaps.join('; ')}. Re-measure.\n`); + return 1; + } deps.stdout(`${differences.length} differences. Wrote ${values.out} and ${values.report}\n`); return 0; } catch (error) { diff --git a/skills/site-to-block-theme/scripts/lib/colour.ts b/skills/site-to-block-theme/scripts/lib/colour.ts index 20f014cc6e..741ad9646a 100644 --- a/skills/site-to-block-theme/scripts/lib/colour.ts +++ b/skills/site-to-block-theme/scripts/lib/colour.ts @@ -45,17 +45,20 @@ export class Colour { if (parts.length < 3) { return null; } - const [r, g, b] = parts.slice(0, 3).map(Number); + // Channels are 0 to 255 or a percentage; alpha is 0 to 1 or a percentage. + const channel = (part: string) => + part.endsWith('%') ? Number(part.slice(0, -1)) / 100 : Number(part) / 255; + const [r, g, b] = parts.slice(0, 3).map(channel); const alpha = parts[3] === undefined ? 1 : parts[3].endsWith('%') - ? parseFloat(parts[3]) / 100 + ? Number(parts[3].slice(0, -1)) / 100 : Number(parts[3]); if ([r, g, b, alpha].some((n) => !Number.isFinite(n))) { return null; } - return { r: r / 255, g: g / 255, b: b / 255, a: alpha }; + return { r, g, b, a: alpha }; } static hex(c: Rgba): string { diff --git a/skills/site-to-block-theme/scripts/lib/css-length.ts b/skills/site-to-block-theme/scripts/lib/css-length.ts index 47866e1828..fd00089159 100644 --- a/skills/site-to-block-theme/scripts/lib/css-length.ts +++ b/skills/site-to-block-theme/scripts/lib/css-length.ts @@ -202,7 +202,8 @@ class Parser { if (args.length !== 3) { throw new Error('clamp() takes three arguments.'); } - return { n: Math.min(Math.max(values[1], values[0]), values[2]), length }; + // CSS: the minimum wins when the bounds are reversed. + return { n: Math.max(values[0], Math.min(values[1], values[2])), length }; } private convert(value: number, unit: string): Value { diff --git a/skills/site-to-block-theme/scripts/lib/theme-tokens.ts b/skills/site-to-block-theme/scripts/lib/theme-tokens.ts index a00ea2ff08..209ca5fd07 100644 --- a/skills/site-to-block-theme/scripts/lib/theme-tokens.ts +++ b/skills/site-to-block-theme/scripts/lib/theme-tokens.ts @@ -53,16 +53,12 @@ const isObject = (value: unknown): value is Json => typeof value === 'object' && value !== null && !Array.isArray(value); export class ThemeTokens { - private readonly byVar = new Map(); - private constructor( private readonly settings: Json, - readonly tokens: Token[] - ) { - for (const token of tokens) { - this.byVar.set(token.cssVar, token); - } - } + readonly tokens: Token[], + /** Every CSS variable the theme emits (presets and all custom values), for var() resolution. */ + private readonly references: Map + ) {} /** Builds the tokens from one or more theme.json documents. Later documents win. */ static fromThemeJson(documents: unknown[]): ThemeTokens { @@ -72,11 +68,18 @@ export class ThemeTokens { settings = ThemeTokens.merge(settings, doc.settings); } } - return new ThemeTokens(settings, ThemeTokens.collect(settings)); + const { tokens, references } = ThemeTokens.collect(settings); + return new ThemeTokens(settings, tokens, references); } + /** + * WordPress core's _wp_to_kebab_case(), which names preset and custom CSS + * variables: words, runs of capitals and runs of digits joined with hyphens, + * so `fontWeight` is `font-weight` and `3xl` is `3-xl`. + */ static kebab(key: string): string { - return key.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase(); + const words = key.replace(/'/g, '').match(/[A-Z]?[a-z]+|[A-Z]+(?![a-z])|\d+/g) ?? []; + return words.join('-').toLowerCase(); } list(family: Family): Token[] { @@ -91,9 +94,9 @@ export class ThemeTokens { const replaced = raw.replace( /var\(\s*(--[a-z0-9-]+)\s*(?:,\s*([^()]*(?:\([^()]*\))?[^()]*))?\)/gi, (match, name: string, fallback?: string) => { - const token = this.byVar.get(name.toLowerCase()); - if (token) { - return token.raw; + const value = this.references.get(name.toLowerCase()); + if (value !== undefined) { + return value; } return fallback !== undefined ? fallback.trim() : match; } @@ -127,7 +130,13 @@ export class ThemeTokens { } const typography = isObject(this.settings.typography) ? this.settings.typography : {}; const fluid = typography.fluid; - if (!fluid || token.fluid === false || /clamp|calc|min\(|max\(|vw/.test(token.raw)) { + // Core: off when the preset says false, or when neither the global setting nor the preset turns it on. + const presetFluid = isObject(token.fluid) ? Object.keys(token.fluid).length > 0 : token.fluid; + if ( + token.fluid === false || + (!fluid && !presetFluid) || + /clamp|calc|min\(|max\(|vw/.test(token.raw) + ) { return size; } const fluidSettings = isObject(fluid) ? fluid : {}; @@ -140,14 +149,15 @@ export class ThemeTokens { const limit = px(fluidSettings.minFontSize, 14); const own = isObject(token.fluid) ? token.fluid : {}; + // Core skips the minimum font size limit when the preset sets its own min or max. + if (!own.min && !own.max && size <= limit) { + return size; + } const max = own.max ? px(own.max, size) : size; let min: number; if (own.min) { min = px(own.min, size); } else { - if (size <= limit) { - return size; - } const factor = Math.min(Math.max(1 - 0.075 * Math.log2(size), 0.25), 0.75); const calculated = Math.round(size * factor * 1000) / 1000; min = calculated <= limit ? limit : calculated; @@ -179,8 +189,9 @@ export class ThemeTokens { return out; } - private static collect(settings: Json): Token[] { + private static collect(settings: Json): { tokens: Token[]; references: Map } { const tokens: Token[] = []; + const references = new Map(); const section = (key: string): Json => (isObject(settings[key]) ? settings[key] : {}); const presets = ( items: unknown, @@ -203,7 +214,7 @@ export class ThemeTokens { const token: Token = { family, slug: item.slug, - cssVar: `--wp--preset--${cssGroup}--${item.slug}`, + cssVar: `--wp--preset--${cssGroup}--${ThemeTokens.kebab(item.slug)}`, preset: `var:preset|${cssGroup}|${item.slug}`, raw: String(raw), semantic: false, @@ -212,6 +223,7 @@ export class ThemeTokens { token.fluid = item.fluid as Token['fluid']; } tokens.push(token); + references.set(token.cssVar, token.raw); } }; @@ -222,7 +234,8 @@ export class ThemeTokens { presets(section('border').radiusSizes, 'radius', 'border-radius', 'size'); presets(section('shadow').presets, 'shadow', 'shadow', 'shadow'); - const walk = (node: unknown, path: string[], family: Family) => { + // Every custom value is a CSS variable other values can reference; only known families become tokens. + const walk = (node: unknown, path: string[], family: Family | undefined) => { if (isObject(node)) { for (const [key, value] of Object.entries(node)) { walk(value, [...path, ThemeTokens.kebab(key)], family); @@ -232,21 +245,22 @@ export class ThemeTokens { if (typeof node !== 'string' && typeof node !== 'number') { return; } - tokens.push({ - family, - slug: path.slice(1).join('--'), - cssVar: `--wp--custom--${path.join('--')}`, - raw: String(node), - semantic: true, - }); + const cssVar = `--wp--custom--${path.join('--')}`; + references.set(cssVar, String(node)); + if (family) { + tokens.push({ + family, + slug: path.slice(1).join('--'), + cssVar, + raw: String(node), + semantic: true, + }); + } }; for (const [key, value] of Object.entries(section('custom'))) { const name = ThemeTokens.kebab(key); - const family = CUSTOM_FAMILIES[name]; - if (family) { - walk(value, [name], family); - } + walk(value, [name], CUSTOM_FAMILIES[name]); } - return tokens; + return { tokens, references }; } } diff --git a/skills/site-to-block-theme/scripts/lib/token-matcher.ts b/skills/site-to-block-theme/scripts/lib/token-matcher.ts index 9081b3701d..5af5d5ce20 100644 --- a/skills/site-to-block-theme/scripts/lib/token-matcher.ts +++ b/skills/site-to-block-theme/scripts/lib/token-matcher.ts @@ -82,7 +82,7 @@ export class TokenMatcher { case 'font-family': return this.matchFontFamily(text); case 'shadow': - return this.matchShadow(text); + return this.matchShadow(text, viewport, fontSize); case 'font-weight': return this.matchNumber(family, Number(text), 0, (t) => Number(this.theme.resolve(t.raw))); case 'line-height': @@ -152,11 +152,13 @@ export class TokenMatcher { }; } - private matchShadow(text: string): Match { - const wanted = this.normaliseShadow(text); + private matchShadow(text: string, viewport: number, fontSize?: number): Match { + const wanted = this.normaliseShadow(text, viewport, fontSize); const tokens = this.theme .list('shadow') - .filter((t) => this.normaliseShadow(this.theme.resolve(t.raw)) === wanted); + .filter( + (t) => this.normaliseShadow(this.theme.resolve(t.raw), viewport, fontSize) === wanted + ); if (tokens.length) { return { family: 'shadow', status: 'exact', tokens: tokens.map(TokenMatcher.ref) }; } @@ -164,7 +166,7 @@ export class TokenMatcher { } /** One string per layer: inset flag, lengths in px and the colour as hex. Order-insensitive within a layer. */ - normaliseShadow(text: string): string { + normaliseShadow(text: string, viewport = 1440, fontSize?: number): string { return TokenMatcher.splitTopLevel(text) .map((layer) => { let rest = layer.trim().toLowerCase(); @@ -179,7 +181,7 @@ export class TokenMatcher { .trim() .split(/\s+/) .filter(Boolean) - .map((part) => CssLength.toPx(part, { viewport: 1440 }) ?? NaN); + .map((part) => CssLength.toPx(part, { viewport, fontSize }) ?? NaN); while (lengths.length < 4) { lengths.push(0); } diff --git a/skills/site-to-block-theme/scripts/map-to-tokens.ts b/skills/site-to-block-theme/scripts/map-to-tokens.ts index cd3c58edfe..114a74e3d3 100644 --- a/skills/site-to-block-theme/scripts/map-to-tokens.ts +++ b/skills/site-to-block-theme/scripts/map-to-tokens.ts @@ -31,6 +31,8 @@ export interface MappingRow { export interface Mapping { url: string; + /** Widths whose capture failed: the mapping is incomplete when this is not empty. */ + failures: { width: number; error: string }[]; counts: Record; rows: MappingRow[]; } @@ -61,12 +63,14 @@ export class TokenMapper { for (const row of rows) { counts[row.match.status]++; } - return { url: measure.url, counts, rows }; + return { url: measure.url, failures: measure.failures ?? [], counts, rows }; } static markdown(mapping: Mapping): string { + // GitHub tables split on pipes even inside code spans, and every preset reference has them. + const cell = (text: string) => text.replace(/\|/g, '\\|'); const tokenText = (refs: TokenRef[]) => - refs.length ? refs.map((r) => `\`${r.preset ?? `var(${r.cssVar})`}\``).join(', ') : '-'; + refs.length ? refs.map((r) => `\`${cell(r.preset ?? `var(${r.cssVar})`)}\``).join(', ') : '-'; const matchText = (match: Match): string => match.parts ? match.parts @@ -76,21 +80,26 @@ export class TokenMapper { .join(' / ') : `${tokenText(match.tokens)}${match.delta ? ` (${match.delta})` : ''}`; const row = (r: MappingRow) => - `| ${r.name} | ${r.width} | ${r.state} | ${r.property} | \`${r.value.replace(/\|/g, '\\|')}\` | ${r.match.status} | ${matchText(r.match)} |`; + `| ${cell(r.name)} | ${r.width} | ${r.state} | ${r.property} | \`${cell(r.value)}\` | ${r.match.status} | ${matchText(r.match)} |`; const header = '| Element | Width | State | Property | Live value | Match | Token |\n| --- | --- | --- | --- | --- | --- | --- |'; const open = mapping.rows.filter((r) => r.match.status !== 'exact'); const exact = mapping.rows.filter((r) => r.match.status === 'exact'); - const lines = [ - `# Token mapping: ${mapping.url}`, - '', + const lines = [`# Token mapping: ${mapping.url}`, '']; + if (mapping.failures.length) { + lines.push( + `**Incomplete capture:** measuring failed at ${mapping.failures.map((f) => `${f.width}px (${f.error})`).join(', ')}. Re-measure before relying on this report.`, + '' + ); + } + lines.push( `${mapping.counts.exact} exact, ${mapping.counts.near} near, ${mapping.counts.none} with no token.`, '', 'Exact matches list every token with that value, semantic tokens first: pick the one whose role fits.', '', '## Needs a decision', - '', - ]; + '' + ); if (open.length) { lines.push( 'Use the nearest token and list it under "Differences from live", or propose a new token for approval. Never hardcode the value.', @@ -163,6 +172,12 @@ export function runMapCli(argv: string[], deps: MapCliDeps): number { const mapping = new TokenMapper(new TokenMatcher(theme)).map(measure); deps.writeFile(out, `${JSON.stringify(mapping, null, 2)}\n`); deps.writeFile(report, TokenMapper.markdown(mapping)); + if (mapping.failures.length) { + deps.stderr( + `map-to-tokens: incomplete capture, measuring failed at ${mapping.failures.map((f) => `${f.width}px`).join(', ')}. Re-measure.\n` + ); + return 1; + } deps.stdout( `${mapping.counts.exact} exact, ${mapping.counts.near} near, ${mapping.counts.none} with no token. Wrote ${out} and ${report}\n` ); diff --git a/skills/site-to-block-theme/scripts/measure-page.ts b/skills/site-to-block-theme/scripts/measure-page.ts index 79cd28ed7e..6ecc6db14b 100644 --- a/skills/site-to-block-theme/scripts/measure-page.ts +++ b/skills/site-to-block-theme/scripts/measure-page.ts @@ -163,11 +163,23 @@ export class PageMeasurer { private readonly now: () => Date = () => new Date() ) {} - async measure(options: MeasureOptions): Promise { - const url = new URL(options.url); + /** Parses the URL and refuses admin and login pages. Call it before launching a browser. */ + static checkUrl(value: string): URL { + const url = new URL(value); if (FORBIDDEN_PATH.test(url.pathname)) { throw new Error(`Refusing ${url.href}: measure public pages only, never wp-admin or login.`); } + return url; + } + + async measure(options: MeasureOptions): Promise { + let url: URL; + try { + url = PageMeasurer.checkUrl(options.url); + } catch (error) { + await this.driver.close(); + throw error; + } const widths = options.widths ?? [390, 768, 1440]; const states = options.states ?? ['default', 'hover', 'focus']; const properties = options.properties ?? DEFAULT_PROPERTIES; @@ -365,6 +377,8 @@ export async function runMeasureCli(argv: string[], deps: MeasureCliDeps): Promi if (unknown.length) { throw new Error(`Unknown state ${unknown.join(', ')}.`); } + // Validate before launching the browser, so a refused URL never starts Chromium. + PageMeasurer.checkUrl(values.url); if (values.shots) { deps.makeDir(values.shots); } @@ -411,8 +425,14 @@ export async function createPuppeteerDriver(): Promise { // tsx (esbuild) can add __name() helpers to function source; define it in the page. await page.evaluate('globalThis.__name = (f) => f'); // Lazy-loaded images and scroll-triggered sections: scroll to the end and back. + // Bounded, so an infinite-scroll page can't hold the width until the protocol times out. await page.evaluate(async () => { - for (let y = 0; y < document.body.scrollHeight; y += 600) { + const started = Date.now(); + for ( + let y = 0; + y < Math.min(document.body.scrollHeight, 30000) && Date.now() - started < 10000; + y += 600 + ) { window.scrollTo(0, y); await new Promise((resolve) => setTimeout(resolve, 100)); }