From 95eaba134e4e044d26615afc4bcc2a10152780ba Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sat, 21 Nov 2026 18:38:01 +0100 Subject: [PATCH 1/6] Pin the slice C contracts --- docs/specs/PHASE-32-SPEC.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/specs/PHASE-32-SPEC.md b/docs/specs/PHASE-32-SPEC.md index e54cf3a..5998735 100644 --- a/docs/specs/PHASE-32-SPEC.md +++ b/docs/specs/PHASE-32-SPEC.md @@ -138,6 +138,18 @@ And one is housekeeping the follow-ups will land in. 140 tests and `test-env.ts` - `structures.ts:2157-2164`: drop the five tints and `danger` from seeding. - `checkStructure`'s token census (`evaluate.ts:722`, `:735`, `:2758`): the merged tokens, resolved refs only. +**Slice C — contracts pinned before build (2026-11-21; frozen at the commit that adds this block).** Two departures from the FR text, each on evidence measured before freezing, are marked *(changed)*. +- **M1: copy props.** `COPY_PROPS` in `src/primitives.ts` replaces `PRIMITIVE_COPY_PROPS`: its current entries (copy and enums) plus `content`, `text`, `closeLabel`, `name`, and `centerValue` and `centerLabel` (a donut's centre text, where `"$1.2M"` is ordinary copy; found by listing every string prop on `SceneNode`). `deepResolve` skips them, as do the token census and `unknown-token`. Nested copy (`leading.label`, `items[].label`, `actions[].label`) is never resolved today and stays so. +- **M2: what a ref is.** A ref is a string starting with `$` that the resolver walks: a top-level prop other than `id`, `type`, `children` and `COPY_PROPS`; an entry of `padding` or `cornerRadius`; `borderTop/Right/Bottom/Left.color`; `series[i].stroke`; `segments[i].color`; `actions[i].fill|color|stroke`; `action.color`. One exported walker (`tokenRefs(node)` in `src/variables.ts`, yielding `{ path, ref }`) is the list, read by `unknown-token` and the census, so the rule and the resolver cannot disagree. +- **M3: defined, and its kind.** A ref is defined when `lookupToken` finds it in the merged base tokens (colors, spacing, radius, typography, then dotted `.`) or it names a derived colour (M6). Its kind is the category it was found in: colors and the derived names are `color`, spacing and radius `number`, typography `typography`, dotted `elevation.*` `elevation`, any other dotted category its own name. A ref undefined in the base but defined in the dark layer (`dark.colors`, `dark.elevation`) is reported as dark-only (M4). The dark layer only adds keys over the base, so a ref defined in the base is defined in every theme. +- **M4: the rule.** `unknown-token` joins `DEFAULT_RULES` (`src/surfaces.ts`) and runs unless `rules.off` lists it; category structure, severity warning, `rule: "unknown-token"`, −10 per finding like an unknown icon. Three cases: *unknown* (`Unknown token "$space-mdd" on gap: no such token is defined, so the value is dropped`), *dark-only* (`… is defined only in the dark layer, so light renders it raw`; suggestion: define it in the base colors; no candidates, no fix), *wrong kind* (`"$body" on fill is a typography token (16), not a color`; no fix). Prop kinds: colour props are `fill`, `stroke`, `color`, `iconColor`, `secondaryColor`, `badgeColor`, `dotColor` and every nested path of M2 (all colours); number props are `width`, `height`, `minWidth`, `maxWidth`, `minHeight`, `gap`, `rowGap`, `padding[i]`, `cornerRadius[i]`, `x`, `y`, `bottom`, `right`, `strokeWidth`, `opacity`, `blur`, `backdropBlur`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `iconSize`, `labelWidth`, `inset`, `depth`, `rows`, `innerRatio`, `gridlines`; `shadow` takes elevation. A colour prop accepts `color` only; a number prop accepts `number` and `typography` (a typography ref resolves to its size). `shadow` and every other prop get the existence check only. +- **M5: candidates and the fix.** Candidates are defined names of the prop's kind (colour props: colours plus derived names; number props: spacing and radius, plus typography for `fontSize`; `shadow`: `elevation.*`; any other prop: every name), ranked by Levenshtein distance, ties by name, at most three, each within distance 3. A rename fix exists only for an *unknown* ref when the nearest is within 2 and strictly closer than the second, and the stored node (not a component node, not an override) holds that ref at that path: `U(id, { : })`, so a `padding` array or a `borderTop` object is rewritten whole. +- **M6: derived colours** *(changed)*. `resolveVariables` fills the six derived names into the effective colours (after the dark merge, so a dark render derives from dark inks and a dark surface) when they are missing; every reader (refs, `applyControlDefaults`, the evaluator's resolved trees) sees them, and `get_variables` does not. Surface: `bg-surface`, else `bg-primary`, else `#FFFFFF`, its alpha ignored; unparseable counts as `#FFFFFF`. Mode: dark when the surface contrasts more with white than with black (a tie is light). `danger`: `danger`, else `error`, else **`#DC2626` in light mode and `#F87171` in dark mode** (FR-C5 says `#DC2626` alone; measured, `#DC2626` is 3.91:1 on the unthemed scaffold surface `#111111` against today's seed `#F87171` at 6.83:1, so the literal would turn every unthemed destructive label into a contrast failure; `#F87171` is the old dark seed). Inks: `accent` (else `primary`, else `#2563EB`), `success` (else `#16A34A`), `warning` (else `#D97706`), the resolved `danger`, `text-secondary` (else `#6B7280`); an ink that does not parse takes its literal; an ink with alpha is composited over the surface. Each tint is `tintFor(ink, mode)`, a new export of `src/color-system.ts` that `tintLayer` now maps over (generator output unchanged). *(changed)* An ink with OKLCH chroma under 0.005 gets a grey tint (chroma 0 at the lightness `tintLayer`'s search finds), because its hue is noise: measured, the unthemed `text-secondary` `#ffffffa0` over `#111111` gave a maroon `#44212D` neutral tint. The generator never hits this: its inks measured 0.0094 or more on five seeds, grey and black included, and it calls `tintFor` without the grey rule. The `mixHex` 12% fallback goes. +- **M7: old seeds.** `RETIRED_SEEDS` in `src/variables.ts` holds the six old values; `getCanvasTokens` drops a canvas-layer base colour equal to one (case-insensitive) before merging. Dark layers and the project and workspace layers are not touched. `applyStructure` stops seeding the six, and `PRIMITIVE_COLOR_TOKENS` drops `danger`. +- **M8: census.** `checkStructure`'s hasVariables test and both token-usage counts read the merged tokens, and count a ref only when it is defined (M3, base). +- **M9: the mid-grey case.** `bg-surface: "#777777"` (4.48:1 with white, 4.69:1 with black) derives light tints; `#757575` (4.61 and 4.56) derives dark. +- **M10: acceptance tests.** `test/unit/test-unknown-token.ts` (FR-C1, C2, C3, C4 and M2's nested paths, each pass with a failing twin), `test/unit/test-derived-tints.ts` (FR-C5, C6, M6, M9). Existing pins that move are listed in the PR: `test-patterns.ts:239` (a non-seed dark value), `test-desktop-primitives.ts:66,75` (the derived tint, not the 12% mix). + **Slice D: desktop-app checks and stress (FR-D1 to FR-D4).** - `variables.ts` select branch: `$border-strong` when defined. `state-checks.ts:268`: `select` measured. - `renderTreeRow` (`renderer.ts:1610`): `position: relative` with `renderNavItem`'s guard, and the bar. `indicatorPairs` (`state-checks.ts:211-236`): `tree-row`. From 846ed20e9f5d7bd591c51ec7497fe521525d3fe6 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sat, 21 Nov 2026 18:49:56 +0100 Subject: [PATCH 2/6] Re-freeze the slice C contracts after the pre-freeze check --- docs/specs/PHASE-32-SPEC.md | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/docs/specs/PHASE-32-SPEC.md b/docs/specs/PHASE-32-SPEC.md index 5998735..92f986e 100644 --- a/docs/specs/PHASE-32-SPEC.md +++ b/docs/specs/PHASE-32-SPEC.md @@ -138,17 +138,18 @@ And one is housekeeping the follow-ups will land in. 140 tests and `test-env.ts` - `structures.ts:2157-2164`: drop the five tints and `danger` from seeding. - `checkStructure`'s token census (`evaluate.ts:722`, `:735`, `:2758`): the merged tokens, resolved refs only. -**Slice C — contracts pinned before build (2026-11-21; frozen at the commit that adds this block).** Two departures from the FR text, each on evidence measured before freezing, are marked *(changed)*. -- **M1: copy props.** `COPY_PROPS` in `src/primitives.ts` replaces `PRIMITIVE_COPY_PROPS`: its current entries (copy and enums) plus `content`, `text`, `closeLabel`, `name`, and `centerValue` and `centerLabel` (a donut's centre text, where `"$1.2M"` is ordinary copy; found by listing every string prop on `SceneNode`). `deepResolve` skips them, as do the token census and `unknown-token`. Nested copy (`leading.label`, `items[].label`, `actions[].label`) is never resolved today and stays so. -- **M2: what a ref is.** A ref is a string starting with `$` that the resolver walks: a top-level prop other than `id`, `type`, `children` and `COPY_PROPS`; an entry of `padding` or `cornerRadius`; `borderTop/Right/Bottom/Left.color`; `series[i].stroke`; `segments[i].color`; `actions[i].fill|color|stroke`; `action.color`. One exported walker (`tokenRefs(node)` in `src/variables.ts`, yielding `{ path, ref }`) is the list, read by `unknown-token` and the census, so the rule and the resolver cannot disagree. -- **M3: defined, and its kind.** A ref is defined when `lookupToken` finds it in the merged base tokens (colors, spacing, radius, typography, then dotted `.`) or it names a derived colour (M6). Its kind is the category it was found in: colors and the derived names are `color`, spacing and radius `number`, typography `typography`, dotted `elevation.*` `elevation`, any other dotted category its own name. A ref undefined in the base but defined in the dark layer (`dark.colors`, `dark.elevation`) is reported as dark-only (M4). The dark layer only adds keys over the base, so a ref defined in the base is defined in every theme. -- **M4: the rule.** `unknown-token` joins `DEFAULT_RULES` (`src/surfaces.ts`) and runs unless `rules.off` lists it; category structure, severity warning, `rule: "unknown-token"`, −10 per finding like an unknown icon. Three cases: *unknown* (`Unknown token "$space-mdd" on gap: no such token is defined, so the value is dropped`), *dark-only* (`… is defined only in the dark layer, so light renders it raw`; suggestion: define it in the base colors; no candidates, no fix), *wrong kind* (`"$body" on fill is a typography token (16), not a color`; no fix). Prop kinds: colour props are `fill`, `stroke`, `color`, `iconColor`, `secondaryColor`, `badgeColor`, `dotColor` and every nested path of M2 (all colours); number props are `width`, `height`, `minWidth`, `maxWidth`, `minHeight`, `gap`, `rowGap`, `padding[i]`, `cornerRadius[i]`, `x`, `y`, `bottom`, `right`, `strokeWidth`, `opacity`, `blur`, `backdropBlur`, `fontSize`, `fontWeight`, `lineHeight`, `letterSpacing`, `iconSize`, `labelWidth`, `inset`, `depth`, `rows`, `innerRatio`, `gridlines`; `shadow` takes elevation. A colour prop accepts `color` only; a number prop accepts `number` and `typography` (a typography ref resolves to its size). `shadow` and every other prop get the existence check only. -- **M5: candidates and the fix.** Candidates are defined names of the prop's kind (colour props: colours plus derived names; number props: spacing and radius, plus typography for `fontSize`; `shadow`: `elevation.*`; any other prop: every name), ranked by Levenshtein distance, ties by name, at most three, each within distance 3. A rename fix exists only for an *unknown* ref when the nearest is within 2 and strictly closer than the second, and the stored node (not a component node, not an override) holds that ref at that path: `U(id, { : })`, so a `padding` array or a `borderTop` object is rewritten whole. -- **M6: derived colours** *(changed)*. `resolveVariables` fills the six derived names into the effective colours (after the dark merge, so a dark render derives from dark inks and a dark surface) when they are missing; every reader (refs, `applyControlDefaults`, the evaluator's resolved trees) sees them, and `get_variables` does not. Surface: `bg-surface`, else `bg-primary`, else `#FFFFFF`, its alpha ignored; unparseable counts as `#FFFFFF`. Mode: dark when the surface contrasts more with white than with black (a tie is light). `danger`: `danger`, else `error`, else **`#DC2626` in light mode and `#F87171` in dark mode** (FR-C5 says `#DC2626` alone; measured, `#DC2626` is 3.91:1 on the unthemed scaffold surface `#111111` against today's seed `#F87171` at 6.83:1, so the literal would turn every unthemed destructive label into a contrast failure; `#F87171` is the old dark seed). Inks: `accent` (else `primary`, else `#2563EB`), `success` (else `#16A34A`), `warning` (else `#D97706`), the resolved `danger`, `text-secondary` (else `#6B7280`); an ink that does not parse takes its literal; an ink with alpha is composited over the surface. Each tint is `tintFor(ink, mode)`, a new export of `src/color-system.ts` that `tintLayer` now maps over (generator output unchanged). *(changed)* An ink with OKLCH chroma under 0.005 gets a grey tint (chroma 0 at the lightness `tintLayer`'s search finds), because its hue is noise: measured, the unthemed `text-secondary` `#ffffffa0` over `#111111` gave a maroon `#44212D` neutral tint. The generator never hits this: its inks measured 0.0094 or more on five seeds, grey and black included, and it calls `tintFor` without the grey rule. The `mixHex` 12% fallback goes. -- **M7: old seeds.** `RETIRED_SEEDS` in `src/variables.ts` holds the six old values; `getCanvasTokens` drops a canvas-layer base colour equal to one (case-insensitive) before merging. Dark layers and the project and workspace layers are not touched. `applyStructure` stops seeding the six, and `PRIMITIVE_COLOR_TOKENS` drops `danger`. -- **M8: census.** `checkStructure`'s hasVariables test and both token-usage counts read the merged tokens, and count a ref only when it is defined (M3, base). -- **M9: the mid-grey case.** `bg-surface: "#777777"` (4.48:1 with white, 4.69:1 with black) derives light tints; `#757575` (4.61 and 4.56) derives dark. -- **M10: acceptance tests.** `test/unit/test-unknown-token.ts` (FR-C1, C2, C3, C4 and M2's nested paths, each pass with a failing twin), `test/unit/test-derived-tints.ts` (FR-C5, C6, M6, M9). Existing pins that move are listed in the PR: `test-patterns.ts:239` (a non-seed dark value), `test-desktop-primitives.ts:66,75` (the derived tint, not the 12% mix). +**Slice C — contracts pinned before build (2026-11-21; frozen at the commit that adds this block).** Drafted, then broken on paper by one pre-freeze verifier (14 findings, 9 confirmed); this is the re-frozen version. Departures from the FR text, each on measured evidence, are marked *(changed)*. +- **M1: copy props.** `COPY_PROPS` in `src/primitives.ts` replaces `PRIMITIVE_COPY_PROPS`: its current entries (copy and enums) plus `content`, `text`, `closeLabel`, `name`, and `centerValue` and `centerLabel` (a donut's centre text, where `"$1.2M"` is ordinary copy; found by listing every string prop on `SceneNode`). `deepResolve` skips them, as do the token census and `unknown-token`. Deliberate false negatives, named in GUIDELINES: copy is never a ref (`content: "$body"` renders the string); nested copy (`leading.label`, `items[].label`, `actions[].label`) and `gradient.stops[].color` / `shadows[].color` are not walked by the resolver, so a ref there renders raw and is not reported. +- **M2: what a ref is.** A string starting with `$` at a place the resolver walks: a top-level prop other than `id`, `type`, `children` and `COPY_PROPS`; an entry of `padding` or `cornerRadius`; `borderTop/Right/Bottom/Left.color`; `series[i].stroke`; `segments[i].color`; `actions[i].fill|color|stroke`; `action.color`. One walker exported from `src/variables.ts` (`tokenRefs(node)`, yielding `{ path, key, ref }`, `key` being the top-level prop) is the list `unknown-token` reads. +- **M3: defined, and its kind.** `tokenKind(name, tokens)` sits beside `lookupToken` and follows its order: `colors` → `color`; `spacing`, `radius` → `number`; `typography` → `typography`; then dotted `.`: `colors.*` → `color`, `spacing.*`, `radius.*`, `state.*` → `number`, `elevation.*` → `elevation`, `motion.*` → `motion`, `typography.*` → `object` (it returns the whole spec, valid nowhere), any other category → `object`. The six derived names (M6) are always `color` in the base, never dark-only. A ref undefined in the base but defined in `dark.colors` or `dark.elevation` is dark-only. The dark layer only adds keys, so a ref defined in the base is defined in every theme. +- **M4: the rule.** `unknown-token` joins `DEFAULT_RULES` (`src/surfaces.ts`) and runs unless `rules.off` lists it; category structure, severity warning, `rule: "unknown-token"`, −10 per finding as for an unknown icon. Cases: *unknown* (`Unknown token "$space-mdd" on gap: no such token is defined, so the value is dropped`), *dark-only* (suggestion: define it in the base colors; no candidates, no fix), *wrong kind* (`"$body" on fill is a typography token, not a color`; no fix), *takes no token* (a ref on a prop that accepts none, e.g. `fontFamily: "$display"`, which renders `40`; no fix). What each prop accepts: colour props `fill`, `stroke`, `color`, `iconColor`, `secondaryColor`, `badgeColor`, `dotColor` and every nested path of M2 take `color`; `fontSize` takes `number` or `typography`; the number props `width`, `height`, `minWidth`, `maxWidth`, `minHeight`, `gap`, `rowGap`, `padding[i]`, `cornerRadius[i]`, `x`, `y`, `bottom`, `right`, `strokeWidth`, `opacity`, `blur`, `backdropBlur`, `fontWeight`, `lineHeight`, `letterSpacing`, `iconSize`, `labelWidth`, `inset`, `depth`, `rows`, `innerRatio`, `gridlines` take `number`; `shadow` takes `elevation`; `transition` takes `motion`; every other prop takes none. +- **M5: candidates and the fix.** Candidates are defined names the prop accepts (colour props: colours and the derived names; number props: spacing and radius; `fontSize`: those plus typography; `shadow`: `elevation.*`; `transition`: `motion.*`), by Levenshtein distance, ties by name, at most three, each within distance 3. A rename fix exists only for an *unknown* ref when (a) the nearest is within 2 and strictly closer than the second; (b) the ref and the nearest do not both end in a ladder step that differs (a last segment like `3xs`, `xxs`, `xs`, `sm`, `md`, `lg`, `xl`, `2xl` or a number), so `$space-lg` on a ladder with only `space-md` is warn-only: a different size is not a spelling; (c) the stored node itself holds the ref (not a component node, not an override, not an instance root whose value comes from its component); and (d) the ref is a top-level scalar, a `padding` / `cornerRadius` entry or a `borderX.color` (the `U` parser cannot round-trip arbitrary `actions` / `action` / `series` / `segments` objects, so those are warn-only). The op is `U(id, { : })`, so two typos in one `padding` array carry the same op and applying both is idempotent. A warn-only finding inside a component says to fix the component definition or override the prop on the instance (`overrides`); one inside an override says to edit that override. +- **M6: one finding per origin.** The rule walks the raw expanded tree and, for components no instance uses, their definitions. Each `(origin, path, ref)` reports once, at its first occurrence. Origin: a stored node's own value is the node; an instance root's value is the instance when the instance holds it, else `def::`; a node inside an instance is `ovr::` when that instance's override for the node's name sets the key to that value, else `def::`, the component being the immediate instance's. A finding on a node inside an instance goes through slice B's K4 pass (owner, `innerNodeId`, no fix); a finding in an unused definition keeps the definition's node id and names the component. +- **M7: derived colours** *(changed)*. `resolveVariables` fills the six derived names into the effective colours (after the dark merge, so a dark render derives from dark inks and a dark surface) when they are missing; every reader (refs, `applyControlDefaults`, the evaluator's resolved trees) sees them; `get_variables` does not. Colours parse with `variables.ts`'s `rgbOf` (hex, `rgb()`, `hsl()`) and are normalised to hex. Surface: the first of `bg-surface`, `bg-primary` that parses, else `#FFFFFF`; a translucent surface is composited over the next opaque one in that chain, else over white. Mode: dark when the surface contrasts more with white than with black (a tie is light). `danger`: `danger`, else `error`, else **`#DC2626` in light mode and `#F87171` in dark mode** (FR-C5 says `#DC2626` alone; measured, it is 3.91:1 on the unthemed scaffold surface `#111111`, where today's seed `#F87171` is 6.83:1; `#DC2626` stays the light value because it is what an unthemed light canvas renders today, and it clears 4.5:1 on white, `#fafafa` and `#f8f9fa`). Inks: `accent` (else `primary`, else `#2563EB`), `success` (else `#16A34A`), `warning` (else `#D97706`), the resolved `danger`, `text-secondary` (else `#6B7280`); an ink that does not parse takes its literal; an ink with alpha is composited over the surface. Each tint is `tintFor(ink, mode, { grey: true })`, a new export of `src/color-system.ts` that `tintLayer` maps over without the grey option (generator output unchanged). *(changed)* With `grey`, an ink of OKLCH chroma under 0.005 gets a grey tint (chroma 0 at the lightness the search finds): its hue is noise, and the unthemed `text-secondary` `#ffffffa0` over `#111111` gave a maroon `#44212D`. Generated inks measured chroma 0.0094 or more on five seeds, grey and black included. The `mixHex` 12% fallback goes. A tint clears 4.5:1 with its ink only when the ink can: under the light preset `success` (3.06), the surviving seed `warning` (1.53) and `error` (3.44) do not, and the contrast check reports those inks (FR-C5's last sentence). The generator's own light `accent-tint` is below 4.5:1 on 7 of 14 seeds measured (its 0.97 lightness cap, unchanged here), so the acceptance tests use seed `#2563EB`. +- **M8: old seeds** *(changed: by name)*. `RETIRED_SEEDS` in `src/variables.ts` maps each of the six names to its old value; `getCanvasTokens` drops a canvas-layer base colour whose name is one and whose value equals it, case-insensitive. Dark layers and the project and workspace layers are not touched (a workspace that copied a seed keeps it: a deliberate limit). `applyPresetTokens` treats such a value as not the canvas's own, so a canvas-scope preset or generated system preserves an inherited tint instead of overwriting the dead seed. `get_variables` omits them. `applyStructure` stops seeding the six, and `PRIMITIVE_COLOR_TOKENS` drops `danger`. The `sha256r:` hash moves once for a canvas holding a seed, whether or not its render changes; a legacy `sha256:` hash digests the stored variables and does not move; a canvas holding no seed keeps its hash even where its render changes (the active fill's 12% mix becomes the derived tint), as for any change to defaults. +- **M9: census.** `checkStructure`'s hasVariables test and both token-usage counts read the merged tokens; they stay top-level string props only (as today), and the numerator counts a ref only when it is defined (M3, base). +- **M10: the mid-grey case.** `bg-surface: "#777777"` (4.48:1 with white, 4.69:1 with black) derives light tints; `#757575` (4.61 and 4.56) derives dark. +- **M11: tests.** `test/unit/test-unknown-token.ts` (FR-C1 to C4, M2's nested paths, M3's dotted kinds, M5's ladder and multi-typo cases, M6's origins), `test/unit/test-derived-tints.ts` (FR-C5, C6, M7, M8, M10), and a gate in `test/unit/test-patterns.ts`: no `unknown-token` finding on any structure stamped unthemed, then under each preset, then under a generated system. Pins that move, listed in the PR: `test-patterns.ts:67-69` replaces `canvas.variables` wholesale with a preset's, which drops every seeded spacing, radius and type token and so fires the rule on every stamp; it applies the preset through `applyPresetTokens`, as `apply_preset` does. `test-patterns.ts:239` (a non-seed dark value); `test-desktop-primitives.ts:66,75` (the derived tint, not the 12% mix); `test-structures.ts:218-226` (`danger` no longer seeded). **Slice D: desktop-app checks and stress (FR-D1 to FR-D4).** - `variables.ts` select branch: `$border-strong` when defined. `state-checks.ts:268`: `select` measured. From c96094459b94fcd18e68ca6a275d66e02b3a9fe9 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sat, 21 Nov 2026 19:06:16 +0100 Subject: [PATCH 3/6] Warn on unknown tokens and derive the tint layer A $ref no token defines, of the wrong kind, or on a prop that takes none is an unknown-token warning with a rename fix when one name is closest. Copy props never resolve. The tint layer and danger derive from the inks in the surface's mode instead of dark seeds, and old seeds count as unset. --- README.md | 6 +- VISION.md | 6 +- docs/GUIDELINES.md | 25 ++- docs/specs/PHASE-32-SPEC.md | 5 + src/color-system.ts | 35 ++-- src/evaluate.ts | 283 ++++++++++++++++++++++----- src/index.ts | 19 +- src/primitives.ts | 10 + src/structures.ts | 22 +-- src/surfaces.ts | 5 +- src/variables.ts | 179 ++++++++++++++--- src/workspaces.ts | 6 +- test/unit/test-derived-tints.ts | 209 ++++++++++++++++++++ test/unit/test-desktop-primitives.ts | 21 +- test/unit/test-discoverability.ts | 4 +- test/unit/test-patterns.ts | 66 ++++++- test/unit/test-structures.ts | 8 +- test/unit/test-unknown-token.ts | 204 +++++++++++++++++++ 18 files changed, 978 insertions(+), 135 deletions(-) create mode 100644 test/unit/test-derived-tints.ts create mode 100644 test/unit/test-unknown-token.ts diff --git a/README.md b/README.md index 5a97a09..0553188 100644 --- a/README.md +++ b/README.md @@ -532,7 +532,7 @@ The headline call for a new project's look: **one seed color + one personality - **Typography roles** the structures speak — `$display`, `$heading`, `$title` (page/screen titles — one step below `$display`), `$text-lg` / `$text-sm` (untracked in-between sizes for card titles, nav, prose, and metadata), `$body`, `$label`, `$caption` (+ `$figures` with a mono face) — with per-role weight and tracking, alongside the `text-xs`…`text-3xl` steps. `$label` is the one *tracked* role (it carries `letterSpacing`), so structures reserve it for genuine control/CTA/table-header labels and use `$text-sm` for ordinary prose — labeling prose as `$label` reads as a section eyebrow to the cliché census. - **A radius stance** (`radius-sm/md/lg` — e.g. 6/10/14 for `technical`, 12/16/20 for `soft`) and a **density stance** (the space scale pivots on the personality). - **`chart-1`…`chart-6`** — a categorical series palette hue-walked from the seed (≥ 30° apart, purple band avoided unless the seed itself is purple, each ≥ 3:1 on both themes' surfaces per WCAG 1.4.11) for chart segments, series, and legend dots. Near-neutral seeds anchor at a stable blue and say so in the result (`rangeNote`). -- **`accent-tint` / `success-tint` / `warning-tint` / `danger-tint` / `neutral-tint`** — the tint layer: soft same-hue surfaces for status chips, icon tiles, pill badges, and initials avatars. One pairing rule: tint as the fill, base color as the ink (`fill: "$success-tint"` + `color: "$success"`) — AA by construction, dark layer included. +- **`accent-tint` / `success-tint` / `warning-tint` / `danger-tint` / `neutral-tint`** — the tint layer: soft same-hue surfaces for status chips, icon tiles, pill badges, and initials avatars. One pairing rule: tint as the fill, base color as the ink (`fill: "$success-tint"` + `color: "$success"`) — AA by construction, dark layer included. A canvas without them (unthemed, or styled by a preset) derives each tint from its ink in the surface's light or dark mode, and `$danger` from `$error`. - **`focus-ring` / `border-strong`** — the control colors, each at 3:1 or more (WCAG 1.4.11) in both themes: `focus-ring` against every `bg-*` and `-tint` token, `border-strong` against `bg-primary` and `bg-surface`, for a control whose border is its only boundary. - **`state`** — element-state opacities (`hover` 0.08, `focus` 0.10, `pressed` 0.10, `disabledContent` 0.38, `disabledContainer` 0.12; Material 3's values), written to the layer's `state` section. The result reports them as `state`, and the two control colors as `controls`. - **`$elevation.flat` / `raised` / `floating` / `overlay`** — layered soft shadow tokens referenced from any node as `shadow: "$elevation.raised"`. The dark layer **re-states** each depth (stronger black ink) so elevation reads on dark surfaces instead of vanishing. @@ -954,7 +954,7 @@ Whenever the `coverage` category runs on a **base** canvas, the result also carr | `spacing` | 20 | Off-scale padding/gap values (`gap: 0`, a flush stack, is never flagged), plus spacing variety measured against the canvas's **declared** scale (`set_variables`/`generate_scale` spacing tokens) — only values *not* on that scale count toward sprawl, so a design built entirely from its own multi-step scale (framesmith's generated scale ships nine: `space-3xs`…`space-3xl`) isn't penalized for using it. No declared scale falls back to the old total-unique-values count, with a suggestion to declare one | | `color` | 25 | WCAG AA contrast ratios for text against nearest background — checked in BOTH themes when a `dark` token layer exists (dark-run issues carry `theme: "dark"`, score takes the worse theme, and dark failures point at the dark layer instead of carrying a literal fix). WCAG-passing pairs that are perceptually weak by **APCA** get an info advisory (Lc vs ~75 body / ~60 large) — APCA is a candidate method, not a standard; it never blocks. On a desktop-app canvas it also carries the four element-state rules (`desktop-app-focus-visible`, `desktop-app-state-contrast`, `desktop-app-boundary`, `desktop-app-disabled`; see the rules table above), each judged in both themes. Text inside a disabled clickable primitive is exempt, on every type | | `typography` | 20 | Type-scale ratios (1.1–2.0; adjacent sizes both declared as typography tokens are pinned and skip the check), font-family count, weight variation — plus score-neutral craft advisories: measure (prose past ~75 characters per line; warning past 90), tracking (display text ≥28px without negative letter-spacing, autofixable), and tabular numerals (numeric table columns without `tabularNums`, autofixable) On a mobile canvas `mobile-type-floor` adds −10 per warning. | -| `structure` | 15 | Tree depth, naming coverage, design-token usage %, component reuse, unknown icon names (an icon node, or a mobile primitive's icon prop — `button.icon`, `leading.icon`, nav-bar `trailing[].icon`, `tab-bar` `items[].icon` (required) and `fab.icon` — that resolves in neither set renders an empty slot: a directive-blocking warning, −10 structure score each; autofixable for icon nodes and `button.icon` when one spelling resolves) `mobile-artboard` adds −10 per warning, on every type. | +| `structure` | 15 | Tree depth, naming coverage, design-token usage %, component reuse, unknown icon names (an icon node, or a mobile primitive's icon prop — `button.icon`, `leading.icon`, nav-bar `trailing[].icon`, `tab-bar` `items[].icon` (required) and `fab.icon` — that resolves in neither set renders an empty slot: a directive-blocking warning, −10 structure score each; autofixable for icon nodes and `button.icon` when one spelling resolves), and `unknown-token` (a `$ref` no token defines, of the wrong kind for its prop, on a prop that takes no token, or defined only in the dark layer: a directive-blocking warning, −10 each; autofixable when one defined name is closest, see [GUIDELINES](docs/GUIDELINES.md#unknown-tokens)). `mobile-artboard` adds −10 per warning, on every type. | | `consistency` | 20 | Frames missing `layout`, sibling overlap (detailed mode; positioned siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt, while a bar pinned to the top still counts) — plus score-neutral advisories: **token detachment** (a literal `fill`/`stroke`/`color`/`cornerRadius` that exactly equals a token's value flags with a mechanical `$ref` autofix; ambiguous matches list candidates and never guess) and **ad-hoc motion** (3+ distinct duration/easing combos with no motion tokens declared) | | `cliche` | 15 | Machine-made tells: default purple/indigo accent, gradient/glow overuse, fake browser/OS chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated metrics/testimonials/logos, eyebrow rhythm (an eyebrow above nearly every section), slop copy (stock AI phrasing — filler verbs, scroll cues, placeholder names, hype labels), radius consistency (too many distinct corner radii), pure black/white (`#000000` ink / `#ffffff` page vs off-black/off-white), accent consistency (multiple competing accent hues — the `$success`/`$warning`/`$danger` status vocabulary is exempt when referenced as tokens, since those are semantics rather than a second accent; the same hues as literals still count). Each issue carries a `tell` discriminator. Tells are warning or info severity, but **every tell blocks the directive**, whatever its severity (see the `directive` above). Relaxable per `genre`. The tells know dashboard vocabulary: a violet reached only through a `$chart-*` or `$*-tint` token doesn't count as the default-purple tell (a literal violet, or one through any other token, still does), a gradient reached through a `$token` doesn't count toward gradient overuse, thin rounded sparkline bars aren't mistaken for traffic-light dots (fake-chrome now requires a near-square shape), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric, not an eyebrow. It also knows retail copy: a numeral bound to a unit noun by a tight hyphen (`"30-day returns"`, `"2-year warranty"`, `"24/7 support"`) is a compound modifier, not a numbered section eyebrow. | | `coverage` | 10 | State coverage on **base** canvases with data-bearing content: a detected table demands designed `empty` + `loading` variants, a form (3+ input controls, `text-input` included) demands `error` — each missing state is a directive-blocking warning whose suggestion names the `canvas_add_variant` + scaffold path. Variant canvases and non-data screens get no findings. Table detection needs three matching horizontal rows to read as data (two stacked rows are treated as a layout, e.g. a topbar over a greeting); an import-named `Table` frame keeps the looser two-row shape. A list whose every row leads with an icon, a dot or a small image (a sidebar of projects) is navigation and never reads as a table, on every type. On a **`loading`** variant itself, a warning fires per data surface (a detected table, or a frame with 2+ large tabular/numeric texts) that still shows live values while a sibling region is skeletoned — "Loading state is half-designed" — naming the region and suggesting the matching skeleton scaffold. The result's `coverage` field reports `{ dataBearing, states, missing }`. | @@ -1047,7 +1047,7 @@ Runs `canvas_evaluate` in fast mode and returns just the subset of issues with a - **Consistency** — frames with multiple children but no `layout` get `layout: "vertical"`; a literal `fill`/`stroke`/`color`/`cornerRadius` that exactly equals a single token's value gets re-pointed to `$token` (a value shared by multiple tokens is reported with candidates but never auto-fixed — no guessing). - **Color** — recoverable WCAG contrast failures get `color: "#000000"` or `"#FFFFFF"`, whichever wins against the resolved background. Failures so bad that neither black nor white meets the threshold are not auto-fixed (the background also needs to change). - **Cliché** — a *known-default* purple/indigo accent (`#6366f1` and friends) written literally on a node swaps to a neutral accent; a dedicated fake-chrome strip (a row that is just traffic-light dots) gets a `D(...)` delete; pure-black ink (`#000000` text/icon/stroke) softens to off-black. Taste-dependent tells (gradient/glow overuse, the hanging header, fabricated copy, eyebrow rhythm, slop copy, mixed radius systems, competing accents) are reported by `canvas_evaluate` with a suggestion but carry **no** auto-fix op. -- **Structure** — an unknown icon name with exactly one spelling that resolves (hyphen ↔ underscore, or a missing `material:` prefix; if several resolve, the one matching the icon set the rest of the canvas uses) is rewritten via `U(id, { icon: "" })`. Icons inside component definitions are flagged but carry no fix op — edit the component. A name with no resolving spelling is reported with a suggestion only. +- **Structure** — an unknown icon name with exactly one spelling that resolves (hyphen ↔ underscore, or a missing `material:` prefix; if several resolve, the one matching the icon set the rest of the canvas uses) is rewritten via `U(id, { icon: "" })`. Icons inside component definitions are flagged but carry no fix op — edit the component. A name with no resolving spelling is reported with a suggestion only. A misspelt `$token` (`unknown-token`) whose nearest defined name is the only one within two edits, and not another rung of a size ladder, is renamed via `U(id, { gap: "$space-md" })` when the ref is the node's own (a `padding` array or border object is rewritten whole); a wrong-kind token, a ref inside a component or override, and a typo near several names get a suggestion only. - **Coverage** — missing state variants (empty/loading/error) have no mechanical fix either — designing a state is a judgment call. `canvas_evaluate` reports the gap with a suggestion naming the `canvas_add_variant` + scaffold path. **Return shape** diff --git a/VISION.md b/VISION.md index f5c3e0b..d361e62 100644 --- a/VISION.md +++ b/VISION.md @@ -568,7 +568,7 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 - [x] Slice B — vocabulary: a 24px `button` with an accessible name, `link`, `text-input`, `nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row` and `divider`, plus identity dots that never count as accents (moved here from slice A: it keys on `nav-item`) - [x] Slice C — app rules: every click target measured, hand-built targets named, icon-only actions named, one current item per navigation group, a dense type ladder, row rhythm, honest truncation (a tablist whose every label is truncated included), one primary per region, the declaration matching the window, and form coverage counting text-inputs - [x] Slice D — panes: resolution for any number of types, six desktop-app realisations (workbench, list-detail, editor-inspector, browser, dashboard, settings) and the `data-table-app` / `skeleton-table-app` components under the pattern gate, scrolling panes that stress reads as scrolling, and stress runs that triple app rows and card grids -- [ ] Follow-up — the web scaffolds' tint tokens (`success-tint` and the rest) are seeded dark and survive a later light `apply_preset`, as `accent-tint` did before Phase 31 slice D stopped seeding it; derive them from the applied palette instead +- [x] Follow-up — the web scaffolds' tint tokens (`success-tint` and the rest) are seeded dark and survive a later light `apply_preset`, as `accent-tint` did before Phase 31 slice D stopped seeding it; derive them from the applied palette instead (done in Phase 32 slice C) - [x] Slice E — overlays: one overlay layer at the root with a fixed ladder, and the `tooltip`, `popover`, `menu`, `modal`, `toast` and `drawer` primitives, with overlay screen states as variants - [x] Slice F — overlay rules: one modal, text-only tooltips, no large tables in modals, overlays inside the viewport, nothing under a scrim, and advisories on stacked toasts, error toasts and dangling anchors - [x] Slice G — element states: hover, focus, pressed and disabled as a primitive property (and on the items of tabs, tab-bar, nav-bar, modal and toast), drawn from state tokens; focus is a 2px ring at a 2px gap, disabled renders in the on-surface colour, and `state: "disabled"` counts as disabled in the 24px census and the primary count @@ -576,7 +576,7 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 - [x] Slice H — state checks: focus rings, active indicators, disabled renders and control boundaries checked analytically on every interactive primitive, without being drawn, in each theme; text inside a disabled target is exempt from text contrast on every type - [ ] Follow-up — `select` is not in the boundary check, though its `$border` is its only boundary too; and `tree-row` and the contained `tabs` draw no indicator mark when active (a tint and a heavier weight only), so the active-indicator check has nothing to measure on them - [x] Slice I — the acceptance re-run: the viewer's gallery, detail with inspector and archive rebuilt as canvases, with the comment popover and delete-confirm states and the empty archive, all six CLEAN in fast and detailed mode in both themes with a CLEAN stress run, and the six baseline defects fixed (`test/e2e/test-viewer-rebuild.ts`); detailed evaluate now lays out in the design system's own fonts, and a drawer or a scrolling popover reads as scrolling under stress -- [ ] Follow-up — a misspelt `$token` in a non-colour prop (`gap: "$space-xxs"`, which does not exist) resolves to nothing and evaluate says nothing; the slice I rebuild caught one only through its own resolved-tree check. Warn on any `$ref` the merged tokens do not define +- [x] Follow-up — a misspelt `$token` in a non-colour prop (`gap: "$space-xxs"`, which does not exist) resolves to nothing and evaluate says nothing; the slice I rebuild caught one only through its own resolved-tree check. Warn on any `$ref` the merged tokens do not define (done in Phase 32 slice C) - [ ] Follow-up — `nav-item.count` is not a stress slot, so a sidebar count of "999+" is never exercised; add it (and `tabs.items[].count`) to the big-numbers perturbation All nine slices are merged and the acceptance re-run passed. The phase is closed. @@ -589,7 +589,7 @@ Phases 30 and 31 closed with seven follow-ups open, and five of them are quiet f - [x] Slice A — tests in folders: `test/unit`, `test/browser`, `test/e2e` and `test/manual` set the tier, a Chrome guard on `test/unit` proves it at run time, tests are type-checked under `strict`, and files are named by subject, not phase or issue - [x] Slice B — one tree: instances expanded and resolved once, so the renderer and every rule (contrast, spacing and cliché included) see the same thing inside a component, and findings there name the instance -- [ ] Slice C — tokens: an `unknown-token` warning for any `$ref` the merged tokens do not define or that is the wrong kind, with a rename autofix when only one name is close; copy props never resolve; tints and `danger` derive from the applied palette, on new stamps and on canvases holding the old seeds +- [x] Slice C — tokens: an `unknown-token` warning for any `$ref` the merged tokens do not define or that is the wrong kind, with a rename autofix when only one name is close; copy props never resolve; tints and `danger` derive from the applied palette, on new stamps and on canvases holding the old seeds - [ ] Slice D — desktop-app checks: `select` gets a `$border-strong` boundary and joins the boundary check, an active `tree-row` draws a bar the indicator check measures, and stress widens `nav-item` and `tabs` counts - [ ] Slice E — phone targets: `link` and `text-input` (with a new 44px `size: "lg"`) join the 44px census, and `modal` and `toast` take a `controlSize` the census measures diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 563a21a..6aa3c41 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -136,7 +136,7 @@ Build application screens from these primitives, never from hand-built frames: a - **`property-row`** `{ label, labelWidth? }` with one child is an inspector row: a muted label column (96px by default) and the value (a control, a `text-input`, a `button`, a text). Every row's value starts at the same edge. The row's `label` names a control directly inside it; with a blank label only text inside the row itself does, and otherwise the control gets the usability warning "has no text label" (a sibling row's text does not count). A control that is its only target (directly inside, nothing clickable beside it) is measured by the row's 32px box. Only `property-row` renders children; the other desktop-app primitives draw their own anatomy and drop any children you give them. - **`divider`** `{ orientation?: "horizontal" | "vertical", inset? }` is a 1px `$border` hairline; vertical dividers separate panes. Not a target. -Repeated desktop-app primitives count as component reuse. On an unthemed canvas, stamping a structure that holds them seeds `$border-strong` along with the usual neutrals, never `$accent-tint`: without that token an active fill mixes 12% of `$accent` into whatever surface is applied later. +Repeated desktop-app primitives count as component reuse. On an unthemed canvas, stamping a structure that holds them seeds `$border-strong` along with the usual neutrals, never `$accent-tint`: without that token the active fill is the tint derived from `$accent` in the mode of whatever surface is applied later (see [the tint layer](#the-tint-layer-derives-when-undefined)). ### Overlays (screen states) @@ -256,7 +256,7 @@ Two components join them: `data-table-app` (the `data-table` anatomy on desktop- - **They fill the window and scroll by pane.** A desktop-app page stamp sets the root's `overflow` to `"hidden"`, which keeps the root at the artboard's height (a root with no authored overflow grows with its content). The shell is `height: "100%"`, and the sidebar, list, detail, work area, inspector and content panes are each `overflow: "auto"`, so long content scrolls inside its pane while the window stays put. Stamping a different page with `replace` removes that root `overflow` again, unless it no longer reads `"hidden"` (an `overflow` you set to anything else stays). Keep the pattern when you adapt one: put new content inside a pane, never give a pane's direct child a fixed `height` or an `overflow` (either lets the pane squash it instead of scrolling), and give a fixed-width pane a matching `minWidth` (a scrolling pane may otherwise shrink below its width). Rows go inside the frame that already holds rows (in `settings-app`, a group's `Rows` frame; in `list-detail-app`, the `Rows` frame of the list pane), which is a direct child of the pane only through its group, so it grows and the pane scrolls. - **They pass the gate the docs promise.** Each scores > 95 with zero cliché tells, zero desktop-app findings at any severity and zero warnings or errors in fast mode, under the default theme, the four presets applied after the stamp, every personality on three seeds and a workspace design system inherited from above; in detailed mode as stamped and with every list tripled; with a CLEAN `canvas_stress` run unthemed and under every personality; and at 1024×768 and 1280×800, where long labels truncate instead of pushing a bar past the window (the shell fills any artboard height, and the narrowest window the desktop-app layouts are built for is 1024 wide; 1440×900 is the default). Infos from other categories may remain; nothing that blocks the directive does, so after a stamp `canvas_evaluate` says READY TO PRESENT unless coverage asks for a state. Coverage is the exception: a stamp with a table or a form asks for the states in the table above, which you design with `canvas_add_variant`. -- **Stamp after `generate_design_system`, or apply a preset after the stamp.** Both work. A stamp on an unthemed canvas seeds `$border-strong` but not `$accent-tint`: without the token an active `nav-item` or `tabs` fill mixes 12% of `$accent` into whatever surface is applied later, so a light preset never inherits a dark tint. +- **Stamp after `generate_design_system`, or apply a preset after the stamp.** Both work. A stamp on an unthemed canvas seeds `$border-strong` but never `$danger` or a tint: without them an active `nav-item` or `tabs` fill, a status chip and a danger zone derive their colours from the inks and whatever surface is applied later, so a light preset never inherits a dark tint. - **Adapt it from the placeholders.** As on mobile, the result's `placeholders` list every copy field with its `prop` path (`label`, `placeholder`, `value`, `items[0].label`). A control inside a `property-row` is labelled by that row's `label`, so keep it filled. - **Web-only components stay web-only.** `toolbar`, `toggle-row`, `segmented-control` and `breadcrumb` are refused on desktop-app with the list of components that stamp there; `realisation: "web"` forces one anyway. The realisations draw their own breadcrumb from a `link`. @@ -379,6 +379,21 @@ A design language is a set of COMMITTED choices, and `generate_design_system` ma **Chips, tiles, and pills use the tint pair.** Every soft-colored surface — a status chip, a KPI card's icon tile, a pill badge, an initials avatar — is `fill: "$success-tint"` (or `accent-tint` / `warning-tint` / `danger-tint` / `neutral-tint`) with its BASE color as the ink: `color: "$success"`. The pair is AA by construction in both themes; hand-mixed pastel + hex ink combinations are exactly the thing this layer exists to end. Chart series and legend dots take `$chart-1`…`$chart-6` — hue-walked from the seed, distinct, and safe on both surfaces. The cliché tells recognize this vocabulary: a violet referenced through `$chart-*` or `$*-tint` never flags (a literal violet still does), and uppercase KPI labels beside big tabular figures don't count as eyebrows — the evaluator knows a metric label from a section eyebrow. +#### The tint layer derives when undefined + +On a canvas whose design system has no tint tokens (unthemed, or styled by a preset, since no preset defines tints), `$accent-tint`, `$success-tint`, `$warning-tint`, `$danger-tint` and `$neutral-tint` still resolve: each is derived from its ink (`$accent`, `$success`, `$warning`, `$danger`, `$text-secondary`) with the generator's own tint rule, in the mode of the surface they sit on. The surface is `$bg-surface`, else `$bg-primary`, else white; a translucent surface is laid over the next opaque one; the mode is dark when that surface contrasts more with white than with black. A grey ink gets a grey tint. `$danger` resolves to `$error`, else `#DC2626` on a light surface and `#F87171` on a dark one. A dark render derives from the dark layer's inks and surface. The pair clears 4.5:1 whenever the ink can: the light preset's `success` and `error` fall below 4.5:1 even on white, and the contrast check reports those inks. A canvas stamped before this still holding an old scaffold seed (`#152A47` for `accent-tint`, `#0F2E1B`, `#33260A`, `#3A1715`, `#25282D` for the other tints, `#F87171` for `danger`, matched by name and value) renders as if it were unset: an inherited value shows through, else the derived one. Its stored JSON is untouched, `get_variables` leaves those values out, and its `sha256r:` version hash moves once, so an approval recorded on it reads STALE. + +#### Unknown tokens + +`canvas_evaluate` warns (rule `unknown-token`, structure category, directive-blocking, −10 each) on every `$ref` that renders something other than intended: + +- **A name no token defines** — `gap: "$space-mdd"`. The suggestion names up to three defined tokens of the kind the prop takes, nearest spelling first. When exactly one is closest (within two edits) and it is not another rung of the same size ladder, a ref on the node's own top-level prop, `padding` / `cornerRadius` entry or border colour carries a rename fix that `canvas_autofix` applies: `$space-mdd` → `$space-md`, `$bg-surfce` → `$bg-surface`. `$space-xxs` is as close to `$space-3xs`, `$space-2xs` and `$space-xs`, so it is reported with all three and no fix; `$space-lg` on a ladder without it is a different size, never renamed to `$space-md`. +- **The wrong kind** — a typography or spacing token on a colour prop (`fill: "$body"` renders `16`), a colour on a number prop (`gap: "$accent"`), a whole token group (`$typography.body`). A typography ref is valid only on `fontSize`, where it applies the whole role. +- **A prop that takes no token** — `fontFamily: "$display"` renders the role's size as the font name. +- **A name defined only in the dark layer** — light renders it raw; define it in the base colours too. + +Refs inside a component or an instance's `overrides` are judged as rendered, once per place they are written, and reported on the instance with no fix: fix the component, or edit the override. The rule reads top-level props, `padding` / `cornerRadius` entries, `borderTop`/`Right`/`Bottom`/`Left.color`, chart `series[].stroke` and `segments[].color`, and a modal's `actions[]` and a toast's `action` colours. Deliberately not checked: copy (`content`, `text`, `title`, `label`, `value`, `count`, `centerValue` and the rest never resolve, so `content: "$49"` is a price), and `gradient.stops[].color` and `shadows[].color`, which the resolver does not read either, so a ref there renders raw and silent. `$elevation.*`, `$motion.*`, `$colors.*`, `$spacing.*` and names starting with a digit (`$2xl`) are valid when defined, and the derived tints and `$danger` always are. The token-usage stat counts only refs that resolve, against the tokens the canvas inherits too. + **Motion comes from tokens.** `transition: "$motion.fast"` for hover/focus feedback, `"$motion.base"` for state changes, `"$motion.slow"` for surfaces entering/leaving. The personality sets the temperament; scattering literal millisecond values breaks it. ## Components & reuse @@ -466,8 +481,8 @@ Exit codes are gate-friendly for both commands: `0` pass, `1` drift/mismatch, `2 ## After designing -- **`canvas_evaluate`** scores the design on 8 categories (spacing, color, typography, structure, consistency, cliche, coverage, usability) and surfaces actionable issues with `nodeId` references — see "Design every state" below for what `coverage` demands. The `usability` category holds the mechanical UX floors beyond contrast: a pointer target below the 24px floor fails (WCAG 2.5.8 — a lone control inherits its padded row's box, so real settings rows pass, and a smaller target passes by the spacing exception; fast mode warns, detailed mode errors, see [the 24px floor](#the-24px-floor-web-and-desktop-app); on a canvas declared mobile the floor is 44px instead, `mobile-touch-target` in [the mobile ruleset](#the-mobile-ruleset)), an unlabeled control is a warning, and vague action copy ("Click here") is an info. The `structure` category also warns — directive-blocking — on unknown icon names (an empty slot in the render). Controls also render with accent-derived `:focus-visible` rings in the live viewer — screenshots stay byte-identical because nothing is focused in a static capture. Use it in a generator-evaluator loop: `batch_design` → `canvas_evaluate` → fix the returned nodeIds. **Repeated findings fold**: three or more warnings or infos with the same rule (or tell), category and theme come back as ONE entry carrying `nodeIds`, `count` and, when they had fixes, `fixes: [{ nodeId, op }]` — act on every node it lists. Members with a fix fold on the message's shape (the fix op holds each node's numbers); members without one fold only when they read the same apart from quoted node text, so two type-ratio warnings with different sizes stay separate. Errors never fold. `canvas_autofix` works from the unfolded list, so it still returns one op per node. -- **`canvas_autofix`** runs `canvas_evaluate` internally and returns just the subset of issues that have a mechanically derived fix — off-scale spacing snaps to scale (`gap`, scalar padding, and array padding via a whole-array snap), missing layout becomes `vertical`, recoverable WCAG contrast failures get `#000` or `#FFF` based on background luminance, and an unknown icon name with exactly one resolving spelling is rewritten to it. Pass `apply: true` to write every fix in the same call (the result reports applied/failed per op), or run the returned ops via `batch_design` yourself — either way, re-evaluate after. Closes the loop without judgment calls on your part. +- **`canvas_evaluate`** scores the design on 8 categories (spacing, color, typography, structure, consistency, cliche, coverage, usability) and surfaces actionable issues with `nodeId` references — see "Design every state" below for what `coverage` demands. The `usability` category holds the mechanical UX floors beyond contrast: a pointer target below the 24px floor fails (WCAG 2.5.8 — a lone control inherits its padded row's box, so real settings rows pass, and a smaller target passes by the spacing exception; fast mode warns, detailed mode errors, see [the 24px floor](#the-24px-floor-web-and-desktop-app); on a canvas declared mobile the floor is 44px instead, `mobile-touch-target` in [the mobile ruleset](#the-mobile-ruleset)), an unlabeled control is a warning, and vague action copy ("Click here") is an info. The `structure` category also warns — directive-blocking — on unknown icon names (an empty slot in the render), and on token refs that render something other than intended (rule `unknown-token`, see [Unknown tokens](#unknown-tokens)). Controls also render with accent-derived `:focus-visible` rings in the live viewer — screenshots stay byte-identical because nothing is focused in a static capture. Use it in a generator-evaluator loop: `batch_design` → `canvas_evaluate` → fix the returned nodeIds. **Repeated findings fold**: three or more warnings or infos with the same rule (or tell), category and theme come back as ONE entry carrying `nodeIds`, `count` and, when they had fixes, `fixes: [{ nodeId, op }]` — act on every node it lists. Members with a fix fold on the message's shape (the fix op holds each node's numbers); members without one fold only when they read the same apart from quoted node text, so two type-ratio warnings with different sizes stay separate. Errors never fold. `canvas_autofix` works from the unfolded list, so it still returns one op per node. +- **`canvas_autofix`** runs `canvas_evaluate` internally and returns just the subset of issues that have a mechanically derived fix — off-scale spacing snaps to scale (`gap`, scalar padding, and array padding via a whole-array snap), missing layout becomes `vertical`, recoverable WCAG contrast failures get `#000` or `#FFF` based on background luminance, an unknown icon name with exactly one resolving spelling is rewritten to it, and a misspelt `$token` whose nearest defined name is the only one that close is renamed to it. Pass `apply: true` to write every fix in the same call (the result reports applied/failed per op), or run the returned ops via `batch_design` yourself — either way, re-evaluate after. Closes the loop without judgment calls on your part. - **`canvas_evaluate` with `mode: "llm"`** runs fast-mode heuristics plus a vision-model critique against a **fixed rubric** (Claude or GPT-4.1, picked from env). Returns the heuristic result with an extra `llmCritique` field: five axes — **hierarchy, execution, specificity, restraint, variety** — each scored 1–5 with a rationale, plus a derived overall, `summary`, `suggestions`, and `needsRevision` / `failingAxes` (any axis below the `floor`, default 3). The verdict is stamped on the canvas + build log so quality is auditable over time. Use this for the "is this visually well-designed?" question heuristics can't answer — composition, hierarchy, polish. Costs one API call per run; reach for it after the heuristic score plateaus. - **`canvas_revise`** closes the loop: it judges, and for any failing axis asks the model for targeted `batch_design` ops, applies them, and re-judges — up to `maxIterations` passes (1–3). It **mutates the canvas**, reverts any pass that doesn't improve the overall, and stops on pass / cap / no-improvement. Opt-in and costly (≥2 API calls per pass); reach for it when you want the model to act on its own critique instead of you hand-translating it. It never gates presenting: if it stops with axes still failing, present and name them. - **`screenshot_responsive`** renders the same scene at mobile / tablet / desktop. Inspect all three; if `responsive` hints are set correctly the mobile layout will look right with no extra work. @@ -529,7 +544,7 @@ The bar is "designers say *wow*," not "competent." The cliché tells below are t Polishing the design to the bar is **your** job, not the user's — they should never have to point out a missing icon, an off-scale gap, or a low score. So the loop is part of designing, not an afterthought: 1. `canvas_evaluate` the canvas. -2. **Resolve every warning and every cliché tell** — `canvas_autofix` for the mechanical subset (spacing/contrast/known-default accent/misspelled icon), `batch_design` for the rest. (Cliché tells are info/warning but they're the slop signal — always fix them.) Pure advisories like "consider extracting components" are optional refinements that don't block. +2. **Resolve every warning and every cliché tell** — `canvas_autofix` for the mechanical subset (spacing/contrast/known-default accent/misspelled icon/misspelled token), `batch_design` for the rest. (Cliché tells are info/warning but they're the slop signal — always fix them.) Pure advisories like "consider extracting components" are optional refinements that don't block. 3. Re-run `canvas_evaluate`. 4. Repeat until there are **zero errors, zero warnings, and zero cliché tells**. diff --git a/docs/specs/PHASE-32-SPEC.md b/docs/specs/PHASE-32-SPEC.md index 92f986e..cc48716 100644 --- a/docs/specs/PHASE-32-SPEC.md +++ b/docs/specs/PHASE-32-SPEC.md @@ -151,6 +151,11 @@ And one is housekeeping the follow-ups will land in. 140 tests and `test-env.ts` - **M10: the mid-grey case.** `bg-surface: "#777777"` (4.48:1 with white, 4.69:1 with black) derives light tints; `#757575` (4.61 and 4.56) derives dark. - **M11: tests.** `test/unit/test-unknown-token.ts` (FR-C1 to C4, M2's nested paths, M3's dotted kinds, M5's ladder and multi-typo cases, M6's origins), `test/unit/test-derived-tints.ts` (FR-C5, C6, M7, M8, M10), and a gate in `test/unit/test-patterns.ts`: no `unknown-token` finding on any structure stamped unthemed, then under each preset, then under a generated system. Pins that move, listed in the PR: `test-patterns.ts:67-69` replaces `canvas.variables` wholesale with a preset's, which drops every seeded spacing, radius and type token and so fires the rule on every stamp; it applies the preset through `applyPresetTokens`, as `apply_preset` does. `test-patterns.ts:239` (a non-seed dark value); `test-desktop-primitives.ts:66,75` (the derived tint, not the 12% mix); `test-structures.ts:218-226` (`danger` no longer seeded). +**Slice C — as built (recorded 2026-11-21).** Decisions the pinned contracts did not settle: +- **N1: a stamp that reads a derived colour seeds the surface** *(spec change during build)*. A lone `status-chip` on an unthemed canvas seeds only its ink (`success` `#4ADE80`, tuned for the dark scaffold palette), so with no surface token its tint derived light and the pair read about 1.5:1, where the old dark seed tint read 7.6:1. `applyStructure` now seeds `bg-surface` (the scaffold default `#111111`) whenever the stamp references a derived name and the canvas resolves neither `bg-surface` nor `bg-primary`. Red before the change: `test-derived-tints.ts` "unthemed: a dark-mode tint" (it derived `#E0FEE6`). A sweep in the same test now holds every structure, unthemed and under the dark, material and minimal presets, to no contrast error against a derived tint; measured against master, every theme has fewer contrast findings than before (the old seeds failed the initials avatar unthemed and every tint chip under the light, material and minimal presets). +- **N2: the patterns harness defines what it references.** The desktop-app gate gives a component stamp a `$bg-primary` backdrop; a component stamp never seeds it, so unthemed it was undefined and drew nothing. The harness now defines it (`#0a0a0a`, the scaffold default); `unknown-token` is what caught it. The gate's tint predicate reads the tokens the render uses (merged, old seeds dropped, missing tints derived) instead of the stored canvas layer. +- **N3: masters in the tree.** A component's master can sit in the stored tree as well as in `canvas.components` (`batch_design` registers the inserted node itself). M6's origins treat a master's subtree as the definition, so a typo in it is one finding, warn-only, whether or not an instance shows it, and a definition walked through its master is not walked again. + **Slice D: desktop-app checks and stress (FR-D1 to FR-D4).** - `variables.ts` select branch: `$border-strong` when defined. `state-checks.ts:268`: `select` measured. - `renderTreeRow` (`renderer.ts:1610`): `position: relative` with `renderNavItem`'s guard, and the bar. `indicatorPairs` (`state-checks.ts:211-236`): `tree-row`. diff --git a/src/color-system.ts b/src/color-system.ts index 1225642..db682f9 100644 --- a/src/color-system.ts +++ b/src/color-system.ts @@ -7,7 +7,7 @@ // Gamut policy (spec ANALYZE): out-of-gamut colors clip toward LOWER CHROMA // at fixed lightness and hue — never hue-shift, never lightness-shift. -import { contrastRatio, parseColor } from './evaluate.js'; +import { contrastRatio, parseColor } from './color-math.js'; export interface Oklch { l: number; // 0..1 @@ -281,22 +281,29 @@ export function tintLayer( mode: 'light' | 'dark', ): TintLayer { const out = {} as TintLayer; - for (const [name, ink] of Object.entries(inks) as Array<[keyof TintLayer, string]>) { - const hue = hexToOklch(ink).h; - let tint: Oklch = mode === 'light' - ? { l: 0.93, c: 0.045, h: hue } - : { l: 0.3, c: 0.055, h: hue }; - const inkRgb = rgbOf(ink); - // Back the tint off (lighter in light mode, darker in dark) until the - // pair reads at AA text contrast. - for (let i = 0; i < 20 && contrastRatio(inkRgb, rgbOf(oklchToHex(tint))) < 4.5; i++) { - tint = { ...tint, l: mode === 'light' ? Math.min(0.97, tint.l + 0.01) : Math.max(0.2, tint.l - 0.01) }; - } - out[name] = oklchToHex(tint); - } + for (const [name, ink] of Object.entries(inks) as Array<[keyof TintLayer, string]>) out[name] = tintFor(ink, mode); return out; } +/** One tint of the tint layer for a hex ink. With `grey`, an ink with no + * usable hue (OKLCH chroma under 0.005) gets a grey tint: its hue is noise, + * and a pure grey would otherwise wash into an arbitrary colour. The + * generator never passes it. */ +export function tintFor(ink: string, mode: 'light' | 'dark', opts: { grey?: boolean } = {}): string { + const { c, h } = hexToOklch(ink); + const grey = opts.grey && c < 0.005; + let tint: Oklch = mode === 'light' + ? { l: 0.93, c: grey ? 0 : 0.045, h } + : { l: 0.3, c: grey ? 0 : 0.055, h }; + const inkRgb = rgbOf(ink); + // Back the tint off (lighter in light mode, darker in dark) until the + // pair reads at AA text contrast. + for (let i = 0; i < 20 && contrastRatio(inkRgb, rgbOf(oklchToHex(tint))) < 4.5; i++) { + tint = { ...tint, l: mode === 'light' ? Math.min(0.97, tint.l + 0.01) : Math.max(0.2, tint.l - 0.01) }; + } + return oklchToHex(tint); +} + export type StatusColors = Record<'success' | 'warning' | 'danger', string>; /** Phase 31 FR-A8 — the control colors an app needs: a focus ring that reads diff --git a/src/evaluate.ts b/src/evaluate.ts index fe116f7..1a5b22a 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -2,6 +2,7 @@ import type { Canvas, SceneNode, DesignVariables, TabItem } from './types.js'; import { getCanvasTokens } from './workspaces.js'; import { renderToHtml, type RenderOptions } from './renderer.js'; import { expandTree } from './expand.js'; +import { DERIVED_COLORS, refPath, themeTokens, tokenKind, tokenRefs, type RefSite, type TokenKind } from './variables.js'; import { computeLayout, type LayoutRect } from './screenshot.js'; import { checkCurrent, checkDesktopArtboard, checkHandbuiltTargetsApp, checkIconLabels, checkOverlays, checkPrimaryCount, checkRowRhythm, checkTruncation, @@ -14,7 +15,7 @@ import { checkStates, STATE_RULES } from './state-checks.js'; import { storedGenre } from './genre.js'; import { relaxedByPreset, relaxedByGenre, canonicalGenre, genreRulesets, activeRulesets, composeRulesets, resolveSurface, deviceProfile, DEVICE_PROFILES, DEFAULT_DEVICE, MOBILE_RULES, DESKTOP_APP_RULES, DEFAULT_WINDOW, WINDOW_PROFILES, windowProfile, type SurfaceType } from './surfaces.js'; import { checkArtboard, checkHandbuiltTargets, checkOneColumn, checkSafeAreaDetailed, checkSafeAreaFast, checkTabBars, checkTypeFloor, paddingSides, type MobileContext } from './mobile-rules.js'; -import { CHROME_EDGE, FAB_SIZE, NAV_ACTION, TAPPABLE_PRIMITIVES, CLICKABLE_PRIMITIVES, CONTROL_OWNERS, LIST_ROW_HEIGHT, MENU_ROW_HEIGHT, NAV_ITEM_HEIGHT, PROPERTY_ROW_HEIGHT, buttonBox, desktopTargets, overlayTargets, effectivePosition, isDisabled, STATEFUL_TYPES, listRowMinHeight, navActions, pinsBottom, tabItemBox, tabItems } from './primitives.js'; +import { COPY_PROPS, CHROME_EDGE, FAB_SIZE, NAV_ACTION, TAPPABLE_PRIMITIVES, CLICKABLE_PRIMITIVES, CONTROL_OWNERS, LIST_ROW_HEIGHT, MENU_ROW_HEIGHT, NAV_ITEM_HEIGHT, PROPERTY_ROW_HEIGHT, buttonBox, desktopTargets, overlayTargets, effectivePosition, isDisabled, STATEFUL_TYPES, listRowMinHeight, navActions, pinsBottom, tabItemBox, tabItems } from './primitives.js'; // --- Types --- @@ -675,7 +676,7 @@ function checkTypography(entries: NodeEntry[], variables: DesignVariables = {}, return { score: Math.max(0, Math.min(100, Math.round(score))), issues }; } -function checkStructure(entries: NodeEntry[], canvas: Canvas): CheckResult { +function checkStructure(entries: NodeEntry[], canvas: Canvas, tokens: DesignVariables, unknownTokens: boolean): CheckResult { const issues: EvaluationIssue[] = []; let score = 100; @@ -722,26 +723,14 @@ function checkStructure(entries: NodeEntry[], canvas: Canvas): CheckResult { } } - // Token usage (copy and variant names on the mobile primitives are not - // style values — they could never be tokens) - const hasVariables = canvas.variables && ( - Object.keys(canvas.variables.colors ?? {}).length > 0 || - Object.keys(canvas.variables.spacing ?? {}).length > 0 - ); + // Token usage, against the tokens the canvas resolves (its own and what it + // inherits). Copy and enum names are not style values, and a ref counts only + // when it is defined: a typo is not token use. + const hasVariables = Object.keys(tokens.colors ?? {}).length > 0 || Object.keys(tokens.spacing ?? {}).length > 0; if (hasVariables) { - let tokenRefs = 0; - let totalProps = 0; - for (const { node } of entries) { - for (const [key, val] of Object.entries(node)) { - if (['id', 'type', 'name', 'children'].includes(key) || PRIMITIVE_COPY_PROPS.has(key)) continue; - if (typeof val === 'string') { - totalProps++; - if (val.startsWith('$')) tokenRefs++; - } - } - } - if (totalProps > 0) { - const tokenPercent = Math.round((tokenRefs / totalProps) * 100); + const { refs, total } = tokenCensus(entries, tokens); + if (total > 0) { + const tokenPercent = Math.round((refs / total) * 100); if (tokenPercent < 30) { score -= 10; issues.push({ @@ -761,6 +750,14 @@ function checkStructure(entries: NodeEntry[], canvas: Canvas): CheckResult { score -= 10 * iconFindings.length; issues.push(...iconFindings); + // Phase 32 slice C — unknown and wrong-kind token refs render something + // other than intended (usually nothing). Same weight as an unknown icon. + if (unknownTokens) { + const tokenFindings = checkUnknownTokens(canvas, tokens); + score -= 10 * tokenFindings.length; + issues.push(...tokenFindings); + } + // Component reuse. Phase 30 slice D — a repeated primitive (list rows, // buttons, tab bars) is reuse too: the primitive is the component. Phase 31 // slice B adds the desktop-app vocabulary. @@ -808,16 +805,6 @@ function iconSlots(root: SceneNode): Array<{ node: SceneNode; path: string; ref: return out; } -/** Phase 30 slice D — the mobile primitives' copy and enum props: words and - * variant names, never style values, so the token census skips them. */ -const PRIMITIVE_COPY_PROPS = new Set([ - 'title', 'subtitle', 'label', 'time', 'variant', 'size', 'detent', 'appearance', 'iconPosition', - // Phase 31 slice B — the desktop-app primitives' copy and enums. - 'placeholder', 'value', 'shortcut', 'error', 'ariaLabel', 'count', 'orientation', - // Phase 31 slice G — the element state is an enum, not a style value. - 'state', -]); - /** Spellings worth trying for an icon name that didn't resolve: Material * Symbols names multi-word icons with `_` (chevron_right), Lucide with `-` * (chevron-right), and Material needs the `material:` prefix. Each candidate @@ -910,6 +897,224 @@ function checkUnknownIcons(canvas: Canvas): EvaluationIssue[] { return issues; } +/** The token census: top-level string style props, and how many of them are + * refs the tokens define. */ +function tokenCensus(entries: NodeEntry[], tokens: DesignVariables): { refs: number; total: number } { + let refs = 0; + let total = 0; + for (const { node } of entries) { + for (const [key, val] of Object.entries(node)) { + if (key === 'id' || key === 'type' || key === 'children' || COPY_PROPS.has(key) || typeof val !== 'string') continue; + total++; + if (val.startsWith('$') && tokenKind(val.slice(1), tokens) !== undefined) refs++; + } + } + return { refs, total }; +} + +// ── Phase 32 slice C: unknown-token (FR-C1, FR-C2; contracts M2–M6) ───────── + +const COLOR_PROPS = new Set(['fill', 'stroke', 'color', 'iconColor', 'secondaryColor', 'badgeColor', 'dotColor']); +const NUMBER_PROPS = new Set([ + 'width', 'height', 'minWidth', 'maxWidth', 'minHeight', 'gap', 'rowGap', 'padding', 'cornerRadius', 'x', 'y', 'bottom', 'right', + 'strokeWidth', 'opacity', 'blur', 'backdropBlur', 'fontWeight', 'lineHeight', 'letterSpacing', 'iconSize', 'labelWidth', + 'inset', 'depth', 'rows', 'innerRatio', 'gridlines', +]); +const KIND_NAMES: Record = { + color: 'a color token', number: 'a spacing or radius token', typography: 'a typography token', + elevation: 'an elevation token', motion: 'a motion token', object: 'a whole token group', +}; + +/** The token kinds a ref site takes (M4); empty when it takes none. */ +function siteAccepts(site: RefSite): TokenKind[] { + if (site.sub) return ['color']; + if (COLOR_PROPS.has(site.key)) return ['color']; + if (site.key === 'fontSize') return ['number', 'typography']; + if (NUMBER_PROPS.has(site.key)) return ['number']; + if (site.key === 'shadow') return ['elevation']; + if (site.key === 'transition') return ['motion']; + return []; +} + +/** The defined names a site could have meant (M5). */ +function candidatePool(accepts: TokenKind[], tokens: DesignVariables): string[] { + const names = new Set(); + const add = (cat: object | undefined, prefix = '') => { for (const k of Object.keys(cat ?? {})) names.add(prefix + k); }; + if (accepts.includes('color')) { add(tokens.colors); DERIVED_COLORS.forEach((n) => names.add(n)); } + if (accepts.includes('number')) { add(tokens.spacing); add(tokens.radius); } + if (accepts.includes('typography')) add(tokens.typography); + if (accepts.includes('elevation')) add(tokens.elevation, 'elevation.'); + if (accepts.includes('motion')) add(tokens.motion, 'motion.'); + return [...names]; +} + +function levenshtein(a: string, b: string): number { + const row = Array.from({ length: b.length + 1 }, (_, i) => i); + for (let i = 1; i <= a.length; i++) { + let prev = row[0]; + row[0] = i; + for (let j = 1; j <= b.length; j++) { + const cur = row[j]; + row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); + prev = cur; + } + } + return row[b.length]; +} + +/** The size step a token name ends in (md, 2xl, 3xs, 4), if any. */ +function ladderStep(name: string): string | undefined { + const last = name.slice(name.lastIndexOf('-') + 1).toLowerCase(); + return /^(\d*x*[sml]|sm|md|lg|\d+)$/.test(last) ? last : undefined; +} + +/** The value at a ref site on an object (a node or an override). */ +function valueAt(obj: unknown, site: RefSite): unknown { + let v = (obj as Record | undefined)?.[site.key]; + if (site.at !== undefined) v = Array.isArray(v) ? v[site.at] : undefined; + if (site.sub) v = v && typeof v === 'object' ? (v as Record)[site.sub] : undefined; + return v; +} + +/** M5 (d): the sites a rename op can rewrite whole through the U parser. */ +const fixableSite = (site: RefSite) => + (!site.sub && site.at === undefined) || ((site.key === 'padding' || site.key === 'cornerRadius') && !site.sub) || NESTED_BORDER.has(site.key); +const NESTED_BORDER = new Set(['borderTop', 'borderRight', 'borderBottom', 'borderLeft']); + +function checkUnknownTokens(canvas: Canvas, tokens: DesignVariables): EvaluationIssue[] { + const dark = themeTokens(tokens, 'dark'); + const raw = expandTree(canvas.root, canvas).root; + + // Expanded id of every expanded instance root → that instance node (stored, + // or inside a component definition), mirroring expandTree's id scheme. + const instAt = new Map(); + const used = new Set(); + (function walk(node: SceneNode, prefix: string, inside: boolean, open: Set) { + const id = inside ? prefix + node.id : node.id; + const cid = node.type === 'instance' ? node.componentId : undefined; + const component = cid && !open.has(cid) ? canvas.components[cid] : undefined; + if (component) { + instAt.set(id, node); + used.add(cid!); + open.add(cid!); + for (const c of component.children ?? []) walk(c, `${prefix}${node.id}/`, true, open); + open.delete(cid!); + return; + } + for (const c of node.children ?? []) walk(c, prefix, inside, open); + })(canvas.root, '', false, new Set()); + + // M6 — where a value on an expanded node was written. A component's master + // can sit in the stored tree as well as in canvas.components: inside it + // (`master`), a stored node's own value is the definition's. + const defNode = (cid: string, id: string) => `def:${cid}:${id === cid ? '(root)' : id}`; + const originOf = (id: string, node: SceneNode, site: RefSite, ref: string, master?: string): string => { + const slash = id.lastIndexOf('/'); + const parent = slash < 0 ? undefined : instAt.get(id.slice(0, slash)); + const own = () => (parent ? defNode(parent.componentId!, id.slice(slash + 1)) : master ? defNode(master, id) : `node:${id}`); + const inst = instAt.get(id); + if (inst) return valueAt(inst, site) === ref ? own() : `def:${inst.componentId}:(root)`; + if (!parent) return own(); + const override = node.name ? parent.overrides?.[node.name] : undefined; + if (override && valueAt(override, site) === ref) return `ovr:${id.slice(0, slash)}:${node.name}`; + return `def:${parent.componentId}:${id.slice(slash + 1)}`; + }; + + const issues: EvaluationIssue[] = []; + const seen = new Set(); + // Renames per (stored node, top-level key), so two typos in one array carry + // one op that applies both. + const renames = new Map>(); + const pending: Array<{ issue: EvaluationIssue; nodeId: string; key: string }> = []; + + // A master in the stored tree is walked there, so its definition is not + // walked again. + const masters = new Set(); + (function find(n: SceneNode) { if (n.type === 'component' && canvas.components[n.id]) masters.add(n.id); n.children?.forEach(find); })(canvas.root); + + /** `component`: the id of the definition the ref is read from directly (a + * master in the tree, or a definition no instance uses). */ + const judge = (node: SceneNode, site: RefSite, ref: string, origin: string, component?: string) => { + const path = refPath(site); + const dedupe = `${origin}\u0000${path}\u0000${ref}`; + if (seen.has(dedupe)) return; + seen.add(dedupe); + const name = ref.slice(1); + const accepts = siteAccepts(site); + const kind = tokenKind(name, tokens); + const base = { category: 'structure' as const, severity: 'warning' as const, rule: 'unknown-token', nodeId: node.id, nodeName: node.name }; + const where = component ? ` (in component "${canvas.components[component]?.name ?? component}"${used.has(component) ? '' : ', which no instance uses'})` : ''; + const fromOverride = origin.startsWith('ovr:') ? ' It is set by the instance\'s override for this node: edit that override.' : ''; + + if (accepts.length === 0) { + issues.push({ ...base, message: `${path} takes no token: "${ref}" ${kind ? `is ${KIND_NAMES[kind]} and renders as its value` : 'renders as written'}${where}.`, suggestion: `Write the value itself.${fromOverride}` }); + return; + } + if (kind && !accepts.includes(kind)) { + const pool = candidatePool(accepts, tokens).sort(); + const examples = pool.length ? ` (the canvas defines ${pool.slice(0, 3).map((n) => `"$${n}"`).join(', ')}${pool.length > 3 ? ', …' : ''})` : ''; + issues.push({ ...base, message: `"${ref}" on ${path} is ${KIND_NAMES[kind]}, not ${KIND_NAMES[accepts[0]]}${where}.`, suggestion: `Use ${KIND_NAMES[accepts[0]]}${examples}.${fromOverride}` }); + return; + } + if (kind) return; + if (tokenKind(name, dark) !== undefined) { + issues.push({ ...base, message: `Token "${ref}" on ${path} is defined only in the dark layer, so light renders it raw${where}.`, suggestion: `Define "${name}" in the base colors too (set_variables), not only under dark.${fromOverride}` }); + return; + } + const ranked = candidatePool(accepts, tokens) + .map((n) => ({ n, d: levenshtein(name, n) })) + .filter((c) => c.d <= 3) + .sort((a, b) => a.d - b.d || a.n.localeCompare(b.n)); + const named = ranked.slice(0, 3).map((c) => `"$${c.n}"`); + const issue: EvaluationIssue = { + ...base, + message: `Unknown token "${ref}" on ${path}: no such token is defined, so the value is dropped${where}.`, + suggestion: named.length + ? `Did you mean ${named.length === 1 ? named[0] : `${named.slice(0, -1).join(', ')} or ${named[named.length - 1]}`}?${fromOverride}` + : `Define it with set_variables (or generate_design_system), or use a token the canvas defines.${fromOverride}`, + }; + issues.push(issue); + + const [first, second] = ranked; + if (!first || first.d > 2 || (second && second.d <= first.d)) return; + const stepA = ladderStep(name); + const stepB = ladderStep(first.n); + // A different rung of the same ladder is a different size, not a spelling. + if (stepA && stepB && stepA !== stepB) return; + if (!origin.startsWith('node:') || !fixableSite(site)) return; + const k = `${node.id}\u0000${site.key}`; + renames.set(k, [...(renames.get(k) ?? []), { site, to: `$${first.n}` }]); + pending.push({ issue, nodeId: node.id, key: site.key }); + }; + + (function walk(node: SceneNode, master?: string) { + const inMaster = master ?? (node.type === 'component' && !node.id.includes('/') && canvas.components[node.id] ? node.id : undefined); + for (const { ref, ...site } of tokenRefs(node)) judge(node, site, ref, originOf(node.id, node, site, ref, inMaster), inMaster); + node.children?.forEach((c) => walk(c, inMaster)); + })(raw); + // Components no instance uses are still the canvas's: judge their definitions. + for (const [cid, component] of Object.entries(canvas.components)) { + if (used.has(cid) || masters.has(cid)) continue; + (function walk(node: SceneNode) { + for (const { ref, ...site } of tokenRefs(node)) judge(node, site, ref, defNode(cid, node.id), cid); + node.children?.forEach(walk); + })(component); + } + + const stored = new Map(); + (function index(n: SceneNode) { stored.set(n.id, n); n.children?.forEach(index); })(canvas.root); + for (const { issue, nodeId, key } of pending) { + let next: unknown = structuredClone((stored.get(nodeId) as unknown as Record)[key]); + for (const { site, to } of renames.get(`${nodeId}\u0000${key}`) ?? []) { + if (site.at === undefined && !site.sub) next = to; + else if (site.at !== undefined && Array.isArray(next)) next[site.at] = to; + else if (site.sub && next && typeof next === 'object') (next as Record)[site.sub] = to; + } + issue.fix = { op: formatUpdateOp(nodeId, { [key]: next }), rationale: 'The token is misspelt; the nearest defined name is the only one that close.' }; + } + return issues; +} + /** Phase 25 slice E — raw entries + merged tokens power the token-detachment * lint and the motion nudge. Both are SCORE-NEUTRAL info advisories. */ interface ConsistencyContext { @@ -2619,7 +2824,7 @@ export async function evaluateCanvas( ])); } if (activeCategories.includes('structure')) { - results.set('structure', withRuleIssues(checkStructure(storedEntries, canvas), [ + results.set('structure', withRuleIssues(checkStructure(storedEntries, canvas, mergedTokens, !rules.off.includes('unknown-token')), [ ...(ruleOn.has('mobile-artboard') ? checkArtboard(mobile, declared) : []), ...(ruleOn.has('desktop-app-artboard') ? checkDesktopArtboard(resolvedRoot, declared) : []), ...(desktop && ruleOn.has('desktop-app-primary-count') ? checkPrimaryCount(desktop) : []), @@ -2730,17 +2935,7 @@ export async function evaluateCanvas( const maxDepth = Math.max(...storedEntries.map((e) => e.depth)); const instanceNodes = storedEntries.filter((e) => e.node.type === 'instance').length; - let tokenRefs = 0; - let totalStringProps = 0; - for (const { node } of storedEntries) { - for (const [key, val] of Object.entries(node)) { - if (['id', 'type', 'name', 'children'].includes(key) || PRIMITIVE_COPY_PROPS.has(key)) continue; - if (typeof val === 'string') { - totalStringProps++; - if (val.startsWith('$')) tokenRefs++; - } - } - } + const census = tokenCensus(storedEntries, mergedTokens); return { overallScore, @@ -2755,7 +2950,7 @@ export async function evaluateCanvas( textNodes, frameNodes, maxDepth, - tokenUsagePercent: totalStringProps > 0 ? Math.round((tokenRefs / totalStringProps) * 100) : 0, + tokenUsagePercent: census.total > 0 ? Math.round((census.refs / census.total) * 100) : 0, componentReusePercent: totalNodes > 0 ? Math.round((instanceNodes / totalNodes) * 100) : 0, }, mode: options.mode, diff --git a/src/index.ts b/src/index.ts index 258bc3e..6aa9a76 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,7 +15,7 @@ import { detectBinding, projectStartDir, readWorkspaceFile, setRepoBackend, regi import { bindRepo, initWorkspace } from './bind.js'; import { parseAndExecute, ignoredShadowWarning } from './operations.js'; import { promoteToComponent, copyNodesAcross } from './components.js'; -import { resolveVariables, setVariables, getVariables, applyPresetTokens, type PresetApplyResult } from './variables.js'; +import { resolveVariables, setVariables, getVariables, applyPresetTokens, withoutRetiredSeeds, type PresetApplyResult } from './variables.js'; import { renderToHtml, type RenderOptions } from './renderer.js'; import { ensureFontsForRender, bodyFontFamilyFromTokens, resolveFamily, warmFamilies, resolveStylesheetUrl, isStylesheetUrl, collectReferencedFamilies, unverifiedFamiliesInOps } from './fonts.js'; import { takeScreenshot, computeLayout, exportToFile, takeResponsiveScreenshots, computeDiff, shutdown } from './screenshot.js'; @@ -52,7 +52,7 @@ Organizing model — Workspace > Project > Canvas: - Canvases live in a project, projects in a workspace. A default "Personal > Untitled" always exists. - To scope work to a code repo, call **canvas_bind** once: it stores canvases as checked-in JSON under the repo's .framesmith/ and makes that the source of truth. Heads up — bind RE-KEYS the workspace and every project ID to repo-* form, so pre-bind workspace/project IDs stop resolving; the result's idMap gives old → new for both. Canvas IDs survive the bind unchanged. -Design tokens are a layered system (workspace > project > canvas). Reference them in node properties with $name (e.g. fill: "$surface"); set them with workspace_/project_/set_variables. Lower layers override higher ones — author tokens once at the workspace and inherit down. +Design tokens are a layered system (workspace > project > canvas). Reference them in node properties with $name (e.g. fill: "$surface"); set them with workspace_/project_/set_variables. Lower layers override higher ones — author tokens once at the workspace and inherit down. A $ref no token defines, or of the wrong kind for its prop, is an unknown-token warning (canvas_autofix renames an unambiguous misspelling); copy props (content, label, title, value…) never resolve. The tint layer ($accent-tint, $success-tint, $warning-tint, $danger-tint, $neutral-tint) and $danger derive when no layer defines them: each tint from its ink in the mode of the surface ($bg-surface, else $bg-primary), $danger from $error. Your job is to craft beautiful UI with real UX — designs a designer would sign off on — not wireframes. The bar is non-negotiable, and polishing to it is YOUR work, never the user's. @@ -138,6 +138,7 @@ const GOTCHAS = [ 'Row rules / accent bars: per-side borders — borderTop: { width: 1, color: "$border" } per table row, borderLeft: { width: 3, color: "$primary" } for accent edges; style "dashed"|"dotted" marks forecast/draft; strokeDasharray ("6 4") dashes SVG paths. Never fake hairlines with gap: 1 + fill bleed-through. gap: 0 (flush rows, tab bars) is always on-scale.', 'Prefer structured gradient / shadows ({ stops: [...] } and [{ x, y, blur, color }]); a raw CSS string on those fields is accepted too. The plural `shadows` always beats the singular `shadow` — writing `shadow` on a node that has `shadows` is a no-op (batch_design warns when this happens).', 'import_design_md reliably imports spacing + component skeletons; set colors / typography / radius explicitly via set_variables.', + 'Tokens: a $ref no token defines ("$space-mdd"), of the wrong kind for its prop ("$body" on fill, "$accent" on gap), on a prop that takes none (fontFamily: "$display"), or defined only in the dark layer is an unknown-token warning that blocks presenting — canvas_autofix renames an unambiguous misspelling on the node itself; fix the rest by hand (inside a component: fix the component or the override). Copy never resolves: content: "$49" is a price. $danger and the five -tint tokens always resolve: undefined, they derive from the inks and the surface, light or dark by the surface.', 'Binding (canvas_bind, or init on first run) re-keys the workspace + every project ID to repo-* form (canvas IDs are kept) — retarget from canvas_bind\'s idMap or the IDs init returns, never cache pre-bind workspace/project IDs.', 'Point-and-tell feedback: the user clicks elements in the viewer (Comment mode) to leave node-anchored or whole-page comments, stored on the canvas at metadata.feedback. get_feedback returns them (with a node snapshot; orphaned: true = the node is gone but the concern likely still applies); open feedback blocks presenting, same as open inspector comments — address each item, then resolve_feedback with a one-line note of what changed (shown as your reply in the viewer\'s Feedback tab). canvas_list rows and canvas_evaluate results carry an openFeedback count (and the evaluate directive stays blocking) while comments are open.', 'Cliché tells (canvas_evaluate "cliche" category): avoid default purple/indigo accents, gradient/glow overuse, fake window chrome, fabricated metrics, slop copy (filler verbs / scroll cues / "Jane Doe" / hype labels), an eyebrow above every section (keep to ~1 per 3 sections), mixed radius systems (one radius scale), pure black/white (use off-black/off-white), and competing accents (one accent hue + neutrals; the $success/$warning/$danger status vocabulary is exempt when referenced as tokens). The tells KNOW dashboard vocabulary (Phase 28): violets referenced via \$chart-*/\$*-tint tokens, token-referenced gradients, thin rounded sparkline bars, and uppercase KPI labels beside big tabular figures are all sanctioned — the literal versions still flag.', @@ -932,12 +933,12 @@ server.tool( // --- get_variables --- server.tool( 'get_variables', - 'Get design variables (tokens) for a canvas.', + 'Get design variables (tokens) for a canvas: its own layer, without the old scaffold seeds that count as unset (an exact #152A47 accent-tint and the other retired tint and danger seeds).', { canvasId: z.string().describe('Canvas ID') }, async ({ canvasId }) => { const canvas = getCanvas(canvasId); if (!canvas) return { content: [{ type: 'text', text: 'Error: Canvas not found' }], isError: true }; - return { content: [{ type: 'text', text: JSON.stringify(getVariables(canvas), null, 2) }] }; + return { content: [{ type: 'text', text: JSON.stringify(withoutRetiredSeeds(getVariables(canvas)), null, 2) }] }; } ); @@ -1071,7 +1072,7 @@ server.tool( 'generate_color_system', `One seed color → a full perceptual color system: OKLCH ramps primary-50…900 (even lightness steps, chroma tapered at the extremes, gamut-clipped toward lower chroma — never hue-shifted), a matched neutral ramp (a whisper of the seed's hue — never dead grey, never visibly tinted), status colors (success / warning / danger, hue held but darkened until each clears WCAG AA as TEXT on the generated light page surface — the invariant is shared contrast, not shared lightness, and tuning against that off-white surface rather than pure white is the stricter target, so white passes too), and the SEMANTIC tokens the structures already speak: bg-primary, bg-surface, bg-elevated, text-primary, text-secondary, border, accent. Text and accent steps are picked by MEASURED contrast — every semantic text/surface pair clears WCAG AA by construction, not by hope. -Phase 31 adds two CONTROL colors, each at 3:1 or more (WCAG 1.4.11) in both themes: focus-ring (against every bg-* and *-tint token) and border-strong (against bg-primary and bg-surface — for a control whose border is its only boundary cue); generate_design_system writes them too. The DARK theme ships in the same call (the Radix pattern: a reversed walk of the same ramps, not inverted hex): the semantic dark mapping is WRITTEN to the layer's dark.colors override — so theme: "dark" on screenshot/export renders it and canvas_evaluate contrast-checks BOTH themes from then on. Status colors get a SECOND pass for dark: the light-tuned success/warning/danger are re-lit (hue held) until each clears AA against the lightest dark surface (bg-elevated) too, so a $danger message reads in both themes. Phase 28 adds THE COLOR RANGE in the same call: chart-1…chart-6 categorical series tokens (a deterministic hue walk from the seed, ≥ 30° apart, each clearing the 3:1 graphical-object floor on BOTH themes' surfaces — reference them from chart segments/series and legend dots) and the TINT LAYER — accent-tint / success-tint / warning-tint / danger-tint / neutral-tint: soft same-hue surfaces for status chips, icon tiles, pill badges, and initials avatars. The pairing rule is one sentence: tint as the FILL, its base color as the INK (fill: "$success-tint" + color: "$success") — that pair is AA by construction in both themes, and the dark layer re-states every tint. Writes the light system to exactly ONE of canvasId / projectId / workspaceId. Canvas scope honors the inherited-design-system contract: tokens the canvas inherits from workspace/project are PRESERVED and reported — ordinary ones under \`preservedFromDesignSystem\`, and ones in the semantic vocabulary this call defines under \`designSystemConflicts\` (an inherited \`border\` or \`text-primary\` on a freshly generated palette means two color languages on one screen; each entry names the fix). Take the generated value with set_variables, or pass \`preserveInherited: false\` to write the palette whole. Raise your palette floor: generate first, then adjust individual tokens — don't eyeball ten hexes.`, +Phase 31 adds two CONTROL colors, each at 3:1 or more (WCAG 1.4.11) in both themes: focus-ring (against every bg-* and *-tint token) and border-strong (against bg-primary and bg-surface — for a control whose border is its only boundary cue); generate_design_system writes them too. The DARK theme ships in the same call (the Radix pattern: a reversed walk of the same ramps, not inverted hex): the semantic dark mapping is WRITTEN to the layer's dark.colors override — so theme: "dark" on screenshot/export renders it and canvas_evaluate contrast-checks BOTH themes from then on. Status colors get a SECOND pass for dark: the light-tuned success/warning/danger are re-lit (hue held) until each clears AA against the lightest dark surface (bg-elevated) too, so a $danger message reads in both themes. Phase 28 adds THE COLOR RANGE in the same call: chart-1…chart-6 categorical series tokens (a deterministic hue walk from the seed, ≥ 30° apart, each clearing the 3:1 graphical-object floor on BOTH themes' surfaces — reference them from chart segments/series and legend dots) and the TINT LAYER — accent-tint / success-tint / warning-tint / danger-tint / neutral-tint: soft same-hue surfaces for status chips, icon tiles, pill badges, and initials avatars. The pairing rule is one sentence: tint as the FILL, its base color as the INK (fill: "$success-tint" + color: "$success") — that pair is AA by construction in both themes, and the dark layer re-states every tint. Without these tokens (an unthemed canvas, a preset) the tints derive at render from the same inks in the surface's mode, and the pair holds whenever the ink itself clears its surface. Writes the light system to exactly ONE of canvasId / projectId / workspaceId. Canvas scope honors the inherited-design-system contract: tokens the canvas inherits from workspace/project are PRESERVED and reported — ordinary ones under \`preservedFromDesignSystem\`, and ones in the semantic vocabulary this call defines under \`designSystemConflicts\` (an inherited \`border\` or \`text-primary\` on a freshly generated palette means two color languages on one screen; each entry names the fix). Take the generated value with set_variables, or pass \`preserveInherited: false\` to write the palette whole. Raise your palette floor: generate first, then adjust individual tokens — don't eyeball ten hexes.`, { seed: z.string().describe('The brand color to derive everything from (#RRGGBB)'), canvasId: z.string().optional().describe('Write to this canvas\'s variables'), @@ -1176,7 +1177,7 @@ Personalities (required — pick a stance, don't default into sameness): On a canvas declared "mobile" the type pivot is the phone body (17px; 16 for data-dense); on a canvas declared "desktop-app" it is 14px (13 for data-dense) — the result reports baseSize and baseSizeSource ("mobile" | "desktop-app" | "explicit" | "personality"). Every system also writes the element-STATE tokens: a state section of opacities ({ hover: 0.08, focus: 0.10, pressed: 0.10, disabledContent: 0.38, disabledContainer: 0.12 } — Material 3's values; hover/focus/pressed are the share of the ink over a control's fill) plus the focus-ring and border-strong control colors; the result reports them as state and controls. -The typography layer ships ROLE tokens the structures speak — $display / $heading / $title (page/screen titles, one step below $display — every archetype's page title references it) / $body / $label / $caption (+ $figures when a mono face exists) — alongside the text-xs…text-3xl steps. Depth: reference elevation from any node as shadow: "$elevation.flat|raised|floating|overlay" — the dark layer re-states each depth so it reads on dark surfaces. The COLOR RANGE rides along (Phase 28): $chart-1…$chart-6 categorical series tokens for dataviz, and the tint layer ($accent-tint / $success-tint / … — tint as fill, base color as ink, AA by construction both themes) for chips, icon tiles, pills, and avatars. Writes to exactly ONE of canvasId / projectId / workspaceId. Canvas scope keeps tokens the canvas resolves through an inherited design system rather than clobbering them — but preservation is FIELD-WISE for typography, so an inherited role that carries only a size keeps that size and still picks up this personality's family/weight/tracking (before v2.1 it swallowed the whole spec and the role silently rendered in the fallback stack). What was kept is reported two ways: \`preservedFromDesignSystem\` for ordinary tokens, and \`designSystemConflicts\` for tokens in the semantic vocabulary THIS system defines (the surface/ink/border/accent semantics, the STATUS colours and their paired -tint layer, the \$chart-* range, and the type roles — an inherited success keeps pairing with the GENERATED success-tint and fails contrast) — a conflict means the screen is running two design languages at once, and each entry names the fix. \`preserveInherited: false\` writes the generated language whole. The response's typographyRoles reports what the canvas ACTUALLY resolves, not what was generated — the two differ exactly when preservation fired. The two single-purpose generators stay available for targeted regeneration (just the palette, just the scale). On a canvas declared type: "mobile" (canvas_create / canvas_set_type) the type scale pivots on the device body size — 17px for every personality except data-dense, which uses 16px — so the generated $body meets the phone body floor; an explicit baseSize still wins. The result reports the GENERATED pivot as baseSize + baseSizeSource ("explicit" | "personality" | "mobile"); if the canvas inherits a $body from a workspace/project design system, that body is preserved by default and shows up in designSystemConflicts (typographyRoles.body is what renders) — pass preserveInherited: false to take the mobile body.`, +The typography layer ships ROLE tokens the structures speak — $display / $heading / $title (page/screen titles, one step below $display — every archetype's page title references it) / $body / $label / $caption (+ $figures when a mono face exists) — alongside the text-xs…text-3xl steps. Depth: reference elevation from any node as shadow: "$elevation.flat|raised|floating|overlay" — the dark layer re-states each depth so it reads on dark surfaces. The COLOR RANGE rides along (Phase 28): $chart-1…$chart-6 categorical series tokens for dataviz, and the tint layer ($accent-tint / $success-tint / … — tint as fill, base color as ink, AA by construction both themes) for chips, icon tiles, pills, and avatars. A canvas without them derives each tint from its ink in the surface's mode. Writes to exactly ONE of canvasId / projectId / workspaceId. Canvas scope keeps tokens the canvas resolves through an inherited design system rather than clobbering them — but preservation is FIELD-WISE for typography, so an inherited role that carries only a size keeps that size and still picks up this personality's family/weight/tracking (before v2.1 it swallowed the whole spec and the role silently rendered in the fallback stack). What was kept is reported two ways: \`preservedFromDesignSystem\` for ordinary tokens, and \`designSystemConflicts\` for tokens in the semantic vocabulary THIS system defines (the surface/ink/border/accent semantics, the STATUS colours and their paired -tint layer, the \$chart-* range, and the type roles — an inherited success keeps pairing with the GENERATED success-tint and fails contrast) — a conflict means the screen is running two design languages at once, and each entry names the fix. \`preserveInherited: false\` writes the generated language whole. The response's typographyRoles reports what the canvas ACTUALLY resolves, not what was generated — the two differ exactly when preservation fired. The two single-purpose generators stay available for targeted regeneration (just the palette, just the scale). On a canvas declared type: "mobile" (canvas_create / canvas_set_type) the type scale pivots on the device body size — 17px for every personality except data-dense, which uses 16px — so the generated $body meets the phone body floor; an explicit baseSize still wins. The result reports the GENERATED pivot as baseSize + baseSizeSource ("explicit" | "personality" | "mobile"); if the canvas inherits a $body from a workspace/project design system, that body is preserved by default and shows up in designSystemConflicts (typographyRoles.body is what renders) — pass preserveInherited: false to take the mobile body.`, { seed: z.string().describe('The brand color to derive everything from (#RRGGBB)'), personality: z.enum(['technical', 'editorial', 'soft', 'data-dense']).describe('The design stance — required. Genre guide: dashboards → data-dense or technical; marketing/content → editorial; consumer → soft.'), @@ -1568,7 +1569,7 @@ server.tool( - page scaffolds insert at the canvas root and record provenance; refuses if the root already has content unless replace is true. - component scaffolds (data-table, form-field, toolbar, stat-card, toggle-row, …) insert under targetId (default root), repeatably — every stamp re-keys its node IDs and returns an idMap (templateId → live id) for follow-up batch_design ops. The name resolves by the canvas's declared type: an anatomy name stamps that anatomy's realisation for the type — "dashboard" on a mobile canvas stamps dashboard-mobile (status bar, nav bar, list rows, pinned tab bar, all primitives) — and on a desktop-app canvas dashboard-app (a sidebar of nav-items, panes that scroll on their own; the page stamp sets root overflow "hidden" so the root keeps the window height, and a later page stamp with replace removes it again unless you changed it) — and the result names the anatomy and surface it stamped; its placeholders include every copy field of its primitives, with prop the field's path. A realisation name (dashboard-mobile, dashboard-app) is used as is. A name with no realisation for the canvas's type is refused with the anatomies that have one (pricing on a phone or desktop-app canvas; list-detail, editor-inspector and browser on web or a phone; components not marked for every type too); realisation: "web" | "mobile" | "desktop-app" stamps that type's realisation anyway. -Scaffolds reference $space-*/$radius-*/$elevation.*/type-role tokens ($display/$title/$heading/$text-lg/$text-sm/$body/$label/$caption) for spacing, corner radius, depth, and EVERY text node's size (not just $color, and not just titles) — stamp AFTER generate_design_system on a project and the pattern already reads in that system's density, personality, and voice; no scaffold can inject a size the generated scale doesn't have. Also hardened to survive hostile-length content (canvas_stress CLEAN). Seeds neutral defaults (the pre-generator literal values) for any of those tokens the canvas can't already resolve, so an unthemed canvas still renders correctly; the result's seededColors/seededTokens list exactly what got seeded (a stamp holding a desktop-app primitive also seeds $border-strong, never $accent-tint — without it an active fill mixes 12% accent into whatever surface is applied later; a stamp holding a mobile primitive also seeds the colours primitives read by default: $text-primary, $text-secondary, $border, and $accent / $bg-surface / $danger unless the canvas resolves $primary / $surface / $error — a scaffold node that names $accent or $bg-surface itself still seeds it, so define $accent and $bg-surface on a hand-themed canvas before stamping). Returns the placeholder node ids to populate — fill them with batch_design U ops, then call screenshot to verify the layout.`, +Scaffolds reference $space-*/$radius-*/$elevation.*/type-role tokens ($display/$title/$heading/$text-lg/$text-sm/$body/$label/$caption) for spacing, corner radius, depth, and EVERY text node's size (not just $color, and not just titles) — stamp AFTER generate_design_system on a project and the pattern already reads in that system's density, personality, and voice; no scaffold can inject a size the generated scale doesn't have. Also hardened to survive hostile-length content (canvas_stress CLEAN). Seeds neutral defaults (the pre-generator literal values) for any of those tokens the canvas can't already resolve, so an unthemed canvas still renders correctly; the result's seededColors/seededTokens list exactly what got seeded (a stamp holding a desktop-app primitive also seeds $border-strong, never $accent-tint — without it an active fill mixes 12% accent into whatever surface is applied later; a stamp holding a mobile primitive also seeds the colours primitives read by default: $text-primary, $text-secondary, $border, and $accent / $bg-surface unless the canvas resolves $primary / $surface — a scaffold node that names $accent or $bg-surface itself still seeds it, so define $accent and $bg-surface on a hand-themed canvas before stamping). No stamp seeds $danger or the tint layer ($accent-tint, $success-tint, $warning-tint, $danger-tint, $neutral-tint): they derive at render from the inks and the surface ($danger from $error), in the surface's light or dark mode, so a later light preset gets light tints; a stamp that reads one seeds $bg-surface unless the canvas resolves $bg-primary, so an unthemed stamp's tints come out dark like its seeded inks. A canvas stamped before still holding an old seed value (#152A47 accent-tint and the like) renders as if it were unset. Returns the placeholder node ids to populate — fill them with batch_design U ops, then call screenshot to verify the layout.`, { canvasId: z.string().describe('Canvas ID'), structure: z.string().describe('Structure name (use list_structures, e.g. marquee-hero, data-table)'), @@ -2147,7 +2148,7 @@ server.tool( // --- canvas_evaluate --- server.tool( 'canvas_evaluate', - `Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Every check reads the canvas as it renders: each component instance is expanded (its props and overrides applied) and the design system resolved inside it, so contrast, spacing, typography, cliché and every type rule see inside components. A finding on a node inside an instance reports the instance in nodeId (the stored node: fix it in the component, or with an override on the instance), the inner node's expanded id in innerNodeId ("/", the id snapshot_layout and canvas_stress use; batch_design cannot address it), names the component in its message, and carries no fix op. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls, text-inputs included (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action, link, text-input, nav-item, each tab of a tabs node, tree-row, menu-row — inline text links and dividers are not targets, and a control that is the only target directly inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too: one finding per icon in the component, reported on the first instance that shows it, with no fix op. Modes: + `Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Every check reads the canvas as it renders: each component instance is expanded (its props and overrides applied) and the design system resolved inside it, so contrast, spacing, typography, cliché and every type rule see inside components. A finding on a node inside an instance reports the instance in nodeId (the stored node: fix it in the component, or with an override on the instance), the inner node's expanded id in innerNodeId ("/", the id snapshot_layout and canvas_stress use; batch_design cannot address it), names the component in its message, and carries no fix op. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls, text-inputs included (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action, link, text-input, nav-item, each tab of a tabs node, tree-row, menu-row — inline text links and dividers are not targets, and a control that is the only target directly inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too: one finding per icon in the component, reported on the first instance that shows it, with no fix op. It also WARNS (rule "unknown-token", directive-blocking, -10 structure score each; on for every type unless a ruleset turns it off) on every $ref the resolver reads that renders something other than intended: a name no token defines ("$space-mdd"), a token of the wrong kind for the prop (a typography or spacing token on fill / stroke / color and the other colour props, a colour on gap / padding / width and the other number props; a typography ref is valid only on fontSize), a ref on a prop that takes no token (fontFamily: "$display" renders 40), and a name defined only in the dark layer (light renders it raw). It reads top-level props, padding / cornerRadius entries, borderTop/Right/Bottom/Left.color, series[].stroke, segments[].color, modal actions[].fill/color/stroke and a toast action.color, inside components too, one finding per place the ref is written. Copy never resolves (content, text, title, subtitle, label, value, placeholder, count, centerValue and the other copy props), so "$49" is a price, not a token, and is not checked. The derived names ($accent-tint, $success-tint, $warning-tint, $danger-tint, $neutral-tint, $danger) always count as defined. The suggestion names up to three defined tokens of the kind the prop takes, nearest spelling first; when exactly one is closest (within 2 edits, and not another rung of a size ladder: $space-lg is never "fixed" to $space-md) and the ref sits on the stored node itself (a top-level prop, a padding / cornerRadius entry or a border colour), it carries a rename fix canvas_autofix applies (two typos in one array share one op that renames both). Wrong-kind, dark-only and takes-no-token findings, refs inside a component or an override, and the nested chart and overlay props carry no fix. Token usage in the stats counts only refs that resolve, against the tokens the canvas inherits too. Modes: - "fast": JSON-only, <100ms, deterministic heuristics only. - "detailed": adds Puppeteer-based pixel overlap detection in the consistency category, laid out at the canvas's artboard size in the design system's own fonts, as screenshot and canvas_stress render them (a face that cannot load renders in the fallback stack and the result carries a "Font warnings" item) (siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt; a bar pinned to the top over in-flow content still counts). - "llm": fast-mode heuristics plus a vision-model critique against a FIXED rubric (provider picked from FRAMESMITH_LLM_PROVIDER env var, or whichever of ANTHROPIC_API_KEY / OPENAI_API_KEY is set). Adds an "llmCritique" field: { rubric: { hierarchy, execution, specificity, restraint, variety } each {score 1-5, rationale}, score (0-100 derived), summary, suggestions, needsRevision, failingAxes }. The verdict is stamped on the canvas (metadata.critique) + the per-project build log for auditability. Cost: one paid API call per invocation. To CLOSE the loop and auto-fix failing axes, use canvas_revise. @@ -2232,7 +2233,7 @@ REPEATED FINDINGS FOLD in this result: three or more warnings or infos sharing a // --- canvas_autofix --- server.tool( 'canvas_autofix', - `Run canvas_evaluate in fast mode and return the subset of issues that have a mechanically derived fix (off-scale spacing — gap, scalar AND array-form padding (the fix writes the complete snapped array) — → snap to scale; missing layout on multi-child frame → set vertical; recoverable WCAG contrast failure → switch text to #000 or #FFF, whichever wins; default-purple accent → swap to a neutral accent; fake-chrome strip → delete; pure-black ink → soften to off-black; a literal fill/stroke/color/cornerRadius that exactly equals a SINGLE token's value → re-pointed to the \$ref — a value shared by multiple tokens is reported with candidates but never auto-fixed). By default this PROPOSES: each fix carries a ready-to-paste \`batch_design\` op string and a one-line rationale. Also: an unknown icon name with exactly one spelling that resolves (hyphens ↔ underscores, or a missing material: prefix — ties broken by the icon set the canvas already uses) → rewritten to that name. Pass apply: true to also WRITE the fixes to the canvas in the same call — the result then reports applied/failed per op. Taste-dependent cliche tells (gradient/glow overuse, the hanging header, fabricated content, eyebrow-rhythm overuse, slop copy, mixed radius systems, competing accents) carry a suggestion but no auto-fix — call canvas_evaluate to see those. Coverage warnings (missing empty/loading/error state variants) also have no mechanical fix: designing a state is judgment — the suggestion names the canvas_add_variant + scaffold path. Usability findings (hit-target size, label association, vague action copy) and the mobile ruleset's findings (touch targets, safe areas, type floor, artboard) likewise have no mechanical fix — growing a control, writing a label, or renaming a button is a judgment call; call canvas_evaluate and fix them via batch_design. Closes the generator-evaluator loop: generate with batch_design → autofix (apply: true) → re-evaluate. The result carries the same "genre" and "surface" reports as canvas_evaluate.`, + `Run canvas_evaluate in fast mode and return the subset of issues that have a mechanically derived fix (off-scale spacing — gap, scalar AND array-form padding (the fix writes the complete snapped array) — → snap to scale; missing layout on multi-child frame → set vertical; recoverable WCAG contrast failure → switch text to #000 or #FFF, whichever wins; default-purple accent → swap to a neutral accent; fake-chrome strip → delete; pure-black ink → soften to off-black; a literal fill/stroke/color/cornerRadius that exactly equals a SINGLE token's value → re-pointed to the \$ref — a value shared by multiple tokens is reported with candidates but never auto-fixed). By default this PROPOSES: each fix carries a ready-to-paste \`batch_design\` op string and a one-line rationale. Also: an unknown icon name with exactly one spelling that resolves (hyphens ↔ underscores, or a missing material: prefix — ties broken by the icon set the canvas already uses) → rewritten to that name; a misspelt $token (rule unknown-token) whose nearest defined name is the only one that close, on a stored node's own prop → renamed (U(id, { gap: \"$space-md\" }); a padding array or border object is rewritten whole with every rename applied). A wrong-kind token, a ref inside a component or override, and a typo near two names are reported but never renamed. Pass apply: true to also WRITE the fixes to the canvas in the same call — the result then reports applied/failed per op. Taste-dependent cliche tells (gradient/glow overuse, the hanging header, fabricated content, eyebrow-rhythm overuse, slop copy, mixed radius systems, competing accents) carry a suggestion but no auto-fix — call canvas_evaluate to see those. Coverage warnings (missing empty/loading/error state variants) also have no mechanical fix: designing a state is judgment — the suggestion names the canvas_add_variant + scaffold path. Usability findings (hit-target size, label association, vague action copy) and the mobile ruleset's findings (touch targets, safe areas, type floor, artboard) likewise have no mechanical fix — growing a control, writing a label, or renaming a button is a judgment call; call canvas_evaluate and fix them via batch_design. Closes the generator-evaluator loop: generate with batch_design → autofix (apply: true) → re-evaluate. The result carries the same "genre" and "surface" reports as canvas_evaluate.`, { canvasId: z.string().describe('Canvas ID to autofix'), categories: z.array(z.enum(['spacing', 'color', 'typography', 'structure', 'consistency', 'cliche', 'coverage', 'usability'])) diff --git a/src/primitives.ts b/src/primitives.ts index 74ccd3a..dd2b6df 100644 --- a/src/primitives.ts +++ b/src/primitives.ts @@ -23,6 +23,16 @@ export const FLOATING_INSET = 16; export const TAPPABLE_PRIMITIVES = new Set(['button', 'list-row', 'tab-bar', 'nav-bar']); +/** Words and enum names, never style values: the resolver leaves them as + * written (a price such as "$49" is copy, not a token), and the token census + * and the unknown-token rule skip them. */ +export const COPY_PROPS = new Set([ + 'name', 'content', 'text', 'title', 'subtitle', 'label', 'time', 'placeholder', 'value', 'shortcut', + 'error', 'ariaLabel', 'count', 'closeLabel', 'centerValue', 'centerLabel', + // Enums. + 'variant', 'size', 'detent', 'appearance', 'iconPosition', 'orientation', 'state', +]); + // Phase 31 slice B — the desktop-app vocabulary's geometry, on the 24 / 32 / // 40 / 48 density ladder. export const LINK_MIN_HEIGHT = 24; diff --git a/src/structures.ts b/src/structures.ts index dbd612d..2485680 100644 --- a/src/structures.ts +++ b/src/structures.ts @@ -2,6 +2,7 @@ import type { BuildLogEntry, Canvas, SceneNode, Structure, StructureAxes } from import { resolveSurface, SURFACE_TYPES, type SurfaceType } from './surfaces.js'; import { COLOR, SPACE, RADIUS, ELEV, TYPE, TINT } from './structure-tokens.js'; import { DESKTOP_APP_STRUCTURES } from './structures-desktop.js'; +import { DERIVED_COLORS } from './variables.js'; // Phase 11 — layout scaffold library. A Structure is a named page shape: a // partial scene tree of *labeled placeholder* children (C8 — never fabricated @@ -1862,15 +1863,9 @@ const DEFAULT_SCAFFOLD_COLORS: Record = { // AA against the dark defaults above; generated systems override. 'success': '#4ADE80', 'warning': '#FBBF24', - 'danger': '#F87171', - // Phase 28 — the tint layer (chips, icon tiles, pills, avatars). Dark - // washes paired with the inks above; generated systems override with - // seed-derived tints in both themes. - 'accent-tint': '#152A47', - 'success-tint': '#0F2E1B', - 'warning-tint': '#33260A', - 'danger-tint': '#3A1715', - 'neutral-tint': '#25282D', + // Phase 32 slice C — `danger` and the tint layer are not seeded: they derive + // from these inks and the applied surface (variables.ts withDerivedColors), + // so a later light preset gets light tints. Generated systems define them. // Phase 31 — a control's only boundary: 3:1 against every dark surface above. 'border-strong': '#666666', }; @@ -1932,14 +1927,14 @@ const PRIMITIVE_COLOR_TOKENS: Record = { 'text-primary': [], 'text-secondary': [], border: [], // The token, then the names applyControlDefaults falls back to: a canvas // that resolves the fallback keeps it rather than getting a seeded default. - accent: ['primary'], 'bg-surface': ['surface'], danger: ['error'], + accent: ['primary'], 'bg-surface': ['surface'], }; /** Phase 31 — the extra token the desktop-app vocabulary reads: a * text-input's and a control's boundary (which falls back to `border`). * Mobile stamps never seed it. Slice D (spec change S6) stopped seeding * `accent-tint`, the active fill of nav-item / tree-row / contained tabs: * presets carry no tint, so a dark seed survived a later light preset; without - * the token the renderer mixes 12% accent into whatever surface is applied. */ + * the token it derives from the accent and whatever surface is applied. */ const DESKTOP_PRIMITIVE_TYPES = new Set(['link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row', 'divider']); const DESKTOP_PRIMITIVE_COLOR_TOKENS: Record = { 'border-strong': ['border'] }; @@ -2154,6 +2149,11 @@ export function applyStructure( // Seed neutral defaults for referenced colors not already resolvable (A-P4). const existingColors = opts.existingColors ?? new Set(); + // Phase 32 slice C — `danger` and the tints derive in the mode of the + // surface (variables.ts withDerivedColors). A stamp that reads one seeds that + // surface too unless the canvas has one, so an unthemed stamp's tints come + // out dark, the mode its seeded inks are tuned for. + if ([...referenced].some((t) => (DERIVED_COLORS as readonly string[]).includes(t)) && !existingColors.has('bg-primary')) referenced.add('bg-surface'); const seededColors: string[] = []; for (const token of referenced) { if (existingColors.has(token)) continue; diff --git a/src/surfaces.ts b/src/surfaces.ts index b8063cd..f768542 100644 --- a/src/surfaces.ts +++ b/src/surfaces.ts @@ -208,8 +208,9 @@ export const DESKTOP_APP_RULES: readonly string[] = [ ]; /** Phase 31: default rules — they run unless an active ruleset disables them. - * A rule id appears here when some type replaces the check. */ -export const DEFAULT_RULES = ['type-scale-ratio'] as const; + * A rule id appears here when some type replaces the check, or (Phase 32 + * `unknown-token`) when a ruleset may need to. */ +export const DEFAULT_RULES = ['type-scale-ratio', 'unknown-token'] as const; /** Keyed by axis, then value. Genre rows are canonical names only; aliases * fold through GENRE_ALIASES first. A rule id lands here in the same change as diff --git a/src/variables.ts b/src/variables.ts index 82476f1..0819818 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -1,26 +1,168 @@ import type { Canvas, DesignVariables, SceneNode, ShadowSpec, StateStyle } from './types.js'; -import { STATE_LAYERS, STATEFUL_TYPES } from './primitives.js'; +import { COPY_PROPS, STATE_LAYERS, STATEFUL_TYPES } from './primitives.js'; +import { composite, contrastRatio, parseAlpha } from './color-math.js'; +import { tintFor } from './color-system.js'; export function resolveVariables(node: SceneNode, variables: DesignVariables, opts?: { theme?: 'light' | 'dark' }): SceneNode { - // Phase 25 slice D — dark is a sparse override layer: merge it over colors - // and resolve exactly as light does. Theme is a pure RENDER/EVALUATE - // parameter, never canvas state (versionHash and drift baselines must not - // fork on it). - const effective = opts?.theme === 'dark' && (variables.dark?.colors || variables.dark?.elevation) + return deepResolve(structuredClone(node), withDerivedColors(themeTokens(variables, opts?.theme))); +} + +/** The tokens a theme renders with. Phase 25 slice D — dark is a sparse + * override layer merged over colors and elevation. Theme is a pure + * RENDER/EVALUATE parameter, never canvas state (versionHash and drift + * baselines must not fork on it). */ +export function themeTokens(variables: DesignVariables, theme?: 'light' | 'dark'): DesignVariables { + return theme === 'dark' && (variables.dark?.colors || variables.dark?.elevation) ? { ...variables, colors: { ...variables.colors, ...variables.dark?.colors }, elevation: { ...variables.elevation, ...variables.dark?.elevation }, } : variables; - return deepResolve(structuredClone(node), effective); +} + +// Phase 32 slice C (FR-C5, contract M7) — the tint layer and `danger` derive +// when the design system does not define them, so a scaffold never needs a +// seed that a later preset cannot replace. +export const DERIVED_COLORS = ['accent-tint', 'success-tint', 'warning-tint', 'danger-tint', 'neutral-tint', 'danger'] as const; +const DERIVED_NAMES = new Set(DERIVED_COLORS); + +/** The colours a scaffold used to seed (structures.ts) before they derived. + * A canvas-layer colour holding one counts as unset (FR-C6). */ +export const RETIRED_SEEDS = new Map([ + ['accent-tint', '#152A47'], ['success-tint', '#0F2E1B'], ['warning-tint', '#33260A'], + ['danger-tint', '#3A1715'], ['neutral-tint', '#25282D'], ['danger', '#F87171'], +]); + +export function isRetiredSeed(name: string, value: unknown): boolean { + const seed = RETIRED_SEEDS.get(name); + return seed !== undefined && typeof value === 'string' && value.trim().toLowerCase() === seed.toLowerCase(); +} + +/** A token layer without the retired seeds in its colours. */ +export function withoutRetiredSeeds(v: DesignVariables): DesignVariables { + const colors = v.colors; + if (!colors || !Object.entries(colors).some(([k, val]) => isRetiredSeed(k, val))) return v; + return { ...v, colors: Object.fromEntries(Object.entries(colors).filter(([k, val]) => !isRetiredSeed(k, val))) }; +} + +/** The tokens with every missing derived colour filled in. */ +export function withDerivedColors(v: DesignVariables): DesignVariables { + const c = v.colors ?? {}; + if (DERIVED_COLORS.every((name) => c[name] !== undefined)) return v; + return { ...v, colors: { ...deriveColors(c), ...c } }; +} + +const WHITE: [number, number, number] = [255, 255, 255]; +const BLACK: [number, number, number] = [0, 0, 0]; +const hexOf = (rgb: [number, number, number]) => '#' + rgb.map((x) => x.toString(16).padStart(2, '0')).join('').toUpperCase(); + +/** The surface tints sit on: bg-surface, else bg-primary, else white; a + * translucent one laid over the next opaque one in that chain. */ +function tintSurface(c: Record): [number, number, number] { + const chain = [c['bg-surface'], c['bg-primary']].filter((x): x is string => typeof x === 'string' && rgbOf(x) !== undefined); + const opaque = (from: number): [number, number, number] => { + const next = chain.slice(from).find((x) => parseAlpha(x) >= 1); + return next ? rgbOf(next)! : WHITE; + }; + if (!chain.length) return WHITE; + const alpha = parseAlpha(chain[0]); + return alpha >= 1 ? rgbOf(chain[0])! : composite(rgbOf(chain[0])!, alpha, opaque(1)); +} + +function deriveColors(c: Record): Record { + const surface = tintSurface(c); + const mode = contrastRatio(surface, WHITE) > contrastRatio(surface, BLACK) ? 'dark' : 'light'; + // An ink as opaque hex over the surface; its literal when it does not parse. + const ink = (value: string | undefined, literal: string): string => { + const rgb = value === undefined ? undefined : rgbOf(value); + if (!rgb) return literal; + const alpha = parseAlpha(value!); + return hexOf(alpha < 1 ? composite(rgb, alpha, surface) : rgb); + }; + const danger = c.danger ?? c.error ?? (mode === 'dark' ? '#F87171' : '#DC2626'); + const tint = (value: string | undefined, literal: string) => tintFor(ink(value, literal), mode, { grey: true }); + return { + danger, + 'accent-tint': tint(c.accent ?? c.primary, '#2563EB'), + 'success-tint': tint(c.success, '#16A34A'), + 'warning-tint': tint(c.warning, '#D97706'), + 'danger-tint': tint(danger, mode === 'dark' ? '#F87171' : '#DC2626'), + 'neutral-tint': tint(c['text-secondary'], '#6B7280'), + }; +} + +/** Where a token ref sits on a node: a top-level prop (`key`), optionally an + * array entry (`at`) and/or a field of an object (`sub`). */ +export interface RefSite { key: string; at?: number; sub?: string } + +export function refPath(site: RefSite): string { + return `${site.key}${site.at !== undefined ? `[${site.at}]` : ''}${site.sub ? `.${site.sub}` : ''}`; +} + +/** Every `$ref` on a node the resolver resolves (contract M2), in the order + * `deepResolve` visits them. */ +export function tokenRefs(node: SceneNode): Array { + const out: Array = []; + const isRef = (v: unknown): v is string => typeof v === 'string' && v.startsWith('$'); + const rec = node as unknown as Record; + for (const [key, value] of Object.entries(rec)) { + if (key === 'id' || key === 'type' || key === 'children' || COPY_PROPS.has(key)) continue; + if (isRef(value)) out.push({ key, ref: value }); + } + for (const key of ['padding', 'cornerRadius']) { + const arr = rec[key]; + if (Array.isArray(arr)) arr.forEach((v, at) => { if (isRef(v)) out.push({ key, at, ref: v }); }); + } + for (const key of NESTED_TOKEN_PROPS) { + const obj = rec[key] as Record | undefined; + if (obj && typeof obj === 'object' && isRef(obj.color)) out.push({ key, sub: 'color', ref: obj.color }); + } + const each = (key: string, subs: string[]) => { + const arr = rec[key]; + if (!Array.isArray(arr)) return; + arr.forEach((item, at) => { + if (!item || typeof item !== 'object') return; + for (const sub of subs) { const v = (item as Record)[sub]; if (isRef(v)) out.push({ key, at, sub, ref: v }); } + }); + }; + each('series', ['stroke']); + each('actions', ['fill', 'color', 'stroke']); + const action = rec.action as Record | undefined; + if (action && typeof action === 'object' && isRef(action.color)) out.push({ key: 'action', sub: 'color', ref: action.color }); + each('segments', ['color']); + return out; +} + +export type TokenKind = 'color' | 'number' | 'typography' | 'elevation' | 'motion' | 'object'; + +/** What a token name resolves to, in `lookupToken`'s order (contract M3); + * undefined when it resolves to nothing. The derived colours always count. */ +export function tokenKind(name: string, v: DesignVariables): TokenKind | undefined { + const has = (cat: object | undefined) => !!cat && Object.hasOwn(cat, name) && (cat as Record)[name] !== undefined; + if (has(v.colors)) return 'color'; + if (has(v.spacing) || has(v.radius)) return 'number'; + if (has(v.typography)) return 'typography'; + const dot = name.indexOf('.'); + if (dot > 0) { + const category = name.slice(0, dot); + const cat = (v as Record)[category]; + if (cat && typeof cat === 'object' && Object.hasOwn(cat, name.slice(dot + 1))) { + if (category === 'colors') return 'color'; + if (category === 'spacing' || category === 'radius' || category === 'state') return 'number'; + if (category === 'elevation') return 'elevation'; + if (category === 'motion') return 'motion'; + return 'object'; + } + } + return DERIVED_NAMES.has(name) ? 'color' : undefined; } const NESTED_TOKEN_PROPS = ['borderTop', 'borderRight', 'borderBottom', 'borderLeft'] as const; function deepResolve(node: SceneNode, variables: DesignVariables): SceneNode { for (const [key, value] of Object.entries(node)) { - if (key === 'id' || key === 'type' || key === 'children') continue; + if (key === 'id' || key === 'type' || key === 'children' || COPY_PROPS.has(key)) continue; if (typeof value === 'string' && value.startsWith('$')) { const tokenName = value.slice(1); @@ -224,10 +366,10 @@ function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { const surface = c['bg-surface'] ?? c.surface ?? CONTROL_FALLBACK.surface; const text = c['text-primary'] ?? CONTROL_FALLBACK.text; const secondary = c['text-secondary'] ?? '#6B7280'; - const danger = c.danger ?? c.error ?? '#DC2626'; - // Without an accent-tint token the active fill is the accent washed into the - // surface (12%), so it reads on a dark palette as well as a light one. - const tint = c['accent-tint'] ?? mixHex(accent, surface, 0.12) ?? '#EFF4FF'; + // Both derive when the design system has neither (withDerivedColors): the + // tint from the accent, in the surface's mode. + const danger = c.danger; + const tint = c['accent-tint']; const set = (key: K, value: SceneNode[K]) => { if (node[key] === undefined) node[key] = value; }; legacyDisabled(node, v); @@ -396,14 +538,6 @@ function rgbOf(color: string): [number, number, number] | undefined { return [hue(h + 1 / 3), hue(h), hue(h - 1 / 3)].map((v) => Math.round(v * 255)) as [number, number, number]; } -/** `top` laid over `base` at `alpha`, as #RRGGBB; undefined unless both parse (see `rgbOf`). */ -function mixHex(top: string, base: string, alpha: number): string | undefined { - const t = rgbOf(top); - const b = rgbOf(base); - if (!t || !b) return undefined; - return '#' + [0, 1, 2].map((i) => Math.round(alpha * t[i] + (1 - alpha) * b[i]).toString(16).padStart(2, '0')).join('').toUpperCase(); -} - /** A prop as text, for "is it set?" checks. */ function text_(value: unknown): string { return typeof value === 'string' ? value.trim() : ''; @@ -424,7 +558,7 @@ function onFill(fill: string | undefined): string { return 1.05 / (l + 0.05) >= (l + 0.05) / (lum('111827') + 0.05) ? '#FFFFFF' : '#111827'; } -function lookupToken(name: string, variables: DesignVariables): unknown { +export function lookupToken(name: string, variables: DesignVariables): unknown { // Check each category if (variables.colors?.[name] !== undefined) return variables.colors[name]; if (variables.spacing?.[name] !== undefined) return variables.spacing[name]; @@ -507,7 +641,8 @@ export function applyPresetTokens( const own = canvas.variables[cat] as Record; const inh = (inherited[cat] ?? {}) as Record; for (const [key, val] of Object.entries(pv)) { - const hasOwn = own[key] !== undefined; + // A retired scaffold seed is not the canvas's own choice (FR-C6). + const hasOwn = own[key] !== undefined && !(cat === 'colors' && isRetiredSeed(key, own[key])); const inhVal = inh[key]; if (options.preserveInherited === false || hasOwn || inhVal === undefined || tokenEquals(inhVal, val)) { own[key] = val; diff --git a/src/workspaces.ts b/src/workspaces.ts index b11f74d..584b4e8 100644 --- a/src/workspaces.ts +++ b/src/workspaces.ts @@ -13,7 +13,7 @@ import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { homedir } from 'node:os'; import { DEFAULT_PROJECT_ID, DEFAULT_WORKSPACE_ID, type Canvas, type DesignVariables, type Project, type Workspace } from './types.js'; -import { mergeDesignTokens } from './variables.js'; +import { mergeDesignTokens, withoutRetiredSeeds } from './variables.js'; import { isRepoBound, repoDir, writeWorkspaceFile, readWorkspaceFile, recordWorkspaceFileState, workspaceFileModified, registerProjectDir, getProjectDir, uniqueProjectDir, type RepoWorkspaceFile } from './repo-store.js'; const workspaces = new Map(); @@ -361,7 +361,9 @@ export function getCanvasTokens(canvas: Canvas): DesignVariables { ensureWorkspaceFresh(); const project = projects.get(canvas.projectId); const workspace = project ? workspaces.get(project.workspaceId) : undefined; - return mergeDesignTokens(workspace?.designSystem, project?.designSystem, canvas.variables); + // Phase 32 slice C (FR-C6) — a colour a scaffold used to seed counts as + // unset, so what the canvas inherits, or derives, shows through. + return mergeDesignTokens(workspace?.designSystem, project?.designSystem, withoutRetiredSeeds(canvas.variables)); } /** The tokens a canvas inherits from the workspace + project layers, *excluding* diff --git a/test/unit/test-derived-tints.ts b/test/unit/test-derived-tints.ts new file mode 100644 index 0000000..56fb23f --- /dev/null +++ b/test/unit/test-derived-tints.ts @@ -0,0 +1,209 @@ +import '../env.js'; +// Phase 32 slice C (FR-C5, FR-C6; contracts M7, M8, M10): the tint layer and +// `danger` derive from the inks and the surface when the design system does +// not define them, and a canvas still holding an old scaffold seed renders as +// if it were unset. Every asserted pass has a twin that must fail. +// +// Usage: npx tsx test/unit/test-derived-tints.ts + +import { createCanvas } from '../../src/scene-graph.js'; +import { applyStructure } from '../../src/structures.js'; +import { getPreset } from '../../src/presets.js'; +import { expandTree } from '../../src/expand.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { applyPresetTokens, resolveVariables, withoutRetiredSeeds } from '../../src/variables.js'; +import { contrastRatio, parseColor } from '../../src/color-math.js'; +import { tintFor, tintLayer } from '../../src/color-system.js'; +import { generateDesignSystem } from '../../src/design-language.js'; +import { canvasVersionHash } from '../../src/version.js'; +import { createProject, createWorkspace, getCanvasTokens, getInheritedTokens, setWorkspaceDesignSystem } from '../../src/workspaces.js'; +import type { Canvas, DesignVariables, SceneNode } from '../../src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +const ratio = (a: string, b: string) => contrastRatio(parseColor(a)!, parseColor(b)!); +/** A colour's mode: dark when it contrasts more with white than with black. */ +const modeOf = (hex: string) => (ratio(hex, '#FFFFFF') > ratio(hex, '#000000') ? 'dark' : 'light'); +const isGrey = (hex: string) => { const [r, g, b] = parseColor(hex)!; return r === g && g === b; }; + +/** Resolve one token through the resolver, as a fill. */ +function resolveFill(ref: string, vars: DesignVariables, theme?: 'light' | 'dark'): string { + return resolveVariables({ id: 'x', type: 'frame', fill: ref } as SceneNode, vars, { theme }).fill as string; +} + +/** The resolved node whose authored prop was `ref`, in a canvas's one tree. */ +function resolvedBy(canvas: Canvas, prop: 'fill' | 'color' | 'stroke', ref: string, theme?: 'light' | 'dark'): SceneNode | undefined { + const raw = expandTree(canvas.root, canvas).root; + let id: string | undefined; + (function find(n: SceneNode) { if (!id && n[prop] === ref) id = n.id; n.children?.forEach(find); })(raw); + const resolved = expandTree(canvas.root, canvas, getCanvasTokens(canvas), { theme }).root; + let out: SceneNode | undefined; + (function find(n: SceneNode) { if (n.id === id) out = n; n.children?.forEach(find); })(resolved); + return out; +} + +function stamped(structure: string, preset?: string, type?: 'desktop-app'): Canvas { + const canvas = createCanvas(`dt-${structure}-${preset ?? 'unthemed'}`, undefined, {}, type ? { type } : undefined); + applyStructure(canvas, structure); + if (preset) applyPresetTokens(canvas, getPreset(preset)!.variables, getInheritedTokens(canvas)); + return canvas; +} + +// ── FR-C5: tints follow the surface ─────────────────────────────────────────── +{ + const light = resolvedBy(stamped('status-chip', 'light'), 'fill', '$success-tint')?.fill as string; + check('status-chip then apply_preset light: a light-mode tint', !!light && modeOf(light) === 'light', light); + const dark = resolvedBy(stamped('status-chip', 'dark'), 'fill', '$success-tint')?.fill as string; + check('...under apply_preset dark: a dark-mode tint', !!dark && modeOf(dark) === 'dark', dark); + const unthemed = resolvedBy(stamped('status-chip'), 'fill', '$success-tint')?.fill as string; + check('...unthemed: a dark-mode tint (the scaffold palette is dark)', !!unthemed && modeOf(unthemed) === 'dark', unthemed); + // Twin: a hand-set dark tint that is NOT the old seed survives the light + // preset, as any canvas token does. + const kept = stamped('status-chip'); + kept.variables.colors = { ...kept.variables.colors, 'success-tint': '#0F2E1C' }; + applyPresetTokens(kept, getPreset('light')!.variables, getInheritedTokens(kept)); + check('twin: a non-seed dark tint is kept under the light preset', resolvedBy(kept, 'fill', '$success-tint')?.fill === '#0F2E1C'); +} +{ + // A generated system's inks on tints derived from them clear 4.5:1 in both + // themes (seed #2563EB; the generator's own light accent-tint cap makes + // some seeds miss, contract M7). + const sys = generateDesignSystem('#2563EB', 'technical').variables; + const strip = (c: Record | undefined) => Object.fromEntries(Object.entries(c ?? {}).filter(([k]) => !k.endsWith('-tint'))); + const vars: DesignVariables = { ...sys, colors: strip(sys.colors), dark: { ...sys.dark, colors: strip(sys.dark?.colors) } }; + for (const theme of ['light', 'dark'] as const) { + for (const [ink, tint] of [['$success', '$success-tint'], ['$accent', '$accent-tint'], ['$danger', '$danger-tint']]) { + const node = resolveVariables({ id: 'x', type: 'text', content: 'x', fill: tint, color: ink } as SceneNode, vars, { theme }); + const r = ratio(node.color as string, node.fill as string); + check(`generated system, ${theme}: ${ink} on a derived ${tint} clears 4.5:1`, r >= 4.5, r.toFixed(2)); + } + } +} +{ + const light = stamped('settings-app', 'light', 'desktop-app'); + const resolved = expandTree(light.root, light, getCanvasTokens(light)).root; + let deleteFill: string | undefined; + (function find(n: SceneNode) { if (n.id === 'sta-delete') deleteFill = n.fill as string; n.children?.forEach(find); })(resolved); + check('settings-app then apply_preset light: the danger action draws the preset\'s error', deleteFill?.toLowerCase() === '#ef4444', deleteFill); + const unthemed = stamped('settings-app', undefined, 'desktop-app'); + const ev = await evaluateCanvas(unthemed, { mode: 'fast', categories: ['structure'] }); + check('...unthemed, it resolves with no unknown-token finding', !ev.issues.some((i) => i.rule === 'unknown-token')); + const unthemedFill = resolvedBy(unthemed, 'stroke', '$danger')?.stroke; + check('...and unthemed, danger is #F87171 (the dark-mode fallback on the dark scaffold surface)', unthemedFill === '#F87171', unthemedFill as string); +} +{ + check('danger: an explicit error wins', resolveFill('$danger', { colors: { error: '#B00020' } }) === '#B00020'); + check('danger: no token on a light surface is #DC2626', resolveFill('$danger', { colors: { 'bg-surface': '#FFFFFF' } }) === '#DC2626'); + check('twin: on a dark surface it is #F87171', resolveFill('$danger', { colors: { 'bg-surface': '#111111' } }) === '#F87171'); + check('a defined danger is never replaced', resolveFill('$danger', { colors: { danger: '#123456', error: '#B00020' } }) === '#123456'); +} + +// ── M7: the surface, alpha and grey inks ────────────────────────────────────── +{ + check('M10: a #777777 surface derives light tints', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#777777' } })) === 'light'); + check('M10 twin: a #757575 surface derives dark tints', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#757575' } })) === 'dark'); + check('a translucent surface lies over bg-primary: a glass card on a dark page is dark', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#ffffff0a', 'bg-primary': '#0a0a0a' } })) === 'dark'); + check('twin: the same glass over a light page is light', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#ffffff0a', 'bg-primary': '#fafafa' } })) === 'light'); + check('an hsl() surface parses (dark)', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': 'hsl(222 47% 11%)' } })) === 'dark'); + check('an unparseable surface falls to bg-primary', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': 'var(--x)', 'bg-primary': '#0a0a0a' } })) === 'dark'); + const neutral = resolveFill('$neutral-tint', { colors: { 'bg-surface': '#111111', 'text-secondary': '#ffffffa0' } }); + check('a grey ink with alpha (composited over the surface) gets a grey tint', isGrey(neutral) && modeOf(neutral) === 'dark', neutral); + check('twin: the generator\'s tintLayer is unchanged and gives that ink a hue', !isGrey(tintLayer({ 'accent-tint': '#a5a5a5', 'success-tint': '#a5a5a5', 'warning-tint': '#a5a5a5', 'danger-tint': '#a5a5a5', 'neutral-tint': '#a5a5a5' }, 'dark')['neutral-tint'])); + check('tintLayer output matches its pre-slice value (#1d4ed8 light → #DDE8FF)', tintLayer({ 'accent-tint': '#1d4ed8', 'success-tint': '#1d4ed8', 'warning-tint': '#1d4ed8', 'danger-tint': '#1d4ed8', 'neutral-tint': '#1d4ed8' }, 'light')['accent-tint'] === '#DDE8FF'); + check('a defined tint is never replaced', resolveFill('$accent-tint', { colors: { 'accent-tint': '#ABCDEF' } }) === '#ABCDEF'); + check('a dark render derives from the dark layer', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#FFFFFF' }, dark: { colors: { 'bg-surface': '#111111' } } }, 'dark')) === 'dark'); + check('twin: the same tokens in light derive light', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#FFFFFF' }, dark: { colors: { 'bg-surface': '#111111' } } })) === 'light'); + check('the derived accent-tint is tintFor of the accent', resolveFill('$accent-tint', { colors: { accent: '#0E7490', 'bg-surface': '#FFFFFF' } }) === tintFor('#0E7490', 'light')); +} + +// ── FR-C6 and M8: old seeds count as unset ──────────────────────────────────── +{ + const seeded = stamped('status-chip'); + seeded.variables.colors = { ...seeded.variables.colors, 'success-tint': '#0f2e1b' }; + applyPresetTokens(seeded, getPreset('light')!.variables, getInheritedTokens(seeded)); + const fill = resolvedBy(seeded, 'fill', '$success-tint')?.fill as string; + check('a canvas stored with success-tint "#0f2e1b" renders the derived tint under a light preset', modeOf(fill) === 'light', fill); + check('...and its stored JSON is not rewritten', seeded.variables.colors?.['success-tint'] === '#0f2e1b'); + + const ws = createWorkspace('dt-ws'); + setWorkspaceDesignSystem(ws.id, { colors: { 'success-tint': '#DAF8DF' } }); + const project = createProject(ws.id, 'dt-p')!; + const inherits = createCanvas('dt-inherits', project.id); + applyStructure(inherits, 'status-chip'); + inherits.variables.colors = { ...inherits.variables.colors, 'success-tint': '#0F2E1B' }; + check('a seed under a workspace that generated success-tint renders the workspace\'s value', resolvedBy(inherits, 'fill', '$success-tint')?.fill === '#DAF8DF'); + inherits.variables.colors['success-tint'] = '#0F2E1C'; + check('twin: a non-seed canvas value still wins over the workspace', resolvedBy(inherits, 'fill', '$success-tint')?.fill === '#0F2E1C'); + + // apply_preset / generate at canvas scope preserve the inherited tint + // instead of overwriting the dead seed. + inherits.variables.colors['success-tint'] = '#0F2E1B'; + const merge = applyPresetTokens(inherits, { colors: { 'success-tint': '#E0FFE0' } }, getInheritedTokens(inherits)); + check('a canvas-scope system preserves the inherited tint over a seed', merge.preserved.some((p) => p.key === 'success-tint') && inherits.variables.colors['success-tint'] === '#0F2E1B'); + inherits.variables.colors['success-tint'] = '#0F2E1C'; + const merge2 = applyPresetTokens(inherits, { colors: { 'success-tint': '#E0FFE0' } }, getInheritedTokens(inherits)); + check('twin: over a non-seed own value it writes', !merge2.preserved.some((p) => p.key === 'success-tint') && inherits.variables.colors['success-tint'] === '#E0FFE0'); + + check('danger "#F87171" counts as a seed too', !getCanvasTokens({ ...seeded, variables: { colors: { danger: '#F87171' } } }).colors?.danger); + check('get_variables omits the seeds', !withoutRetiredSeeds({ colors: { 'accent-tint': '#152a47', accent: '#2563EB' } }).colors?.['accent-tint']); + check('...and keeps everything else', withoutRetiredSeeds({ colors: { 'accent-tint': '#152a48', accent: '#2563EB' } }).colors?.['accent-tint'] === '#152a48'); + check('a seed value under another name is kept (matched by name and value)', getCanvasTokens({ ...seeded, variables: { colors: { error: '#F87171' } } }).colors?.error === '#F87171'); +} +{ + // The version hash reads the tokens getCanvasTokens returns. + const plain = createCanvas('dt-hash'); + plain.variables = { colors: { accent: '#2563EB' } }; + const withSeed = structuredClone(plain); + withSeed.variables.colors!['accent-tint'] = '#152A47'; + check('a canvas holding a seed hashes as if it were unset', canvasVersionHash(withSeed) === canvasVersionHash(plain)); + const withOther = structuredClone(plain); + withOther.variables.colors!['accent-tint'] = '#152A48'; + check('twin: any other value moves the hash', canvasVersionHash(withOther) !== canvasVersionHash(plain)); +} + +// ── No stamp reads badly on a derived tint ───────────────────────────────────── +// Every structure, unthemed and under each preset whose inks clear on its own +// surface (the light preset's success and error do not: FR-C5's last +// sentence), has no contrast error against a tint it derived. This sweep +// caught a lone status-chip deriving a light tint under its dark-tuned ink +// before stamps seeded the surface the derivation reads. +{ + const { listStructures } = await import('../../src/structures.js'); + const misses: string[] = []; + for (const theme of [undefined, 'dark', 'material', 'minimal']) { + for (const s of listStructures()) { + const type = s.surface === 'mobile' || s.surface === 'desktop-app' ? s.surface : undefined; + const canvas = createCanvas(`dt-sweep-${s.name}-${theme}`, undefined, {}, type ? { type } : undefined); + applyStructure(canvas, s.name, { replace: true }); + if (theme) applyPresetTokens(canvas, getPreset(theme)!.variables, getInheritedTokens(canvas)); + const tokens = getCanvasTokens(canvas); + const tints = ['accent-tint', 'success-tint', 'warning-tint', 'danger-tint', 'neutral-tint'] + .filter((t) => !tokens.colors?.[t]) + .map((t) => resolveFill(`$${t}`, tokens).toUpperCase()); + const ev = await evaluateCanvas(canvas, { mode: 'fast', categories: ['color'] }); + for (const i of ev.issues) { + const against = /against (#[0-9A-Fa-f]{6})/.exec(i.message)?.[1]?.toUpperCase(); + if (i.severity !== 'info' && against && tints.includes(against)) misses.push(`${s.name} @ ${theme ?? 'unthemed'}: ${i.message.slice(0, 80)}`); + } + } + } + check('no stamp has a contrast error against a derived tint (unthemed, dark, material, minimal)', misses.length === 0, misses.slice(0, 4).join(' ;; ')); + // Twin: a light tint under a dark-tuned ink (the bug the seeding fixed) is caught. + const chip = createCanvas('dt-sweep-twin'); + applyStructure(chip, 'status-chip'); + chip.variables.colors = { ...chip.variables.colors, 'bg-surface': '#FFFFFF' }; + const twin = await evaluateCanvas(chip, { mode: 'fast', categories: ['color'] }); + const lightTint = resolveFill('$success-tint', getCanvasTokens(chip)).toUpperCase(); + check('twin: a dark-tuned ink on a light derived tint is a contrast error the sweep sees', twin.issues.some((i) => i.severity === 'error' && i.message.toUpperCase().includes(`AGAINST ${lightTint}`)), lightTint); +} + +if (!allPass) { + console.log('\nSOME CHECKS FAILED'); + process.exit(1); +} +console.log('\nAll checks passed.'); +process.exit(0); diff --git a/test/unit/test-desktop-primitives.ts b/test/unit/test-desktop-primitives.ts index ff65d49..aa6c8bc 100644 --- a/test/unit/test-desktop-primitives.ts +++ b/test/unit/test-desktop-primitives.ts @@ -14,6 +14,7 @@ import { readFileSync } from 'node:fs'; import { evaluateCanvas } from '../../src/evaluate.js'; import { renderToHtml } from '../../src/renderer.js'; import { resolveVariables } from '../../src/variables.js'; +import { tintFor } from '../../src/color-system.js'; import { applyPerturbation } from '../../src/stress.js'; import { getStructure, applyStructure } from '../../src/structures.js'; import { createCanvas } from '../../src/scene-graph.js'; @@ -61,18 +62,24 @@ const html = (n: SceneNode, colors?: Record) => { // ── FR-B3..B9: markup and defaults ───────────────────────────────────────── { const nav = html({ id: 'n', name: 'n', type: 'nav-item', label: 'Projects', icon: 'folder', active: true, count: 12 }); - check('an active nav-item draws fill, bar and weight, with aria-current', /aria-current="page"/.test(nav) && /width: 2px/.test(nav) && /font-weight: 600/.test(nav) && /background-color: #E5ECFD/.test(nav), (nav.match(/background-color: #[0-9A-F]{6}/gi) ?? []).join(' ')); - const darkNav = html({ id: 'nd', name: 'nd', type: 'nav-item', label: 'A', active: true }, { accent: '#60A5FA', 'bg-surface': '#111827' }); - check('without an accent-tint token the active fill is the accent washed into the surface (dark stays dark)', /background-color: #1A2940/.test(darkNav), (darkNav.match(/background-color: #[0-9A-F]{6}/gi) ?? []).join(' ')); + // Phase 32 slice C (FR-C5) — without an accent-tint token the active fill is + // the tint derived from the accent, in the mode of the surface it sits on. + const fill = (h: string) => new RegExp(`background-color: ${tintFor('#2563EB', 'light')}`).test(h); + check('an active nav-item draws fill, bar and weight, with aria-current', /aria-current="page"/.test(nav) && /width: 2px/.test(nav) && /font-weight: 600/.test(nav) && fill(nav), (nav.match(/background-color: #[0-9A-F]{6}/gi) ?? []).join(' ')); const fills = (h: string) => (h.match(/background-color: #[0-9A-F]{6}/gi) ?? []).join(' '); + const has = (h: string, hex: string) => h.includes(`background-color: ${hex}`); + const darkNav = html({ id: 'nd', name: 'nd', type: 'nav-item', label: 'A', active: true }, { accent: '#60A5FA', 'bg-surface': '#111827' }); + check('without an accent-tint token the active fill derives from the accent (dark stays dark)', has(darkNav, tintFor('#60A5FA', 'dark')), fills(darkNav)); + check('twin: it is not the light tint', !has(darkNav, tintFor('#60A5FA', 'light'))); const rgbNav = html({ id: 'nr', name: 'nr', type: 'nav-item', label: 'A', active: true }, { accent: 'rgb(96, 165, 250)', 'bg-surface': '#111827' }); - check('an rgb() accent washes into the surface like its hex twin', /background-color: #1A2940/.test(rgbNav), fills(rgbNav)); + check('an rgb() accent derives like its hex twin', has(rgbNav, tintFor('#60A5FA', 'dark')), fills(rgbNav)); const hslNav = html({ id: 'nh', name: 'nh', type: 'nav-item', label: 'A', active: true }, { accent: 'hsl(213 94% 68%)', 'bg-surface': 'rgb(17 24 39)' }); - check('an hsl() accent on an rgb() surface washes in too (dark stays dark)', /background-color: #1B2940/.test(hslNav), fills(hslNav)); + // #192F49: the dark tint of hsl(213 94% 68%), which parses to #60A6FA. + check('an hsl() accent on an rgb() surface derives too (dark stays dark)', has(hslNav, '#192F49') && has(hslNav, tintFor('#60A6FA', 'dark')), fills(hslNav)); const shortNav = html({ id: 'ns', name: 'ns', type: 'nav-item', label: 'A', active: true }, { accent: '#06F', 'bg-surface': '#FFF' }); - check('a #RGB accent and surface mix', /background-color: #E0EDFF/.test(shortNav), fills(shortNav)); + check('a #RGB accent on a #RGB surface derives a light tint', has(shortNav, tintFor('#0066FF', 'light')), fills(shortNav)); const namedNav = html({ id: 'nn', name: 'nn', type: 'nav-item', label: 'A', active: true }, { accent: 'royalblue', 'bg-surface': '#111827' }); - check('a named accent still falls back to the light tint', /background-color: #EFF4FF/.test(namedNav), fills(namedNav)); + check('a named accent takes the #2563EB literal, in the surface\'s mode', has(namedNav, tintFor('#2563EB', 'dark')), fills(namedNav)); const rail = html({ id: 'n2', name: 'n2', type: 'nav-item', label: 'Projects', icon: 'folder', collapsed: true }); check('a collapsed nav-item is 32×32 with its label as the accessible name', /width: 32px/.test(rail) && /aria-label="Projects"/.test(rail) && !/>Projects ruleIds.add(id)); } + // Default rules run unless a ruleset turns them off (Phase 32: unknown-token). + DEFAULT_RULES.forEach((id) => ruleIds.add(id)); expect('the ruleset table registers rule ids', ruleIds.size > 0); for (const [label, src] of [['src/index.ts', indexSrc], ['GUIDELINES', guidelines], ['README', readme]] as const) { const missing = [...ruleIds].filter((id) => !src.includes(id)); diff --git a/test/unit/test-patterns.ts b/test/unit/test-patterns.ts index 7c50bd5..bd563d1 100644 --- a/test/unit/test-patterns.ts +++ b/test/unit/test-patterns.ts @@ -11,7 +11,7 @@ import { listStructures, applyStructure } from '../../src/structures.js'; import { getPreset } from '../../src/presets.js'; import { evaluateCanvas, contrastRatio, parseColor } from '../../src/evaluate.js'; import { generateDesignSystem, PERSONALITY_NAMES } from '../../src/design-language.js'; -import { setVariables, applyPresetTokens, getVariables } from '../../src/variables.js'; +import { setVariables, applyPresetTokens, getVariables, themeTokens, withDerivedColors } from '../../src/variables.js'; import { getCanvasTokens, createWorkspace, createProject, setWorkspaceDesignSystem } from '../../src/workspaces.js'; import type { Canvas, SceneNode } from '../../src/types.js'; @@ -63,10 +63,10 @@ async function main() { // not their type scale: every built-in preset sets a 14–15px body, // which mobile-type-floor rightly flags on every phone screen whatever // its structure. generate_design_system is the phone type path, and - // the personalities below hold the realisations to it. - if (preset) canvas.variables = mobile - ? { ...structuredClone(preset.variables), typography: canvas.variables.typography } - : structuredClone(preset.variables); + // the personalities below hold the realisations to it. The preset + // merges as apply_preset merges it: replacing the variables wholesale + // would drop the stamp's seeded spacing, radius and type tokens. + if (preset) applyPresetTokens(canvas, mobile ? { ...preset.variables, typography: undefined } : preset.variables, {}); } // The gate measures the PATTERN's taste/craft — coverage (Phase 24) // demands sibling state variants, which is a property of a designed @@ -113,12 +113,49 @@ async function main() { } await desktopGate(); + await unknownTokenGate(); console.log(`\n${passed} passed, ${failed} failed`); process.exit(failed > 0 ? 1 : 0); } main(); +// ── Phase 32 slice C (M11) — no stamp ever references a token it lacks ────── +// Every structure, of every kind and surface, stamped unthemed, then under +// each preset (merged, as apply_preset does), then over a generated system: +// zero unknown-token findings. A scaffold that adds a ref nothing seeds or +// derives fails here first. +async function unknownTokenGate() { + const all = listStructures(); + const presets = ['dark', 'light', 'material', 'minimal'] as const; + console.log(`\nunknown-token gate — ${all.length} structures × (unthemed + ${presets.length} presets + a generated system)\n`); + let clean = 0; + const misses: string[] = []; + for (const s of all) { + const opts = s.surface === 'mobile' ? { type: 'mobile' as const } : s.surface === 'desktop-app' ? { type: 'desktop-app' as const } : undefined; + const variants: Array<[string, (c: Canvas) => void]> = [ + ['unthemed', (c) => { applyStructure(c, s.name, { replace: true }); }], + ...presets.map((p): [string, (c: Canvas) => void] => [p, (c) => { applyStructure(c, s.name, { replace: true }); applyPresetTokens(c, getPreset(p)!.variables, {}); }]), + ['generated', (c) => { setVariables(c, generateDesignSystem('#2563EB', 'technical').variables); applyStructure(c, s.name, { replace: true, ...existing(c) }); }], + ]; + for (const [label, stamp] of variants) { + const canvas = createCanvas(`ut-${s.name}-${label}`, undefined, {}, opts); + stamp(canvas); + const found = (await evaluateCanvas(canvas, { mode: 'fast', categories: ['structure'] })).issues.filter((i) => i.rule === 'unknown-token'); + if (found.length) misses.push(`${s.name} @ ${label}: ${found.map((f) => f.message).join(' | ')}`); + else clean++; + } + } + assert(misses.length === 0, `every stamp resolves every ref (${clean} clean)${misses.length ? ' — ' + misses.slice(0, 5).join(' ;; ') : ''}`); + // Twin: a stamp whose variables were replaced wholesale by a preset loses its + // seeded spacing tokens, and the gate sees it. + const wiped = createCanvas('ut-wiped'); + applyStructure(wiped, 'dashboard', { replace: true }); + wiped.variables = structuredClone(getPreset('light')!.variables); + const wipedFound = (await evaluateCanvas(wiped, { mode: 'fast', categories: ['structure'] })).issues.filter((i) => i.rule === 'unknown-token'); + assert(wipedFound.length > 0, `twin: a stamp whose variables a preset replaced wholesale fails the gate (${wipedFound.length} findings)`); +} + // ── Phase 31 slice D (FR-D3, G2 + G4) — the desktop-app gate ──────────────── // Every desktop-app realisation, and data-table-app / skeleton-table-app, // stamped on a desktop-app canvas under the inputs the docs promise agents: @@ -148,9 +185,13 @@ const blocking = (issues: { severity: string; rule?: string; category: string; t /** `$text-primary` on `$accent-tint`, light and dark, where the canvas has a tint. */ function tintContrast(canvas: Canvas): number[] { - const merged = getVariables(canvas); + // The tokens the render uses: merged, old seeds dropped, and (Phase 32 + // slice C) a missing tint derived in each theme. + const merged = getCanvasTokens(canvas); const ratios: number[] = []; - for (const colors of [merged.colors, merged.dark?.colors ? { ...merged.colors, ...merged.dark.colors } : undefined]) { + for (const theme of ['light', 'dark'] as const) { + if (theme === 'dark' && !merged.dark?.colors) continue; + const colors = withDerivedColors(themeTokens(merged, theme)).colors; const tint = colors?.['accent-tint']; const ink = colors?.['text-primary']; const fg = typeof ink === 'string' ? parseColor(ink) : null; @@ -163,7 +204,13 @@ function tintContrast(canvas: Canvas): number[] { /** A desktop-app canvas; a component goes under a root painted as a page is. */ function appCanvas(name: string, component: boolean): Canvas { const canvas = createCanvas(name, undefined, {}, { type: 'desktop-app' }); - if (component) canvas.root.fill = '$bg-primary'; + // A component stamp seeds only what it references, so the backdrop the + // harness gives it defines its own token (the scaffold default): an + // undefined $bg-primary is an unknown-token warning, and drew nothing. + if (component) { + canvas.root.fill = '$bg-primary'; + canvas.variables.colors = { ...canvas.variables.colors, 'bg-primary': '#0a0a0a' }; + } return canvas; } @@ -236,7 +283,8 @@ async function desktopGate() { assert(blocking((await evaluateCanvas(unnamed, { mode: 'fast', categories: CATEGORIES })).issues).some((b) => b.includes('desktop-app-icon-label')), 'twin: an icon-only button without ariaLabel fails the gate'); const darkTint = appCanvas('twin-tint', false); applyStructure(darkTint, 'split-workbench-app'); - darkTint.variables.colors = { ...darkTint.variables.colors, 'accent-tint': '#152A47' }; + // Not the retired seed #152A47 itself, which now counts as unset and derives. + darkTint.variables.colors = { ...darkTint.variables.colors, 'accent-tint': '#152A48' }; applyPresetTokens(darkTint, getPreset('light')!.variables, getVariables(darkTint)); assert(tintContrast(darkTint).some((r) => r < 4.5) && !(await verdict(darkTint, 'light')).ok, 'twin: a dark $accent-tint left under the light preset fails the gate'); // An info-level desktop-app finding (a hand-built 28px icon frame) fails it too. diff --git a/test/unit/test-structures.ts b/test/unit/test-structures.ts index 4892aec..3ede6ed 100644 --- a/test/unit/test-structures.ts +++ b/test/unit/test-structures.ts @@ -217,14 +217,16 @@ check(detailPh.some((p) => p.id === 'dtm-nav' && p.prop === 'leading.label' && p const fallbacks = applyStructure(createCanvas('e-fallback', undefined, {}, { type: 'mobile' }), 'feed', { existingColors: new Set(['primary', 'surface', 'error']) }); check(!['accent', 'bg-surface', 'danger'].some((t) => fallbacks.seededColors.includes(t)) && fallbacks.seededColors.includes('text-primary'), 'a canvas resolving primary / surface / error keeps them: the primitives\' accent / bg-surface / danger are not seeded over them', fallbacks.seededColors.join(', ')); -check(['text-primary', 'text-secondary', 'border', 'bg-surface', 'danger', 'accent'].every((t) => r1.seededColors.includes(t)), 'the colour tokens primitives read are seeded'); +check(['text-primary', 'text-secondary', 'border', 'bg-surface', 'accent'].every((t) => r1.seededColors.includes(t)), 'the colour tokens primitives read are seeded'); +// Phase 32 slice C (FR-C5) — danger and the tints derive; they are never seeded. +check(!['danger', 'accent-tint', 'success-tint', 'warning-tint', 'danger-tint', 'neutral-tint'].some((t) => r1.seededColors.includes(t)), 'danger and the tint layer are not seeded', r1.seededColors.join(', ')); const plain = applyStructure(createCanvas('e-plain', undefined, {}, { type: 'mobile' }), 'feed'); check(plain.seededColors.includes('text-primary'), 'a stamp that references no $text-primary still seeds it for its primitives'); for (const type of ['status-bar', 'home-indicator', 'nav-bar', 'tab-bar', 'button', 'list-row', 'sheet'] as const) { registerStructure(page(`seed-${type}`, { surface: 'any', nodes: [{ id: `seed-${type}-n`, type }] })); const seeded = applyStructure(createCanvas(`e-seed-${type}`), `seed-${type}`).seededColors; - const want = ['accent', 'bg-surface', 'border', 'danger', 'text-primary', 'text-secondary']; - check(want.every((t) => seeded.includes(t)), `a lone ${type} seeds all six colours the primitives read`, seeded.join(', ')); + const want = ['accent', 'bg-surface', 'border', 'text-primary', 'text-secondary']; + check(want.every((t) => seeded.includes(t)) && !seeded.includes('danger'), `a lone ${type} seeds the five colours the primitives read, and not danger (it derives)`, seeded.join(', ')); } const forced = applyStructure(createCanvas('e-forced', undefined, {}, { type: 'mobile' }), 'dashboard', { realisation: 'web' }); check(forced.applied === 'dashboard' && forced.surface === 'web', 'realisation: "web" stamps the web dashboard on a mobile canvas'); diff --git a/test/unit/test-unknown-token.ts b/test/unit/test-unknown-token.ts new file mode 100644 index 0000000..f632485 --- /dev/null +++ b/test/unit/test-unknown-token.ts @@ -0,0 +1,204 @@ +import '../env.js'; +// Phase 32 slice C (FR-C1 to FR-C4; contracts M1 to M6): a `$ref` that no +// token defines, or that names the wrong kind of token, is an `unknown-token` +// warning; an unambiguous misspelling on a stored node carries a rename fix; +// copy is never resolved; token usage counts only refs that resolve. Every +// asserted pass has a twin that must fail. +// +// Usage: npx tsx test/unit/test-unknown-token.ts + +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { evaluateCanvas, type EvaluationIssue } from '../../src/evaluate.js'; +import { generateSpaceScale } from '../../src/scales.js'; +import { createProject, createWorkspace, setWorkspaceDesignSystem } from '../../src/workspaces.js'; +import type { Canvas, DesignVariables, SceneNode } from '../../src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +const SYSTEM: DesignVariables = { + colors: { 'bg-surface': '#FFFFFF', 'text-primary': '#111827', accent: '#2563EB' }, + spacing: generateSpaceScale(16), + typography: { body: { fontSize: 16 } }, + elevation: { md: [{ x: 0, y: 2, blur: 8, spread: 0, color: 'rgba(0,0,0,0.1)' }] }, + state: { hover: 0.08 }, +}; + +function canvasWith(children: SceneNode[], variables: DesignVariables = SYSTEM): Canvas { + const canvas = createCanvas('unknown token'); + canvas.variables = structuredClone(variables); + canvas.root.children = children; + return canvas; +} + +async function findings(canvas: Canvas): Promise { + const ev = await evaluateCanvas(canvas, { mode: 'fast', categories: ['structure'] }); + return ev.issues.filter((i) => i.rule === 'unknown-token'); +} + +const frame = (id: string, props: Partial): SceneNode => ({ id, type: 'frame', name: id, ...props } as SceneNode); +const about = (fs: EvaluationIssue[], text: string) => fs.filter((f) => f.message.includes(text)); + +// ── FR-C1: unknown refs, candidates and the fix ────────────────────────────── +{ + const fs = await findings(canvasWith([frame('a', { gap: '$space-mdd' }), frame('b', { gap: '$space-md' })])); + const [mdd] = about(fs, '$space-mdd'); + check('gap "$space-mdd" warns', !!mdd && mdd.severity === 'warning' && mdd.category === 'structure' && mdd.nodeId === 'a'); + check('...and autofixes to $space-md', mdd?.fix?.op === 'U("a", { gap: "$space-md" })', mdd?.fix?.op); + check('twin: gap "$space-md" is silent', fs.length === 1, fs.map((f) => f.message).join(' | ')); +} +{ + const [xxs] = await findings(canvasWith([frame('a', { gap: '$space-xxs' })])); + check('gap "$space-xxs" warns with no fix', !!xxs && !xxs.fix); + check('...naming space-2xs, space-3xs and space-xs', ['$space-2xs', '$space-3xs', '$space-xs'].every((n) => xxs?.suggestion?.includes(`"${n}"`)), xxs?.suggestion); +} +{ + const [surf] = await findings(canvasWith([frame('a', { fill: '$bg-surfce' })])); + check('fill "$bg-surfce" autofixes to $bg-surface', surf?.fix?.op === 'U("a", { fill: "$bg-surface" })', surf?.fix?.op); +} +{ + const fs = await findings(canvasWith([frame('a', { shadow: '$elevation.md' }), frame('b', { shadow: '$elevation.mdd' })])); + check('a defined $elevation.md is silent, $elevation.mdd warns', fs.length === 1 && fs[0].nodeId === 'b', fs.map((f) => f.message).join(' | ')); +} +{ + const fs = await findings(canvasWith([frame('a', { fill: '$success-tint' }), frame('b', { fill: '$success-tnt' })])); + check('$success-tint with no such token is silent (it derives); $success-tnt warns', fs.length === 1 && fs[0].nodeId === 'b', fs.map((f) => f.message).join(' | ')); +} +{ + const vars = structuredClone(SYSTEM); + vars.dark = { colors: { 'night-only': '#000000' } }; + const fs = await findings(canvasWith([frame('a', { fill: '$night-only' })], vars)); + check('a token defined only in the dark layer warns for light, with no fix', fs.length === 1 && /only in the dark layer/.test(fs[0].message) && !fs[0].fix, fs.map((f) => f.message).join(' | ')); + vars.colors!['night-only'] = '#FFFFFF'; + check('twin: defined in the base too, it is silent', (await findings(canvasWith([frame('a', { fill: '$night-only' })], vars))).length === 0); +} + +// ── FR-C2 and M3, M4: kinds ─────────────────────────────────────────────────── +{ + const fs = await findings(canvasWith([ + frame('fill-body', { fill: '$body' }), + frame('gap-accent', { gap: '$accent' }), + frame('gap-body', { gap: '$body' }), + { id: 'family', type: 'text', name: 'family', content: 'x', fontFamily: '$body' } as SceneNode, + { id: 'size', type: 'text', name: 'size', content: 'x', fontSize: '$body' } as SceneNode, + frame('dotted-color', { fill: '$colors.accent' }), + frame('dotted-number', { gap: '$spacing.space-md' }), + frame('dotted-state', { opacity: '$state.hover' } as unknown as Partial), + frame('dotted-object', { gap: '$typography.body' }), + ])); + const on = (id: string) => fs.filter((f) => f.nodeId === id); + check('fill "$body" warns naming the kind it got', /typography token, not a color/.test(on('fill-body')[0]?.message ?? ''), on('fill-body')[0]?.message); + check('gap "$accent" warns', /color token, not a spacing/.test(on('gap-accent')[0]?.message ?? '')); + check('gap "$body" warns (a typography ref is valid only on fontSize)', on('gap-body').length === 1); + check('fontFamily "$body" warns that the prop takes no token', /fontFamily takes no token/.test(on('family')[0]?.message ?? '')); + check('twin: fontSize "$body" is silent', on('size').length === 0); + check('dotted refs into colours, spacing and state are their kinds (silent)', ['dotted-color', 'dotted-number', 'dotted-state'].every((id) => on(id).length === 0), fs.map((f) => f.message).join(' | ')); + check('a dotted ref to a whole typography token warns', on('dotted-object').length === 1); + check('wrong-kind findings carry no fix', fs.every((f) => !f.fix)); +} + +// ── M2: nested refs; M5: the fix's reach ────────────────────────────────────── +{ + const fs = await findings(canvasWith([ + frame('pad', { padding: ['$space-mdd', '$space-lgg'] }), + frame('border', { borderTop: { width: 1, color: '$accnt' } }), + { id: 'chart', type: 'chart', name: 'chart', kind: 'line', series: [{ values: [1, 2], stroke: '$accnt' }] } as unknown as SceneNode, + frame('radius', { cornerRadius: ['$radius-mdd', 0, 0, 0] }), + ])); + const pad = fs.filter((f) => f.nodeId === 'pad'); + const op = 'U("pad", { padding: ["$space-md","$space-lg"] })'; + check('two typos in one padding array: two findings carrying one op that renames both', pad.length === 2 && pad.every((f) => f.fix?.op === op), pad.map((f) => f.fix?.op).join(' | ')); + const border = fs.find((f) => f.nodeId === 'border'); + check('a borderTop.color typo rewrites the whole object', border?.fix?.op === 'U("border", { borderTop: {"width":1,"color":"$accent"} })', border?.fix?.op); + const chart = fs.find((f) => f.nodeId === 'chart'); + check('a series[].stroke typo warns with no fix (the U parser cannot round-trip it)', !!chart && /series\[0\]\.stroke/.test(chart.message) && !chart.fix, chart?.message); + check('a cornerRadius entry with no radius tokens warns with no candidates', fs.some((f) => f.nodeId === 'radius' && !f.fix)); + + // The ops apply: both renames land. + const canvas = canvasWith([frame('pad', { padding: ['$space-mdd', '$space-lgg'] })]); + const [first] = await findings(canvas); + parseAndExecute(canvas.root, first.fix!.op, canvas); + parseAndExecute(canvas.root, first.fix!.op, canvas); + const after = canvas.root.children![0].padding; + check('applying the op twice leaves both renames', JSON.stringify(after) === '["$space-md","$space-lg"]', JSON.stringify(after)); + check('...and the canvas is clean', (await findings(canvas)).length === 0); +} +{ + const ladder: DesignVariables = { ...SYSTEM, spacing: { 'space-md': 16 } }; + const [lg] = await findings(canvasWith([frame('a', { gap: '$space-lg' })], ladder)); + check('$space-lg on a ladder with only space-md warns with no fix (a different size)', !!lg && !lg.fix); + const [md] = await findings(canvasWith([frame('a', { gap: '$spce-md' })], ladder)); + check('twin: $spce-md, the same rung misspelt, is fixed', md?.fix?.op === 'U("a", { gap: "$space-md" })', md?.fix?.op); +} + +// ── M6: one finding per origin; components and overrides ────────────────────── +{ + const canvas = canvasWith([]); + const [page] = parseAndExecute(canvas.root, 'page=I("document", {type: "frame", name: "page", layout: "vertical"})', canvas); + const [card] = parseAndExecute(canvas.root, 'card=I("document", {type: "component", name: "Card", layout: "vertical", fill: "$bg-surfce"})', canvas); + parseAndExecute(canvas.root, `t=I("${card.nodeId}", {type: "frame", name: "inner", gap: "$space-mdd"})`, canvas); + parseAndExecute(canvas.root, ` +a=I("${page.nodeId}", {type: "instance", name: "card-a", componentId: "${card.nodeId}"}) +b=I("${page.nodeId}", {type: "instance", name: "card-b", componentId: "${card.nodeId}", overrides: {"inner": {"gap": "$space-lgg"}}}) +`, canvas); + const fs = await findings(canvas); + const inner = about(fs, '$space-mdd'); + check('a typo inside a component used by two instances warns once', inner.length === 1, fs.map((f) => f.message).join(' | ')); + check('...on the instance, naming the inner node, with no fix', !!inner[0] && !!inner[0].innerNodeId && inner[0].innerNodeId.includes('/') && !inner[0].fix); + check('a typo on the component root, seen through two instances, warns once with no fix', about(fs, '$bg-surfce').length === 1 && !about(fs, '$bg-surfce')[0].fix); + const ovr = about(fs, '$space-lgg'); + check('an override typo warns once, no fix, and names the override', ovr.length === 1 && !ovr[0].fix && /override/.test(ovr[0].suggestion ?? '')); +} +{ + const canvas = canvasWith([frame('a', { gap: '$space-md' })]); + parseAndExecute(canvas.root, 'card=I("document", {type: "component", name: "Unused card", gap: "$space-mdd"})', canvas); + const fs = await findings(canvas); + check('a typo in a component no instance uses warns and names it', fs.length === 1 && /Unused card/.test(fs[0].message) && !fs[0].fix, fs.map((f) => f.message).join(' | ')); +} + +// ── FR-C3: copy is never resolved ───────────────────────────────────────────── +{ + const canvas = canvasWith([ + { id: 't1', type: 'text', name: 't1', content: '$body' } as SceneNode, + { id: 't2', type: 'text', name: 't2', content: '$49' } as SceneNode, + { id: 'd', type: 'chart', name: 'd', kind: 'donut', segments: [{ value: 1, color: '#2563EB' }], centerValue: '$1.2M', centerLabel: '$ revenue' } as unknown as SceneNode, + ]); + let html = ''; + let crashed = false; + try { html = renderToHtml(canvas.root, 400, 300, canvas); } catch { crashed = true; } + check('content "$body" renders the string with no crash', !crashed && html.includes('$body')); + check('content "$49" renders literally', html.includes('$49')); + check('copy raises no unknown-token finding', (await findings(canvas)).length === 0); + const twin = canvasWith([{ id: 't1', type: 'text', name: 't1', content: 'x', color: '$49' } as SceneNode]); + check('twin: the same "$49" on a style prop warns', (await findings(twin)).length === 1); +} + +// ── FR-C4: token usage counts real tokens ───────────────────────────────────── +{ + const typos = canvasWith([frame('a', { gap: '$space-mdd', fill: '$bg-surfce' })]); + const ev = await evaluateCanvas(typos, { mode: 'fast', categories: ['structure'] }); + check('a canvas whose only refs are typos reports 0% token usage', ev.stats.tokenUsagePercent === 0, String(ev.stats.tokenUsagePercent)); + const real = canvasWith([frame('a', { gap: '$space-md', fill: '$bg-surface' })]); + check('twin: real refs count', (await evaluateCanvas(real, { mode: 'fast', categories: ['structure'] })).stats.tokenUsagePercent > 0); + + const ws = createWorkspace('inherits'); + setWorkspaceDesignSystem(ws.id, SYSTEM); + const project = createProject(ws.id, 'p')!; + const inherits = createCanvas('inherits', project.id); + inherits.root.children = [frame('a', { gap: '$space-md', fill: '$bg-surface', stroke: '#000000', layout: 'vertical' })]; + const iev = await evaluateCanvas(inherits, { mode: 'fast', categories: ['structure'] }); + check('a canvas that inherits every token reports its real usage', iev.stats.tokenUsagePercent > 0, String(iev.stats.tokenUsagePercent)); + check('...and its refs raise no unknown-token finding', !iev.issues.some((i) => i.rule === 'unknown-token')); +} + +if (!allPass) { + console.log('\nSOME CHECKS FAILED'); + process.exit(1); +} +console.log('\nAll checks passed.'); +process.exit(0); From fc3da95b9cbe12d4440aa6ab0b8fb25c90c949c4 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sat, 21 Nov 2026 19:20:08 +0100 Subject: [PATCH 4/6] Judge id-less nodes and give component backdrops their token --- docs/specs/PHASE-32-SPEC.md | 3 +- src/evaluate.ts | 39 +++++++++++++++----- test/browser/test-patterns-desktop-window.ts | 7 +++- test/browser/test-patterns-desktop.ts | 7 +++- test/unit/test-unknown-token.ts | 15 ++++++++ 5 files changed, 58 insertions(+), 13 deletions(-) diff --git a/docs/specs/PHASE-32-SPEC.md b/docs/specs/PHASE-32-SPEC.md index cc48716..f5ad1c0 100644 --- a/docs/specs/PHASE-32-SPEC.md +++ b/docs/specs/PHASE-32-SPEC.md @@ -153,8 +153,9 @@ And one is housekeeping the follow-ups will land in. 140 tests and `test-env.ts` **Slice C — as built (recorded 2026-11-21).** Decisions the pinned contracts did not settle: - **N1: a stamp that reads a derived colour seeds the surface** *(spec change during build)*. A lone `status-chip` on an unthemed canvas seeds only its ink (`success` `#4ADE80`, tuned for the dark scaffold palette), so with no surface token its tint derived light and the pair read about 1.5:1, where the old dark seed tint read 7.6:1. `applyStructure` now seeds `bg-surface` (the scaffold default `#111111`) whenever the stamp references a derived name and the canvas resolves neither `bg-surface` nor `bg-primary`. Red before the change: `test-derived-tints.ts` "unthemed: a dark-mode tint" (it derived `#E0FEE6`). A sweep in the same test now holds every structure, unthemed and under the dark, material and minimal presets, to no contrast error against a derived tint; measured against master, every theme has fewer contrast findings than before (the old seeds failed the initials avatar unthemed and every tint chip under the light, material and minimal presets). -- **N2: the patterns harness defines what it references.** The desktop-app gate gives a component stamp a `$bg-primary` backdrop; a component stamp never seeds it, so unthemed it was undefined and drew nothing. The harness now defines it (`#0a0a0a`, the scaffold default); `unknown-token` is what caught it. The gate's tint predicate reads the tokens the render uses (merged, old seeds dropped, missing tints derived) instead of the stored canvas layer. +- **N2: the patterns harness defines what it references.** The desktop-app gate gives a component stamp a `$bg-primary` backdrop; a component stamp never seeds it, so unthemed it was undefined and drew nothing. The harness (`test-patterns.ts` and the two `test/browser` desktop gates) now defines it (`#0a0a0a`, the scaffold default); `unknown-token` is what caught it. The gate's tint predicate reads the tokens the render uses (merged, old seeds dropped, missing tints derived) instead of the stored canvas layer. - **N3: masters in the tree.** A component's master can sit in the stored tree as well as in `canvas.components` (`batch_design` registers the inserted node itself). M6's origins treat a master's subtree as the definition, so a typo in it is one finding, warn-only, whether or not an instance shows it, and a definition walked through its master is not walked again. +- **N4: nodes with no id.** An inline `children` entry of a `batch_design` insert has no `id` (an existing shape the renderer tolerates). The full tier's viewer rebuild crashed evaluate on one: the rule reports such a node on its nearest ancestor with an id, as its own origin, with no fix. The unknown-icon check crashed the same way on master (found in passing, fixed alike: an id-less icon is reported on its ancestor and never gets a fix, which would rewrite the ancestor's `icon`). Red on the build snapshot: `test-unknown-token.ts` "an id-less inline child does not crash evaluate". **Slice D: desktop-app checks and stress (FR-D1 to FR-D4).** - `variables.ts` select branch: `$border-strong` when defined. `state-checks.ts:268`: `select` measured. diff --git a/src/evaluate.ts b/src/evaluate.ts index 1a5b22a..5e38717 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -785,10 +785,18 @@ function checkStructure(entries: NodeEntry[], canvas: Canvas, tokens: DesignVari * primitives' icon props (a blank glyph in a tab bar is the same defect). */ function iconSlots(root: SceneNode): Array<{ node: SceneNode; path: string; ref: string; flat: boolean; required: boolean }> { const out: Array<{ node: SceneNode; path: string; ref: string; flat: boolean; required: boolean }> = []; + // A node with no id (an inline child of a batch_design insert) is reported + // on its nearest ancestor with one. + let anchor = root.id; const add = (node: SceneNode, path: string, ref: unknown, flat: boolean, required: boolean) => { - if (typeof ref === 'string' || required) out.push({ node, path, ref: typeof ref === 'string' ? ref : '', flat, required }); + const hasId = typeof node.id === 'string'; + const reported = hasId ? node : { ...node, id: anchor }; + // `flat` gates the fix: one with no id of its own has no op to target. + if (typeof ref === 'string' || required) out.push({ node: reported, path, ref: typeof ref === 'string' ? ref : '', flat: flat && hasId, required }); }; (function walk(n: SceneNode) { + const outer = anchor; + if (typeof n.id === 'string') anchor = n.id; if (n.type === 'icon') add(n, 'icon', n.icon, true, true); else if (n.type === 'button') add(n, 'icon', n.icon, true, false); // Phase 31 slice B — the desktop-app primitives draw their `icon` too. @@ -801,6 +809,7 @@ function iconSlots(root: SceneNode): Array<{ node: SceneNode; path: string; ref: if (n.variant === 'fab') add(n, 'fab.icon', n.fab?.icon, false, false); } n.children?.forEach(walk); + anchor = outer; })(root); return out; } @@ -1087,18 +1096,28 @@ function checkUnknownTokens(canvas: Canvas, tokens: DesignVariables): Evaluation pending.push({ issue, nodeId: node.id, key: site.key }); }; - (function walk(node: SceneNode, master?: string) { - const inMaster = master ?? (node.type === 'component' && !node.id.includes('/') && canvas.components[node.id] ? node.id : undefined); - for (const { ref, ...site } of tokenRefs(node)) judge(node, site, ref, originOf(node.id, node, site, ref, inMaster), inMaster); - node.children?.forEach((c) => walk(c, inMaster)); - })(raw); + // A node with no id (inline children of a batch_design insert) is its own + // origin, reported on its nearest ancestor with one, and never fixed. + let anon = 0; + const judgeNode = (node: SceneNode, anchor: string, origin: (site: RefSite, ref: string) => string, component?: string) => { + const hasId = typeof node.id === 'string'; + const own = hasId ? undefined : `anon:${anon++}`; + const reported = hasId ? node : { ...node, id: anchor }; + for (const { ref, ...site } of tokenRefs(node)) judge(reported, site, ref, own ?? origin(site, ref), component); + }; + (function walk(node: SceneNode, anchor: string, master?: string) { + const hasId = typeof node.id === 'string'; + const inMaster = master ?? (node.type === 'component' && hasId && !node.id.includes('/') && canvas.components[node.id] ? node.id : undefined); + judgeNode(node, anchor, (site, ref) => originOf(node.id, node, site, ref, inMaster), inMaster); + node.children?.forEach((c) => walk(c, hasId ? node.id : anchor, inMaster)); + })(raw, raw.id); // Components no instance uses are still the canvas's: judge their definitions. for (const [cid, component] of Object.entries(canvas.components)) { if (used.has(cid) || masters.has(cid)) continue; - (function walk(node: SceneNode) { - for (const { ref, ...site } of tokenRefs(node)) judge(node, site, ref, defNode(cid, node.id), cid); - node.children?.forEach(walk); - })(component); + (function walk(node: SceneNode, anchor: string) { + judgeNode(node, anchor, () => defNode(cid, node.id), cid); + node.children?.forEach((c) => walk(c, typeof node.id === 'string' ? node.id : anchor)); + })(component, cid); } const stored = new Map(); diff --git a/test/browser/test-patterns-desktop-window.ts b/test/browser/test-patterns-desktop-window.ts index 3ced60b..70390b4 100644 --- a/test/browser/test-patterns-desktop-window.ts +++ b/test/browser/test-patterns-desktop-window.ts @@ -40,7 +40,12 @@ function check(name: string, cond: boolean, extra?: string) { function stamped(name: string, component: boolean, size: { width: number; height: number }, personality?: PersonalityName): Canvas { const canvas = createCanvas(`win-${name}`, undefined, size, { type: 'desktop-app' }); - if (component) canvas.root.fill = '$bg-primary'; + // The backdrop defines its own token (the scaffold default): a component + // stamp never seeds $bg-primary, and undefined it is an unknown-token warning. + if (component) { + canvas.root.fill = '$bg-primary'; + canvas.variables.colors = { ...canvas.variables.colors, 'bg-primary': '#0a0a0a' }; + } if (personality) setVariables(canvas, generateDesignSystem('#166534', personality, { surface: 'desktop-app' }).variables); const m = getCanvasTokens(canvas); applyStructure(canvas, name, { diff --git a/test/browser/test-patterns-desktop.ts b/test/browser/test-patterns-desktop.ts index ea067c3..7746799 100644 --- a/test/browser/test-patterns-desktop.ts +++ b/test/browser/test-patterns-desktop.ts @@ -64,7 +64,12 @@ async function detailedFindings(canvas: Canvas, infos = true): Promise * painted as a page stamp paints it. */ function stamped(name: string, component: boolean, personality?: PersonalityName, size: { width?: number; height?: number } = {}): Canvas { const canvas = createCanvas(`gate-${name}-${personality ?? 'plain'}`, undefined, size, { type: 'desktop-app' }); - if (component) canvas.root.fill = '$bg-primary'; + // The backdrop defines its own token (the scaffold default): a component + // stamp never seeds $bg-primary, and undefined it is an unknown-token warning. + if (component) { + canvas.root.fill = '$bg-primary'; + canvas.variables.colors = { ...canvas.variables.colors, 'bg-primary': '#0a0a0a' }; + } if (personality) setVariables(canvas, generateDesignSystem('#166534', personality, { surface: 'desktop-app' }).variables); const m = getCanvasTokens(canvas); applyStructure(canvas, name, { diff --git a/test/unit/test-unknown-token.ts b/test/unit/test-unknown-token.ts index f632485..7c330e4 100644 --- a/test/unit/test-unknown-token.ts +++ b/test/unit/test-unknown-token.ts @@ -161,6 +161,21 @@ b=I("${page.nodeId}", {type: "instance", name: "card-b", componentId: "${card.no check('a typo in a component no instance uses warns and names it', fs.length === 1 && /Unused card/.test(fs[0].message) && !fs[0].fix, fs.map((f) => f.message).join(' | ')); } +// ── Nodes with no id (inline children of a batch_design insert) ───────────── +{ + const canvas = canvasWith([]); + parseAndExecute(canvas.root, 'box=I("document", {type: "frame", name: "box", children: [{type: "text", content: "x", color: "$nope"}, {type: "icon", icon: "no-such-icon-xyz"}]})', canvas); + const box = canvas.root.children![0].id; + let crashed = ''; + let ev: Awaited> | undefined; + try { ev = await evaluateCanvas(canvas, { mode: 'fast', categories: ['structure'] }); } catch (e) { crashed = (e as Error).message; } + check('an id-less inline child does not crash evaluate', !crashed, crashed); + const token = ev?.issues.find((i) => i.rule === 'unknown-token'); + check('...its unknown token is reported on its nearest ancestor with an id, with no fix', token?.nodeId === box && !token.fix, token?.nodeId); + const icon = ev?.issues.find((i) => /Unknown icon/.test(i.message)); + check('...and so is its unknown icon, with no fix (an op would rewrite the parent)', icon?.nodeId === box && !icon.fix, icon?.nodeId); +} + // ── FR-C3: copy is never resolved ───────────────────────────────────────────── { const canvas = canvasWith([ From 2cff8888d5b56b285ca5af0bcef062353bd067da Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sat, 21 Nov 2026 20:10:13 +0100 Subject: [PATCH 5/6] Fix the slice C verify findings --- README.md | 9 +- docs/GUIDELINES.md | 16 ++- docs/specs/PHASE-32-SPEC.md | 5 + src/evaluate.ts | 26 ++++- src/expand.ts | 6 +- src/index.ts | 8 +- src/structures.ts | 4 +- src/tailwind-map.ts | 9 +- src/variables.ts | 21 ++-- src/viewer.ts | 4 +- test/unit/test-derived-tints.ts | 58 +++++++++ test/unit/test-tailwind-map.ts | 5 + test/unit/test-unknown-token.ts | 200 ++++++++++++++++++++++++++++++++ 13 files changed, 339 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 0553188..3a4605f 100644 --- a/README.md +++ b/README.md @@ -594,6 +594,8 @@ Reference an elevation token from a node as `shadow: "$elevation.raised"` (resol Then use in nodes: `{ fill: "$primary", padding: "$md", cornerRadius: "$sm", transition: "$motion.fast" }` +`get_variables` leaves out a colour still holding an old scaffold seed (`accent-tint` `#152A47`, `success-tint` `#0F2E1B`, `warning-tint` `#33260A`, `danger-tint` `#3A1715`, `neutral-tint` `#25282D`, `danger` `#F87171`, matched by name and value, any case): it counts as unset, so an inherited value or the derived one shows through, and the canvas's `sha256r:` version hash moves once (an approval recorded on it reads STALE). The stored JSON is untouched. A `$ref` no token defines is an `unknown-token` warning (see `canvas_evaluate`); copy props (`content`, `label`, `value`…) never resolve. + ### `workspace_set_design_system` / `workspace_get_design_system` / `workspace_apply_preset` Set tokens at the workspace level — every project + canvas under the workspace inherits them. Resolution order at render is `canvas.variables` (override) → `project.designSystem` → `workspace.designSystem` → built-in defaults, with the rightmost layer winning. Per-category merge: setting only `colors` doesn't reset `spacing`. @@ -659,7 +661,7 @@ List available style guide presets. No params. Returns preset names and descript ### `apply_preset` -Apply a style guide preset to a canvas. Merges preset design tokens into the canvas variables, and copies in any reusable components (`button`, `card`, `badge`) the preset defines so they can be instanced. The preset is recorded in `metadata.provenance.preset` and the per-project build log. It never changes the canvas's genre (`canvas_set_genre` owns that); a genre an older framesmith stored in the preset field is moved to `provenance.genre` first. The material preset relaxes the accent-hue and pure-black-white tells on its own, whatever the genre. Tokens the canvas already resolves through an inherited workspace/project design system are kept rather than overwritten and reported as `preservedFromDesignSystem` — for typography this merge is field-wise (a partially-specified inherited token, e.g. just `fontSize`, is filled out with the preset's other fields rather than shadowing the whole role); set them explicitly with `set_variables` if you want the preset's values instead. +Apply a style guide preset to a canvas. Merges preset design tokens into the canvas variables, and copies in any reusable components (`button`, `card`, `badge`) the preset defines so they can be instanced. The preset is recorded in `metadata.provenance.preset` and the per-project build log. It never changes the canvas's genre (`canvas_set_genre` owns that); a genre an older framesmith stored in the preset field is moved to `provenance.genre` first. The material preset relaxes the accent-hue and pure-black-white tells on its own, whatever the genre. Tokens the canvas already resolves through an inherited workspace/project design system are kept rather than overwritten and reported as `preservedFromDesignSystem` — for typography this merge is field-wise (a partially-specified inherited token, e.g. just `fontSize`, is filled out with the preset's other fields rather than shadowing the whole role); set them explicitly with `set_variables` if you want the preset's values instead. A colour on the canvas that still holds an old scaffold seed counts as unset, so the preset's value replaces it rather than being preserved. | Param | Type | Description | |-------|------|-------------| @@ -687,7 +689,7 @@ Two kinds: ### `apply_structure` -Stamp a layout structure onto a canvas and return the placeholder node IDs to populate. Scaffolds are token-driven, not hard-coded: every scaffold's spacing, radius, elevation, and typography — all of it, every text node's `fontSize`, not just titles — reference `$space-*` / `$radius-*` / `$elevation.*` / the type-role tokens (`$display`/`$title`/`$heading`/`$text-lg`/`$text-sm`/`$body`/`$label`/`$caption`, plus the usual `$color` tokens), so once a project has a generated design system, stamping a pattern already reads in its density, depth, and voice — no re-theming pass needed, and no scaffold can inject a size the generated scale doesn't have. `apply_structure` seeds neutral defaults (the pre-generator literal values) for any of those tokens the canvas can't already resolve, so an unthemed canvas still renders correctly; the result's `seededColors` / `seededTokens` list exactly which names got seeded. Populate the placeholders with `batch_design` `U` ops, then `screenshot` to verify. +Stamp a layout structure onto a canvas and return the placeholder node IDs to populate. Scaffolds are token-driven, not hard-coded: every scaffold's spacing, radius, elevation, and typography — all of it, every text node's `fontSize`, not just titles — reference `$space-*` / `$radius-*` / `$elevation.*` / the type-role tokens (`$display`/`$title`/`$heading`/`$text-lg`/`$text-sm`/`$body`/`$label`/`$caption`, plus the usual `$color` tokens), so once a project has a generated design system, stamping a pattern already reads in its density, depth, and voice — no re-theming pass needed, and no scaffold can inject a size the generated scale doesn't have. `apply_structure` seeds neutral defaults (the pre-generator literal values) for any of those tokens the canvas can't already resolve, so an unthemed canvas still renders correctly; the result's `seededColors` / `seededTokens` list exactly which names got seeded. No stamp seeds `$danger` or the tint layer: they derive at render from the inks and the surface. A stamp that reads one of them seeds `$bg-surface` unless the canvas resolves a surface (`$bg-surface`, `$surface`, `$bg-primary` or `$background`), so an unthemed stamp's tints come out dark, like its seeded inks. Populate the placeholders with `batch_design` `U` ops, then `screenshot` to verify. - **Page scaffolds** insert at the canvas root (refusing on a non-empty canvas unless `replace`), record provenance (`metadata.provenance`), and append to the **per-project build log** that feeds the `diversification` signal. - **Component scaffolds** insert under `targetId` (default root), repeatably — every stamp re-keys its node IDs (`form-field-1-…`, `form-field-2-…`) and returns an `idMap` (template ID → live ID) for follow-up ops. Component stamps don't touch provenance or the build log: they don't shape the page. @@ -920,6 +922,7 @@ Every result also carries a **`surface`** field: `{ type, device, source, rulesO | `mobile-artboard` | structure | warning / info | Runs on every type. A mobile canvas 500px or wider warns, and any other size than the device's is an info. An undeclared canvas narrower than 500px warns until `canvas_set_type` declares it; one declared `web` gets an info. | | `desktop-app-artboard` | structure | warning / info | Runs on every type. Warns on a desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for. Also warns on a canvas that holds a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) and was never declared, or is declared `mobile`; one declared `web` gets an info. An undeclared canvas holding an overlay (`tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer`) warns too; declared web or mobile, overlays alone raise nothing. Primitives inside an instance count. | | `type-scale-ratio` | typography | warning | On by default: adjacent font sizes stepping by a ratio below 1.1 or above 2.0 (pinned typography tokens skip it). The desktop-app ruleset turns it off, since dense apps step 12 / 13 / 14 on purpose; it then appears in `rulesOff`, and `desktop-app-type-ladder` judges the sizes instead. | +| `unknown-token` | structure | warning | On by default, on every type: a `$ref` no token defines, of the wrong kind for its prop, on a prop that takes no token, defined only in the dark layer, or defined as another ref. −10 structure score each. A ruleset may turn it off (it would then appear in `rulesOff`); none does. See [Unknown tokens](docs/GUIDELINES.md#unknown-tokens). | | `desktop-app-target` | usability | warning / error | Desktop-app only: the 24px floor (the `usability` row under Categories below), under its rule id. Fast mode warns on a target under 24px in either dimension; detailed mode errors when its 24px circle reaches a neighbour. An unlabelled `link` with no width (or `"auto"`) is measured at its glyphs (14px wide, 30 with `external`), on web too. | | `desktop-app-handbuilt-target` | usability | info | Desktop-app only: a frame below 32px holding one icon, an icon plus a label of up to three words, or (bordered and padded) one such label alone, the shape an imported text button takes. Frames inside a clickable primitive or a `property-row` are never counted. Rebuild it as a `button` or `link` if it is clickable. | | `desktop-app-icon-label` | usability | warning | Desktop-app only: an icon-only `button` or `link` with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`. | @@ -954,7 +957,7 @@ Whenever the `coverage` category runs on a **base** canvas, the result also carr | `spacing` | 20 | Off-scale padding/gap values (`gap: 0`, a flush stack, is never flagged), plus spacing variety measured against the canvas's **declared** scale (`set_variables`/`generate_scale` spacing tokens) — only values *not* on that scale count toward sprawl, so a design built entirely from its own multi-step scale (framesmith's generated scale ships nine: `space-3xs`…`space-3xl`) isn't penalized for using it. No declared scale falls back to the old total-unique-values count, with a suggestion to declare one | | `color` | 25 | WCAG AA contrast ratios for text against nearest background — checked in BOTH themes when a `dark` token layer exists (dark-run issues carry `theme: "dark"`, score takes the worse theme, and dark failures point at the dark layer instead of carrying a literal fix). WCAG-passing pairs that are perceptually weak by **APCA** get an info advisory (Lc vs ~75 body / ~60 large) — APCA is a candidate method, not a standard; it never blocks. On a desktop-app canvas it also carries the four element-state rules (`desktop-app-focus-visible`, `desktop-app-state-contrast`, `desktop-app-boundary`, `desktop-app-disabled`; see the rules table above), each judged in both themes. Text inside a disabled clickable primitive is exempt, on every type | | `typography` | 20 | Type-scale ratios (1.1–2.0; adjacent sizes both declared as typography tokens are pinned and skip the check), font-family count, weight variation — plus score-neutral craft advisories: measure (prose past ~75 characters per line; warning past 90), tracking (display text ≥28px without negative letter-spacing, autofixable), and tabular numerals (numeric table columns without `tabularNums`, autofixable) On a mobile canvas `mobile-type-floor` adds −10 per warning. | -| `structure` | 15 | Tree depth, naming coverage, design-token usage %, component reuse, unknown icon names (an icon node, or a mobile primitive's icon prop — `button.icon`, `leading.icon`, nav-bar `trailing[].icon`, `tab-bar` `items[].icon` (required) and `fab.icon` — that resolves in neither set renders an empty slot: a directive-blocking warning, −10 structure score each; autofixable for icon nodes and `button.icon` when one spelling resolves), and `unknown-token` (a `$ref` no token defines, of the wrong kind for its prop, on a prop that takes no token, or defined only in the dark layer: a directive-blocking warning, −10 each; autofixable when one defined name is closest, see [GUIDELINES](docs/GUIDELINES.md#unknown-tokens)). `mobile-artboard` adds −10 per warning, on every type. | +| `structure` | 15 | Tree depth, naming coverage, design-token usage % (string style props that are a `$ref` the canvas's own or inherited tokens define; a misspelt ref counts as a literal, copy props are skipped), component reuse, unknown icon names (an icon node, or a mobile primitive's icon prop — `button.icon`, `leading.icon`, nav-bar `trailing[].icon`, `tab-bar` `items[].icon` (required) and `fab.icon` — that resolves in neither set renders an empty slot: a directive-blocking warning, −10 structure score each; autofixable for icon nodes and `button.icon` when one spelling resolves), and `unknown-token` (a `$ref` no token defines, of the wrong kind for its prop, on a prop that takes no token, or defined only in the dark layer: a directive-blocking warning, −10 each; autofixable when one defined name is closest, see [GUIDELINES](docs/GUIDELINES.md#unknown-tokens)). `mobile-artboard` adds −10 per warning, on every type. | | `consistency` | 20 | Frames missing `layout`, sibling overlap (detailed mode; positioned siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt, while a bar pinned to the top still counts) — plus score-neutral advisories: **token detachment** (a literal `fill`/`stroke`/`color`/`cornerRadius` that exactly equals a token's value flags with a mechanical `$ref` autofix; ambiguous matches list candidates and never guess) and **ad-hoc motion** (3+ distinct duration/easing combos with no motion tokens declared) | | `cliche` | 15 | Machine-made tells: default purple/indigo accent, gradient/glow overuse, fake browser/OS chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated metrics/testimonials/logos, eyebrow rhythm (an eyebrow above nearly every section), slop copy (stock AI phrasing — filler verbs, scroll cues, placeholder names, hype labels), radius consistency (too many distinct corner radii), pure black/white (`#000000` ink / `#ffffff` page vs off-black/off-white), accent consistency (multiple competing accent hues — the `$success`/`$warning`/`$danger` status vocabulary is exempt when referenced as tokens, since those are semantics rather than a second accent; the same hues as literals still count). Each issue carries a `tell` discriminator. Tells are warning or info severity, but **every tell blocks the directive**, whatever its severity (see the `directive` above). Relaxable per `genre`. The tells know dashboard vocabulary: a violet reached only through a `$chart-*` or `$*-tint` token doesn't count as the default-purple tell (a literal violet, or one through any other token, still does), a gradient reached through a `$token` doesn't count toward gradient overuse, thin rounded sparkline bars aren't mistaken for traffic-light dots (fake-chrome now requires a near-square shape), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric, not an eyebrow. It also knows retail copy: a numeral bound to a unit noun by a tight hyphen (`"30-day returns"`, `"2-year warranty"`, `"24/7 support"`) is a compound modifier, not a numbered section eyebrow. | | `coverage` | 10 | State coverage on **base** canvases with data-bearing content: a detected table demands designed `empty` + `loading` variants, a form (3+ input controls, `text-input` included) demands `error` — each missing state is a directive-blocking warning whose suggestion names the `canvas_add_variant` + scaffold path. Variant canvases and non-data screens get no findings. Table detection needs three matching horizontal rows to read as data (two stacked rows are treated as a layout, e.g. a topbar over a greeting); an import-named `Table` frame keeps the looser two-row shape. A list whose every row leads with an icon, a dot or a small image (a sidebar of projects) is navigation and never reads as a table, on every type. On a **`loading`** variant itself, a warning fires per data surface (a detected table, or a frame with 2+ large tabular/numeric texts) that still shows live values while a sibling region is skeletoned — "Loading state is half-designed" — naming the region and suggesting the matching skeleton scaffold. The result's `coverage` field reports `{ dataBearing, states, missing }`. | diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 6aa3c41..2bc16bc 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -381,18 +381,24 @@ A design language is a set of COMMITTED choices, and `generate_design_system` ma #### The tint layer derives when undefined -On a canvas whose design system has no tint tokens (unthemed, or styled by a preset, since no preset defines tints), `$accent-tint`, `$success-tint`, `$warning-tint`, `$danger-tint` and `$neutral-tint` still resolve: each is derived from its ink (`$accent`, `$success`, `$warning`, `$danger`, `$text-secondary`) with the generator's own tint rule, in the mode of the surface they sit on. The surface is `$bg-surface`, else `$bg-primary`, else white; a translucent surface is laid over the next opaque one; the mode is dark when that surface contrasts more with white than with black. A grey ink gets a grey tint. `$danger` resolves to `$error`, else `#DC2626` on a light surface and `#F87171` on a dark one. A dark render derives from the dark layer's inks and surface. The pair clears 4.5:1 whenever the ink can: the light preset's `success` and `error` fall below 4.5:1 even on white, and the contrast check reports those inks. A canvas stamped before this still holding an old scaffold seed (`#152A47` for `accent-tint`, `#0F2E1B`, `#33260A`, `#3A1715`, `#25282D` for the other tints, `#F87171` for `danger`, matched by name and value) renders as if it were unset: an inherited value shows through, else the derived one. Its stored JSON is untouched, `get_variables` leaves those values out, and its `sha256r:` version hash moves once, so an approval recorded on it reads STALE. +On a canvas whose design system has no tint tokens (unthemed, or styled by a preset, since no preset defines tints), `$accent-tint`, `$success-tint`, `$warning-tint`, `$danger-tint` and `$neutral-tint` still resolve: each is derived from its ink (`$accent`, else `$primary`; `$success`; `$warning`; `$danger`; `$text-secondary`) with the generator's own tint rule. The mode is chosen once per render from the design system's surface, not from the node's parent: the surface is the first of `$bg-surface`, `$surface`, `$bg-primary` and `$background` that is a colour, else white; a translucent one is laid over the next opaque one; the mode is dark when that surface contrasts more with white than with black. A chip on a dark card inside a light page still gets the light tint, so give such a card its own tint tokens. A grey ink gets a grey tint. `$danger` resolves to `$error`, else `#DC2626` on a light surface and `#F87171` on a dark one. A dark render derives from the dark layer's inks and surface. The pair clears 4.5:1 whenever the ink can: the light preset's `success` (`#16a34a`, 3.3:1 on white) and `error` (`#ef4444`, 3.8:1) cannot, and the contrast check reports them as text-contrast errors; darken the ink with `set_variables` (or generate a system) and the tint follows. Earlier stamps seeded dark values for these names. A canvas colour still holding one counts as unset: + +- **Which:** `accent-tint` `#152A47`, `success-tint` `#0F2E1B`, `warning-tint` `#33260A`, `danger-tint` `#3A1715`, `neutral-tint` `#25282D`, `danger` `#F87171`, matched by name and value in any case (the same value under another name is kept). +- **What renders:** a workspace or project value of that name, else the derived one. +- **What you see:** the stored JSON is untouched; `get_variables` leaves the value out; `apply_preset` and a canvas-scope `generate_design_system` treat it as unset (they write their value, or keep an inherited one). +- **Approvals:** the `sha256r:` version hash moves once, so an approval recorded on the canvas reads STALE; re-approve after looking at it. #### Unknown tokens `canvas_evaluate` warns (rule `unknown-token`, structure category, directive-blocking, −10 each) on every `$ref` that renders something other than intended: -- **A name no token defines** — `gap: "$space-mdd"`. The suggestion names up to three defined tokens of the kind the prop takes, nearest spelling first. When exactly one is closest (within two edits) and it is not another rung of the same size ladder, a ref on the node's own top-level prop, `padding` / `cornerRadius` entry or border colour carries a rename fix that `canvas_autofix` applies: `$space-mdd` → `$space-md`, `$bg-surfce` → `$bg-surface`. `$space-xxs` is as close to `$space-3xs`, `$space-2xs` and `$space-xs`, so it is reported with all three and no fix; `$space-lg` on a ladder without it is a different size, never renamed to `$space-md`. -- **The wrong kind** — a typography or spacing token on a colour prop (`fill: "$body"` renders `16`), a colour on a number prop (`gap: "$accent"`), a whole token group (`$typography.body`). A typography ref is valid only on `fontSize`, where it applies the whole role. +- **A name no token defines** — `gap: "$space-mdd"`. One finding per ref (two typos in one `padding` array are two findings). The suggestion names up to three defined tokens of the kind the prop takes, nearest spelling first, within two edits (an edit adds, drops or changes one character); with none that close it says to define the token. When exactly one is closest and it is not another rung of the same size ladder (a name ending in `3xs`, `2xs`, `xxs`, `xs`, `sm`, `md`, `lg`, `xl`, `2xl`, `3xl` or a number), a ref on the node's own top-level prop, `padding` / `cornerRadius` entry or border colour carries a rename fix that `canvas_autofix` applies: `$space-mdd` → `$space-md`, `$bg-surfce` → `$bg-surface`. `$space-xxs` is as close to `$space-3xs`, `$space-2xs` and `$space-xs`, so it is reported with all three and no fix; `$space-lg` on a ladder without it is a different size, never renamed to `$space-md`. +- **The wrong kind** — a typography or spacing token on a colour prop (`fill: "$body"` renders `16`), a colour on a number prop (`gap: "$accent"`), a dotted path ending at a whole token rather than one value (`$typography.body`). A typography ref is valid only on `fontSize`, where it applies the whole role (size, weight, family, line height, tracking); `lineHeight: "$heading"` is wrong-kind. - **A prop that takes no token** — `fontFamily: "$display"` renders the role's size as the font name. -- **A name defined only in the dark layer** — light renders it raw; define it in the base colours too. +- **A name defined only in the dark layer** — light renders it raw; define it in the base colours (or elevation) too. +- **A token defined as another ref** — `colors: { brand: "$accent" }` then `fill: "$brand"`: the resolver does not follow a ref inside a token, so it renders raw. Give the token a value. -Refs inside a component or an instance's `overrides` are judged as rendered, once per place they are written, and reported on the instance with no fix: fix the component, or edit the override. The rule reads top-level props, `padding` / `cornerRadius` entries, `borderTop`/`Right`/`Bottom`/`Left.color`, chart `series[].stroke` and `segments[].color`, and a modal's `actions[]` and a toast's `action` colours. Deliberately not checked: copy (`content`, `text`, `title`, `label`, `value`, `count`, `centerValue` and the rest never resolve, so `content: "$49"` is a price), and `gradient.stops[].color` and `shadows[].color`, which the resolver does not read either, so a ref there renders raw and silent. `$elevation.*`, `$motion.*`, `$colors.*`, `$spacing.*` and names starting with a digit (`$2xl`) are valid when defined, and the derived tints and `$danger` always are. The token-usage stat counts only refs that resolve, against the tokens the canvas inherits too. +Refs inside a component or an instance's `overrides` are judged as rendered and reported once per place they are written: a typo in a component used by three instances is one finding, on the first instance that shows it; one in a stored instance's `overrides` is one finding on that instance; one in a component's master or a definition no instance uses names the component. None carries a fix: fix the component, or edit the override. A node with no id (an inline child of a `batch_design` insert) is reported on its nearest ancestor with one, never with a fix. Chart, modal and toast colours are reported with a suggestion but no fix. The rule reads top-level props, `padding` / `cornerRadius` entries, `borderTop`/`Right`/`Bottom`/`Left.color`, chart `series[].stroke` and `segments[].color`, and a modal's `actions[]` and a toast's `action` colours. Deliberately not checked: copy (`content`, `text`, `title`, `label`, `value`, `count`, `centerValue` and the rest never resolve, so `content: "$49"` is a price), and `gradient.stops[].color` and `shadows[].color`, which the resolver does not read either, so a ref there renders raw and silent: write a colour there, or use `shadow: "$elevation.*"`. Dotted paths to one value (`$elevation.raised`, `$motion.fast`, `$colors.accent`, `$spacing.space-md`, `$state.hover`) and names starting with a digit (`$2xl`) are valid when defined, and the derived tints and `$danger` always are, bare or as `$colors.*`. "Directive-blocking" means `canvas_evaluate`'s directive withholds READY while the warning stands. The token-usage stat counts only refs that resolve, against the tokens the canvas inherits too. **Motion comes from tokens.** `transition: "$motion.fast"` for hover/focus feedback, `"$motion.base"` for state changes, `"$motion.slow"` for surfaces entering/leaving. The personality sets the temperament; scattering literal millisecond values breaks it. diff --git a/docs/specs/PHASE-32-SPEC.md b/docs/specs/PHASE-32-SPEC.md index f5ad1c0..2b04451 100644 --- a/docs/specs/PHASE-32-SPEC.md +++ b/docs/specs/PHASE-32-SPEC.md @@ -157,6 +157,11 @@ And one is housekeeping the follow-ups will land in. 140 tests and `test-env.ts` - **N3: masters in the tree.** A component's master can sit in the stored tree as well as in `canvas.components` (`batch_design` registers the inserted node itself). M6's origins treat a master's subtree as the definition, so a typo in it is one finding, warn-only, whether or not an instance shows it, and a definition walked through its master is not walked again. - **N4: nodes with no id.** An inline `children` entry of a `batch_design` insert has no `id` (an existing shape the renderer tolerates). The full tier's viewer rebuild crashed evaluate on one: the rule reports such a node on its nearest ancestor with an id, as its own origin, with no fix. The unknown-icon check crashed the same way on master (found in passing, fixed alike: an id-less icon is reported on its ancestor and never gets a fix, which would rewrite the ancestor's `icon`). Red on the build snapshot: `test-unknown-token.ts` "an id-less inline child does not crash evaluate". +**Slice C — verify round 1 (recorded 2026-11-21).** Four verifiers on fc3da95 (spec conformance, mutation, review and gate attack, docs-steward) and a cold-reader. Fixes, each with a test red on fc3da95: +- **V1:** `getCanvasTokens` threw on a stored canvas with no `variables` key (`withoutRetiredSeeds` read `v.colors` unguarded); a colour layer holding only seeds now drops whole, so it hashes as absent, not `{}`. An override written inside a component definition was one finding per outer instance; its origin is now where the instance node is written. Lone letters (`m`, `s`, `l`) are not ladder steps, so `$space-m` → `$space-md` is fixed. An id-less node inside an instance no longer gets the id `/undefined` (`expandTree`). The viewer's token-source label and `generate_color_system`'s `overwrote` list read through `withoutRetiredSeeds`. +- **V3 (changed M3, M4, M5, M7):** `$colors.accent-tint` and the other dotted derived names are valid. The tint surface reads the same chain as every other default (`bg-surface`, `surface`, `bg-primary`, `background`), and N1's seeding skips a canvas that resolves any of them (a design.md import names its colours `surface` and `background`). A token whose value is itself a `$ref` (`brand: "$accent"`) is a fifth case: the resolver does not follow it, so it renders raw; it warns, no fix. The dark-only suggestion names the elevation layer for an elevation ref. Candidates are names within two edits (three padded the list with noise: `$space-mdd` suggested `$space-2xl`). The Tailwind importer no longer maps non-colour `text-` and `bg-` utilities (`text-balance`, `bg-cover`, `bg-gradient-to-r` and the like) to colour refs. +- **Not fixed, named:** `lookupToken` reads spacing before radius, so `cornerRadius: "$md"` under a preset that defines both renders the spacing value (16, not 8). The rule sees one `number` kind and stays silent, and the README's own `get_variables` example (`cornerRadius: "$sm"`) hits it. It predates this slice and changing the order changes existing renders, so it is a follow-up. A node id containing `"` gives an op the U parser rejects (pre-existing in `formatUpdateOp`). `withDerivedColors` costs about 1.4 ms per resolve, unmemoised. + **Slice D: desktop-app checks and stress (FR-D1 to FR-D4).** - `variables.ts` select branch: `$border-strong` when defined. `state-checks.ts:268`: `select` measured. - `renderTreeRow` (`renderer.ts:1610`): `position: relative` with `renderNavItem`'s guard, and the bar. `indicatorPairs` (`state-checks.ts:211-236`): `tree-row`. diff --git a/src/evaluate.ts b/src/evaluate.ts index 5e38717..7da5e12 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -2,7 +2,7 @@ import type { Canvas, SceneNode, DesignVariables, TabItem } from './types.js'; import { getCanvasTokens } from './workspaces.js'; import { renderToHtml, type RenderOptions } from './renderer.js'; import { expandTree } from './expand.js'; -import { DERIVED_COLORS, refPath, themeTokens, tokenKind, tokenRefs, type RefSite, type TokenKind } from './variables.js'; +import { DERIVED_COLORS, lookupToken, refPath, themeTokens, tokenKind, tokenRefs, type RefSite, type TokenKind } from './variables.js'; import { computeLayout, type LayoutRect } from './screenshot.js'; import { checkCurrent, checkDesktopArtboard, checkHandbuiltTargetsApp, checkIconLabels, checkOverlays, checkPrimaryCount, checkRowRhythm, checkTruncation, @@ -971,10 +971,11 @@ function levenshtein(a: string, b: string): number { return row[b.length]; } -/** The size step a token name ends in (md, 2xl, 3xs, 4), if any. */ +/** The size step a token name ends in (3xs, xxs, xs, sm, md, lg, xl, 2xl, a + * number), if any. A lone letter is a typo, not a step. */ function ladderStep(name: string): string | undefined { const last = name.slice(name.lastIndexOf('-') + 1).toLowerCase(); - return /^(\d*x*[sml]|sm|md|lg|\d+)$/.test(last) ? last : undefined; + return /^(\d*x+[sl]|sm|md|lg|\d+)$/.test(last) ? last : undefined; } /** The value at a ref site on an object (a node or an override). */ @@ -1017,6 +1018,13 @@ function checkUnknownTokens(canvas: Canvas, tokens: DesignVariables): Evaluation // can sit in the stored tree as well as in canvas.components: inside it // (`master`), a stored node's own value is the definition's. const defNode = (cid: string, id: string) => `def:${cid}:${id === cid ? '(root)' : id}`; + // Where an instance node itself is written: stored, or a node of the + // component (or master) that holds it. + const instanceOrigin = (instId: string, master?: string): string => { + const at = instId.lastIndexOf('/'); + const holder = at < 0 ? undefined : instAt.get(instId.slice(0, at)); + return holder ? defNode(holder.componentId!, instId.slice(at + 1)) : master ? defNode(master, instId) : instId; + }; const originOf = (id: string, node: SceneNode, site: RefSite, ref: string, master?: string): string => { const slash = id.lastIndexOf('/'); const parent = slash < 0 ? undefined : instAt.get(id.slice(0, slash)); @@ -1025,7 +1033,7 @@ function checkUnknownTokens(canvas: Canvas, tokens: DesignVariables): Evaluation if (inst) return valueAt(inst, site) === ref ? own() : `def:${inst.componentId}:(root)`; if (!parent) return own(); const override = node.name ? parent.overrides?.[node.name] : undefined; - if (override && valueAt(override, site) === ref) return `ovr:${id.slice(0, slash)}:${node.name}`; + if (override && valueAt(override, site) === ref) return `ovr:${instanceOrigin(id.slice(0, slash), master)}:${node.name}`; return `def:${parent.componentId}:${id.slice(slash + 1)}`; }; @@ -1065,14 +1073,20 @@ function checkUnknownTokens(canvas: Canvas, tokens: DesignVariables): Evaluation issues.push({ ...base, message: `"${ref}" on ${path} is ${KIND_NAMES[kind]}, not ${KIND_NAMES[accepts[0]]}${where}.`, suggestion: `Use ${KIND_NAMES[accepts[0]]}${examples}.${fromOverride}` }); return; } + const value = lookupToken(name, tokens); + if (kind && typeof value === 'string' && value.startsWith('$')) { + issues.push({ ...base, message: `Token "${ref}" on ${path} is defined as another ref ("${value}"), which the resolver does not follow, so it renders raw${where}.`, suggestion: `Set "${name}" to a value, or write "${value}" here instead.${fromOverride}` }); + return; + } if (kind) return; if (tokenKind(name, dark) !== undefined) { - issues.push({ ...base, message: `Token "${ref}" on ${path} is defined only in the dark layer, so light renders it raw${where}.`, suggestion: `Define "${name}" in the base colors too (set_variables), not only under dark.${fromOverride}` }); + const layer = name.startsWith('elevation.') ? 'elevation' : 'colors'; + issues.push({ ...base, message: `Token "${ref}" on ${path} is defined only in the dark layer, so light renders it raw${where}.`, suggestion: `Define "${name.replace(/^elevation\./, '')}" in the base ${layer} too (set_variables), not only under dark.${fromOverride}` }); return; } const ranked = candidatePool(accepts, tokens) .map((n) => ({ n, d: levenshtein(name, n) })) - .filter((c) => c.d <= 3) + .filter((c) => c.d <= 2) .sort((a, b) => a.d - b.d || a.n.localeCompare(b.n)); const named = ranked.slice(0, 3).map((c) => `"$${c.n}"`); const issue: EvaluationIssue = { diff --git a/src/expand.ts b/src/expand.ts index eeb2f94..919e53b 100644 --- a/src/expand.ts +++ b/src/expand.ts @@ -34,8 +34,10 @@ export function expandTree( // inside itself stays unexpanded instead of recursing forever. const open = new Set(); const walk = (node: SceneNode, owner: SceneNode | undefined, prefix: string): SceneNode => { - const id = owner ? prefix + node.id : node.id; - if (owner) owners.set(id, owner); + // A node with no id (an inline child of a batch_design insert) stays + // without one inside an instance too. + const id = owner && node.id !== undefined ? prefix + node.id : node.id; + if (owner && id !== undefined) owners.set(id, owner); const cid = node.type === 'instance' ? node.componentId : undefined; const resolved = cid && !open.has(cid) ? resolveInstance(node, canvas) : null; const source = resolved ?? node; diff --git a/src/index.ts b/src/index.ts index 6aa9a76..bf1dc57 100644 --- a/src/index.ts +++ b/src/index.ts @@ -52,7 +52,7 @@ Organizing model — Workspace > Project > Canvas: - Canvases live in a project, projects in a workspace. A default "Personal > Untitled" always exists. - To scope work to a code repo, call **canvas_bind** once: it stores canvases as checked-in JSON under the repo's .framesmith/ and makes that the source of truth. Heads up — bind RE-KEYS the workspace and every project ID to repo-* form, so pre-bind workspace/project IDs stop resolving; the result's idMap gives old → new for both. Canvas IDs survive the bind unchanged. -Design tokens are a layered system (workspace > project > canvas). Reference them in node properties with $name (e.g. fill: "$surface"); set them with workspace_/project_/set_variables. Lower layers override higher ones — author tokens once at the workspace and inherit down. A $ref no token defines, or of the wrong kind for its prop, is an unknown-token warning (canvas_autofix renames an unambiguous misspelling); copy props (content, label, title, value…) never resolve. The tint layer ($accent-tint, $success-tint, $warning-tint, $danger-tint, $neutral-tint) and $danger derive when no layer defines them: each tint from its ink in the mode of the surface ($bg-surface, else $bg-primary), $danger from $error. +Design tokens are a layered system (workspace > project > canvas). Reference them in node properties with $name (e.g. fill: "$surface"); set them with workspace_/project_/set_variables. Lower layers override higher ones — author tokens once at the workspace and inherit down. A $ref no token defines, or of the wrong kind for its prop, is an unknown-token warning (canvas_autofix renames an unambiguous misspelling); copy props (content, label, title, value…) never resolve. The tint layer ($accent-tint, $success-tint, $warning-tint, $danger-tint, $neutral-tint) and $danger derive when no layer defines them: each tint from its ink in the mode of the surface ($bg-surface, else $surface, $bg-primary, $background), $danger from $error. Your job is to craft beautiful UI with real UX — designs a designer would sign off on — not wireframes. The bar is non-negotiable, and polishing to it is YOUR work, never the user's. @@ -1099,7 +1099,7 @@ Phase 31 adds two CONTROL colors, each at 3:1 or more (WCAG 1.4.11) in both them ensureFresh(canvasId); const canvas = getCanvas(canvasId); if (!canvas) return { content: [{ type: 'text', text: 'Error: Canvas not found' }], isError: true }; - overwrote = Object.keys(colors).filter((k) => canvas.variables.colors?.[k] !== undefined); + overwrote = Object.keys(colors).filter((k) => withoutRetiredSeeds(canvas.variables).colors?.[k] !== undefined); const merge = applyPresetTokens(canvas, { colors }, getInheritedTokens(canvas), { preserveInherited }); preserved = merge.preserved; setVariables(canvas, { dark: { colors: { ...system.dark, ...system.darkRange } } }); @@ -1617,7 +1617,7 @@ Scaffolds reference $space-*/$radius-*/$elevation.*/type-role tokens ($display/$ // --- apply_preset --- server.tool( 'apply_preset', - "Apply a style guide preset to a canvas. Merges the preset's design tokens into the canvas variables and copies in any reusable components (button, card, badge) the preset defines. Tokens the canvas inherits from the workspace/project design system are preserved (and reported as \`preservedFromDesignSystem\`) instead of being silently overwritten — set them explicitly with set_variables if you want the preset's values. Records the preset at metadata.provenance.preset and never changes the canvas's genre (canvas_set_genre owns that). The material preset relaxes the accent-hue and pure-black-white cliché tells on its own, whatever the genre.", + "Apply a style guide preset to a canvas. Merges the preset's design tokens into the canvas variables and copies in any reusable components (button, card, badge) the preset defines. Tokens the canvas inherits from the workspace/project design system are preserved (and reported as \`preservedFromDesignSystem\`) instead of being silently overwritten — set them explicitly with set_variables if you want the preset's values. Records the preset at metadata.provenance.preset and never changes the canvas's genre (canvas_set_genre owns that). The material preset relaxes the accent-hue and pure-black-white cliché tells on its own, whatever the genre. A canvas colour still holding an old scaffold seed (#152A47 accent-tint and the like) counts as unset, so the preset's value replaces it.", { canvasId: z.string().describe('Canvas ID'), preset: z.string().describe('Preset name (dark, light, material, minimal)'), @@ -2148,7 +2148,7 @@ server.tool( // --- canvas_evaluate --- server.tool( 'canvas_evaluate', - `Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Every check reads the canvas as it renders: each component instance is expanded (its props and overrides applied) and the design system resolved inside it, so contrast, spacing, typography, cliché and every type rule see inside components. A finding on a node inside an instance reports the instance in nodeId (the stored node: fix it in the component, or with an override on the instance), the inner node's expanded id in innerNodeId ("/", the id snapshot_layout and canvas_stress use; batch_design cannot address it), names the component in its message, and carries no fix op. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls, text-inputs included (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action, link, text-input, nav-item, each tab of a tabs node, tree-row, menu-row — inline text links and dividers are not targets, and a control that is the only target directly inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too: one finding per icon in the component, reported on the first instance that shows it, with no fix op. It also WARNS (rule "unknown-token", directive-blocking, -10 structure score each; on for every type unless a ruleset turns it off) on every $ref the resolver reads that renders something other than intended: a name no token defines ("$space-mdd"), a token of the wrong kind for the prop (a typography or spacing token on fill / stroke / color and the other colour props, a colour on gap / padding / width and the other number props; a typography ref is valid only on fontSize), a ref on a prop that takes no token (fontFamily: "$display" renders 40), and a name defined only in the dark layer (light renders it raw). It reads top-level props, padding / cornerRadius entries, borderTop/Right/Bottom/Left.color, series[].stroke, segments[].color, modal actions[].fill/color/stroke and a toast action.color, inside components too, one finding per place the ref is written. Copy never resolves (content, text, title, subtitle, label, value, placeholder, count, centerValue and the other copy props), so "$49" is a price, not a token, and is not checked. The derived names ($accent-tint, $success-tint, $warning-tint, $danger-tint, $neutral-tint, $danger) always count as defined. The suggestion names up to three defined tokens of the kind the prop takes, nearest spelling first; when exactly one is closest (within 2 edits, and not another rung of a size ladder: $space-lg is never "fixed" to $space-md) and the ref sits on the stored node itself (a top-level prop, a padding / cornerRadius entry or a border colour), it carries a rename fix canvas_autofix applies (two typos in one array share one op that renames both). Wrong-kind, dark-only and takes-no-token findings, refs inside a component or an override, and the nested chart and overlay props carry no fix. Token usage in the stats counts only refs that resolve, against the tokens the canvas inherits too. Modes: + `Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Every check reads the canvas as it renders: each component instance is expanded (its props and overrides applied) and the design system resolved inside it, so contrast, spacing, typography, cliché and every type rule see inside components. A finding on a node inside an instance reports the instance in nodeId (the stored node: fix it in the component, or with an override on the instance), the inner node's expanded id in innerNodeId ("/", the id snapshot_layout and canvas_stress use; batch_design cannot address it), names the component in its message, and carries no fix op. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls, text-inputs included (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action, link, text-input, nav-item, each tab of a tabs node, tree-row, menu-row — inline text links and dividers are not targets, and a control that is the only target directly inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too: one finding per icon in the component, reported on the first instance that shows it, with no fix op. It also WARNS (rule "unknown-token", directive-blocking, -10 structure score each; on for every type unless a ruleset turns it off) on every $ref the resolver reads that renders something other than intended: a name no token defines ("$space-mdd"), a token of the wrong kind for the prop (a typography or spacing token on fill / stroke / color and the other colour props, a colour on gap / padding / width and the other number props; a typography ref is valid only on fontSize), a ref on a prop that takes no token (fontFamily: "$display" renders 40), and a name defined only in the dark layer (light renders it raw). It reads top-level props, padding / cornerRadius entries, borderTop/Right/Bottom/Left.color, series[].stroke, segments[].color, modal actions[].fill/color/stroke and a toast action.color, inside components too, one finding per place the ref is written. Copy never resolves (content, text, title, subtitle, label, value, placeholder, count, centerValue and the other copy props), so "$49" is a price, not a token, and is not checked. The derived names ($accent-tint, $success-tint, $warning-tint, $danger-tint, $neutral-tint, $danger) always count as defined. The suggestion names up to three defined tokens of the kind the prop takes, nearest spelling first; when exactly one is closest (within 2 edits, and not another rung of a size ladder: $space-lg is never "fixed" to $space-md) and the ref sits on the stored node itself (a top-level prop, a padding / cornerRadius entry or a border colour), it carries a rename fix canvas_autofix applies (two typos in one array share one op that renames both). Wrong-kind, dark-only and takes-no-token findings, a token defined as another ref ($brand: "$accent" — the resolver does not follow it), refs inside a component or an override (reported once per place written, on the first instance that shows it; a master or an unused definition names its component), a node with no id (an inline child, reported on its nearest ancestor with one), and the nested chart and overlay props carry no fix. Token usage in the stats counts only refs that resolve, against the tokens the canvas inherits too. Modes: - "fast": JSON-only, <100ms, deterministic heuristics only. - "detailed": adds Puppeteer-based pixel overlap detection in the consistency category, laid out at the canvas's artboard size in the design system's own fonts, as screenshot and canvas_stress render them (a face that cannot load renders in the fallback stack and the result carries a "Font warnings" item) (siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt; a bar pinned to the top over in-flow content still counts). - "llm": fast-mode heuristics plus a vision-model critique against a FIXED rubric (provider picked from FRAMESMITH_LLM_PROVIDER env var, or whichever of ANTHROPIC_API_KEY / OPENAI_API_KEY is set). Adds an "llmCritique" field: { rubric: { hierarchy, execution, specificity, restraint, variety } each {score 1-5, rationale}, score (0-100 derived), summary, suggestions, needsRevision, failingAxes }. The verdict is stamped on the canvas (metadata.critique) + the per-project build log for auditability. Cost: one paid API call per invocation. To CLOSE the loop and auto-fix failing axes, use canvas_revise. diff --git a/src/structures.ts b/src/structures.ts index 2485680..dbd24a2 100644 --- a/src/structures.ts +++ b/src/structures.ts @@ -2,7 +2,7 @@ import type { BuildLogEntry, Canvas, SceneNode, Structure, StructureAxes } from import { resolveSurface, SURFACE_TYPES, type SurfaceType } from './surfaces.js'; import { COLOR, SPACE, RADIUS, ELEV, TYPE, TINT } from './structure-tokens.js'; import { DESKTOP_APP_STRUCTURES } from './structures-desktop.js'; -import { DERIVED_COLORS } from './variables.js'; +import { DERIVED_COLORS, SURFACE_CHAIN } from './variables.js'; // Phase 11 — layout scaffold library. A Structure is a named page shape: a // partial scene tree of *labeled placeholder* children (C8 — never fabricated @@ -2153,7 +2153,7 @@ export function applyStructure( // surface (variables.ts withDerivedColors). A stamp that reads one seeds that // surface too unless the canvas has one, so an unthemed stamp's tints come // out dark, the mode its seeded inks are tuned for. - if ([...referenced].some((t) => (DERIVED_COLORS as readonly string[]).includes(t)) && !existingColors.has('bg-primary')) referenced.add('bg-surface'); + if ([...referenced].some((t) => (DERIVED_COLORS as readonly string[]).includes(t)) && !SURFACE_CHAIN.some((n) => existingColors.has(n))) referenced.add('bg-surface'); const seededColors: string[] = []; for (const token of referenced) { if (existingColors.has(token)) continue; diff --git a/src/tailwind-map.ts b/src/tailwind-map.ts index b7ca394..99d0b9c 100644 --- a/src/tailwind-map.ts +++ b/src/tailwind-map.ts @@ -26,6 +26,11 @@ const SCALE = 4; // 1 unit = 0.25rem = 4px * without this, `border-collapse` becomes a bogus `$collapse` stroke ref * (issue #92's noisy-warning repro). */ const BORDER_NON_COLOR = new Set(['collapse', 'separate', 'solid', 'dashed', 'dotted', 'double', 'hidden', 'none']); +// Phase 32 slice C — text- and bg- utilities that are not colours (wrapping, +// alignment, image placement, gradients): mapped as colours they became +// $refs no token defines. +const TEXT_NON_COLOR = /^(balance|pretty|wrap|nowrap|ellipsis|clip|justify|start|end|shadow(-.+)?)$/; +const BG_NON_COLOR = /^(cover|contain|auto|none|fixed|local|scroll|center|top|bottom|left|right|(left|right)-(top|bottom)|(no-)?repeat(-.+)?|clip-.+|origin-.+|blend-.+|gradient-.+|linear-.+|radial(-.+)?|conic(-.+)?|opacity-.+|size-.+|position-.+)$/; const TEXT_SIZES: Record = { xs: 12, sm: 14, base: 16, lg: 18, xl: 20, '2xl': 24, '3xl': 30, '4xl': 36, '5xl': 48, '6xl': 60, '7xl': 72, '8xl': 96, '9xl': 128 }; const FONT_WEIGHTS: Record = { thin: 100, extralight: 200, light: 300, normal: 400, medium: 500, semibold: 600, bold: 700, extrabold: 800, black: 900 }; @@ -152,7 +157,7 @@ export function classesToProps(classes: string[], theme?: Record if (rest !== 'left') props.textAlign = rest; continue; } - setColor('color', rest, cls); + if (!TEXT_NON_COLOR.test(rest)) setColor('color', rest, cls); continue; } m = cls.match(/^font-(.+)$/); @@ -163,7 +168,7 @@ export function classesToProps(classes: string[], theme?: Record // ── background ── m = cls.match(/^bg-(.+)$/); - if (m) { setColor('fill', m[1], cls); continue; } + if (m) { if (!BG_NON_COLOR.test(m[1])) setColor('fill', m[1], cls); continue; } // ── misc ── if (cls === 'overflow-hidden') { props.overflow = 'hidden'; continue; } diff --git a/src/variables.ts b/src/variables.ts index 0819818..c736cbe 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -39,11 +39,14 @@ export function isRetiredSeed(name: string, value: unknown): boolean { return seed !== undefined && typeof value === 'string' && value.trim().toLowerCase() === seed.toLowerCase(); } -/** A token layer without the retired seeds in its colours. */ -export function withoutRetiredSeeds(v: DesignVariables): DesignVariables { - const colors = v.colors; +/** A token layer without the retired seeds in its colours; a colour layer + * that held nothing else is dropped, as if it had never been set. */ +export function withoutRetiredSeeds(v: T): T { + const colors = v?.colors; if (!colors || !Object.entries(colors).some(([k, val]) => isRetiredSeed(k, val))) return v; - return { ...v, colors: Object.fromEntries(Object.entries(colors).filter(([k, val]) => !isRetiredSeed(k, val))) }; + const kept = Object.entries(colors).filter(([k, val]) => !isRetiredSeed(k, val)); + const { colors: _colors, ...rest } = v!; + return (kept.length ? { ...rest, colors: Object.fromEntries(kept) } : rest) as T; } /** The tokens with every missing derived colour filled in. */ @@ -57,10 +60,13 @@ const WHITE: [number, number, number] = [255, 255, 255]; const BLACK: [number, number, number] = [0, 0, 0]; const hexOf = (rgb: [number, number, number]) => '#' + rgb.map((x) => x.toString(16).padStart(2, '0')).join('').toUpperCase(); -/** The surface tints sit on: bg-surface, else bg-primary, else white; a - * translucent one laid over the next opaque one in that chain. */ +/** The surface names, in the order every default reads them. */ +export const SURFACE_CHAIN = ['bg-surface', 'surface', 'bg-primary', 'background'] as const; + +/** The surface tints sit on: the first of SURFACE_CHAIN that parses, else + * white; a translucent one laid over the next opaque one in that chain. */ function tintSurface(c: Record): [number, number, number] { - const chain = [c['bg-surface'], c['bg-primary']].filter((x): x is string => typeof x === 'string' && rgbOf(x) !== undefined); + const chain = SURFACE_CHAIN.map((n) => c[n]).filter((x): x is string => typeof x === 'string' && rgbOf(x) !== undefined); const opaque = (from: number): [number, number, number] => { const next = chain.slice(from).find((x) => parseAlpha(x) >= 1); return next ? rgbOf(next)! : WHITE; @@ -147,6 +153,7 @@ export function tokenKind(name: string, v: DesignVariables): TokenKind | undefin if (dot > 0) { const category = name.slice(0, dot); const cat = (v as Record)[category]; + if (category === 'colors' && DERIVED_NAMES.has(name.slice(dot + 1))) return 'color'; if (cat && typeof cat === 'object' && Object.hasOwn(cat, name.slice(dot + 1))) { if (category === 'colors') return 'color'; if (category === 'spacing' || category === 'radius' || category === 'state') return 'number'; diff --git a/src/viewer.ts b/src/viewer.ts index bf18606..546a310 100644 --- a/src/viewer.ts +++ b/src/viewer.ts @@ -9,6 +9,7 @@ import { evaluateCanvas, resolveGenre, type EvaluationResult, type EvaluationIss import { resolveSurface, usableSafeArea, deviceProfile, DEVICE_PROFILES, DEFAULT_DEVICE, windowProfile, WINDOW_PROFILES, DEFAULT_WINDOW, type DeviceProfile } from './surfaces.js'; import { isPresetName } from './genre.js'; import { addFeedback, listFeedback, resolveFeedback, deleteFeedback, openFeedbackCount } from './feedback.js'; +import { withoutRetiredSeeds } from './variables.js'; let runningPort: number | null = null; let externalViewerUrl: string | null = null; @@ -979,7 +980,8 @@ function renderDesignSystem(canvas: Canvas): string { return !!m && Object.prototype.hasOwnProperty.call(m, name); }; const sourceOf = (cat: string, name: string): TokenLayer => { - if (has(canvas.variables, cat, name)) return 'canvas'; + // A retired scaffold seed is not the canvas's value (FR-C6). + if (has(withoutRetiredSeeds(canvas.variables), cat, name)) return 'canvas'; if (has(projectDS, cat, name)) return 'project'; if (has(workspaceDS, cat, name)) return 'workspace'; return 'default'; diff --git a/test/unit/test-derived-tints.ts b/test/unit/test-derived-tints.ts index 56fb23f..4f4fdd3 100644 --- a/test/unit/test-derived-tints.ts +++ b/test/unit/test-derived-tints.ts @@ -109,6 +109,14 @@ function stamped(structure: string, preset?: string, type?: 'desktop-app'): Canv check('a translucent surface lies over bg-primary: a glass card on a dark page is dark', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#ffffff0a', 'bg-primary': '#0a0a0a' } })) === 'dark'); check('twin: the same glass over a light page is light', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#ffffff0a', 'bg-primary': '#fafafa' } })) === 'light'); check('an hsl() surface parses (dark)', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': 'hsl(222 47% 11%)' } })) === 'dark'); + check('the `surface` alias is a surface too (a design.md import names it so)', modeOf(resolveFill('$accent-tint', { colors: { surface: '#1C1C1E', background: '#000000' } })) === 'dark'); + check('twin: and `background` behind a translucent surface', modeOf(resolveFill('$accent-tint', { colors: { surface: '#ffffff10', background: '#000000' } })) === 'dark' && modeOf(resolveFill('$accent-tint', { colors: { surface: '#ffffff10', background: '#fafafa' } })) === 'light'); + { + const c = createCanvas('dt-alias-stamp'); + c.variables = { colors: { surface: '#FAFAFA' } }; + const r = applyStructure(c, 'status-chip', { existingColors: new Set(['surface']) }); + check('a stamp on a canvas naming its surface `surface` does not seed a dark bg-surface over it', !r.seededColors.includes('bg-surface'), r.seededColors.join(', ')); + } check('an unparseable surface falls to bg-primary', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': 'var(--x)', 'bg-primary': '#0a0a0a' } })) === 'dark'); const neutral = resolveFill('$neutral-tint', { colors: { 'bg-surface': '#111111', 'text-secondary': '#ffffffa0' } }); check('a grey ink with alpha (composited over the surface) gets a grey tint', isGrey(neutral) && modeOf(neutral) === 'dark', neutral); @@ -165,6 +173,56 @@ function stamped(structure: string, preset?: string, type?: 'desktop-app'): Canv check('twin: any other value moves the hash', canvasVersionHash(withOther) !== canvasVersionHash(plain)); } +// ── Verify round 1: a canvas without variables, and a seed-only colour layer ── +{ + const bare = createCanvas('dt-bare'); + delete (bare as { variables?: unknown }).variables; + let threw = ''; + try { getCanvasTokens(bare); } catch (e) { threw = (e as Error).message; } + check('a stored canvas with no variables key still resolves its tokens', !threw, threw); + const seedOnly = createCanvas('dt-seed-only'); + seedOnly.variables = { colors: { 'accent-tint': '#152A47' } }; + const none = structuredClone(seedOnly); + none.variables = {}; + check('a colour layer holding only a seed hashes as if it had no colours', canvasVersionHash(seedOnly) === canvasVersionHash(none)); + const empty = structuredClone(seedOnly); + empty.variables = { colors: { 'accent-tint': '#152A48' } }; + check('twin: a non-seed value does not', canvasVersionHash(empty) !== canvasVersionHash(none)); +} + +// ── Verify round 1 (mutation): fallbacks, surface order, each seed ──────────── +{ + check('danger-tint derives from danger, not error', resolveFill('$danger-tint', { colors: { 'bg-surface': '#FFFFFF', danger: '#7C2D12', error: '#B00020' } }) === tintFor('#7C2D12', 'light')); + check('accent-tint derives from primary when there is no accent', resolveFill('$accent-tint', { colors: { 'bg-surface': '#FFFFFF', primary: '#0E7490' } }) === tintFor('#0E7490', 'light')); + const empty = { colors: { 'bg-surface': '#FFFFFF' } }; + const lit: Array<[string, string]> = [['$accent-tint', '#2563EB'], ['$success-tint', '#16A34A'], ['$warning-tint', '#D97706'], ['$danger-tint', '#DC2626'], ['$neutral-tint', '#6B7280']]; + const wrong = lit.filter(([ref, ink]) => resolveFill(ref, empty) !== tintFor(ink, 'light', { grey: true })); + check('with no inks each tint derives from its literal ink', wrong.length === 0, wrong.map(([r]) => r).join(', ')); + check('bg-surface wins over bg-primary', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#FFFFFF', 'bg-primary': '#111111' } })) === 'light'); + check('twin: bg-primary alone decides', modeOf(resolveFill('$accent-tint', { colors: { 'bg-primary': '#111111' } })) === 'dark'); + check('a translucent surface with nothing behind it lies over white', modeOf(resolveFill('$accent-tint', { colors: { 'bg-surface': '#00000010' } })) === 'light'); + const { hexToOklch } = await import('../../src/color-system.js'); + check('an ink of chroma 0.003 counts as grey', hexToOklch('#808082').c < 0.005 && isGrey(resolveFill('$neutral-tint', { colors: { 'bg-surface': '#FFFFFF', 'text-secondary': '#808082' } }))); + check('twin: #6B7280 (chroma 0.023) keeps its hue', !isGrey(resolveFill('$neutral-tint', { colors: { 'bg-surface': '#FFFFFF', 'text-secondary': '#6B7280' } }))); + check('a pure grey ink in light mode gets a grey tint', isGrey(resolveFill('$neutral-tint', { colors: { 'bg-surface': '#FFFFFF', 'text-secondary': '#808080' } }))); + const dark = resolveVariables({ id: 'x', type: 'frame', shadow: '$elevation.raised' } as SceneNode, { elevation: { raised: [{ x: 0, y: 1, blur: 2, spread: 0, color: '#000' }] }, dark: { elevation: { raised: [{ x: 0, y: 9, blur: 9, spread: 0, color: '#fff' }] } } }, { theme: 'dark' }); + check('a dark render merges dark.elevation too', dark.shadows?.[0]?.y === 9, JSON.stringify(dark.shadows)); +} +{ + const seeds: Array<[string, string]> = [['accent-tint', '#152A47'], ['success-tint', '#0F2E1B'], ['warning-tint', '#33260A'], ['danger-tint', '#3A1715'], ['neutral-tint', '#25282D'], ['danger', '#F87171']]; + const kept = seeds.filter(([name, value]) => withoutRetiredSeeds({ colors: { [name]: value.toLowerCase() } }).colors?.[name] !== undefined); + check('each of the six retired seeds counts as unset', kept.length === 0, kept.map(([n]) => n).join(', ')); + const near = seeds.filter(([name, value]) => withoutRetiredSeeds({ colors: { [name]: value.slice(0, 6) + 'F' } }).colors?.[name] === undefined); + check('twin: one digit off, each is kept', near.length === 0, near.map(([n]) => n).join(', ')); + check('a seed with surrounding spaces still counts', withoutRetiredSeeds({ colors: { 'accent-tint': ' #152A47 ' } }).colors === undefined); +} +{ + const c = createCanvas('dt-primary-stamp'); + c.variables = { colors: { 'bg-primary': '#FAFAFA' } }; + const r = applyStructure(c, 'status-chip', { existingColors: new Set(['bg-primary']) }); + check('a stamp on a canvas with bg-primary does not seed bg-surface', !r.seededColors.includes('bg-surface'), r.seededColors.join(', ')); +} + // ── No stamp reads badly on a derived tint ───────────────────────────────────── // Every structure, unthemed and under each preset whose inks clear on its own // surface (the light preset's success and error do not: FR-C5's last diff --git a/test/unit/test-tailwind-map.ts b/test/unit/test-tailwind-map.ts index f498fdd..0b213c6 100644 --- a/test/unit/test-tailwind-map.ts +++ b/test/unit/test-tailwind-map.ts @@ -69,6 +69,11 @@ function el(partial: Partial & { tag: string }): RawDomNode { // Phase 18 FR-A2 — border style/model keywords are not colors (#92's $collapse). const { props: bc, tokenRefs: bcRefs } = classesToProps(['border-collapse', 'border-separate', 'border-dashed', 'border-spacing-2']); expect('border style keywords map nothing', bc.stroke === undefined && bcRefs.length === 0, JSON.stringify(bc)); + // Phase 32 slice C — nor are text- wrapping and bg- placement utilities. + const { props: nc, tokenRefs: ncRefs } = classesToProps(['text-balance', 'text-nowrap', 'text-ellipsis', 'text-justify', 'bg-cover', 'bg-center', 'bg-no-repeat', 'bg-fixed', 'bg-gradient-to-r', 'bg-opacity-50']); + expect('text- and bg- non-colour utilities map no colour', nc.color === undefined && nc.fill === undefined && ncRefs.length === 0, JSON.stringify(nc)); + const { props: tc } = classesToProps(['text-muted', 'bg-surface']); + expect('twin: text- and bg- colours still map', tc.color === '$muted' && tc.fill === '$surface', JSON.stringify(tc)); const { props: bcolor } = classesToProps(['border-muted', 'border-red-500']); expect('border colors still map', bcolor.stroke === '$muted' || bcolor.stroke === '#fb2c36'); // last one wins } diff --git a/test/unit/test-unknown-token.ts b/test/unit/test-unknown-token.ts index 7c330e4..e178805 100644 --- a/test/unit/test-unknown-token.ts +++ b/test/unit/test-unknown-token.ts @@ -176,6 +176,206 @@ b=I("${page.nodeId}", {type: "instance", name: "card-b", componentId: "${card.no check('...and so is its unknown icon, with no fix (an op would rewrite the parent)', icon?.nodeId === box && !icon.fix, icon?.nodeId); } +// ── Verify round 1: an override written inside a component, and a one-letter step ── +{ + const canvas = canvasWith([]); + const [page] = parseAndExecute(canvas.root, 'page=I("document", {type: "frame", name: "page", layout: "vertical"})', canvas); + const [inner] = parseAndExecute(canvas.root, 'inner=I("document", {type: "component", name: "Inner", layout: "vertical"})', canvas); + parseAndExecute(canvas.root, `t=I("${inner.nodeId}", {type: "text", name: "title", content: "x", color: "$text-primary"})`, canvas); + const [outer] = parseAndExecute(canvas.root, 'outer=I("document", {type: "component", name: "Outer", layout: "vertical"})', canvas); + parseAndExecute(canvas.root, `ci=I("${outer.nodeId}", {type: "instance", name: "ci", componentId: "${inner.nodeId}", overrides: {"title": {"color": "$nope-in-def"}}})`, canvas); + parseAndExecute(canvas.root, ` +o1=I("${page.nodeId}", {type: "instance", name: "o1", componentId: "${outer.nodeId}"}) +o2=I("${page.nodeId}", {type: "instance", name: "o2", componentId: "${outer.nodeId}"}) +`, canvas); + check('an override written inside a component, shown through two outer instances, warns once', about(await findings(canvas), '$nope-in-def').length === 1, String(about(await findings(canvas), '$nope-in-def').length)); + // Twin: overrides written on two stored instances are two places. + const twin = canvasWith([]); + const [tp] = parseAndExecute(twin.root, 'page=I("document", {type: "frame", name: "page", layout: "vertical"})', twin); + const [tc] = parseAndExecute(twin.root, 'card=I("document", {type: "component", name: "Card", layout: "vertical"})', twin); + parseAndExecute(twin.root, `t=I("${tc.nodeId}", {type: "text", name: "title", content: "x", color: "$text-primary"})`, twin); + parseAndExecute(twin.root, ` +a=I("${tp.nodeId}", {type: "instance", name: "a", componentId: "${tc.nodeId}", overrides: {"title": {"color": "$nope-own"}}}) +b=I("${tp.nodeId}", {type: "instance", name: "b", componentId: "${tc.nodeId}", overrides: {"title": {"color": "$nope-own"}}}) +`, twin); + check('twin: the same typo in two stored instances\' own overrides is two findings', about(await findings(twin), '$nope-own').length === 2); +} +{ + const ladder: DesignVariables = { ...SYSTEM, spacing: { 'space-md': 16, 'space-lg': 24 } }; + const [m] = await findings(canvasWith([frame('a', { gap: '$space-m' })], ladder)); + check('a lone letter is a typo, not a ladder step: $space-m is fixed to $space-md', m?.fix?.op === 'U("a", { gap: "$space-md" })', m?.fix?.op); + // Twins: real steps still never cross a rung. + const [xl] = await findings(canvasWith([frame('a', { gap: '$space-2xl' })], { ...SYSTEM, spacing: { 'space-xl': 32 } })); + check('twin: $space-2xl with only space-xl defined is not fixed (another rung)', !!xl && !xl.fix); + const [xxs] = await findings(canvasWith([frame('a', { gap: '$space-xxs' })], { ...SYSTEM, spacing: { 'space-xs': 8 } })); + check('twin: $space-xxs with only space-xs defined is not fixed (another rung)', !!xxs && !xxs.fix); +} +{ + const canvas = canvasWith([]); + const [card] = parseAndExecute(canvas.root, 'card=I("document", {type: "component", name: "Card", children: [{type: "text", content: "x", color: "$nope-anon"}]})', canvas); + parseAndExecute(canvas.root, `a=I("document", {type: "instance", name: "a", componentId: "${card.nodeId}"})`, canvas); + const fs = await evaluateCanvas(canvas, { mode: 'fast', categories: ['structure'] }); + const ids = fs.issues.filter((i) => i.rule === 'unknown-token').map((i) => `${i.nodeId}|${i.innerNodeId ?? ''}`); + check('an id-less node inside a component never reports an id ending in "undefined"', ids.length > 0 && ids.every((x) => !x.includes('undefined')), ids.join(', ')); +} + +// ── Verify round 1 (review): dotted derived names, aliases, messages ───────────── +{ + const fs = await findings(canvasWith([frame('a', { fill: '$colors.accent-tint' }), frame('b', { stroke: '$colors.danger' }), frame('c', { fill: '$colors.accnt-tint' })])); + check('a dotted ref to a derived colour is valid ($colors.accent-tint, $colors.danger)', fs.every((f) => f.nodeId === 'c') && fs.length === 1, fs.map((f) => f.message).join(' | ')); +} +{ + const vars: DesignVariables = { ...SYSTEM, colors: { ...SYSTEM.colors, brand: '$accent' } }; + const fs = await findings(canvasWith([frame('a', { fill: '$brand' }), frame('b', { fill: '$accent' })], vars)); + check('a token whose value is itself a ref warns (the resolver does not follow it)', fs.length === 1 && fs[0].nodeId === 'a' && /does not follow/.test(fs[0].message), fs.map((f) => f.message).join(' | ')); +} +{ + const vars = structuredClone(SYSTEM); + vars.dark = { elevation: { glow: [{ x: 0, y: 0, blur: 4, spread: 0, color: '#000' }] } }; + const [f] = await findings(canvasWith([frame('a', { shadow: '$elevation.glow' })], vars)); + check('a dark-only elevation names the elevation layer', /base elevation/.test(f?.suggestion ?? ''), f?.suggestion); +} +{ + const [f] = await findings(canvasWith([frame('a', { gap: '$space-mdd' })])); + check('"Did you mean" lists only names within two edits', f?.suggestion === 'Did you mean "$space-md"?', f?.suggestion); +} + +// ── Verify round 1 (mutation): edges of the fix, dedupe, tables, kill switch ── +{ + const md: DesignVariables = { ...SYSTEM, spacing: { 'space-md': 16 } }; + const [two] = await findings(canvasWith([frame('a', { gap: '$space-mxx' })], md)); + check('a typo two edits away is fixed', two?.fix?.op === 'U("a", { gap: "$space-md" })', two?.fix?.op); + const [three] = await findings(canvasWith([frame('a', { gap: '$space-mxxx' })], md)); + check('twin: three edits away it names no candidate and has no fix', !!three && !three.fix && /Define it/.test(three.suggestion ?? ''), three?.suggestion); + const tie: DesignVariables = { ...SYSTEM, spacing: { 'space-md': 16, 'space-me': 17 } }; + const [t] = await findings(canvasWith([frame('a', { gap: '$space-mx' })], tie)); + check('two names equally close: both named, no fix', !!t && !t.fix && /space-md/.test(t.suggestion ?? '') && /space-me/.test(t.suggestion ?? ''), t?.suggestion); + const steps: Array<[string, Record]> = [ + ['$space-4', { 'space-8': 32 }], + ['$space-LG', { 'space-md': 16 }], + ['$bg-surface-lg', { 'bg-surface-md': 16 }], + ]; + for (const [ref, spacing] of steps) { + const [f] = await findings(canvasWith([frame('a', { gap: ref })], { ...SYSTEM, spacing })); + check(`${ref} against ${Object.keys(spacing)[0]} is another rung: no fix`, !!f && !f.fix, f?.fix?.op); + } +} +{ + for (const side of ['borderRight', 'borderBottom', 'borderLeft'] as const) { + const [f] = await findings(canvasWith([frame('a', { [side]: { width: 1, color: '$accnt' } } as Partial)])); + check(`a ${side}.color typo rewrites the whole object`, f?.fix?.op === `U("a", { ${side}: {"width":1,"color":"$accent"} })`, f?.fix?.op); + } +} +{ + const fs = await findings(canvasWith([frame('a', { gap: '$space-mdd', rowGap: '$space-mdd' }), frame('b', { gap: '$space-mdd' })])); + check('one typo on two props of one node, and on another node, is three findings', fs.length === 3, String(fs.length)); + const anon = canvasWith([]); + parseAndExecute(anon.root, 'box=I("document", {type: "frame", name: "box", children: [{type: "frame", gap: "$space-mdd"}, {type: "frame", gap: "$space-mdd"}]})', anon); + check('two id-less children with one typo are two findings', (await findings(anon)).length === 2); +} +{ + const used = canvasWith([]); + const [p] = parseAndExecute(used.root, 'page=I("document", {type: "frame", name: "page"})', used); + const [c] = parseAndExecute(used.root, 'card=I("document", {type: "component", name: "Used card", gap: "$space-mdd"})', used); + parseAndExecute(used.root, `a=I("${p.nodeId}", {type: "instance", name: "a", componentId: "${c.nodeId}"})`, used); + const [f] = await findings(used); + check('twin: a used component\'s finding does not say no instance uses it', !!f && !/no instance uses/.test(f.message), f?.message); +} +{ + // An override on a different prop is not where the typo comes from. + const canvas = canvasWith([]); + const [p] = parseAndExecute(canvas.root, 'page=I("document", {type: "frame", name: "page"})', canvas); + const [c] = parseAndExecute(canvas.root, 'card=I("document", {type: "component", name: "Card"})', canvas); + parseAndExecute(canvas.root, `t=I("${c.nodeId}", {type: "frame", name: "inner", gap: "$space-mdd", padding: ["$space-mdd", 0]})`, canvas); + parseAndExecute(canvas.root, `a=I("${p.nodeId}", {type: "instance", name: "a", componentId: "${c.nodeId}", overrides: {"inner": {"fill": "#FFFFFF"}}})`, canvas); + const fs = await findings(canvas); + check('an override on another prop does not claim the typo', fs.length === 2 && fs.every((f) => !/override for this node/.test(f.suggestion ?? '')), fs.map((f) => f.suggestion).join(' | ')); + const ovr = canvasWith([]); + const [p2] = parseAndExecute(ovr.root, 'page=I("document", {type: "frame", name: "page"})', ovr); + const [c2] = parseAndExecute(ovr.root, 'card=I("document", {type: "component", name: "Card"})', ovr); + parseAndExecute(ovr.root, `t=I("${c2.nodeId}", {type: "frame", name: "inner", padding: [8, 0]})`, ovr); + parseAndExecute(ovr.root, `a=I("${p2.nodeId}", {type: "instance", name: "a", componentId: "${c2.nodeId}", overrides: {"inner": {"padding": ["$space-mdd", 0]}}})`, ovr); + const [o] = await findings(ovr); + check('twin: an override holding the typo in an array entry says so', /override for this node/.test(o?.suggestion ?? ''), o?.suggestion); +} +{ + // An instance nested in a component, its own prop misspelt, seen through two outer instances. + const canvas = canvasWith([]); + const [p] = parseAndExecute(canvas.root, 'page=I("document", {type: "frame", name: "page"})', canvas); + const [inner] = parseAndExecute(canvas.root, 'inner=I("document", {type: "component", name: "Inner", layout: "vertical"})', canvas); + const [outer] = parseAndExecute(canvas.root, 'outer=I("document", {type: "component", name: "Outer"})', canvas); + parseAndExecute(canvas.root, `ci=I("${outer.nodeId}", {type: "instance", name: "ci", componentId: "${inner.nodeId}", gap: "$space-nested"})`, canvas); + parseAndExecute(canvas.root, `o1=I("${p.nodeId}", {type: "instance", name: "o1", componentId: "${outer.nodeId}"})\no2=I("${p.nodeId}", {type: "instance", name: "o2", componentId: "${outer.nodeId}"})`, canvas); + const fs = about(await findings(canvas), '$space-nested'); + check('a nested instance\'s own typo, seen through two outer instances, is one finding with no fix', fs.length === 1 && !fs[0].fix, String(fs.length)); +} +{ + const vars: DesignVariables = { ...SYSTEM, radius: { 'radius-md': 8 }, motion: { fast: { duration: 150, easing: 'ease-out' } }, colors: { ...SYSTEM.colors, danger: '#DC2626' } }; + const fs = await findings(canvasWith([ + { id: 'fs', type: 'text', name: 'fs', content: 'x', fontSize: '$accent' } as SceneNode, + frame('tr', { transition: '$motion.fastt' } as unknown as Partial), + frame('tk', { transition: '$accent' } as unknown as Partial), + frame('dt', { fill: '$danger-tnt' }), + frame('rd', { cornerRadius: '$radius-mdd' }), + { id: 'bd', type: 'text', name: 'bd', content: 'x', fontSize: '$bodyy' } as SceneNode, + frame('el', { shadow: '$elevation.mdd' }), + ], vars)); + const on = (id: string) => fs.find((f) => f.nodeId === id); + check('fontSize "$accent" warns (a colour is not a size)', /color token/.test(on('fs')?.message ?? ''), on('fs')?.message); + check('transition "$motion.fastt" is fixed to $motion.fast', on('tr')?.fix?.op === 'U("tr", { transition: "$motion.fast" })', on('tr')?.fix?.op); + check('transition "$accent" warns (wrong kind)', /color token, not a motion token/.test(on('tk')?.message ?? ''), on('tk')?.message); + check('a typo near a derived colour names it', /"\$danger-tint"/.test(on('dt')?.suggestion ?? ''), on('dt')?.suggestion); + check('radius, typography and elevation names are candidates with their prefixes', /"\$radius-md"/.test(on('rd')?.suggestion ?? '') && /"\$body"/.test(on('bd')?.suggestion ?? '') && /"\$elevation\.md"/.test(on('el')?.suggestion ?? ''), [on('rd'), on('bd'), on('el')].map((f) => f?.suggestion).join(' | ')); +} +{ + // Every entry of the prop tables, and every copy prop. + const colorProps = ['fill', 'stroke', 'color', 'iconColor', 'secondaryColor', 'badgeColor', 'dotColor']; + const numberProps = ['width', 'height', 'minWidth', 'maxWidth', 'minHeight', 'gap', 'rowGap', 'padding', 'cornerRadius', 'x', 'y', 'bottom', 'right', 'strokeWidth', 'opacity', 'blur', 'backdropBlur', 'fontWeight', 'lineHeight', 'letterSpacing', 'iconSize', 'labelWidth', 'inset', 'depth', 'rows', 'innerRatio', 'gridlines']; + const nodes = [ + ...colorProps.map((p) => frame(`c-${p}`, { [p]: '$body' } as Partial)), + ...numberProps.map((p) => frame(`n-${p}`, { [p]: '$accent' } as Partial)), + ]; + const fs = await findings(canvasWith(nodes)); + const missC = colorProps.filter((p) => !fs.some((f) => f.nodeId === `c-${p}` && /not a color token/.test(f.message))); + const missN = numberProps.filter((p) => !fs.some((f) => f.nodeId === `n-${p}` && /not a spacing or radius token/.test(f.message))); + check('every colour prop rejects a typography token', missC.length === 0, missC.join(', ')); + check('every number prop rejects a colour token', missN.length === 0, missN.join(', ')); + const copy = ['name', 'content', 'text', 'title', 'subtitle', 'label', 'time', 'placeholder', 'value', 'shortcut', 'error', 'ariaLabel', 'count', 'closeLabel', 'centerValue', 'centerLabel']; + const cfs = await findings(canvasWith(copy.map((p) => frame(`k-${p}`, { [p]: '$49' } as Partial)))); + check('no copy prop is read as a token', cfs.length === 0, cfs.map((f) => f.nodeId).join(', ')); +} +{ + // The kill switch: a ruleset that turns the rule off silences it, score included. + const { RULESETS } = await import('../../src/surfaces.js'); + const typo = () => canvasWith([frame('a', { gap: '$space-mdd' })]); + const on = await evaluateCanvas(typo(), { mode: 'fast', categories: ['structure'] }); + const saved = RULESETS.type.web; + RULESETS.type.web = { disable: ['unknown-token'] }; + const off = await evaluateCanvas(typo(), { mode: 'fast', categories: ['structure'] }); + RULESETS.type.web = saved; + const score = (ev: typeof on) => ev.categories.find((c) => c.name === 'structure')!.score; + check('a ruleset that turns unknown-token off silences it and its score', !off.issues.some((i) => i.rule === 'unknown-token') && off.surface.rulesOff.includes('unknown-token') && score(off) === score(on) + 10, `${score(on)} → ${score(off)}`); +} +{ + // Token usage runs on a canvas with colours only, or spacing only. + const colorsOnly = canvasWith([frame('a', { fill: '#123456', stroke: '#654321' })], { colors: { accent: '#2563EB' } }); + const spacingOnly = canvasWith([frame('a', { fill: '#123456', stroke: '#654321' })], { spacing: { md: 16 } }); + const advises = async (c: Canvas) => (await evaluateCanvas(c, { mode: 'fast', categories: ['structure'] })).issues.some((i) => /use design tokens/.test(i.message)); + check('the token-usage advisory runs with colours only, and with spacing only', await advises(colorsOnly) && await advises(spacingOnly)); + check('twin: with no tokens at all it does not', !(await advises(canvasWith([frame('a', { fill: '#123456', stroke: '#654321' })], {})))); +} +{ + // An id-less icon with one resolving spelling: reported on the ancestor, never fixed. + const canvas = canvasWith([]); + parseAndExecute(canvas.root, 'box=I("document", {type: "frame", name: "box", children: [{type: "icon", icon: "material:chevron-right"}]})', canvas); + const ev = await evaluateCanvas(canvas, { mode: 'fast', categories: ['structure'] }); + const icon = ev.issues.find((i) => /Unknown icon/.test(i.message)); + check('an id-less misspelt icon gets no fix (it would rewrite its ancestor)', !!icon && !icon.fix, icon?.fix?.op); + const twin = canvasWith([{ id: 'ic', type: 'icon', name: 'ic', icon: 'material:chevron-right' } as SceneNode]); + const tw = (await evaluateCanvas(twin, { mode: 'fast', categories: ['structure'] })).issues.find((i) => /Unknown icon/.test(i.message)); + check('twin: the same icon with an id is fixed', tw?.fix?.op === 'U("ic", { icon: "material:chevron_right" })', tw?.fix?.op); +} + // ── FR-C3: copy is never resolved ───────────────────────────────────────────── { const canvas = canvasWith([ From 124b865e5ea48a56b4eb58f43883f1c6459f09cd Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sat, 21 Nov 2026 20:36:48 +0100 Subject: [PATCH 6/6] Fix the slice C second-round findings --- docs/GUIDELINES.md | 2 +- docs/specs/PHASE-32-SPEC.md | 9 +++++++++ src/evaluate.ts | 9 +++++---- src/expand.ts | 6 ++---- src/tailwind-map.ts | 12 +++++++++--- src/variables.ts | 2 +- test/unit/test-tailwind-map.ts | 4 ++++ test/unit/test-unknown-token.ts | 24 ++++++++++++++++++++---- 8 files changed, 51 insertions(+), 17 deletions(-) diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 2bc16bc..3c7d557 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -392,7 +392,7 @@ On a canvas whose design system has no tint tokens (unthemed, or styled by a pre `canvas_evaluate` warns (rule `unknown-token`, structure category, directive-blocking, −10 each) on every `$ref` that renders something other than intended: -- **A name no token defines** — `gap: "$space-mdd"`. One finding per ref (two typos in one `padding` array are two findings). The suggestion names up to three defined tokens of the kind the prop takes, nearest spelling first, within two edits (an edit adds, drops or changes one character); with none that close it says to define the token. When exactly one is closest and it is not another rung of the same size ladder (a name ending in `3xs`, `2xs`, `xxs`, `xs`, `sm`, `md`, `lg`, `xl`, `2xl`, `3xl` or a number), a ref on the node's own top-level prop, `padding` / `cornerRadius` entry or border colour carries a rename fix that `canvas_autofix` applies: `$space-mdd` → `$space-md`, `$bg-surfce` → `$bg-surface`. `$space-xxs` is as close to `$space-3xs`, `$space-2xs` and `$space-xs`, so it is reported with all three and no fix; `$space-lg` on a ladder without it is a different size, never renamed to `$space-md`. +- **A name no token defines** — `gap: "$space-mdd"`. One finding per ref (two typos in one `padding` array are two findings). The suggestion names up to three defined tokens of the kind the prop takes, nearest spelling first, within two edits (an edit adds, drops or changes one character); with none that close it says to define the token. When exactly one is closest and it is not another rung of the same size ladder (a name ending in `3xs`, `2xs`, `xxs`, `xs`, `s`, `sm`, `m`, `md`, `l`, `lg`, `xl`, `2xl`, `3xl` or a number; on an s / m / l ladder `$space-m` is a rung, so it is never renamed to `$space-md`), a ref on the node's own top-level prop, `padding` / `cornerRadius` entry or border colour carries a rename fix that `canvas_autofix` applies: `$space-mdd` → `$space-md`, `$bg-surfce` → `$bg-surface`. `$space-xxs` is as close to `$space-3xs`, `$space-2xs` and `$space-xs`, so it is reported with all three and no fix; `$space-lg` on a ladder without it is a different size, never renamed to `$space-md`. - **The wrong kind** — a typography or spacing token on a colour prop (`fill: "$body"` renders `16`), a colour on a number prop (`gap: "$accent"`), a dotted path ending at a whole token rather than one value (`$typography.body`). A typography ref is valid only on `fontSize`, where it applies the whole role (size, weight, family, line height, tracking); `lineHeight: "$heading"` is wrong-kind. - **A prop that takes no token** — `fontFamily: "$display"` renders the role's size as the font name. - **A name defined only in the dark layer** — light renders it raw; define it in the base colours (or elevation) too. diff --git a/docs/specs/PHASE-32-SPEC.md b/docs/specs/PHASE-32-SPEC.md index 2b04451..c00ad03 100644 --- a/docs/specs/PHASE-32-SPEC.md +++ b/docs/specs/PHASE-32-SPEC.md @@ -162,6 +162,15 @@ And one is housekeeping the follow-ups will land in. 140 tests and `test-env.ts` - **V3 (changed M3, M4, M5, M7):** `$colors.accent-tint` and the other dotted derived names are valid. The tint surface reads the same chain as every other default (`bg-surface`, `surface`, `bg-primary`, `background`), and N1's seeding skips a canvas that resolves any of them (a design.md import names its colours `surface` and `background`). A token whose value is itself a `$ref` (`brand: "$accent"`) is a fifth case: the resolver does not follow it, so it renders raw; it warns, no fix. The dark-only suggestion names the elevation layer for an elevation ref. Candidates are names within two edits (three padded the list with noise: `$space-mdd` suggested `$space-2xl`). The Tailwind importer no longer maps non-colour `text-` and `bg-` utilities (`text-balance`, `bg-cover`, `bg-gradient-to-r` and the like) to colour refs. - **Not fixed, named:** `lookupToken` reads spacing before radius, so `cornerRadius: "$md"` under a preset that defines both renders the spacing value (16, not 8). The rule sees one `number` kind and stays silent, and the README's own `get_variables` example (`cornerRadius: "$sm"`) hits it. It predates this slice and changing the order changes existing renders, so it is a follow-up. A node id containing `"` gives an op the U parser rejects (pre-existing in `formatUpdateOp`). `withDerivedColors` costs about 1.4 ms per resolve, unmemoised. +**Slice C — verify round 2 and the last fix round (recorded 2026-11-21).** One verifier on the round-1 fix diff (fc3da95 → 2cff888). It found: +- **Round 1's id-less fix broke attribution.** Giving an id-less node inside an instance no id (instead of `/undefined`) emptied the owners map for it, so every other rule's finding on such a node lost its instance (`nodeId` undefined) and a viewer comment on it failed. Reverted; the `…/undefined` inner id is cosmetic. Consequence, accepted: an id-less node in a component master that also sits in the tree is reported twice, once as the stored master node and once through the instance. +- **Round 1's ladder change was unsafe.** Treating `m`, `s` and `l` as typos let `$space-l` on a ladder with only `space-md` be renamed to it. Single letters are steps again; `$space-m` → `$space-md` is not fixed. A missed rename is cheaper than a wrong size. +- **The importer blocklist was incomplete and over-broad.** `text-sm/6` (size with a line-height modifier), `text-red-500/50` and `bg-(--x)` still became refs, and the blocklists overrode theme colours named `top`, `wrap` and the like. A name with `/` or starting with `(` is never a colour name; a size with a modifier is a size; a theme colour wins over the blocklists. +- **Nits:** the state defaults now read `SURFACE_CHAIN` (same order, one list); a dark-only `$colors.x` suggestion names the bare token. +- **Accepted, named:** the alias order changes the tint mode of a stored canvas holding both `surface` and `bg-primary` (it now matches the state defaults); an override that targets a nested instance node by name is reported as the component's, without the override hint. + +These fixes were proved red on 2cff888 and green after; no agent re-verified them. + **Slice D: desktop-app checks and stress (FR-D1 to FR-D4).** - `variables.ts` select branch: `$border-strong` when defined. `state-checks.ts:268`: `select` measured. - `renderTreeRow` (`renderer.ts:1610`): `position: relative` with `renderNavItem`'s guard, and the bar. `indicatorPairs` (`state-checks.ts:211-236`): `tree-row`. diff --git a/src/evaluate.ts b/src/evaluate.ts index 7da5e12..c857b66 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -971,11 +971,12 @@ function levenshtein(a: string, b: string): number { return row[b.length]; } -/** The size step a token name ends in (3xs, xxs, xs, sm, md, lg, xl, 2xl, a - * number), if any. A lone letter is a typo, not a step. */ +/** The size step a token name ends in (s, m, l, 3xs, xxs, xs, sm, md, lg, + * xl, 2xl, a number), if any. A lone letter counts: on an s / m / l ladder + * `$space-m` is a rung, so it is never renamed to `$space-md`. */ function ladderStep(name: string): string | undefined { const last = name.slice(name.lastIndexOf('-') + 1).toLowerCase(); - return /^(\d*x+[sl]|sm|md|lg|\d+)$/.test(last) ? last : undefined; + return /^(\d*x*[sml]|sm|md|lg|\d+)$/.test(last) ? last : undefined; } /** The value at a ref site on an object (a node or an override). */ @@ -1081,7 +1082,7 @@ function checkUnknownTokens(canvas: Canvas, tokens: DesignVariables): Evaluation if (kind) return; if (tokenKind(name, dark) !== undefined) { const layer = name.startsWith('elevation.') ? 'elevation' : 'colors'; - issues.push({ ...base, message: `Token "${ref}" on ${path} is defined only in the dark layer, so light renders it raw${where}.`, suggestion: `Define "${name.replace(/^elevation\./, '')}" in the base ${layer} too (set_variables), not only under dark.${fromOverride}` }); + issues.push({ ...base, message: `Token "${ref}" on ${path} is defined only in the dark layer, so light renders it raw${where}.`, suggestion: `Define "${name.replace(/^(elevation|colors)\./, '')}" in the base ${layer} too (set_variables), not only under dark.${fromOverride}` }); return; } const ranked = candidatePool(accepts, tokens) diff --git a/src/expand.ts b/src/expand.ts index 919e53b..eeb2f94 100644 --- a/src/expand.ts +++ b/src/expand.ts @@ -34,10 +34,8 @@ export function expandTree( // inside itself stays unexpanded instead of recursing forever. const open = new Set(); const walk = (node: SceneNode, owner: SceneNode | undefined, prefix: string): SceneNode => { - // A node with no id (an inline child of a batch_design insert) stays - // without one inside an instance too. - const id = owner && node.id !== undefined ? prefix + node.id : node.id; - if (owner && id !== undefined) owners.set(id, owner); + const id = owner ? prefix + node.id : node.id; + if (owner) owners.set(id, owner); const cid = node.type === 'instance' ? node.componentId : undefined; const resolved = cid && !open.has(cid) ? resolveInstance(node, canvas) : null; const source = resolved ?? node; diff --git a/src/tailwind-map.ts b/src/tailwind-map.ts index 99d0b9c..dbd4b70 100644 --- a/src/tailwind-map.ts +++ b/src/tailwind-map.ts @@ -29,7 +29,7 @@ const BORDER_NON_COLOR = new Set(['collapse', 'separate', 'solid', 'dashed', 'do // Phase 32 slice C — text- and bg- utilities that are not colours (wrapping, // alignment, image placement, gradients): mapped as colours they became // $refs no token defines. -const TEXT_NON_COLOR = /^(balance|pretty|wrap|nowrap|ellipsis|clip|justify|start|end|shadow(-.+)?)$/; +const TEXT_NON_COLOR = /^(balance|pretty|wrap|nowrap|ellipsis|clip|justify|start|end|shadow(-.+)?|opacity-.+)$/; const BG_NON_COLOR = /^(cover|contain|auto|none|fixed|local|scroll|center|top|bottom|left|right|(left|right)-(top|bottom)|(no-)?repeat(-.+)?|clip-.+|origin-.+|blend-.+|gradient-.+|linear-.+|radial(-.+)?|conic(-.+)?|opacity-.+|size-.+|position-.+)$/; const TEXT_SIZES: Record = { xs: 12, sm: 14, base: 16, lg: 18, xl: 20, '2xl': 24, '3xl': 30, '4xl': 36, '5xl': 48, '6xl': 60, '7xl': 72, '8xl': 96, '9xl': 128 }; @@ -57,6 +57,9 @@ function colorValue(name: string, theme?: Record): string | null if (name === 'black') return '#000000'; if (name === 'transparent' || name === 'current' || name === 'inherit') return null; if (name.startsWith('[')) return null; // arbitrary value — computed styles cover it + // An opacity modifier (red-500/50) or a CSS variable (bg-(--x)): computed + // styles cover it; as a name it would be a $ref no token defines. + if (name.includes('/') || name.startsWith('(')) return null; if (name in TAILWIND_PALETTE && !(theme && name in theme)) return TAILWIND_PALETTE[name]; return `$${name}`; } @@ -153,11 +156,14 @@ export function classesToProps(classes: string[], theme?: Record if (m) { const rest = m[1]; if (rest in TEXT_SIZES) { props.fontSize = TEXT_SIZES[rest]; continue; } + // text-sm/6: a size with a line-height modifier (computed styles own the leading). + const size = rest.split('/')[0]; + if (rest.includes('/') && size in TEXT_SIZES) { props.fontSize = TEXT_SIZES[size]; continue; } if (rest === 'center' || rest === 'right' || rest === 'left') { if (rest !== 'left') props.textAlign = rest; continue; } - if (!TEXT_NON_COLOR.test(rest)) setColor('color', rest, cls); + if ((theme && rest in theme) || !TEXT_NON_COLOR.test(rest)) setColor('color', rest, cls); continue; } m = cls.match(/^font-(.+)$/); @@ -168,7 +174,7 @@ export function classesToProps(classes: string[], theme?: Record // ── background ── m = cls.match(/^bg-(.+)$/); - if (m) { if (!BG_NON_COLOR.test(m[1])) setColor('fill', m[1], cls); continue; } + if (m) { if ((theme && m[1] in theme) || !BG_NON_COLOR.test(m[1])) setColor('fill', m[1], cls); continue; } // ── misc ── if (cls === 'overflow-hidden') { props.overflow = 'hidden'; continue; } diff --git a/src/variables.ts b/src/variables.ts index c736cbe..ec5f070 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -294,7 +294,7 @@ function resolveStateStyle(v: DesignVariables): StateStyle { // FR-H1's chain: the renderer and the check never disagree. ring: c['focus-ring'] ?? c.accent ?? c.primary ?? CONTROL_FALLBACK.accent, onSurface: c['text-primary'] ?? CONTROL_FALLBACK.text, - surface: c['bg-surface'] ?? c.surface ?? c['bg-primary'] ?? c.background ?? CONTROL_FALLBACK.surface, + surface: SURFACE_CHAIN.map((n) => c[n]).find((x) => x !== undefined) ?? CONTROL_FALLBACK.surface, hover: unit(s.hover) ?? STATE_LAYERS.hover, focus: unit(s.focus) ?? STATE_LAYERS.focus, pressed: unit(s.pressed) ?? STATE_LAYERS.pressed, diff --git a/test/unit/test-tailwind-map.ts b/test/unit/test-tailwind-map.ts index 0b213c6..0056854 100644 --- a/test/unit/test-tailwind-map.ts +++ b/test/unit/test-tailwind-map.ts @@ -72,6 +72,10 @@ function el(partial: Partial & { tag: string }): RawDomNode { // Phase 32 slice C — nor are text- wrapping and bg- placement utilities. const { props: nc, tokenRefs: ncRefs } = classesToProps(['text-balance', 'text-nowrap', 'text-ellipsis', 'text-justify', 'bg-cover', 'bg-center', 'bg-no-repeat', 'bg-fixed', 'bg-gradient-to-r', 'bg-opacity-50']); expect('text- and bg- non-colour utilities map no colour', nc.color === undefined && nc.fill === undefined && ncRefs.length === 0, JSON.stringify(nc)); + const { props: mod, tokenRefs: modRefs } = classesToProps(['text-sm/6', 'bg-red-500/20', 'text-opacity-50', 'bg-(--my-var)']); + expect('a size with a line-height modifier is a size; opacity modifiers and CSS variables map no colour', mod.fontSize === 14 && mod.fill === undefined && mod.color === undefined && modRefs.length === 0, JSON.stringify(mod)); + const { props: th } = classesToProps(['bg-top', 'text-wrap'], { top: '#111111', wrap: '#222222' }); + expect('a theme colour named like a non-colour utility still maps', th.fill === '$top' && th.color === '$wrap', JSON.stringify(th)); const { props: tc } = classesToProps(['text-muted', 'bg-surface']); expect('twin: text- and bg- colours still map', tc.color === '$muted' && tc.fill === '$surface', JSON.stringify(tc)); const { props: bcolor } = classesToProps(['border-muted', 'border-red-500']); diff --git a/test/unit/test-unknown-token.ts b/test/unit/test-unknown-token.ts index e178805..820243a 100644 --- a/test/unit/test-unknown-token.ts +++ b/test/unit/test-unknown-token.ts @@ -201,9 +201,13 @@ b=I("${tp.nodeId}", {type: "instance", name: "b", componentId: "${tc.nodeId}", o check('twin: the same typo in two stored instances\' own overrides is two findings', about(await findings(twin), '$nope-own').length === 2); } { - const ladder: DesignVariables = { ...SYSTEM, spacing: { 'space-md': 16, 'space-lg': 24 } }; - const [m] = await findings(canvasWith([frame('a', { gap: '$space-m' })], ladder)); - check('a lone letter is a typo, not a ladder step: $space-m is fixed to $space-md', m?.fix?.op === 'U("a", { gap: "$space-md" })', m?.fix?.op); + // A lone letter is a rung of an s / m / l ladder, so it is never renamed + // across: a missed fix is cheaper than a wrong size. + const sml: DesignVariables = { ...SYSTEM, spacing: { 'space-md': 16 } }; + const [l] = await findings(canvasWith([frame('a', { gap: '$space-l' })], sml)); + check('$space-l on a ladder with only space-md is not renamed to it', !!l && !l.fix, l?.fix?.op); + const [m] = await findings(canvasWith([frame('a', { gap: '$space-m' })], { ...SYSTEM, spacing: { 'space-l': 24 } })); + check('$space-m on a ladder with only space-l is not renamed to it', !!m && !m.fix, m?.fix?.op); // Twins: real steps still never cross a rung. const [xl] = await findings(canvasWith([frame('a', { gap: '$space-2xl' })], { ...SYSTEM, spacing: { 'space-xl': 32 } })); check('twin: $space-2xl with only space-xl defined is not fixed (another rung)', !!xl && !xl.fix); @@ -216,7 +220,15 @@ b=I("${tp.nodeId}", {type: "instance", name: "b", componentId: "${tc.nodeId}", o parseAndExecute(canvas.root, `a=I("document", {type: "instance", name: "a", componentId: "${card.nodeId}"})`, canvas); const fs = await evaluateCanvas(canvas, { mode: 'fast', categories: ['structure'] }); const ids = fs.issues.filter((i) => i.rule === 'unknown-token').map((i) => `${i.nodeId}|${i.innerNodeId ?? ''}`); - check('an id-less node inside a component never reports an id ending in "undefined"', ids.length > 0 && ids.every((x) => !x.includes('undefined')), ids.join(', ')); + const instId = canvas.root.children!.find((n) => n.name === 'a')?.id; + check('an id-less node inside an instance is reported on the instance', fs.issues.some((i) => i.rule === 'unknown-token' && i.nodeId === instId && !i.fix), ids.join(', ')); + // Every rule keeps the instance for such a node (contrast too). + const contrast = canvasWith([]); + const [cc] = parseAndExecute(contrast.root, 'card=I("document", {type: "component", name: "Faint", fill: "#FFFFFF", children: [{type: "text", content: "faint words here", color: "#EEEEEE", fontSize: 12}]})', contrast); + const [ci] = parseAndExecute(contrast.root, `a=I("document", {type: "instance", name: "a", componentId: "${cc.nodeId}"})`, contrast); + const cev = await evaluateCanvas(contrast, { mode: 'fast', categories: ['color'] }); + const onInst = cev.issues.filter((i) => i.category === 'color' && i.severity === 'error' && i.nodeId === ci.nodeId); + check('an id-less text inside an instance keeps its contrast error on the instance', onInst.length >= 1, cev.issues.map((i) => i.nodeId).join(', ')); } // ── Verify round 1 (review): dotted derived names, aliases, messages ───────────── @@ -234,6 +246,10 @@ b=I("${tp.nodeId}", {type: "instance", name: "b", componentId: "${tc.nodeId}", o vars.dark = { elevation: { glow: [{ x: 0, y: 0, blur: 4, spread: 0, color: '#000' }] } }; const [f] = await findings(canvasWith([frame('a', { shadow: '$elevation.glow' })], vars)); check('a dark-only elevation names the elevation layer', /base elevation/.test(f?.suggestion ?? ''), f?.suggestion); + const night = structuredClone(SYSTEM); + night.dark = { colors: { night: '#000000' } }; + const [n] = await findings(canvasWith([frame('a', { fill: '$colors.night' })], night)); + check('a dark-only dotted colour names the bare token and the colors layer', n?.suggestion?.startsWith('Define "night" in the base colors') === true, n?.suggestion); } { const [f] = await findings(canvasWith([frame('a', { gap: '$space-mdd' })]));