diff --git a/CHANGELOG.md b/CHANGELOG.md index bd332f2344..e3b8d1c734 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,6 +73,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Site to Figma Components Manifest** — Templates now follow the sections built in Figma, keep each section's own text and flag files already in the theme. ([#3992](https://github.com/lightspeedwp/.github/issues/3992)) - **Label inventory token** — The organisation label inventory now needs its own dedicated token, refuses the GitHub Actions token and fails when private repositories are missing. (#3734) - **Private Repositories Stay Out Of Public Reports** — The label inventory and the weekly drift report now count private repositories without naming them or listing their labels. Detail goes to a private repository when one is set. (#3734) - **Dependabot Merge Queue Fixed** — Dependabot pull requests no longer fail the Mergify queue check, because the queue now tests each pull request in place. ([PR #3817](https://github.com/lightspeedwp/.github/pull/3817)) diff --git a/skills/figma-to-block-theme/references/patterns.md b/skills/figma-to-block-theme/references/patterns.md index 70662b6c71..3c9c06d0ff 100644 --- a/skills/figma-to-block-theme/references/patterns.md +++ b/skills/figma-to-block-theme/references/patterns.md @@ -85,10 +85,18 @@ Show this, then ask `Approve this plan and proceed with implementation?`: A rebuild that ran `site-to-figma-components` hands over `manifest.json`. Use it instead of choosing nodes, names and targets by hand: -1. Work through `entries` in order: components, template parts, patterns, then templates, so styles exist before the patterns that use them. Skip `skipped` entries. -2. For each entry, read `figma.nodeId` (and `figma.mobileNodeId` for the 390px layout) through `figma-design-to-code`, then follow steps 2 to 9 above. -3. Use the targets as given: `wordpress.file` as the path, `wordpress.slug` as the pattern or part slug, `wordpress.block` as the main block, and `wordpress.styles` as the block styles to create. The plan can question a target, but don't rename silently. -4. Write templates last, from `composition`: `` for parts, `` for patterns, and inline blocks for `local` entries. +1. Run Variables mode first if the Figma variables changed during the build. The design context names presets such as a new font family, and they must exist in `theme.json` before a pattern uses them. +2. Work through `entries` in order: components, template parts, patterns, then templates, so styles exist before the patterns that use them. Skip `skipped` entries, and read `warnings` into the plan. +3. For each entry, read `figma.nodeId` (and `figma.mobileNodeId` for the 390px layout) through `figma-design-to-code`, then follow steps 2 to 9 above. If the Figma server asks whether to set up Code Connect, put the question to the user once for the whole manifest; don't stop at each entry. +4. Use the targets as given: `wordpress.file` as the path, `wordpress.slug` as the pattern or part slug, `wordpress.block` as the main block, and `wordpress.styles` as the block styles to create. The plan can question a target, but don't rename silently. +5. When `wordpress.existsInTheme` is set, the file already holds something else (often a scaffold pattern with the same slug). The plan says whether to replace it or rename the new one. Never leave the old file in place and reference it from a template. +6. Write templates last, from `composition`: + - `` for the header part + - `` for the footer part; use each part's matching landmark tag + - `` for patterns without `overrides` + - the pattern's blocks inline, with every override value applied to its matching text, for an instance with `overrides` (a pattern reference can't change its content, so four card grids would otherwise share one heading) + - inline blocks for `local` entries + - everything between the header and footer parts wrapped in ``, so the template has a main landmark ## Checklist diff --git a/skills/site-to-figma-components/SKILL.md b/skills/site-to-figma-components/SKILL.md index b21a327045..7ca557f74f 100644 --- a/skills/site-to-figma-components/SKILL.md +++ b/skills/site-to-figma-components/SKILL.md @@ -68,10 +68,10 @@ Compare each frame with the live page at both widths, list the differences, and ```bash npx --prefix "$SITE_TO_FIGMA_REPO_ROOT" tsx ${CLAUDE_SKILL_DIR}/scripts/write-manifest.ts inventory.json --nodes figma-nodes.json \ - --out manifest.json --markdown manifest.md + --out manifest.json --markdown manifest.md --theme-dir path/to/theme ``` -Add `--partial` while only some items are built. Hand `manifest.json` to `figma-to-block-theme` Pattern mode and post `manifest.md` on the project's Linear issue. See [references/manifest.md](references/manifest.md). +Record each template's built `composition` first (see [references/figma-build.md](references/figma-build.md#record-node-ids)). `--theme-dir` flags targets that already exist in the theme. Add `--partial` while only some items are built. Hand `manifest.json` to `figma-to-block-theme` Pattern mode and post `manifest.md` on the project's Linear issue. See [references/manifest.md](references/manifest.md). ## Rules diff --git a/skills/site-to-figma-components/references/figma-build.md b/skills/site-to-figma-components/references/figma-build.md index f812257e63..7b354d90c3 100644 --- a/skills/site-to-figma-components/references/figma-build.md +++ b/skills/site-to-figma-components/references/figma-build.md @@ -36,6 +36,33 @@ Use real site content throughout: headings, labels, excerpts, meta and images fr After each call, add the IDs to `figma-nodes.json`: the component set for components; the set and its `Breakpoint=Mobile` variant (`mobileNodeId`) for parts and patterns; the 1440 frame and the 390 frame for templates. See [manifest.md](manifest.md). +When a template is final, record its `composition` with one read-only call. Each built component's description names its inventory ID (`Inventory id pattern:card-grid`), so the sections map back without guessing: + +```js +const frame = await figma.getNodeByIdAsync('TEMPLATE_FRAME_ID'); +const out = []; +for (const child of frame.children) { + if (child.type !== 'INSTANCE') { out.push({ id: `local:${child.name}` }); continue; } + const main = await child.getMainComponentAsync(); + if (!main) { out.push({ id: `unknown:${child.id}` }); continue; } + const owner = main.parent?.type === 'COMPONENT_SET' ? main.parent : main; + const id = /Inventory id ([\w:-]+)/.exec(owner.description)?.[1] ?? `unknown:${owner.name}`; + const overrides = {}; + const definitions = owner.componentPropertyDefinitions; + for (const [name, property] of Object.entries(child.componentProperties)) { + if (property.type === 'TEXT' && property.value !== definitions[name]?.defaultValue) { + overrides[name] = property.value; + } + } + out.push(Object.keys(overrides).length ? { id, overrides } : id); +} +return out; +``` + +Expose every overridable text node as a `TEXT` component property, including nested text needed by templates. Compare all exposed text properties with their source defaults and keep the full property names (including Figma's ID suffix) as override keys, so repeated labels stay distinct. Pattern mode must apply every recorded value to its matching property when writing inline blocks. + +Resolve any `unknown:` or `local:` entry before writing the manifest. An instance whose main component is unavailable is recorded as `unknown:` for review; the scan continues. Resolve local sections to identified inventory items (cut items remain local in the manifest). + ## Archive, never delete `node.remove()` is blocked. Move superseded items to an archive page, grouped in sections, and check the destinations of prototype links before moving anything. diff --git a/skills/site-to-figma-components/references/manifest.md b/skills/site-to-figma-components/references/manifest.md index acaeafe36a..30fd64903d 100644 --- a/skills/site-to-figma-components/references/manifest.md +++ b/skills/site-to-figma-components/references/manifest.md @@ -12,13 +12,25 @@ Assemble it from the IDs each `use_figma` build call returns: "nodes": { "component:button": { "nodeId": "14100:200", "page": "> Components" }, "part:header": { "nodeId": "14100:310", "mobileNodeId": "14100:340" }, - "template:single-tour": { "nodeId": "14101:12", "mobileNodeId": "14101:900" } + "template:front-page": { + "nodeId": "14101:12", + "mobileNodeId": "14101:900", + "composition": [ + "part:header", + "pattern:hero", + { "id": "pattern:card-grid", "overrides": { "heading": "Our Safari Styles" } }, + { "id": "pattern:card-grid", "overrides": { "heading": "Featured Tours" } }, + "part:footer" + ] + } } } ``` Use the component set's ID for components, and the 1440px frame (`nodeId`) and 390px frame (`mobileNodeId`) for parts, patterns and templates. +For each template, record `composition`: the built frame's sections in order, read from Figma with the snippet in [figma-build.md](figma-build.md#record-node-ids). The manifest follows it rather than the crawl, because the reviewer may have dropped or added sections. An entry is an inventory ID, or `{ id, overrides }` when the instance's text properties differ from the pattern's defaults. `overrides` holds every changed `TEXT` property, keyed by its full Figma property name. The writer refuses any ID that isn't in the inventory, including `unknown:` and `local:` entries, so resolve them first. + ## manifest.json ```json @@ -45,6 +57,7 @@ Use the component set's ID for components, and the 1440px frame (`nodeId`) and 3 "composition": [ { "id": "part:header", "target": "template-part", "slug": "header", "file": "parts/header.html" }, { "id": "pattern:hero", "target": "pattern", "slug": "tsp-theme/hero", "file": "patterns/hero.php" }, + { "id": "pattern:card-grid", "target": "pattern", "slug": "tsp-theme/card-grid", "file": "patterns/card-grid.php", "instance": 1, "overrides": { "heading": "Our Safari Styles" } }, { "id": "pattern:map", "target": "local" } ] } @@ -54,10 +67,16 @@ Use the component set's ID for components, and the 1440px frame (`nodeId`) and 3 } ``` -Entries are ordered components, template parts, patterns, then templates, so styles exist before the patterns that use them. `variantProperties` is included for items with variants. A composition entry marked `local` is a section the reviewer cut: build it inline in the template. +Entries are ordered components, template parts, patterns, then templates, so styles exist before the patterns that use them. `variantProperties` is included for items with variants. A composition entry marked `local` is a section the reviewer cut: build it inline in the template. `instance` numbers a pattern that appears more than once, and `overrides` holds that instance's own text. `wordpress.existsInTheme` is set when `--theme-dir` finds the target file already in the theme. + +The writer refuses an unapproved inventory, a node ID not in the form `123:456`, and (without `--partial`) any item with no node. It warns about: -The writer refuses an unapproved inventory, a node ID not in the form `123:456`, and (without `--partial`) any item with no node. It warns about nodes for cut or unknown items, and about templates that change at 390px but have no mobile frame. +- nodes for cut or unknown items +- templates that change at 390px but have no mobile frame +- templates with no recorded `composition` (the crawled order is used instead) +- a built composition that differs from the live page, item by item or in section order (list each for the reviewer) +- targets that already exist in the theme (with `--theme-dir`) ## How Pattern mode uses it -`figma-to-block-theme` Pattern mode reads `manifest.json` in entry order. For each entry it reads the node with `figma-design-to-code`, writes the file named in `wordpress.file`, and uses `wordpress.slug`, `block` and `styles` as given. Templates are written last, from their `composition`: `` for parts and `` for patterns. +`figma-to-block-theme` Pattern mode reads `manifest.json` in entry order. For each entry it reads the node with `figma-design-to-code`, writes the file named in `wordpress.file`, and uses `wordpress.slug`, `block` and `styles` as given. Templates are written last, from their `composition`: `` for parts, with each part's own landmark tag and `` for patterns. An instance with `overrides` is written inline, because a theme pattern reference can't change its text. A target that `existsInTheme` is replaced or renamed after review, never reused as it is. diff --git a/skills/site-to-figma-components/references/verification.md b/skills/site-to-figma-components/references/verification.md index 75160ab144..163adf883a 100644 --- a/skills/site-to-figma-components/references/verification.md +++ b/skills/site-to-figma-components/references/verification.md @@ -20,6 +20,7 @@ Run `audit-design-system` on the build page, or this read-only scan through `use | Auto Layout padding and gaps | Each non-zero value has a bound variable | | Corner radius | Each non-zero radius is bound (component set containers set to 0) | | Text | Every text node has a `textStyleId`; no mixed styles | +| Clipped text | No text is taller than a fixed-height parent that clips content (typical when a heading wraps at 390px); set the parent to hug | | Effects | Every effect uses an effect style | | Detached instances | No frame carries a component's name; every template instance has a `mainComponent` | | Templates | Every direct child of a template frame is an instance | diff --git a/skills/site-to-figma-components/scripts/__tests__/figma-build.test.ts b/skills/site-to-figma-components/scripts/__tests__/figma-build.test.ts new file mode 100644 index 0000000000..4dafc4d3d2 --- /dev/null +++ b/skills/site-to-figma-components/scripts/__tests__/figma-build.test.ts @@ -0,0 +1,54 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { runInNewContext } from 'node:vm'; + +// Exercise the documented read-only scan against synthetic Figma nodes. +const guide = readFileSync( + join(process.cwd(), 'skills/site-to-figma-components/references/figma-build.md'), + 'utf8' +); +const snippet = /```js\n([\s\S]*?)\n```/.exec(guide)![1]; + +describe('documented composition scan', () => { + it('continues after an unresolved instance and records every changed text property', async () => { + const owner = { + type: 'COMPONENT_SET', + description: 'Inventory id pattern:cards', + componentPropertyDefinitions: { + 'Heading#1': { defaultValue: 'Heading' }, + 'Body#2': { defaultValue: 'Body' }, + 'Link#3': { defaultValue: 'Link' }, + }, + }; + const main = { parent: owner }; + const instance = { + type: 'INSTANCE', + getMainComponentAsync: async () => main, + componentProperties: { + 'Heading#1': { type: 'TEXT', value: 'Heading' }, + 'Body#2': { type: 'TEXT', value: 'New body' }, + 'Link#3': { type: 'TEXT', value: '' }, + Visible: { type: 'BOOLEAN', value: false }, + }, + }; + const children = [ + { type: 'INSTANCE', id: '1:2', getMainComponentAsync: async () => null }, + instance, + { + ...instance, + getMainComponentAsync: async () => ({ ...owner, parent: null }), + componentProperties: {}, + }, + { type: 'FRAME', name: 'Custom' }, + ]; + const out = await runInNewContext(`(async () => { ${snippet} })()`, { + figma: { getNodeByIdAsync: async () => ({ children }) }, + }); + expect(out).toEqual([ + { id: 'unknown:1:2' }, + { id: 'pattern:cards', overrides: { 'Body#2': 'New body', 'Link#3': '' } }, + 'pattern:cards', + { id: 'local:Custom' }, + ]); + }); +}); diff --git a/skills/site-to-figma-components/scripts/__tests__/write-manifest.test.ts b/skills/site-to-figma-components/scripts/__tests__/write-manifest.test.ts index 48d911cecf..e114ba20c2 100644 --- a/skills/site-to-figma-components/scripts/__tests__/write-manifest.test.ts +++ b/skills/site-to-figma-components/scripts/__tests__/write-manifest.test.ts @@ -21,6 +21,7 @@ function allNodes(inv: Inventory): FigmaNodes { nodes[i.id] = { nodeId: `100:${n + 1}`, page: '> Rebuild' }; if (i.kind === 'template') { nodes[i.id].mobileNodeId = `200:${n + 1}`; + nodes[i.id].composition = i.composition; } }); return { fileKey: 'abc123', nodes }; @@ -117,6 +118,7 @@ describe('ManifestBuilder', () => { 'pattern:testimonials was cut from the inventory but has a Figma node (1:3). Archive the node or restore the item.', 'pattern:ghost is in figma-nodes.json but not in the inventory.', 'template:front-page changes layout at 390px but has no mobile frame.', + "template:front-page has no built composition in figma-nodes.json; using the crawled order. Record the template frame's sections.", ]); const md = new ManifestBuilder(now).markdown(m); expect(md).toContain('## Not built yet'); @@ -124,6 +126,90 @@ describe('ManifestBuilder', () => { expect(md).toContain('1. template-part `header`'); }); + it('follows the built composition, numbering repeats and keeping overrides', () => { + const inv = approved(); + const nodes = allNodes(inv); + const front = inv.items.find((i) => i.id === 'template:front-page')!; + const crawled = front.composition!; + const repeated = crawled.find((id) => id.startsWith('pattern:'))!; + nodes.nodes['template:front-page'].composition = [ + ...crawled.filter((id) => id !== repeated), + { id: repeated, overrides: { heading: 'First' } }, + { id: repeated, overrides: { heading: 'Second' } }, + { id: repeated, overrides: {} }, + ]; + const builder = new ManifestBuilder(now); + const m = builder.build(inv, nodes); + const entry = m.entries.find((e) => e.id === 'template:front-page')!; + const copies = entry.composition!.filter((c) => c.id === repeated); + expect(copies.map((c) => c.instance)).toEqual([1, 2, 3]); + expect(copies[0].overrides).toEqual({ heading: 'First' }); + expect(copies[2].overrides).toBeUndefined(); + expect(m.warnings).toEqual([ + `template:front-page: the Figma template has 3 × ${repeated}, the live page had ${crawled.filter((id) => id === repeated).length}. The manifest follows Figma; list the difference for the reviewer.`, + ]); + const md = builder.markdown(m); + expect(md).toContain('(instance 1): heading "First"'); + expect(md).toContain('(instance 3)\n'); + }); + + it.each(['pattern:missing', 'unknown:Section', 'local:Section'])( + 'rejects unresolved composition section %s', + (id) => { + const inv = approved(); + const nodes = allNodes(inv); + nodes.nodes['template:front-page'].composition = [id]; + expect(() => new ManifestBuilder(now).build(inv, nodes)).toThrow( + `unresolved composition section ${id}` + ); + } + ); + + it('warns about an equal-count reorder and keeps the built order', () => { + const inv = approved(); + const nodes = allNodes(inv); + const reordered = [ + ...inv.items.find((i) => i.id === 'template:front-page')!.composition!, + ].reverse(); + nodes.nodes['template:front-page'].composition = reordered; + const m = new ManifestBuilder(now).build(inv, nodes); + expect( + m.entries.find((e) => e.id === 'template:front-page')!.composition!.map((s) => s.id) + ).toEqual(reordered); + expect(m.warnings).toEqual([ + 'template:front-page: the Figma section order differs from the live page. The manifest follows Figma; list the difference for the reviewer.', + ]); + }); + + it('flags targets that already exist in the theme', () => { + const inv = approved(); + const m = new ManifestBuilder(now).build( + inv, + allNodes(inv), + false, + (file) => file === 'parts/header.html' + ); + const header = m.entries.find((e) => e.id === 'part:header')!; + expect(header.wordpress.existsInTheme).toBe(true); + expect(m.entries.find((e) => e.id === 'part:footer')!.wordpress.existsInTheme).toBeUndefined(); + expect(m.warnings).toEqual([ + 'part:header: parts/header.html already exists in the theme. Pattern mode must replace or rename it, not reuse it as is.', + ]); + expect(new ManifestBuilder(now).markdown(m)).toContain('parts/header.html (exists)'); + expect(header.wordpress).not.toBe(inv.items.find((i) => i.id === 'part:header')!.wordpress); + const rebuilt = new ManifestBuilder(now).build(inv, allNodes(inv), false, () => false); + const unchecked = new ManifestBuilder(now).build(inv, allNodes(inv)); + for (const result of [rebuilt, unchecked]) { + expect( + result.entries.find((e) => e.id === 'part:header')!.wordpress.existsInTheme + ).toBeUndefined(); + expect(result.warnings).toEqual([]); + } + expect(inv.items.find((i) => i.id === 'part:header')!.wordpress).not.toHaveProperty( + 'existsInTheme' + ); + }); + it('only requires nodes for items in the approved build scope', () => { const inv = new DecisionApplier().apply(approved(), { build: ['component:button'] }); const m = new ManifestBuilder(now).build(inv, { @@ -189,6 +275,25 @@ describe('runManifestCli', () => { expect(t.out.join('')).toMatch(/entries, 0 not built, 0 warnings/); }); + it('checks targets against --theme-dir', () => { + const t = io(files); + const seen: string[] = []; + const exists = (p: string) => { + seen.push(p); + return p === 'theme/parts/footer.html'; + }; + expect( + runManifestCli(['i.json', '--nodes', 'n.json', '--theme-dir', 'theme'], { ...t.io, exists }) + ).toBe(0); + expect(seen).toContain('theme/parts/header.html'); + expect(t.out.join('')).toMatch(/1 warnings/); + const noFs = io(files); + expect(runManifestCli(['i.json', '--nodes', 'n.json', '--theme-dir', 'theme'], noFs.io)).toBe( + 0 + ); + expect(noFs.out.join('')).toMatch(/0 warnings/); + }); + it('accepts --partial and prints usage', () => { const t = io(files); expect(runManifestCli(['i.json', '--nodes', 'p.json', '--partial'], t.io)).toBe(0); diff --git a/skills/site-to-figma-components/scripts/write-manifest.ts b/skills/site-to-figma-components/scripts/write-manifest.ts index 8df1ec089a..9a4babc031 100644 --- a/skills/site-to-figma-components/scripts/write-manifest.ts +++ b/skills/site-to-figma-components/scripts/write-manifest.ts @@ -6,13 +6,17 @@ * * Usage: * npx tsx write-manifest.ts inventory.json --nodes figma-nodes.json \ - * --out manifest.json --markdown manifest.md [--partial] + * --out manifest.json --markdown manifest.md [--theme-dir ../my-theme] [--partial] * * figma-nodes.json is assembled from the IDs the use_figma build calls return: * { "fileKey": "abc", "nodes": { "component:button": { "nodeId": "12:34", "page": "> Components" } } } + * A template's ref can also carry `composition`, read from the built frame's + * children, so the manifest follows what was built rather than the crawl. + * --theme-dir flags targets that already exist in the theme. */ -import { readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import type { Inventory, InventoryItem, Kind, WpTarget } from './propose-inventory'; @@ -21,6 +25,16 @@ export interface FigmaNodeRef { /** The 390px frame, for templates and patterns whose layout changes on mobile. */ mobileNodeId?: string; page?: string; + /** + * Templates only: the built frame's sections in order, each an inventory ID + * or `{ id, overrides }` with the instance's changed text (for example its heading). + */ + composition?: (string | BuiltSection)[]; +} + +export interface BuiltSection { + id: string; + overrides?: Record; } export interface FigmaNodes { @@ -34,6 +48,10 @@ export interface CompositionEntry { target: 'template-part' | 'pattern' | 'local'; slug?: string; file?: string; + /** 1-based count when the same pattern appears more than once in the template. */ + instance?: number; + /** Text that differs from the pattern's own content in this instance. */ + overrides?: Record; } export interface ManifestEntry { @@ -48,7 +66,7 @@ export interface ManifestEntry { page?: string; url: string; }; - wordpress: WpTarget; + wordpress: WpTarget & { existsInTheme?: boolean }; variantProperties?: Record; composition?: CompositionEntry[]; sourcePages: string[]; @@ -72,7 +90,12 @@ const ORDER: Kind[] = ['component', 'template-part', 'pattern', 'template']; export class ManifestBuilder { constructor(private readonly now: () => Date = () => new Date()) {} - build(inventory: Inventory, figma: FigmaNodes, partial = false): Manifest { + build( + inventory: Inventory, + figma: FigmaNodes, + partial = false, + existsInTheme?: (file: string) => boolean + ): Manifest { if (!inventory.approved) { throw new Error( 'The inventory is not approved. Apply the reviewer decisions with "approve": true first.' @@ -102,6 +125,14 @@ export class ManifestBuilder { errors.push(`${id} has an invalid node ID "${nodeId}"; expected the form 123:456.`); } } + for (const section of ref.composition ?? []) { + const sectionId = typeof section === 'string' ? section : section.id; + if (!byId.has(sectionId)) { + errors.push( + `${id}: unresolved composition section ${sectionId}. Resolve it to an inventory item before writing the manifest.` + ); + } + } } const entries: ManifestEntry[] = []; @@ -123,7 +154,14 @@ export class ManifestBuilder { if (item.kind === 'template' && item.mobileLayoutChanges && !ref.mobileNodeId) { warnings.push(`${item.id} changes layout at 390px but has no mobile frame.`); } - entries.push(this.entry(item, ref, figma.fileKey, byId)); + const entry = this.entry(item, ref, figma.fileKey, byId, warnings); + if (existsInTheme && entry.wordpress.file && existsInTheme(entry.wordpress.file)) { + entry.wordpress.existsInTheme = true; + warnings.push( + `${item.id}: ${entry.wordpress.file} already exists in the theme. Pattern mode must replace or rename it, not reuse it as is.` + ); + } + entries.push(entry); } if (errors.length) { throw new Error(errors.join('\n')); @@ -149,7 +187,8 @@ export class ManifestBuilder { item: InventoryItem, ref: FigmaNodeRef, fileKey: string, - byId: Map + byId: Map, + warnings: string[] ): ManifestEntry { const entry: ManifestEntry = { id: item.id, @@ -161,7 +200,7 @@ export class ManifestBuilder { name: item.figmaName, url: `https://www.figma.com/design/${fileKey}/?node-id=${ref.nodeId.replace(':', '-')}`, }, - wordpress: item.wordpress, + wordpress: { ...item.wordpress }, sourcePages: item.pages, }; if (ref.mobileNodeId) { @@ -173,23 +212,77 @@ export class ManifestBuilder { if (Object.keys(item.variantProperties).length) { entry.variantProperties = item.variantProperties; } - if (item.composition) { - entry.composition = item.composition.map((id) => { + const sections = this.sections(item, ref, warnings); + if (sections) { + const seen = new Map(); + const totals = new Map(); + for (const s of sections) { + totals.set(s.id, (totals.get(s.id) ?? 0) + 1); + } + entry.composition = sections.map(({ id, overrides }) => { + // An unknown ID is already an error, and build() throws before returning. const part = byId.get(id); - if (!part || part.status === 'cut') { - return { id, target: 'local' }; + const out: CompositionEntry = + !part || part.status === 'cut' + ? { id, target: 'local' } + : { + id, + target: part.kind === 'template-part' ? 'template-part' : 'pattern', + slug: part.wordpress.slug, + file: part.wordpress.file, + }; + if (totals.get(id)! > 1) { + seen.set(id, (seen.get(id) ?? 0) + 1); + out.instance = seen.get(id); } - return { - id, - target: part.kind === 'template-part' ? 'template-part' : 'pattern', - slug: part.wordpress.slug, - file: part.wordpress.file, - }; + if (overrides && Object.keys(overrides).length) { + out.overrides = overrides; + } + return out; }); } return entry; } + /** The built composition when Figma recorded one, otherwise the crawled one. */ + private sections( + item: InventoryItem, + ref: FigmaNodeRef, + warnings: string[] + ): BuiltSection[] | undefined { + const crawled = item.composition?.map((id) => ({ id })); + if (!ref.composition) { + if (crawled && item.kind === 'template') { + warnings.push( + `${item.id} has no built composition in figma-nodes.json; using the crawled order. Record the template frame's sections.` + ); + } + return crawled; + } + const built = ref.composition.map((s) => (typeof s === 'string' ? { id: s } : s)); + const count = (list: BuiltSection[]) => + list.reduce((m, s) => m.set(s.id, (m.get(s.id) ?? 0) + 1), new Map()); + const want = count(crawled ?? []); + const have = count(built); + let countsDiffer = false; + for (const id of new Set([...want.keys(), ...have.keys()])) { + const w = want.get(id) ?? 0; + const h = have.get(id) ?? 0; + if (w !== h) { + countsDiffer = true; + warnings.push( + `${item.id}: the Figma template has ${h} × ${id}, the live page had ${w}. The manifest follows Figma; list the difference for the reviewer.` + ); + } + } + if (!countsDiffer && crawled && crawled.some((s, n) => s.id !== built[n].id)) { + warnings.push( + `${item.id}: the Figma section order differs from the live page. The manifest follows Figma; list the difference for the reviewer.` + ); + } + return built; + } + markdown(m: Manifest): string { const lines = [ `# Figma to WordPress manifest: ${new URL(m.site).host}`, @@ -208,7 +301,8 @@ export class ManifestBuilder { .filter(Boolean) .join(', '); const node = `[${e.figma.nodeId}](${e.figma.url})${e.figma.mobileNodeId ? ` (mobile ${e.figma.mobileNodeId})` : ''}`; - return `| ${e.kind} | ${e.name} | ${node} | ${target} | ${e.wordpress.file ?? ''} |`; + const file = `${e.wordpress.file ?? ''}${e.wordpress.existsInTheme ? ' (exists)' : ''}`; + return `| ${e.kind} | ${e.name} | ${node} | ${target} | ${file} |`; }), '', ]; @@ -218,10 +312,18 @@ export class ManifestBuilder { for (const t of templates) { lines.push(`### ${t.name} (\`${t.wordpress.file}\`)`, ''); lines.push( - ...t.composition!.map( - (c, n) => - `${n + 1}. ${c.target === 'local' ? `${c.id} (local section, no pattern)` : `${c.target} \`${c.slug}\``}` - ), + ...t.composition!.map((c, n) => { + const what = + c.target === 'local' + ? `${c.id} (local section, no pattern)` + : `${c.target} \`${c.slug}\`${c.instance ? ` (instance ${c.instance})` : ''}`; + const text = c.overrides + ? `: ${Object.entries(c.overrides) + .map(([k, v]) => `${k} "${v}"`) + .join(', ')}` + : ''; + return `${n + 1}. ${what}${text}`; + }), '' ); } @@ -242,19 +344,21 @@ export interface ManifestCliIo { stdout: (text: string) => void; stderr: (text: string) => void; now?: () => Date; + exists?: (path: string) => boolean; } export function runManifestCli(argv: string[], io: ManifestCliIo): number { const values: Record = { out: 'manifest.json', markdown: 'manifest.md' }; let input: string | undefined; let nodes: string | undefined; + let themeDir: string | undefined; let partial = false; try { for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg === '--help' || arg === '-h') { io.stdout( - 'Usage: write-manifest inventory.json --nodes figma-nodes.json [--out manifest.json] [--markdown manifest.md] [--partial]\n' + 'Usage: write-manifest inventory.json --nodes figma-nodes.json [--out manifest.json] [--markdown manifest.md] [--theme-dir path] [--partial]\n' ); return 0; } @@ -267,7 +371,7 @@ export function runManifestCli(argv: string[], io: ManifestCliIo): number { continue; } const key = arg.slice(2); - if (key !== 'nodes' && !(key in values)) { + if (key !== 'nodes' && key !== 'theme-dir' && !(key in values)) { throw new Error(`Unknown argument ${arg}.`); } const value = argv[++i]; @@ -276,6 +380,8 @@ export function runManifestCli(argv: string[], io: ManifestCliIo): number { } if (key === 'nodes') { nodes = value; + } else if (key === 'theme-dir') { + themeDir = value; } else { values[key] = value; } @@ -287,7 +393,8 @@ export function runManifestCli(argv: string[], io: ManifestCliIo): number { const manifest = builder.build( JSON.parse(io.readFile(input)) as Inventory, JSON.parse(io.readFile(nodes)) as FigmaNodes, - partial + partial, + themeDir && io.exists ? (file) => io.exists!(join(themeDir!, file)) : undefined ); io.writeFile(values.out, `${JSON.stringify(manifest, null, 2)}\n`); io.writeFile(values.markdown, builder.markdown(manifest)); @@ -308,5 +415,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) writeFile: (path, content) => writeFileSync(path, content), stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text), + exists: existsSync, }); }