diff --git a/README.md b/README.md index 1cb65ab..5a97a09 100644 --- a/README.md +++ b/README.md @@ -508,7 +508,7 @@ Get computed bounding boxes via browser rendering. | `nodeId` | string? | Root node to start from | | `maxDepth` | number? | Max depth (default 10) | -Returns `{ nodeId, x, y, width, height, children? }` per node — plus, on any node whose content exceeds its box, overflow data (`scrollWidth`/`clientWidth`/`scrollHeight`/`clientHeight` and an `ellipsis` flag for designed truncation): the same capture `canvas_stress` uses to detect clipping. On a primitive, `truncated: true` when one of its own labels is cut by its ellipsis, and `labels` (`[{ chars, scrollWidth, clientWidth }]`, one per own label, in order) on every `tabs` node and on any primitive with a cut label. Overlays (`tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer`) render in a layer after the root: from the root they are listed as its last children wherever they sit in the tree, at root coordinates, and a modal (or a drawer with `scrim: true`) carries `scrim: { x, y, width, height }`, the rect its scrim covers. +Returns `{ nodeId, x, y, width, height, children? }` per node (a node inside a component instance appears under its expanded id, `"/"`, so two instances never share an id; `batch_design` cannot address it, so edit the component or override the child on the instance) — plus, on any node whose content exceeds its box, overflow data (`scrollWidth`/`clientWidth`/`scrollHeight`/`clientHeight` and an `ellipsis` flag for designed truncation): the same capture `canvas_stress` uses to detect clipping. On a primitive, `truncated: true` when one of its own labels is cut by its ellipsis, and `labels` (`[{ chars, scrollWidth, clientWidth }]`, one per own label, in order) on every `tabs` node and on any primitive with a cut label. Overlays (`tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer`) render in a layer after the root: from the root they are listed as its last children wherever they sit in the tree, at root coordinates, and a modal (or a drawer with `scrim: true`) carries `scrim: { x, y, width, height }`, the rect its scrim covers. ### `generate_scale` @@ -859,7 +859,7 @@ Compare two canvases visually. Returns a diff image with changed regions highlig ### `get_feedback` / `resolve_feedback` -Point-and-tell feedback: comments anchored to a specific node (or to the canvas as a whole), stored on the canvas at `metadata.feedback` — plain JSON that travels with the canvas and is git-diffable in bound repos. `get_feedback` returns open entries, each with the comment, the anchor `nodeId`, and a **node snapshot** (`{ type, name, text }`) captured at comment time, so the agent can act without extra lookups; `orphaned: true` marks a comment whose node no longer exists (it stays open — the concern usually applies to the node's replacement). Omit `canvasId` to sweep every canvas in the current context. `resolve_feedback` closes entries with an optional one-line note saying what changed. **Open feedback blocks presenting**, same as open inspector comments — `canvas_list` rows and `canvas_evaluate` results surface an `openFeedback` count (and `init` reports the workspace total) so waiting comments are visible at every checkpoint. +Point-and-tell feedback: comments anchored to a specific node (or to the canvas as a whole), stored on the canvas at `metadata.feedback` — plain JSON that travels with the canvas and is git-diffable in bound repos. `get_feedback` returns open entries, each with the comment, the anchor `nodeId`, and a **node snapshot** (`{ type, name, text }`) captured at comment time, so the agent can act without extra lookups (a comment on a node inside a component instance anchors on the instance, so `nodeId` is always an id `batch_design` can address); `orphaned: true` marks a comment whose node no longer exists (it stays open — the concern usually applies to the node's replacement). Omit `canvasId` to sweep every canvas in the current context. `resolve_feedback` closes entries with an optional one-line note saying what changed. **Open feedback blocks presenting**, same as open inspector comments — `canvas_list` rows and `canvas_evaluate` results surface an `openFeedback` count (and `init` reports the workspace total) so waiting comments are visible at every checkpoint. Comments are authored in the viewer: toggle **Comment** in the detail-page toolbar, click any element in the preview (a breadcrumb lets you re-scope from the exact element to its card, section, or the whole page), and type the note. The **Feedback** inspector tab lists open and resolved comments with click-to-highlight, and shows the agent's resolution note as a reply. Entries added any other way (hand-edited JSON, a teammate's `git pull`) reach the running server just the same. @@ -936,6 +936,8 @@ Every result also carries a **`surface`** field: `{ type, device, source, rulesO Repeated findings fold in this result: three or more warnings or infos with the same severity, category, rule (or tell) and theme come back as one entry when they also share their message — on its shape for members that carry a fix (each fix op holds its node's specifics), word for word apart from quoted node text for members without one. The entry keeps the first one's message and adds `nodeIds` (distinct), `count` and, when they had fixes, `fixes: [{ nodeId, op }]`. Errors never fold, and `canvas_autofix` works from the unfolded list. +Every check reads the canvas as it renders: each component instance is expanded into its component, with the instance's props and overrides applied, and the design system is resolved inside it. A finding on a node inside an instance reports the instance in `nodeId` (the stored node, fixed in the component or with an override). It reports the inner node in `innerNodeId`, as `"/"`, the id `snapshot_layout` and `canvas_stress` give it. Its message names the component, and it carries no `fix`, since `batch_design` cannot address an expanded id. + Whenever the `coverage` category runs on a **base** canvas, the result also carries a **`coverage`** field: `{ dataBearing, states, missing }` — whether the screen carries data-bearing content, which state variants (`canvas_add_variant`) already exist, and which demanded states are missing. It's absent on variant canvases (a variant *is* a designed state, so it doesn't demand states of itself). | Param | Type | Description | @@ -985,7 +987,7 @@ The weights are relative, not points out of 100. Each category scores 0–100, a } ``` -An issue produced by a ruleset rule also carries `rule` (its id, e.g. `"mobile-touch-target"`). +An issue produced by a ruleset rule also carries `rule` (its id, e.g. `"mobile-touch-target"`). An issue on a node inside a component instance has `nodeId` set to the instance and also carries `innerNodeId` (the expanded id, `"/"`) and no `fix`; its message names the component. **With `mode: "llm"`**, the vision model scores a **fixed rubric** — five axes, each 1–5 with a rationale — instead of one opaque number. The verdict is stamped on the canvas (`metadata.critique`) and the per-project build log so quality is auditable over time. Add `floor` (1–5, default 3, or `FRAMESMITH_CRITIQUE_FLOOR`) to set the per-axis threshold that trips `needsRevision`. **Without an `ANTHROPIC_API_KEY` / `OPENAI_API_KEY`, the call doesn't fail** — the full heuristic result still returns with an `llmNote` explaining the critique was skipped, and the heuristic directive alone decides whether the design is ready. @@ -1080,7 +1082,7 @@ Content stress test — does the design survive real data? Re-renders the canvas | `empty` | Detected tables lose their data rows (and runs of two or more consecutive `list-row`s are emptied; on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row`, and card grids) | | `many` | Data rows ×3 (and `list-row` runs ×3; on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row`, and card grids, a grid of three or more same-shaped children). Copies drop `active`, so a tripled list keeps one current row | -Finding kinds: `clip` (content cut off — *info* when a designed `text-overflow: ellipsis` is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet, a `drawer`, or any frame, `popover` or `menu` with `overflow: "auto"` (an app pane, a popover whose body scrolls) scrolls and is never a clip, while its horizontal overflow still is; *warning* otherwise), `overflow-x` (a node escapes its parent box or the canvas), `layout-shift` (an **untouched** node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent are exempt). Only **new** breakage counts: anything already clipping at baseline is the design's standing state. Tables are found with the same inventory drift and coverage use; component instances are expanded first. +Finding kinds: `clip` (content cut off — *info* when a designed `text-overflow: ellipsis` is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet, a `drawer`, or any frame, `popover` or `menu` with `overflow: "auto"` (an app pane, a popover whose body scrolls) scrolls and is never a clip, while its horizontal overflow still is; *warning* otherwise), `overflow-x` (a node escapes its parent box or the canvas), `layout-shift` (an **untouched** node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent are exempt). Only **new** breakage counts: anything already clipping at baseline is the design's standing state. Tables are found with the same inventory drift and coverage use; component instances are expanded first, and a finding on a node inside one names it by its expanded id, `"/"` (the id `snapshot_layout` uses; edit the component or override the child on the instance). | Param | Type | Description | |-------|------|-------------| diff --git a/VISION.md b/VISION.md index 1925ce0..f5c3e0b 100644 --- a/VISION.md +++ b/VISION.md @@ -572,7 +572,7 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 - [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 -- [ ] Follow-up — a disabled control inside a component instance renders undimmed, because instances render after variable resolution (`resolveInstance`); resolve instance subtrees too, so `disabled` and `state` dim inside components as they do outside +- [x] Follow-up — a disabled control inside a component instance renders undimmed, because instances render after variable resolution (`resolveInstance`); resolve instance subtrees too, so `disabled` and `state` dim inside components as they do outside (done in Phase 32 slice B) - [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 @@ -588,7 +588,7 @@ _Full spec-driven breakdown in [`docs/specs/PHASE-31-SPEC.md`](docs/specs/PHASE- Phases 30 and 31 closed with seven follow-ups open, and five of them are quiet false passes: evaluate says READY on a disabled button that renders undimmed inside a component, on a misspelt `$token` the renderer drops, on a `select` border at 1.46:1, and on a phone screen whose links, text inputs and dialogs are never measured. Reproducing them found more: contrast and spacing never look inside a component instance at all, and seeded dark tints and `danger` survive a light preset. This phase clears every follow-up, and first moves the 140 root-level tests into folders that set their tier, so the fixes land in the new layout. - [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 -- [ ] 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 +- [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 - [ ] 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 f9e477c..563a21a 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -99,7 +99,7 @@ Two terms the rules share. A **pane** is a frame that scrolls on its own (`overf - **Warnings**: a second `modal` on one canvas (one dialog at a time; design the other as its own variant); a `tooltip` with children (they never render); inside a modal, a detected table of more than ten body rows (a header row does not count) or a frame with `overflow: "auto"` that renders wider than the modal or scrolls sideways (a dialog is for a short decision, not for browsing data); an overlay whose box leaves the viewport; and each `popover` or `menu` on a canvas that holds a `modal`, or a `drawer` with `scrim: true`, because it renders under the scrim and looks disabled. - **Infos**: a second `toast`; a `toast` with `tone: "danger"` (a transient toast is easy to miss, so put the error inline or in a banner); an `anchor` that names no node, or a node that is not a clickable primitive or control (a frame cannot be clicked). An overlay with no `anchor` raises nothing. Each finding is its own entry, so a second toast with `tone: "danger"` gets two infos. -The last four rules judge [element states](#element-states-a-property-not-a-variant) without anyone drawing them. Like the rules above they run on desktop-app canvases only. They are in the `color` category and run in each theme the canvas ships, so a canvas with a dark layer is checked twice and its dark findings carry `theme: "dark"` (fix those in the dark token layer). A dark finding that would only repeat the light one (the colours are literals, so the dark layer cannot change them) is dropped. When the targets sit inside a component instance, the suggestion says so: the design system does not reach them there, so the fix is on the component's own nodes. They compute what the renderer draws for every target: each clickable primitive and control, each item of a `tabs`, `tab-bar`, `nav-bar`, `modal` or `toast`, and a modal's close button. WCAG 1.4.11 asks 3:1 of each of them, and fast and detailed mode give the same answer. A target inside a component instance renders without the design system (instances are drawn unresolved), so it is judged in the renderer's defaults, its focus ring `#2563EB`, and reported on the instance. A target's own `opacity` dims what it draws; an ancestor's is not modelled. A gradient or a fill the checker cannot read behind a target skips it silently in the last three rules (the first one lists it in an info). +The last four rules judge [element states](#element-states-a-property-not-a-variant) without anyone drawing them. Like the rules above they run on desktop-app canvases only. They are in the `color` category and run in each theme the canvas ships, so a canvas with a dark layer is checked twice and its dark findings carry `theme: "dark"` (fix those in the dark token layer). A dark finding that would only repeat the light one (the colours are literals, so the dark layer cannot change them) is dropped. When the targets sit inside a component instance, the finding names the instance and its component, and the fix goes in the component or an override on the instance. They compute what the renderer draws for every target: each clickable primitive and control, each item of a `tabs`, `tab-bar`, `nav-bar`, `modal` or `toast`, and a modal's close button. WCAG 1.4.11 asks 3:1 of each of them, and fast and detailed mode give the same answer. A target inside a component instance is judged as it renders: the instance's overrides applied and the design system resolved inside it, so its ring is the canvas's `$focus-ring` like any other. A target's own `opacity` dims what it draws; an ancestor's is not modelled. A gradient or a fill the checker cannot read behind a target skips it silently in the last three rules (the first one lists it in an info). - **`desktop-app-focus-visible`** (color, **error**). A target's focus ring (`$focus-ring`, else `$accent`, `$primary`, `#2563EB`) below 3:1 against the pixels it covers when the target is not focused. For the ring drawn outside the box, that is the backdrop behind the target. For a tab or a tab-bar item, whose ring is drawn inside, it is the item's own fill over that backdrop: only a contained tab's active tab has one, so a line tab, an inactive contained tab and a tab-bar item meet the backdrop too. Targets that share a ring and a backdrop make one error: `count` is the number of targets (each tab counts), and `nodeIds` lists each node once (a tab, a tab-bar item, a nav-bar action, a modal's actions and close button and a toast's action report their host). A disabled target draws no ring and is skipped. When the backdrop (or a tab's own fill) is a gradient or a fill the checker cannot read (a named colour, `hsl()`, a translucent overlay), or the ring itself does not parse, one **info** per theme lists those targets. `generate_design_system` picks `$focus-ring` to clear 3:1 against every `bg-*` and `*-tint` token, so a generated system's targets pass on any of those surfaces. - **`desktop-app-state-contrast`** (color, **warning**). The indicator of an active `nav-item` (its 2px bar in `iconColor`) or of an active tab of a line `tabs` (its underline) below 3:1 against the active fill over the backdrop (the backdrop alone when the item has no fill; a line tab never has one), at rest or with the hover layer over it, since hover must not hide the selection. A `tree-row` and a contained tab draw no indicator mark (their active cue is the fill and the heavier weight), so nothing is measured on them. @@ -173,6 +173,7 @@ Draw an element state only when a human should see it: a states sheet that shows - **Focus** also draws a 2px `$focus-ring` outline at a 2px gap, so the ring meets only the backdrop, never a brand fill; without a `$focus-ring` token it is `$accent`, then `$primary`, then `#2563EB`. A tab and a tab-bar item draw it inside their box, since the tablist and a floating bar clip. The live viewer's keyboard focus draws the same ring. - **Disabled.** When the `state` tokens set `disabledContent` or `disabledContainer` (`generate_design_system` writes both; a lone one takes the other's Material value, 0.38 or 0.12), a disabled target renders in `$text-primary`: its content at `disabledContent` and a drawn fill or border at `disabledContainer`, so a disabled primary reads as a grey version of itself on light and dark. A check mark, a toggle knob and a badge numeral take `$bg-surface`, so they show on that grey. A fill that paints nothing (`transparent`, `none`, a zero alpha) stays clear. When neither is set it renders at 0.5 opacity in its own colours, as it did before element states existed. An authored `opacity` wins over both. `disabled: true` means disabled whatever `state` says (`disabled: false` with `state: "disabled"` is disabled too), and a `tabs` node's own `disabled` (or `state: "disabled"`) disables every tab. `state: "rest"` is the default and changes nothing. - **Disabled is the same fact either way.** `state: "disabled"` leaves the tab order (`tabindex="-1"`, `aria-disabled`) and leaves the 24px census and the primary count exactly as `disabled: true` does. The mobile 44px census, which never exempted a disabled target, still measures it. +- **Inside a component.** An instance renders its component with the instance's props and overrides applied and the design system resolved inside it, so `state` or `disabled` on a component's node, or set through an override (`overrides: { "Save": { disabled: true } }`), draws exactly as it does outside a component. - **`active`, `checked` and `expanded` combine with `state`**: a hovered active nav-item keeps its tint, bar and weight under the layer. A states sheet for a toolbar button, a tablist and a sidebar row: @@ -389,6 +390,8 @@ A design language is a set of COMMITTED choices, and `generate_design_system` ma 3. Stamp more copies: `I("parent", { type: "instance", componentId, overrides: { "Title": { content: "Settings" } } })` — overrides match def children **by name**; instance-level props (width, opacity) override the def root. 4. Cross-canvas: `copy_nodes({ fromCanvasId, nodeIds: [instanceId], toCanvasId })` — the component def travels with the copy, so 15 sibling screens share one shell definition. +**An instance is judged as it renders.** Rendering and every `canvas_evaluate` check read one tree: each instance expanded into its component with the instance's props and overrides applied, then the design system resolved over it. So a `disabled` button inside a card instance dims, and a low-contrast label inside it is an error like any other. A node inside an instance has an expanded id, `"/"`, so two instances never share one. `snapshot_layout` and `canvas_stress` name the node by it. A finding on such a node reports the instance in `nodeId`, the inner node in `innerNodeId` and the component in its message, with no fix op: `batch_design` cannot address an expanded id, so fix the component, or override the child on the instance. A viewer comment on a node inside an instance anchors on the instance. + `canvas_evaluate`'s "no component instances found" advisory is the nudge; these two tools are the action. Current sharp edge: `batch_design` ops address the **tree**, so they can't edit a def after promotion — a def child's id no longer resolves (those nodes left the tree), and `U(instanceId, ...)` sets instance-level props, not the def. To revise a component: build the new version as a plain subtree, `create_component` it, point instances at the new `componentId` with `U()`, and delete the scaffold. ## Custom fonts @@ -486,7 +489,7 @@ The happy path of one static frame with ideal data is half a design. Real UX liv **The evaluator demands them.** The `coverage` category warns — directive-blocking — when a base canvas carries data-bearing content with no designed states: a detected table demands `empty` + `loading`; a form (3+ input controls: toggles, checkboxes, radios, selects and `text-input`s outside tables, on every type, so an inspector of three text fields counts too) demands `error`. (Table detection requires three matching horizontal rows — two stacked rows are a layout, not data — so the rare header-plus-one-row table goes undetected; name the frame `Table` to claim the shape explicitly. A list whose every row leads with an icon, a dot or a small image is navigation and never detects.) Variant canvases and non-data screens are silent. The result's `coverage: { dataBearing, states, missing }` tells you where you stand, and `canvas_list` shows the designed states per screen. -**Then stress it.** `canvas_stress` re-renders the canvas under hostile-but-realistic content — `long-text` (×2.2 + an unbroken German compound), `i18n` (×1.4), `big-numbers` (`9` → `999+`, `$1.5M` → `$1,520,847.33`), `empty`, `many` (rows ×3; tables and runs of `list-row`s on every type, and on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row` and card grids, a grid of three or more same-shaped children; a tripled list keeps one active row) — and reports what broke, by node id: `clip` (info when a designed ellipsis is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet, a `drawer`, or any frame, `popover` or `menu` with `overflow: "auto"` scrolls and is never a clip, while its horizontal overflow still is; warning otherwise), `overflow-x`, `layout-shift` (an untouched node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent, like a full-height sidebar next to a growing table, are all exempt). Only *new* breakage counts. Fix findings with the [width strategies](#width-strategies) above — fluid widths, `minWidth` or `minHeight` floors, wrapping — or give a must-stay-single-line label `textOverflow: "ellipsis"` (the designed-truncation property: the clip downgrades to info because truncating is the design) — and re-run until `CLEAN`. A data screen goes to the user with its states designed and a `CLEAN` stress verdict, the same way it goes with a >95 score. `canvas_evaluate` holds you to it: once stress has recorded a verdict, the evaluate result carries a `stress` field (`{ verdict, warnings, type, current }` — `current` is false after an edit or a type change since the run), and a `FRAGILE` verdict keeps the directive `NOT READY` until a full `CLEAN` run (all five perturbations) replaces it — a subset run can record `FRAGILE` but never clear it. The verdict lives in server memory, so a restart forgets it. +**Then stress it.** `canvas_stress` re-renders the canvas under hostile-but-realistic content — `long-text` (×2.2 + an unbroken German compound), `i18n` (×1.4), `big-numbers` (`9` → `999+`, `$1.5M` → `$1,520,847.33`), `empty`, `many` (rows ×3; tables and runs of `list-row`s on every type, and on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row` and card grids, a grid of three or more same-shaped children; a tripled list keeps one active row) — and reports what broke, by node id: `clip` (info when a designed ellipsis is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet, a `drawer`, or any frame, `popover` or `menu` with `overflow: "auto"` scrolls and is never a clip, while its horizontal overflow still is; warning otherwise), `overflow-x`, `layout-shift` (an untouched node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent, like a full-height sidebar next to a growing table, are all exempt). Only *new* breakage counts. Fix findings with the [width strategies](#width-strategies) above — fluid widths, `minWidth` or `minHeight` floors, wrapping — or give a must-stay-single-line label `textOverflow: "ellipsis"` (the designed-truncation property: the clip downgrades to info because truncating is the design) — and re-run until `CLEAN`. A data screen goes to the user with its states designed and a `CLEAN` stress verdict, the same way it goes with a >95 score. `canvas_evaluate` holds you to it: once stress has recorded a verdict, the evaluate result carries a `stress` field (`{ verdict, warnings, type, current }` — `current` is false after an edit or a type change since the run), and a `FRAGILE` verdict keeps the directive `NOT READY` until a full `CLEAN` run (all five perturbations) replaces it — a subset run can record `FRAGILE` but never clear it. The verdict lives in server memory, so a restart forgets it. Component instances are stressed as they render, and a finding on a node inside one names it by its expanded id, `"/"`: edit the component, or override the child on the instance. ## Reviewing the set diff --git a/docs/specs/PHASE-32-SPEC.md b/docs/specs/PHASE-32-SPEC.md index e524a7c..e54cf3a 100644 --- a/docs/specs/PHASE-32-SPEC.md +++ b/docs/specs/PHASE-32-SPEC.md @@ -115,6 +115,21 @@ And one is housekeeping the follow-ups will land in. 140 tests and `test-env.ts` - `evaluate.ts`: `buildTreeContext` reads the expanded, resolved tree; the separate expansions fold into it; `reportOnInstances` (`:2477`) applies to every finding and adds `innerNodeId`; fixes are gated on stored ids as `checkUnknownIcons` does (`:884`). - `addFeedback` (`src/feedback.ts:44`) and the viewer's click chain map expanded ids to the owner. +**Slice B — contracts pinned before build (2026-11-20; frozen at the commit that adds this block).** No pre-freeze verifier: the slice adds no rule and no gate over generated output; it changes which tree existing rules read. +- **K1: the helper.** `expandTree(root, canvas, tokens?, { theme? })` in a new `src/expand.ts` returns `{ root, owners }`. It expands every instance whose component exists (`resolveInstance` moves there from `renderer.ts`: the instance's own props over the component root, then named overrides), then resolves tokens over the whole tree when `tokens` is given; without them the tree stays raw. Ids are `expandForRules`' scheme: a node inside an instance is `/`, nesting as `//`; the instance root keeps its id. Stored ids never contain `/`, so the first segment is the outermost instance (`storedId`), and `owners` maps every id inside an instance to it. +- **K2: the renderer.** `renderToHtml` expands through the helper, with `getCanvasTokens(canvas)` and the new `RenderOptions.theme`, when it is given a canvas and the tree still holds an expandable instance; any other tree renders as given (no resolution added). Its own instance handling (`renderNode`, `collectRendererHints`, the `chromeReservation` expander) goes. Every `src/` caller that resolves today calls the helper instead: `prepareRender`, the viewer's canvas HTML, `canvas_stress`, `evaluateCanvas`. Resolution is idempotent (every default fills only what is unset), so a test that resolves before rendering still renders the same. +- **K3: what evaluate reads.** The resolved expanded tree feeds contrast (both themes), typography, consistency, usability, the state checks and every type rule; the raw expanded tree feeds spacing, the cliché check's literal-or-token reads, the icon and coverage checks, and the type rules' raw lookups. The stored tree keeps four jobs: the empty-canvas check, the stats (node counts and component reuse, which needs the instance nodes), `checkStructure` and the token census (slice C changes the census). Detailed mode always renders the expanded tree, so rects and findings share ids on every type. +- **K4: findings.** One pass at the end applies to every category: a finding whose `nodeId` is inside an instance gets `nodeId` = the owning instance, `nodeName` = its name, `innerNodeId` = the expanded id, the suffix ` (inside instance "" of component "": fix it in the component, or with an override on the instance)`, and no `fix`. A grouped finding maps each of `nodeIds` to its owner as today. A finding on an instance root keeps its id, no `innerNodeId`. The state checks' "the design system never reaches them" advice is removed. +- **K5: expanders retired.** `expandForRules`, `instanceIdsOf` (`evaluate.ts`) and `expandInstances` (`drift.ts`) go; drift, the CLI and `canvas_check_drift` call the helper without tokens. +- **K6: comments.** `addFeedback` stores a comment given an expanded id on its `storedId` when the expanded id is not in the stored tree (the snapshot is the instance's). The viewer's click chain maps each id to its `storedId` and drops repeats, so the popover offers the instance. +- **K7: acceptance tests.** A new `test/unit/test-one-tree.ts` holds FR-B1's render clause (a `disabled` button inside an instance renders with the same opacity and colours as outside, with and without `state` tokens, compared on the `renderToHtml` output) and FR-B2's (1.14:1 text inside an instance: one contrast error, `nodeId` the instance, `innerNodeId` the text's expanded id, no fix; `canvas_autofix` emits no op naming an expanded id; feedback on the expanded id lands on the instance). A new `test/browser/test-one-tree-layout.ts` holds the layout clauses (`snapshot_layout` gives distinct ids for one child in two instances; `canvas_stress` and `snapshot_layout` name the same id for it). + +**Slice B — as built (recorded 2026-11-20).** Decisions the pinned contracts did not settle: +- **L1: unknown icons stay one per origin.** Expanded ids made two instances of one component give two findings for one bad icon. The icon check now dedupes by the node's id inside its component (the last segment of the expanded id), the icon slot and the name, so the same defect is reported once, on the first instance, as before; an override that sets a different icon on one instance is a finding of its own. +- **L2: pins that moved, each to the behaviour this slice specifies.** `test-state-checks.ts`: R2 (a ring inside a component is now the design system's `$focus-ring`, with a twin that passes), V4 (a checkbox inside an instance draws `$border-strong` and passes), the grouped-finding message, and the two 3b instance pins (an instance root is judged with the tokens and reported on its own id; an info names the instance and keeps its own advice). `test-mobile-rules-detailed.ts`: a component's `$space-*` spacer now resolves in detailed mode, with a 4px twin that still fails. `test-components.ts`: promotion renders the same markup once the `/` id prefix is removed. `test-unknown-icons.ts`: the message names the component (L1). `test-element-states.ts` and `test-overlays.ts` keep their raw-tree fallback pins, relabelled: an unresolved tree is now a test's raw tree, never a component. No pattern gate moved: `test-patterns.ts`, `test-patterns-mobile.ts` and `test-patterns-desktop.ts` pass at their bars. +- **L3: verify round 1 fixes.** (a) L1's dedupe hid a stored icon behind a component child with the same id, which lost the stored icon's autofix; a stored node is now its own origin. (b) `addFeedback` fell back to the first segment of any id with a `/`, so `page/nonexistent` landed on `page`; it now falls back only when the id is in the canvas's expansion. (c) `export` with an expanded node id wrote to a subfolder named after the instance and failed; the file name replaces `/` with `-`. (d) A component holding an instance of itself overflowed the stack (on master too); `expandTree` now leaves an instance of a component it is already expanding unexpanded. (e) `RenderOptions.theme` says a dark render of an unexpanded tree must expand first or pass the theme (no `src/` caller does otherwise). Tests for (a), (b) and (d) are in `test-one-tree.ts`. + + **Slice C: tokens (FR-C1 to FR-C6).** - `unknown-token` beside `checkUnknownIcons` (`evaluate.ts:756`, `:838`), reusing its candidate shape; a prop-to-kind table covering the top-level and nested props the resolver walks (`variables.ts:56-118`), shared with FR-C2. - One copy-prop constant, read by `deepResolve`, the token census and `unknown-token`. diff --git a/src/cli.ts b/src/cli.ts index 0d0861c..37479fd 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -20,7 +20,8 @@ import { detectBinding, projectStartDir, readWorkspaceFile, setRepoBackend, migr import { loadPersistedWorkspaces, ensureDefaultWorkspaceAndProject, loadRepoWorkspace } from './workspaces.js'; import { loadPersistedCanvases, listCanvases, getCanvas } from './scene-graph.js'; import { canvasVersionHash, checkVersionHash } from './version.js'; -import { computeStructuralDrift, expandInstances } from './drift.js'; +import { computeStructuralDrift } from './drift.js'; +import { expandTree } from './expand.js'; import type { Canvas } from './types.js'; interface CliFlags { @@ -170,7 +171,7 @@ export async function runCli(argv: string[]): Promise { const w = flags.viewport?.width ?? (typeof canvas.root.width === 'number' ? canvas.root.width : 1440); const h = flags.viewport?.height ?? (typeof canvas.root.height === 'number' ? canvas.root.height : 900); const imported = await importUrl(flags.url, { viewport: { width: w, height: h }, selector: flags.selector, waitFor: flags.waitFor }); - const drift = computeStructuralDrift(expandInstances(canvas.root, canvas), imported.root); + const drift = computeStructuralDrift(expandTree(canvas.root, canvas).root, imported.root); const versionHash = canvasVersionHash(canvas); if (flags.json) { process.stdout.write(JSON.stringify({ canvasId: canvas.id, name: canvas.name, versionHash, url: flags.url, ...drift }, null, 2) + '\n'); diff --git a/src/components.ts b/src/components.ts index 0fddcee..98ff11c 100644 --- a/src/components.ts +++ b/src/components.ts @@ -1,7 +1,7 @@ // Phase 22 slice E (#130) — component ergonomics. // // The render machinery for components has existed since v1 (canvas.components -// + resolveInstance in renderer.ts, override-by-child-name), but nothing in +// + resolveInstance in expand.ts, override-by-child-name), but nothing in // the authoring surface *created* one from existing work: canvas_evaluate // scolded "no component instances found" while the only path was hand-building // a type:"component" node. Two pure operations close the gap: diff --git a/src/drift.ts b/src/drift.ts index d531fcd..c8abc18 100644 --- a/src/drift.ts +++ b/src/drift.ts @@ -9,10 +9,9 @@ // styles, geometry, or nesting depth, because those are exactly what the // import pipeline normalizes away. Pure and fixture-testable without Chrome; // the caller supplies both trees (the canvas side instance-expanded via -// expandInstances, the page side from an ephemeral importUrl). +// expandTree in src/expand.ts, the page side from an ephemeral importUrl). -import type { Canvas, SceneNode } from './types.js'; -import { resolveInstance } from './renderer.js'; +import type { SceneNode } from './types.js'; export type DriftFindingKind = 'missing-in-page' | 'missing-in-canvas' | 'control-mismatch' | 'table-mismatch'; @@ -259,22 +258,6 @@ export function extractInventory(root: SceneNode): Inventory { return inv; } -/** Expand instance nodes against the canvas's component registry so the - * inventory sees through stamped components (app shells). Unknown componentIds - * pass through unexpanded. */ -export function expandInstances(root: SceneNode, canvas: Canvas): SceneNode { - const clone = structuredClone(root); - function walk(node: SceneNode): SceneNode { - if (node.type === 'instance' && node.componentId) { - const resolved = resolveInstance(node, canvas); - if (resolved) return walk(resolved); - } - if (node.children) node.children = node.children.map(walk); - return node; - } - return walk(clone); -} - // ── comparison ────────────────────────────────────────────────────────────── const controlNoun = (c: ControlEntry): string => diff --git a/src/evaluate.ts b/src/evaluate.ts index b3b0db1..fe116f7 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -1,13 +1,13 @@ import type { Canvas, SceneNode, DesignVariables, TabItem } from './types.js'; -import { resolveVariables } from './variables.js'; import { getCanvasTokens } from './workspaces.js'; -import { renderToHtml, resolveInstance, type RenderOptions } from './renderer.js'; +import { renderToHtml, type RenderOptions } from './renderer.js'; +import { expandTree } from './expand.js'; import { computeLayout, type LayoutRect } from './screenshot.js'; import { checkCurrent, checkDesktopArtboard, checkHandbuiltTargetsApp, checkIconLabels, checkOverlays, checkPrimaryCount, checkRowRhythm, checkTruncation, checkTypeLadder, type DesktopContext, } from './desktop-app-rules.js'; -import { extractInventory, expandInstances, isDataLike } from './drift.js'; +import { extractInventory, isDataLike } from './drift.js'; import { getIconSvg, parseIconRef } from './icons.js'; import { backdropBehind, composite, contrastRatio, parseAlpha, parseColor, rgbToHex } from './color-math.js'; import { checkStates, STATE_RULES } from './state-checks.js'; @@ -50,6 +50,10 @@ export interface EvaluationIssue { severity: IssueSeverity; nodeId: string; nodeName?: string; + /** Phase 32 slice B — on a finding about a node inside a component + * instance: the node's expanded id (`/`), while + * `nodeId` names the instance. Not addressable by batch_design. */ + innerNodeId?: string; /** Phase 31 FR-A7 — on a FOLDED finding (canvas_evaluate's serialised result * only): every node the repeated finding names, nodeId being the first. */ nodeIds?: string[]; @@ -837,8 +841,9 @@ function iconCandidates(ref: string, style: SceneNode['iconStyle']): string[] { function checkUnknownIcons(canvas: Canvas): EvaluationIssue[] { // Instance-expanded so icons inside stamped components are checked too; - // ids that aren't in the canvas tree itself live in a component definition. - const expanded = expandInstances(canvas.root, canvas); + // ids that aren't in the canvas tree itself live in a component (the + // findings pass in evaluateCanvas names the instance). + const expanded = expandTree(canvas.root, canvas).root; const ownIds = new Set(); (function walk(n: SceneNode) { ownIds.add(n.id); n.children?.forEach(walk); })(canvas.root); @@ -857,15 +862,18 @@ function checkUnknownIcons(canvas: Canvas): EvaluationIssue[] { const issues: EvaluationIssue[] = []; const seen = new Set(); for (const { node, path, ref: rawRef, flat, required } of icons) { - const key = `${node.id}\u0000${path}`; + // One finding per origin: the same icon in a component, seen through two + // instances (expanded ids /), is one defect with one fix. + // A stored node is its own origin, so it never hides behind an instance. + const origin = node.id.includes('/') ? `component:${node.id.slice(node.id.lastIndexOf('/') + 1)}` : node.id; + const key = `${origin}\u0000${path}\u0000${rawRef}`; if (seen.has(key)) continue; seen.add(key); const ref = rawRef.trim(); if (ref && getIconSvg(ref, 24, undefined, node.iconStyle)) continue; if (!ref && !required) continue; - const where = (ownIds.has(node.id) ? '' : ' (inside a component — fix it in the component definition)') - + (node.type === 'icon' ? '' : ` (${node.type} ${path})`); + const where = node.type === 'icon' ? '' : ` (${node.type} ${path})`; if (!ref) { issues.push({ category: 'structure', @@ -2355,7 +2363,7 @@ function checkCoverage(canvas: Canvas, designedStates: string[]): { result: Chec // shipped loading screen flashes real-looking data next to placeholders. if (canvas.metadata?.variant) { if (canvas.metadata.variant.state === 'loading') { - const root = expandInstances(canvas.root, canvas); + const root = expandTree(canvas.root, canvas).root; const hasSkeleton = (n: SceneNode): boolean => n.type === 'skeleton' || (n.children ?? []).some(hasSkeleton); if (hasSkeleton(root)) { @@ -2401,7 +2409,7 @@ function checkCoverage(canvas: Canvas, designedStates: string[]): { result: Chec return { result: { score: 100, issues: [] } }; } - const expanded = expandInstances(canvas.root, canvas); + const expanded = expandTree(canvas.root, canvas).root; const inv: ReturnType & { textInputs?: number } = extractInventory(expanded); inv.textInputs = countTextInputs(expanded, new Set(inv.tables.map((t) => t.nodeId))); const demanded = new Map(); // state → noun that demanded it @@ -2424,73 +2432,48 @@ function checkCoverage(canvas: Canvas, designedStates: string[]): { result: Chec }; } -/** Phase 30 slice D — the tree with every instance expanded into what it - * renders, for the mobile rules. Nodes inside an instance get ids prefixed by - * the instance path (`inst/child`), so two instances of one component never - * share an id, and `owners` maps each such id to the outermost instance. */ -function expandForRules(root: SceneNode, canvas: Canvas): { root: SceneNode; owners: Map } { - const owners = new Map(); - const walk = (node: SceneNode, owner: SceneNode | undefined, prefix: string): SceneNode => { - const id = owner ? prefix + node.id : node.id; - if (owner) owners.set(id, owner); - const resolved = node.type === 'instance' && node.componentId ? resolveInstance(node, canvas) : null; - if (resolved) { - const childPrefix = `${prefix}${node.id}/`; - return { ...resolved, id, children: resolved.children?.map((c) => walk(c, owner ?? node, childPrefix)) }; - } - return { ...node, id, children: node.children?.map((c) => walk(c, owner, prefix)) }; - }; - return { root: walk(root, undefined, ''), owners }; -} - -/** Re-point findings on nodes inside an instance at the instance (the - * component holds the node), naming the inner node. */ -/** Phase 31 slice H — the state checks' two themes, cleaned up. A dark - * finding that says what the light one says (the same colours: they come - * from literals, not tokens) is dropped, since the dark token layer cannot - * change it. A finding about targets inside a component instance says the - * design system never reaches them (instances render unresolved). */ -function stateFindings(light: EvaluationIssue[], dark: EvaluationIssue[], owners: Map, instanceIds: Set): EvaluationIssue[] { +/** Phase 31 slice H — the state checks' two themes: a dark finding that says + * what the light one says (the same colours: they come from literals, not + * tokens) is dropped, since the dark token layer cannot change it. */ +function stateFindings(light: EvaluationIssue[], dark: EvaluationIssue[]): EvaluationIssue[] { const key = (i: EvaluationIssue) => `${i.rule}|${i.severity}|${(i.nodeIds ?? [i.nodeId]).join(',')}|${i.message}`; const seen = new Set(light.map(key)); - const kept = [...light, ...dark.filter((i) => !seen.has(key({ ...i, message: i.message.replace(' in the dark theme', '') })))]; - const advice = 'These targets sit inside a component instance, which renders without the design system (its tokens and the dark layer never reach them): set the colours on the component\'s own nodes, or move the targets out of the component.'; - return kept.map((i) => { - const ids = i.nodeIds ?? [i.nodeId]; - // An instance whose component root is itself the target keeps its own id - // (owners maps only the nodes under it), so it is named here. - const roots = ids.filter((id) => instanceIds.has(id) && !owners.has(id)); - if (!roots.length && !ids.some((id) => owners.has(id))) return i; - const note = roots.length && !ids.some((id) => owners.has(id)) ? ` (${roots.length === 1 ? 'an instance' : 'instances'} — fix ${roots.length === 1 ? 'it in its component' : 'them in their components'})` : ''; - // An info keeps its own advice (a ring to check by eye) and gains this. - return { ...i, message: `${i.message}${note}`, suggestion: i.severity === 'info' && i.suggestion ? `${i.suggestion} ${advice}` : advice }; - }); -} - -/** Every instance node's id in a tree (the ids an expanded instance root keeps). */ -function instanceIdsOf(root: SceneNode): Set { - const out = new Set(); - (function walk(n: SceneNode) { if (n.type === 'instance') out.add(n.id); n.children?.forEach(walk); })(root); - return out; + return [...light, ...dark.filter((i) => !seen.has(key({ ...i, message: i.message.replace(' in the dark theme', '') })))]; } -function reportOnInstances(issues: EvaluationIssue[], owners: Map): EvaluationIssue[] { +/** Phase 32 slice B (K4) — a finding on a node inside a component instance is + * reported on the instance, the one stored node that holds it: `nodeId` names + * the instance, `innerNodeId` the expanded node, and the message the + * component. Its fix is dropped, since batch_design cannot address the node. + * A grouped finding maps each of its nodes to its owner. */ +function reportOnInstances(issues: EvaluationIssue[], owners: Map, canvas: Canvas): EvaluationIssue[] { + const where = (owner: SceneNode) => { + const component = owner.componentId ? canvas.components[owner.componentId] : undefined; + return `instance "${owner.name ?? owner.id}" of component "${component?.name ?? owner.componentId}"`; + }; return issues.map((i) => { - // A grouped finding (slice H) names several nodes: each maps to its owner. const nodeIds = i.nodeIds ? [...new Set(i.nodeIds.map((id) => owners.get(id)?.id ?? id))] : undefined; - const owner = i.nodeId ? owners.get(i.nodeId) : undefined; - if (nodeIds && i.nodeIds!.length > 1) { - // Several members: say which ids are instances, not just the first's. - const inside = [...new Set(i.nodeIds!.flatMap((id) => { const o = owners.get(id); return o ? [o.name ?? o.id] : []; }))]; - const names = inside.map((n) => `"${n}"`).join(', '); - const all = i.nodeIds!.every((id) => owners.has(id)); - const suffix = !inside.length ? '' - : all ? (inside.length === 1 ? ` (inside instance ${names} — fix it in its component)` : ` (inside instances ${names} — fix them in their components)`) - : ` (some inside instances, listed by instance: ${names} — fix those in their components)`; - return { ...i, ...(owner ? { nodeId: owner.id, nodeName: owner.name } : {}), nodeIds, message: `${i.message}${suffix}` }; + const owner = owners.get(i.nodeId); + if (i.nodeIds && i.nodeIds.length > 1) { + // Several members: name every instance holding one, not just the first's. + const inside = [...new Map(i.nodeIds.flatMap((id) => { const o = owners.get(id); return o ? [[o.id, o] as const] : []; })).values()]; + if (!inside.length) return { ...i, nodeIds }; + const all = i.nodeIds.every((id) => owners.has(id)); + const suffix = all ? ` (inside ${inside.map(where).join(', ')}: fix ${inside.length === 1 ? 'it in the component' : 'them in their components'}, or with an override)` + : ` (some inside ${inside.map(where).join(', ')}: fix those in their components, or with an override)`; + const { fix: _fix, fixes: _fixes, ...rest } = i; + return { ...rest, ...(owner ? { nodeId: owner.id, nodeName: owner.name, innerNodeId: i.nodeId } : {}), nodeIds, message: `${i.message}${suffix}` }; } if (!owner) return nodeIds ? { ...i, nodeIds } : i; - return { ...i, nodeId: owner.id, nodeName: owner.name, ...(nodeIds ? { nodeIds } : {}), message: `${i.message} (inside instance "${owner.name ?? owner.id}" — fix it in its component)` }; + const { fix: _fix, fixes: _fixes, ...rest } = i; + return { + ...rest, + nodeId: owner.id, + nodeName: owner.name, + innerNodeId: i.nodeId, + ...(nodeIds ? { nodeIds } : {}), + message: `${i.message} (inside ${where(owner)}: fix it in the component, or with an override on the instance)`, + }; }); } @@ -2510,7 +2493,12 @@ export async function evaluateCanvas( // canvas itself has empty `variables` and inherits everything from the // workspace design system. const mergedTokens = getCanvasTokens(canvas); - const resolvedRoot = resolveVariables(canvas.root, mergedTokens); + // Phase 32 slice B — one tree: instances expanded, then resolved, as the + // renderer draws them, so every check sees inside components. `rawTree` is + // the same expansion with $refs as authored; `owners` maps each node inside + // an instance to it, for the findings pass at the end. + const { root: resolvedRoot, owners } = expandTree(canvas.root, canvas, mergedTokens); + const rawTree = expandTree(canvas.root, canvas).root; // Phase 30 slice B — one composition of the type, genre and preset rulesets // serves the cliche relaxation and the surface report. const declared = resolveSurface(canvas); @@ -2519,29 +2507,25 @@ export async function evaluateCanvas( const rules = composeRulesets(activeRulesets({ type: declared.type, genre: resolvedGenre.genre, preset })); const surface: SurfaceReport = { ...declared, rulesOn: rules.on, rulesOff: rules.off, conflicts: rules.conflicts }; const ruleOn = new Set(rules.on); - // Phase 30 slice D — the mobile rules judge what the renderer draws, so they - // read the tree with instances expanded (a tab bar inside a component is - // still a tab bar). Findings inside an instance report the instance. - // Expanded after resolution, as the renderer does it: a component's own - // $refs stay as the screenshot draws them. - const { root: mobileRoot, owners } = expandForRules(resolvedRoot, canvas); - const expandedRaw = expandForRules(canvas.root, canvas).root; const mobileTypeRules = MOBILE_RULES.some((id) => ruleOn.has(id)); // Phase 31 slice C — the desktop-app rules read the expanded tree too, and // in detailed mode the rects of that tree. const desktopTypeRules = DESKTOP_APP_RULES.some((id) => ruleOn.has(id)); const expandedRules = mobileTypeRules || desktopTypeRules; const mobile: MobileContext = { - root: mobileRoot, + root: resolvedRoot, profile: deviceProfile(declared.device ?? DEFAULT_DEVICE) ?? DEVICE_PROFILES[DEFAULT_DEVICE], width: typeof resolvedRoot.width === 'number' ? resolvedRoot.width : 1440, height: typeof resolvedRoot.height === 'number' ? resolvedRoot.height : 900, }; const entries = buildTreeContext(resolvedRoot); - // Also walk the unresolved tree for token usage stats - const rawEntries = buildTreeContext(canvas.root); + // The raw expansion: spacing and the cliché check read authored values. + const rawEntries = buildTreeContext(rawTree); + // The stored tree (K3): emptiness, the stats, checkStructure and the token + // census read the canvas as stored, instance nodes included. + const storedEntries = buildTreeContext(canvas.root); - if (entries.length <= 1) { + if (storedEntries.length <= 1) { // A blank document is not a presentable design. This used to return 100 // with the emptiness only mentioned in the summary — so a canvas whose // content never landed (or was wiped) sailed through every gate and the @@ -2558,7 +2542,7 @@ export async function evaluateCanvas( message: 'The canvas is empty — nothing has been designed yet. Stamp a structure (list_structures → apply_structure) or add content before evaluating.', }], summary: 'Canvas is empty — nothing has been designed yet.', - stats: { totalNodes: entries.length, textNodes: 0, frameNodes: 0, maxDepth: 0, tokenUsagePercent: 0, componentReusePercent: 0 }, + stats: { totalNodes: storedEntries.length, textNodes: 0, frameNodes: 0, maxDepth: 0, tokenUsagePercent: 0, componentReusePercent: 0 }, mode: options.mode, surface, }; @@ -2578,19 +2562,19 @@ export async function evaluateCanvas( // the worse theme: a dark-only failure must hurt. const darkLayer = mergedTokens.dark?.colors; const hasDark = !!darkLayer && Object.keys(darkLayer).length > 0; - const darkRoot = hasDark ? resolveVariables(canvas.root, mergedTokens, { theme: 'dark' }) : undefined; + const darkRoot = hasDark ? expandTree(canvas.root, canvas, mergedTokens, { theme: 'dark' }).root : undefined; let color = light; if (darkRoot) { const dark = checkColorContrast(buildTreeContext(darkRoot), 'dark'); color = { score: Math.min(light.score, dark.score), issues: [...light.issues, ...dark.issues] }; } // Phase 31 slice H (FR-H1 to FR-H4) — the element states, checked from - // the tree the renderer draws (instances expanded), in each theme. + // the tree the renderer draws, in each theme. const stateOn = (id: string) => ruleOn.has(id); const states = Object.values(STATE_RULES).some(stateOn) - ? stateFindings(checkStates(mobileRoot, stateOn), darkRoot ? checkStates(expandForRules(darkRoot, canvas).root, stateOn, 'dark') : [], owners, instanceIdsOf(canvas.root)) + ? stateFindings(checkStates(resolvedRoot, stateOn), darkRoot ? checkStates(darkRoot, stateOn, 'dark') : []) : []; - results.set('color', withRuleIssues(color, reportOnInstances(states, owners))); + results.set('color', withRuleIssues(color, states)); } // Phase 25 slice A — detailed-mode layout is computed ONCE and shared by // the consistency and typography (measure) checks. @@ -2601,10 +2585,9 @@ export async function evaluateCanvas( if (options.mode === 'detailed' && (activeCategories.includes('consistency') || activeCategories.includes('typography') || safeAreaDetailed || desktopDetailed)) { const w = typeof canvas.root.width === 'number' ? canvas.root.width : 1440; const h = typeof canvas.root.height === 'number' ? canvas.root.height : 900; - // On a mobile canvas render the tree the mobile rules read: the same - // pixels as the canvas render, with every node inside an instance under - // its own id, so the rects are unambiguous. Web keeps the canvas render. - const html = renderToHtml(expandedRules ? mobileRoot : resolvedRoot, w, h, canvas, options.renderOpts); + // The one tree, so every node inside an instance has its own id and the + // rects and the findings agree. + const html = renderToHtml(resolvedRoot, w, h, canvas, options.renderOpts); detailedLayout = await computeLayout(html, undefined, expandedRules ? 25 : 10, { width: w, height: h }); } // Phase 31 slice C — the desktop-app rules' view of the canvas. @@ -2615,11 +2598,11 @@ export async function evaluateCanvas( const index = (r: LayoutRect) => { rects.set(r.nodeId, r); r.children?.forEach(index); }; detailedLayout?.forEach(index); desktop = { - root: mobileRoot, + root: resolvedRoot, profile: windowProfile(declared.device ?? DEFAULT_WINDOW) ?? WINDOW_PROFILES[DEFAULT_WINDOW], ...(detailedLayout ? { rects } : {}), }; - desktopTables = new Set(extractInventory(mobileRoot).tables.map((t) => t.nodeId)); + desktopTables = new Set(extractInventory(resolvedRoot).tables.map((t) => t.nodeId)); } if (activeCategories.includes('typography')) { const typography = checkTypography(entries, mergedTokens, { @@ -2628,18 +2611,18 @@ export async function evaluateCanvas( layout: detailedLayout, tables: extractInventory(resolvedRoot).tables, }); - const rawById = new Map(buildTreeContext(expandedRaw).map((en) => [en.node.id, en.node])); + const rawById = new Map(rawEntries.map((en) => [en.node.id, en.node])); const pinned = new Set(Object.values(mergedTokens.typography ?? {}).map((t) => t.fontSize).filter((v): v is number => typeof v === 'number')); - results.set('typography', withRuleIssues(typography, reportOnInstances([ + results.set('typography', withRuleIssues(typography, [ ...(ruleOn.has('mobile-type-floor') ? checkTypeFloor(mobile, rawById) : []), ...(desktop && ruleOn.has('desktop-app-type-ladder') ? checkTypeLadder(desktop, rawById, pinned) : []), - ], owners))); + ])); } if (activeCategories.includes('structure')) { - results.set('structure', withRuleIssues(checkStructure(rawEntries, canvas), [ - ...(ruleOn.has('mobile-artboard') ? reportOnInstances(checkArtboard(mobile, declared), owners) : []), - ...(ruleOn.has('desktop-app-artboard') ? reportOnInstances(checkDesktopArtboard(mobileRoot, declared), owners) : []), - ...(desktop && ruleOn.has('desktop-app-primary-count') ? reportOnInstances(checkPrimaryCount(desktop), owners) : []), + results.set('structure', withRuleIssues(checkStructure(storedEntries, canvas), [ + ...(ruleOn.has('mobile-artboard') ? checkArtboard(mobile, declared) : []), + ...(ruleOn.has('desktop-app-artboard') ? checkDesktopArtboard(resolvedRoot, declared) : []), + ...(desktop && ruleOn.has('desktop-app-primary-count') ? checkPrimaryCount(desktop) : []), ])); } if (activeCategories.includes('consistency')) { @@ -2648,24 +2631,20 @@ export async function evaluateCanvas( ? checkConsistencyDetailed(entries, detailedLayout, consistencyCtx) : checkConsistency(entries, consistencyCtx); results.set('consistency', withRuleIssues(consistency, - desktop && ruleOn.has('desktop-app-row-rhythm') ? reportOnInstances(checkRowRhythm(desktop, desktopTables), owners) : [])); + desktop && ruleOn.has('desktop-app-row-rhythm') ? checkRowRhythm(desktop, desktopTables) : [])); } if (activeCategories.includes('usability')) { const touch = ruleOn.has('mobile-touch-target') ? { floor: mobile.profile.touchTarget } : undefined; - // On a mobile canvas the whole usability check reads the expanded tree; - // web keeps the unexpanded one. - let usability = mobileTypeRules - ? (({ score, issues }) => ({ score, issues: reportOnInstances(issues, owners) }))(checkUsability(buildTreeContext(mobileRoot), mobile.width, touch)) - : checkUsability(entries, mobile.width, touch); + let usability = checkUsability(entries, mobile.width, touch); if (!touch) { // Phase 31 FR-A4 — web and desktop-app: the pointer-target census reads // the tree with instances expanded. Detailed mode renders that tree // only when something is undersized, so the circle test has rects. - const targetEntries = buildTreeContext(mobileRoot); + const targetEntries = entries; const targets = pointerTargets(targetEntries, mobile.width); let rects: Map | undefined; if (options.mode === 'detailed' && undersizedTargets(targets).length > 0) { - const layout = await computeLayout(renderToHtml(mobileRoot, mobile.width, mobile.height, canvas, options.renderOpts), undefined, 25, { width: mobile.width, height: mobile.height }); + const layout = await computeLayout(renderToHtml(resolvedRoot, mobile.width, mobile.height, canvas, options.renderOpts), undefined, 25, { width: mobile.width, height: mobile.height }); // computeLayout returns a tree (each rect nests its children). rects = new Map(); const index = (r: LayoutRect) => { rects!.set(r.nodeId, r); r.children?.forEach(index); }; @@ -2680,10 +2659,10 @@ export async function evaluateCanvas( : pointer.issues; usability = { score: Math.max(0, usability.score - (100 - pointer.score)), - issues: [...usability.issues, ...reportOnInstances(named, owners)], + issues: [...usability.issues, ...named], }; } - const extra = reportOnInstances([ + const extra = [ ...(ruleOn.has('mobile-handbuilt-target') ? checkHandbuiltTargets(mobile) : []), ...(ruleOn.has('mobile-safe-area') ? (detailedLayout ? checkSafeAreaDetailed(mobile, detailedLayout) : checkSafeAreaFast(mobile)) : []), ...(ruleOn.has('mobile-one-column') ? checkOneColumn(mobile) : []), @@ -2693,7 +2672,7 @@ export async function evaluateCanvas( ...(desktop && ruleOn.has('desktop-app-current') ? checkCurrent(desktop) : []), ...(desktop && ruleOn.has('desktop-app-truncation') ? checkTruncation(desktop, desktopTables) : []), ...(desktop && ruleOn.has('desktop-app-overlay') ? checkOverlays(desktop, desktopTables) : []), - ], owners); + ]; results.set('usability', withRuleIssues(usability, extra)); } @@ -2729,6 +2708,9 @@ export async function evaluateCanvas( genreReport = buildGenreReport(resolvedGenre, relaxed, preset); } + // K4 — findings on nodes inside an instance are reported on the instance. + for (const [name, result] of results) results.set(name, { ...result, issues: reportOnInstances(result.issues, owners, canvas) }); + const overallScore = aggregateScores(results, CATEGORY_WEIGHTS); const allIssues = [...results.values()].flatMap((r) => r.issues); const categories: CategoryScore[] = []; @@ -2742,15 +2724,15 @@ export async function evaluateCanvas( } // Stats - const totalNodes = entries.length; - const textNodes = entries.filter((e) => e.node.type === 'text').length; - const frameNodes = entries.filter((e) => ['frame', 'component'].includes(e.node.type)).length; - const maxDepth = Math.max(...entries.map((e) => e.depth)); - const instanceNodes = entries.filter((e) => e.node.type === 'instance').length; + const totalNodes = storedEntries.length; + const textNodes = storedEntries.filter((e) => e.node.type === 'text').length; + const frameNodes = storedEntries.filter((e) => ['frame', 'component'].includes(e.node.type)).length; + 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 rawEntries) { + 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') { diff --git a/src/expand.ts b/src/expand.ts new file mode 100644 index 0000000..eeb2f94 --- /dev/null +++ b/src/expand.ts @@ -0,0 +1,94 @@ +// Phase 32 slice B — one tree. The renderer and every rule read the canvas +// through this module: each instance is expanded into the component tree it +// renders (overrides applied), and only then are design tokens resolved, so +// what a check judges inside a component is exactly what the render draws. +// +// Ids: a node inside an instance gets the instance path as a prefix +// (`/`, nesting as `//`), so two +// instances of one component never share an id. The instance's own root keeps +// the instance id. Stored ids never contain "/", so the first segment of an +// expanded id is always the outermost instance, which exists in the stored +// tree and is what a finding or a comment on the node is reported on. +import type { Canvas, DesignVariables, SceneNode } from './types.js'; +import { resolveVariables } from './variables.js'; + +export interface ExpandedTree { + /** The tree with every resolvable instance expanded; resolved when tokens + * were given. */ + root: SceneNode; + /** Expanded id → the outermost instance (a stored node) that holds it. The + * instance roots themselves are not in the map. */ + owners: Map; +} + +/** Expand every instance, then resolve tokens (when given) over the whole + * tree. Without tokens the tree stays raw: `$refs` as authored. */ +export function expandTree( + root: SceneNode, + canvas: Canvas, + tokens?: DesignVariables, + opts?: { theme?: 'light' | 'dark' }, +): ExpandedTree { + const owners = new Map(); + // Components being expanded on the current path: an instance of one of them + // 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); + const cid = node.type === 'instance' ? node.componentId : undefined; + const resolved = cid && !open.has(cid) ? resolveInstance(node, canvas) : null; + const source = resolved ?? node; + const out: SceneNode = { ...source, id }; + if (source.children) { + // Inside an instance, children take its path; elsewhere the current one. + const [childOwner, childPrefix] = resolved ? [owner ?? node, `${prefix}${node.id}/`] : [owner, prefix]; + if (resolved) open.add(cid!); + out.children = source.children.map((c) => walk(c, childOwner, childPrefix)); + if (resolved) open.delete(cid!); + } + return out; + }; + const expanded = walk(root, undefined, ''); + return { root: tokens ? resolveVariables(expanded, tokens, opts) : expanded, owners }; +} + +/** Whether a tree still holds an instance this canvas can expand. */ +export function hasInstances(root: SceneNode, canvas: Canvas): boolean { + if (root.type === 'instance' && root.componentId && canvas.components[root.componentId]) return true; + return (root.children ?? []).some((c) => hasInstances(c, canvas)); +} + +/** The stored node an expanded id belongs to: the outermost instance for a + * node inside one, else the id itself. */ +export function storedId(id: string): string { + const at = id.indexOf('/'); + return at < 0 ? id : id.slice(0, at); +} + +/** One instance as the tree it renders: a clone of its component with the + * instance's id, its own props laid over the component root, and its named + * child overrides applied. Null when the component does not exist. */ +export function resolveInstance(instance: SceneNode, canvas: Canvas): SceneNode | null { + const component = canvas.components[instance.componentId!]; + if (!component) return null; + + const clone = structuredClone(component); + clone.id = instance.id; + + // Instance-level props override the component root. + const { type: _, id: _id, componentId: _cid, overrides: _ov, children: _ch, ...rootOverrides } = instance; + Object.assign(clone, rootOverrides); + + if (instance.overrides) applyOverrides(clone, instance.overrides); + return clone; +} + +/** Named child overrides, matched by node name anywhere in the clone. */ +function applyOverrides(node: SceneNode, overrides: Record>): void { + if (node.name && overrides[node.name]) { + const { type: _, id: _id, children: _ch, ...props } = overrides[node.name]; + Object.assign(node, props); + } + for (const child of node.children ?? []) applyOverrides(child, overrides); +} diff --git a/src/feedback.ts b/src/feedback.ts index 6da917a..242c3a6 100644 --- a/src/feedback.ts +++ b/src/feedback.ts @@ -10,6 +10,7 @@ import { nanoid } from 'nanoid'; import { findNode } from './scene-graph.js'; +import { expandTree, storedId } from './expand.js'; import type { Canvas, FeedbackEntry } from './types.js'; /** Max characters of node text captured into the comment-time snapshot. */ @@ -41,9 +42,13 @@ export function addFeedback(canvas: Canvas, input: { nodeId?: string; comment: s at: new Date().toISOString(), }; if (input.nodeId) { - const found = findNode(canvas.root, input.nodeId); - if (!found) throw new Error(`Node "${input.nodeId}" not found in canvas "${canvas.id}"`); - entry.nodeId = input.nodeId; + // Phase 32 slice B — a node inside an instance (an expanded id, as the + // render and snapshot_layout name it) is anchored on its instance. + const nodeId = findNode(canvas.root, input.nodeId) ? input.nodeId + : findNode(expandTree(canvas.root, canvas).root, input.nodeId) ? storedId(input.nodeId) : undefined; + const found = nodeId ? findNode(canvas.root, nodeId) : null; + if (!nodeId || !found) throw new Error(`Node "${input.nodeId}" not found in canvas "${canvas.id}"`); + entry.nodeId = nodeId; entry.node = { type: found.node.type, ...(found.node.name ? { name: found.node.name } : {}), diff --git a/src/index.ts b/src/index.ts index 988a8fd..258bc3e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,7 +24,8 @@ import { listStructures, applyStructure, computeDiversificationHint } from './st import { parseDesignMd } from './design-md-parser.js'; import { listFeedback, resolveFeedback, openFeedbackCount, appendFeedbackDirective } from './feedback.js'; import { importHtml, importUrl, renderImportedTree, snapToTokens, summarizeImportReport } from './import.js'; -import { computeStructuralDrift, expandInstances } from './drift.js'; +import { computeStructuralDrift } from './drift.js'; +import { expandTree } from './expand.js'; import { applyPerturbation, compareLayouts, lastStressRun, PERTURBATION_NAMES, recordStressRun, type PerturbationName } from './stress.js'; import { buildEvaluateDirective } from './directive.js'; import { generateTypeScale, generateSpaceScale, resolveRatio, type RatioName } from './scales.js'; @@ -126,11 +127,11 @@ const GOTCHAS = [ 'Icons: Lucide ({ type: "icon", icon: "search" }) and Material Symbols (icon: "material:check", iconStyle outlined/rounded/sharp, "-fill" suffix for filled) render by name — never fake them with Unicode glyphs. Spelling differs by set: Lucide hyphenates ("chevron-right"), Material keeps underscores AND needs the prefix ("material:chevron_right") — a bare "chevron_right" is looked up in Lucide and renders nothing; canvas_evaluate warns on any icon that resolves in neither set. Casing: use textTransform: "uppercase", not uppercased content.', 'Controls: toggle / checkbox / radio / select are real node types with checked / disabled / value, token-styled — never assemble them from frames + ellipses. For application screens (type "desktop-app") use the desktop-app primitives — link, text-input, nav-item, tabs, tree-row, menu-row, property-row, divider, button size "xs" — never hand-built frames: a frame is not a measured target.', 'Overlays: tooltip / popover / menu / modal / toast / drawer render in one layer above ALL content whatever their parent (never clipped by a pane, never under a sticky bar), stacked by kind (popover/menu 400 < scrim 500 < modal/drawer 510 < toast 600 < tooltip 800 — a menu or popover on a screen with a modal (or a scrimmed drawer) renders under its scrim, and desktop-app-overlay warns). x / y are ROOT coordinates, not offsets from the parent. Put each in a screen-state variant (canvas_add_variant "menu-open" / "comment-open" / "confirm-delete" / "toast"), not on the base screen.', - 'Element states are a PROPERTY, screen states are variants: state: "hover" | "focus" | "pressed" | "disabled" on a clickable primitive or control (items carry their own: tabs / tab-bar items, nav-bar actions, modal actions, a toast action) draws it from the state tokens — hover / pressed / focus layer the label colour over the fill (8 / 10 / 10%), focus adds a 2px $focus-ring at a 2px gap, disabled renders in $text-primary at 38% (container 12%) when the state tokens set a disabled opacity, else at 0.5. Draw states only for a states sheet or a screenshot: the evaluator computes them itself — on desktop-app, a focus ring below 3:1 against what it covers is an ERROR (desktop-app-focus-visible: fix $focus-ring), and an active bar or underline (desktop-app-state-contrast) or a control boundary (desktop-app-boundary: use $border-strong; a transparent or unresolved border counts as invisible) below 3:1 WARNS. state: "disabled" counts as disabled everywhere disabled: true does (out of the tab order, the 24px census and the primary count; the phone\'s 44px census still measures it); other node types ignore state.', + 'Element states are a PROPERTY, screen states are variants: state: "hover" | "focus" | "pressed" | "disabled" on a clickable primitive or control (items carry their own: tabs / tab-bar items, nav-bar actions, modal actions, a toast action) draws it from the state tokens — hover / pressed / focus layer the label colour over the fill (8 / 10 / 10%), focus adds a 2px $focus-ring at a 2px gap, disabled renders in $text-primary at 38% (container 12%) when the state tokens set a disabled opacity, else at 0.5. Draw states only for a states sheet or a screenshot: the evaluator computes them itself — on desktop-app, a focus ring below 3:1 against what it covers is an ERROR (desktop-app-focus-visible: fix $focus-ring), and an active bar or underline (desktop-app-state-contrast) or a control boundary (desktop-app-boundary: use $border-strong; a transparent or unresolved border counts as invisible) below 3:1 WARNS. state: "disabled" counts as disabled everywhere disabled: true does (out of the tab order, the 24px census and the primary count; the phone\'s 44px census still measures it); a state or disabled inside a component instance (on the component\'s node or through an override) draws there in the design system\'s colours too; other node types ignore state.', 'Bulk edits & queries: replace_matching_properties changes a property across every node matching a value predicate in one call (scope/type filters; dryRun previews the match set); find_nodes is the read-only twin — locate nodes by property/text/name and get ids + paths instead of guessing from read_nodes trees. canvas_autofix apply: true writes the whole mechanical fix set in one call.', 'Component scaffolds: apply_structure with kind "component" structures (data-table, form-field, toolbar, stat-card, toggle-row, the state scaffolds empty-state, skeleton-table, skeleton-card, skeleton-stat-card — plus the Phase 28 dashboard micro-patterns: kpi-card, status-chip, segmented-control, breadcrumb, initials-avatar, all on the tint pair) + targetId stamps reusable fragments with re-keyed IDs — build tables/forms from these, not node-by-node.', 'Charts: the chart node type is data-driven ({ kind: "line"|"bar"|"donut"|"sparkline", series: [{ data, stroke, highlight?, barGradient?, … }], segments? for donuts, gridlines?, xLabels? }) — it does the value→coordinate math, dashes mark projected vs actual, highlight (an index or an array of indices) renders the selected bar solid over muted siblings, donuts take segments + centerValue/centerLabel, sparklines are axis-free with the latest point emphasized. Never hand-compute path d-strings, conic-hack a donut, or hand-place sparkline bars.', - 'Shared chrome is a component, not a copy-paste: create_component promotes a built subtree (render-identical; overrides target named children), batch_design I() stamps more instances, copy_nodes carries subtrees + their component defs to sibling canvases. Rebuilding an app shell node-by-node on every canvas is the anti-pattern.', + 'Shared chrome is a component, not a copy-paste: create_component promotes a built subtree (render-identical; overrides target named children), batch_design I() stamps more instances, copy_nodes carries subtrees + their component defs to sibling canvases. Rebuilding an app shell node-by-node on every canvas is the anti-pattern. Instances render and are judged with the design system resolved inside them; a finding inside one names the instance (nodeId) and the inner node (innerNodeId), with no fix op.', 'canvas_import_html: Tailwind classes map to intent directly (bg-surface → fill "$surface", gap-4 → 16, bg-red-500 → the bundled v4 palette hex) and literal colors snap to the design system — a bare snippet styles via the common utilities + palette; pass the compiled CSS via the css param for everything else. Always read the returned report (snapped/literals/layout/warnings); the import is honest about what it dropped.', 'Imports reconstruct STRUCTURE: tables → proportional columns, grids → rows from the computed template, centered/max-width content stays centered, other multi-column CSS clusters by geometry. Check report.layout — a "stack-fallback" entry names a container that needs hand-fixing; everything else arrived structurally correct, so do not rebuild it.', 'Fonts: a fontFamily named in a typography token loads automatically (Google Fonts, cached locally); typography.body.fontFamily sets the document default. "mono" / "sans" are generic shorthands (render as monospace / sans-serif, no registration). batch_design warns at write time when a family is not yet servable; a "Font warnings" item in a screenshot result means the named face is NOT rendering — fix the name or register it via set_fonts (with a css2 URL, YOUR family label is what gets registered).', @@ -577,7 +578,7 @@ Icons: two bundled sets render by name — use these instead of Unicode glyph st - Material Symbols (3,800+, fill style): icon: "material:check" + optional iconStyle: "outlined"|"rounded"|"sharp" (default outlined); "-fill" suffix selects the filled variant (e.g. "material:star-fill"); multi-word names use Material's underscores ("material:chevron_right", "material:chevron_right-fill") — browse at fonts.google.com/icons - Spelling differs by set: Lucide hyphenates (chevron-right), Material uses underscores + the material: prefix. A name that resolves in neither set renders an empty slot; canvas_evaluate reports it as a structure warning -Components: I("parent", { type: "instance", componentId: "cmp-shell", overrides: { "": { content: "..." } } }) stamps a registered component (create_component promotes an existing subtree into one; overrides match def children by NAME). Instance-level props override the def root. +Components: I("parent", { type: "instance", componentId: "cmp-shell", overrides: { "": { content: "..." } } }) stamps a registered component (create_component promotes an existing subtree into one; overrides match def children by NAME). Instance-level props override the def root. An instance renders and is evaluated as its component with those props and overrides applied, $tokens resolved inside it; a node inside one is named "/" in snapshot_layout and findings, not an id batch_design can address. Input controls: toggle / checkbox / radio / select are real node types — I("parent", { type: "toggle", checked: true }), I("parent", { type: "select", value: "Admin", width: 200 }). Colors default from design tokens ($accent / $border / $bg-surface / $text-primary, neutral fallbacks when unthemed); fill / stroke / color override; checked / disabled / state (see Element states below) set what they show. NEVER fake a control from frames + ellipses. @@ -613,7 +614,7 @@ Overlays (screen states — put one in a state variant made with canvas_add_vari - drawer { size?: "sm"|"md" (320/480) or width, scrim?: false, children } — pinned to the right edge, full height, padding 16; scrim: true dims what is behind it. A modal's close button and actions and a toast's action are pointer targets (32 / 32 / 24 tall), sized for a pointer: on a phone use a sheet for a dialog. On a root with a safeArea or a pinned tab-bar, a centred modal, a default toast and a drawer keep clear of the insets and the tab bar. snapshot_layout lists every overlay under the root, and a modal (or a drawer with a scrim) carries its scrim's rect. -Element states (state?: "rest"|"hover"|"focus"|"pressed"|"disabled", default rest): on button, link, text-input, nav-item, tree-row, menu-row, list-row, toggle, checkbox, radio, select, and on the items of tabs, tab-bar, nav-bar (leading / trailing), modal (actions[]) and toast (action). Hover, focus and pressed layer the target's label colour over its fill (the state tokens' hover / focus / pressed, Material's 8 / 10 / 10% without them); focus adds a 2px $focus-ring outline at a 2px gap (inside the tab for a tab or tab-bar item); a link also underlines in hover and pressed; active, checked and expanded keep their fill under the layer. disabled (or disabled: true, which wins over any state) renders the whole target in $text-primary at the state tokens' disabledContent (38%), a drawn fill or border at disabledContainer (12%), and a check mark, knob or badge numeral in $bg-surface, when the tokens set either disabled opacity (a lone one takes the other's Material value), else at 0.5 opacity in its own colours; an authored opacity wins. A disabled target leaves the tab order, the 24px census and the primary count (the phone's 44px census still measures it). A tabs node's own state "disabled" disables every tab. Other node types ignore state. +Element states (state?: "rest"|"hover"|"focus"|"pressed"|"disabled", default rest): on button, link, text-input, nav-item, tree-row, menu-row, list-row, toggle, checkbox, radio, select, and on the items of tabs, tab-bar, nav-bar (leading / trailing), modal (actions[]) and toast (action). Hover, focus and pressed layer the target's label colour over its fill (the state tokens' hover / focus / pressed, Material's 8 / 10 / 10% without them); focus adds a 2px $focus-ring outline at a 2px gap (inside the tab for a tab or tab-bar item); a link also underlines in hover and pressed; active, checked and expanded keep their fill under the layer. disabled (or disabled: true, which wins over any state) renders the whole target in $text-primary at the state tokens' disabledContent (38%), a drawn fill or border at disabledContainer (12%), and a check mark, knob or badge numeral in $bg-surface, when the tokens set either disabled opacity (a lone one takes the other's Material value), else at 0.5 opacity in its own colours; an authored opacity wins. A disabled target leaves the tab order, the 24px census and the primary count (the phone's 44px census still measures it). A tabs node's own state "disabled" disables every tab. Inside a component instance, a state or disabled on the component's node, or set through an override (overrides: { "": { disabled: true } }), draws exactly as it does outside one, in the design system's colours. Other node types ignore state. Responsive layout (author desktop-first, adapt down): - responsive: "stack" — on a horizontal container, flips to vertical below 768px (multi-column layouts that should stack on mobile) @@ -815,7 +816,8 @@ The shared-app-shell workflow: build the shell once, create_component it, then c * the fallback stack + a warning, never a render failure). */ async function prepareRender(canvas: Canvas, theme?: 'light' | 'dark'): Promise<{ resolved: SceneNode; renderOpts: RenderOptions; fontWarnings: string[] }> { const merged = getCanvasTokens(canvas); - const resolved = resolveVariables(canvas.root, merged, { theme }); + // Phase 32 slice B — instances expanded, then resolved: one tree. + const resolved = expandTree(canvas.root, canvas, merged, { theme }).root; const { extraFonts, warnings } = await ensureFontsForRender(resolved, canvas, merged); return { resolved, renderOpts: { extraFonts, bodyFontFamily: bodyFontFamilyFromTokens(merged) }, fontWarnings: warnings }; } @@ -905,7 +907,7 @@ server.tool( // --- snapshot_layout --- server.tool( 'snapshot_layout', - 'Get computed bounding boxes for all nodes by rendering the canvas in a browser. Returns { nodeId, x, y, width, height } for each node — plus, on any node whose content exceeds its box, overflow data: scrollWidth/clientWidth/scrollHeight/clientHeight and an ellipsis flag when a designed text-overflow truncation is active (the same capture canvas_stress uses to detect clipping). On a primitive: truncated: true when one of its own labels is cut by its ellipsis, and labels ([{ chars, scrollWidth, clientWidth }], one per own label, in order) on every tabs node and on any primitive with a cut label. Overlays (tooltip, popover, menu, modal, toast, drawer) render in a layer after the root: from the root they are listed as the root\'s last children wherever they sit in the tree, at root coordinates; a modal (or a drawer with scrim: true) also carries scrim: { x, y, width, height }, the rect its scrim covers. A nodeId inside an overlay walks that overlay.', + 'Get computed bounding boxes for all nodes by rendering the canvas in a browser. Returns { nodeId, x, y, width, height } for each node (a node inside a component instance appears under its expanded id, "/", so two instances never share an id; batch_design cannot address it: edit the component, or override the child on the instance) — plus, on any node whose content exceeds its box, overflow data: scrollWidth/clientWidth/scrollHeight/clientHeight and an ellipsis flag when a designed text-overflow truncation is active (the same capture canvas_stress uses to detect clipping). On a primitive: truncated: true when one of its own labels is cut by its ellipsis, and labels ([{ chars, scrollWidth, clientWidth }], one per own label, in order) on every tabs node and on any primitive with a cut label. Overlays (tooltip, popover, menu, modal, toast, drawer) render in a layer after the root: from the root they are listed as the root\'s last children wherever they sit in the tree, at root coordinates; a modal (or a drawer with scrim: true) also carries scrim: { x, y, width, height }, the rect its scrim covers. A nodeId inside an overlay walks that overlay.', { canvasId: z.string().describe('Canvas ID'), nodeId: z.string().optional().describe('Root node ID to start from'), @@ -1403,7 +1405,7 @@ server.tool( if (nodeIds?.length) { for (const nodeId of nodeIds) { - const filePath = await exportToFile(html, { width: w, height: h, scale, format, outputPath, nodeId, fileName: nodeId }); + const filePath = await exportToFile(html, { width: w, height: h, scale, format, outputPath, nodeId, fileName: nodeId.replace(/\//g, '-') }); exportedFiles.push(filePath); } } else { @@ -1905,7 +1907,7 @@ Run this when PICKING UP a canvas that describes a shipped view — designing on const imported = await importUrl(url, { viewport: { width: w, height: h }, selector, waitFor, auth }); // Instance-expanded so stamped components (app shells) are inventoried. - const drift = computeStructuralDrift(expandInstances(canvas.root, canvas), imported.root); + const drift = computeStructuralDrift(expandTree(canvas.root, canvas).root, imported.root); const blocking = drift.findings.filter((f) => f.severity !== 'info').length; return { @@ -2011,7 +2013,7 @@ where value is a color (\`#hex\`, \`rgba(...)\`) for colors, \`Npx\` for spacing // --- get_feedback --- server.tool( 'get_feedback', - `Read point-and-tell feedback: comments the user left by clicking elements in the viewer, each anchored to a specific node (or to the canvas as a whole when nodeId is absent). Returns open entries by default — each carries the comment, the anchor nodeId, and a node snapshot { type, name, text } captured at comment time, so you can act without extra lookups. "orphaned": true marks a comment whose anchor node no longer exists — it stays open because the concern usually still applies to the node's replacement. Omit canvasId to sweep every canvas in the current context and find where feedback is waiting. OPEN FEEDBACK BLOCKS PRESENTING, same as open inspector comments: check this tool when picking up a canvas, address each item (batch_design etc.), then close it with resolve_feedback.`, + `Read point-and-tell feedback: comments the user left by clicking elements in the viewer, each anchored to a specific node (or to the canvas as a whole when nodeId is absent). Returns open entries by default — each carries the comment, the anchor nodeId (a comment on a node inside a component instance anchors on the instance), and a node snapshot { type, name, text } captured at comment time, so you can act without extra lookups. "orphaned": true marks a comment whose anchor node no longer exists — it stays open because the concern usually still applies to the node's replacement. Omit canvasId to sweep every canvas in the current context and find where feedback is waiting. OPEN FEEDBACK BLOCKS PRESENTING, same as open inspector comments: check this tool when picking up a canvas, address each item (batch_design etc.), then close it with resolve_feedback.`, { canvasId: z.string().optional().describe('Canvas ID. Omit to sweep all canvases in the current context and return only those with feedback.'), includeResolved: z.boolean().optional().describe('Also return resolved entries (default false — open only)'), @@ -2145,7 +2147,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. 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; they point at the component definition and carry 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. 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. @@ -2155,7 +2157,7 @@ THE HEURISTIC DIRECTIVE IS THE PRESENTATION GATE. mode: "llm" adds optional dept The result's "genre" field (present whenever cliche ran) makes the genre decision auditable: { active, source ("explicit" param | "provenance" stamp | null), relaxed (tells skipped, by the genre and by the applied preset), notRelaxed ([{ tell, relaxedBy }] — tells still flagging that a DIFFERENT genre would relax), byPreset ({ preset, relaxed } — present when the applied preset relaxed tells on its own, e.g. the material preset) }. active is the canonical genre: an alias reports as its canonical name ("dashboard" → "data", "checkout" → "commerce"). If the score is pinned by tells listed in notRelaxed, the genre is probably wrong — genre follows what the screen is FOR (read screens with the user's own figures → "data"; a screen you complete a purchase on → "commerce"; the Material style → "material" (an editor or admin console is a type, not a genre: declare it with canvas_create / canvas_set_type type "desktop-app")), not what it contains. -The result's "surface" field (always present) reports the canvas TYPE and the rules it selected: { type ("web" | "mobile" | "desktop-app"), device (the profile: a phone such as "iphone-390" on mobile, a window such as "window-1440" on desktop-app, null on web), source ("declared" by canvas_create type / canvas_set_type, or "default" — never declared, judged as web), rulesOn (rule ids the composed type + genre + preset rulesets turned on), rulesOff (rule ids they turned off), conflicts (ids both enabled and disabled — those stay ON) }. On a web canvas rulesOn is ["desktop-app-artboard", "mobile-artboard"] (the base rules, on for every type). On a desktop-app canvas rulesOff lists "type-scale-ratio" (the adjacent font-size ratio check, which tags its warnings with that rule id on web and mobile; dense apps step 12/13/14 on purpose), and desktop-app-artboard (structure, every type) WARNS when a desktop-app canvas is narrower than its window's 1024px minimum, and when a canvas holding a desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) never declared its type or is declared mobile — a canvas declared web gets an info instead; an undeclared canvas holding an overlay (tooltip, popover, menu, modal, toast, drawer) warns too, while declared web or mobile canvases may hold overlays. On a desktop-app canvas rulesOn also lists the desktop-app ruleset, each finding tagged with its "rule": desktop-app-target (usability: the 24px floor above, named — fast WARNING, detailed ERROR when the 24px circle reaches a neighbour; an unlabelled link with no width (or "auto") measures its glyphs, 14px wide or 30 with external, on web too), desktop-app-handbuilt-target (usability info, never blocks: a frame below 32px holding one icon, an icon plus a label of ≤3 words, or a bordered padded frame holding one such label — the shape an imported text button takes; never inside a clickable primitive; rebuild it as a button or link if clickable), desktop-app-icon-label (usability WARNING: an icon-only button or link with no ariaLabel, a collapsed nav-item with a blank label), desktop-app-current (usability WARNING: in one pane — a frame with overflow "auto", a modal, a drawer, or the root; each node belongs to its nearest, so give each navigation region its own pane — two active nav-items at one depth, or two or more nav-items with none active; a tabs node with no active tab or more than one; two active tree-rows under one parent; info: a tree with a current row nesting past two levels), desktop-app-type-ladder (typography WARNING, replaces type-scale-ratio: adjacent sizes a/" (the id snapshot_layout uses; batch_design cannot address it, so edit the component or override the child on the instance). Finding kinds: clip (content cut off — INFO when a designed text-overflow ellipsis is doing its job (a primitive's label truncating included), or when it is just a root with an authored overflow clipping or scrolling inside itself; WARNING otherwise; the vertical overflow of a sheet, a drawer, or any frame, popover or menu with overflow "auto" (an app pane, a popover whose body scrolls) scrolls and is never a clip; its horizontal overflow still is), overflow-x (a node escapes its parent box or the canvas), layout-shift (an UNTOUCHED node ballooning — perturbed nodes, their ancestors, and siblings that merely stretch with a growing parent are exempt). Only NEW breakage counts: anything already clipping at baseline is the design's standing state, not the perturbation's fault. verdict is CLEAN only with zero warnings — fix findings with fluid widths, minWidth or minHeight floors, wrapping, or textOverflow: "ellipsis" on labels that must stay single-line (that is the designed-truncation property the info path rewards), then re-run. The verdict is remembered for canvas_evaluate, with the canvas type it ran under: any run with warnings records FRAGILE (the directive stays NOT READY), and only a run of the full default set records CLEAN — a passing subset never clears an earlier FRAGILE. On a mobile canvas, long-text leaves strings of three characters or fewer alone (monograms, short labels), and the tab and nav-bar action labels (fixed vocabulary; i18n still lengthens them). The mobile primitives' own copy is perturbed (button label, list-row title / subtitle / trailing text, nav-bar title and action labels, tab labels), and two or more consecutive sibling list-rows are a list for empty and many. Chrome required; ~1 render per perturbation.`, { @@ -2321,7 +2323,7 @@ Finding kinds: clip (content cut off — INFO when a designed text-overflow elli const { renderOpts, fontWarnings } = await prepareRender(canvas); // Instance-expanded so stamped components stress like everything else; // the expanded tree is the base for BOTH sides so node ids align. - const expandedBase = expandInstances(canvas.root, canvas); + const expandedBase = expandTree(canvas.root, canvas).root; const { type } = resolveSurface(canvas); const baselineHtml = renderToHtml(resolveVariables(structuredClone(expandedBase), merged), w, h, canvas, renderOpts); const baselineLayout = await computeLayout(baselineHtml, undefined, 25, { width: w, height: h }); diff --git a/src/primitives.ts b/src/primitives.ts index d9296ce..74ccd3a 100644 --- a/src/primitives.ts +++ b/src/primitives.ts @@ -289,16 +289,12 @@ export function unpinsFixed(n: SceneNode): boolean { /** How far each edge's pinned chrome reaches: the largest chrome height + * offset per edge, over every effectively fixed status-bar (top) and tab-bar / - * home-indicator (bottom) in the tree. A sheet's subtree is skipped. `expand` - * resolves an instance to the tree it renders. */ -export function chromeReservation( - root: SceneNode, - expand: (n: SceneNode) => SceneNode = (n) => n, -): { top: number; bottom: number } { + * home-indicator (bottom) in the tree. A sheet's subtree is skipped. Read it + * on an expanded tree (src/expand.ts) to see chrome inside instances. */ +export function chromeReservation(root: SceneNode): { top: number; bottom: number } { const insets = rootInsets(root); const out = { top: 0, bottom: 0 }; - (function walk(raw: SceneNode) { - const n = expand(raw); + (function walk(n: SceneNode) { if (n.type === 'sheet') return; const edge = CHROME_EDGE[n.type]; if (edge && effectivePosition(n) === 'fixed') { diff --git a/src/renderer.ts b/src/renderer.ts index fde9164..2acac7e 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -2,6 +2,8 @@ import type { Canvas, ElementState, FontFace, SceneNode, StateStyle } from './ty import { getIconSvg } from './icons.js'; import { aliasFamilyStack } from './fonts.js'; import { usableSafeArea } from './surfaces.js'; +import { expandTree, hasInstances } from './expand.js'; +import { getCanvasTokens } from './workspaces.js'; import { BUTTON_FONT, BUTTON_PADDING, CHROME_EDGE, FAB_RAISE, FAB_SIZE, FLOATING_INSET, NAV_ACTION, NAV_BAR_HEIGHT, NAV_BAR_LARGE_HEIGHT, TAB_BAND, buttonHeight, chromeHeight, chromeReservation, effectivePosition, listRowMinHeight, navBarHeight, rootInsets, @@ -65,6 +67,10 @@ export interface RenderOptions { * renders are byte-comparable (canvas_diff / visual baselines never * flicker). */ skeletonPulse?: boolean; + /** Phase 32 slice B — the theme a tree that still holds instances is + * resolved in when the renderer expands it (light when unset). A caller + * rendering dark should expand first (expandTree), or pass this. */ + theme?: 'light' | 'dark'; } // Registered canvas.fonts family names (lowercased) — a generic shorthand @@ -108,17 +114,21 @@ interface RenderCtx { } export function renderToHtml(root: SceneNode, width = 1440, height = 900, canvas?: Canvas, opts?: RenderOptions): string { + // Phase 32 slice B — instances render as the one tree every rule reads: + // expanded, then resolved. Callers that already expanded pass through. + if (canvas && hasInstances(root, canvas)) { + root = expandTree(root, canvas, getCanvasTokens(canvas), { theme: opts?.theme }).root; + } const registered = registeredFamilies(canvas); - const expand = (n: SceneNode) => (n.type === 'instance' && n.componentId && canvas ? resolveInstance(n, canvas) ?? n : n); const columnWidth = Math.min(typeof root.width === 'number' ? root.width : width, width); const designWidth = typeof root.width === 'number' && root.width > 0 ? root.width : DESIGN_WIDTH; const overlays: SceneNode[] = []; - const reservation = chromeReservation(root, expand); + const reservation = chromeReservation(root); const safe = root.type === 'document' ? usableSafeArea(root.safeArea) : {}; const clear = { top: Math.max(safe.top ?? 0, reservation.top), bottom: Math.max(safe.bottom ?? 0, reservation.bottom) }; const rc: RenderCtx = { canvas, registered, bodyWidth: width, columnWidth, insets: rootInsets(root), reservation, designWidth, overlays, clear }; const body = renderNode(root, rc) + overlayLayer(rc, height); - const responsiveCss = buildRendererStylesheet(root, canvas); + const responsiveCss = buildRendererStylesheet(root); // Phase 24 slice B — the pulse keyframes exist ONLY when the caller opts in // (the live viewer). Without them the fs-skeleton class is inert, so every // screenshot/export/diff render is static and deterministic. @@ -602,13 +612,6 @@ function rootBackgroundCss(root: SceneNode): string { } function renderNode(node: SceneNode, rc: RenderCtx): string { - const { canvas } = rc; - // Resolve instances: clone the component tree and apply overrides - if (node.type === 'instance' && node.componentId && canvas) { - const resolved = resolveInstance(node, canvas); - if (resolved) return renderNode(resolved, rc); - } - // Phase 31 slice E — an overlay renders in the overlay layer, not here. if (OVERLAY_TYPES.has(node.type)) { rc.overlays.push(node); @@ -674,44 +677,6 @@ function renderNode(node: SceneNode, rc: RenderCtx): string { return `${renderChildren(node, rc)}`; } -// Exported for drift.ts (Phase 23 slice B): the structural inventory must see -// through instances — an app shell stamped as a component still has controls -// and text the shipped page either has or hasn't. -export function resolveInstance(instance: SceneNode, canvas: Canvas): SceneNode | null { - const component = canvas.components[instance.componentId!]; - if (!component) return null; - - // Deep clone the component tree - const clone = structuredClone(component); - // Give the clone the instance's ID so it's targetable - clone.id = instance.id; - - // Apply instance-level style overrides to the root - const { type: _, id: _id, componentId: _cid, overrides: _ov, children: _ch, ...rootOverrides } = instance; - Object.assign(clone, rootOverrides); - - // Apply named child overrides - if (instance.overrides) { - applyOverrides(clone, instance.overrides); - } - - return clone; -} - -function applyOverrides(node: SceneNode, overrides: Record>): void { - // Match overrides by node name - if (node.name && overrides[node.name]) { - const { type: _, id: _id, children: _ch, ...props } = overrides[node.name]; - Object.assign(node, props); - } - - if (node.children) { - for (const child of node.children) { - applyOverrides(child, overrides); - } - } -} - function renderChildren(node: SceneNode, rc: RenderCtx): string { if (!node.children?.length) return ''; const rootChild = node.type === 'document' && node.layout !== 'horizontal' && node.layout !== 'grid'; @@ -1013,8 +978,8 @@ function renderSelect(node: SceneNode, dataAttr: string): string { // ── mobile primitives (Phase 30 slice D) ───────────────────────────────────── // Fixed anatomy like the controls: each builder hand-rolls its styles from // src/primitives.ts geometry, and colours arrive pre-defaulted by -// resolveVariables (the fallbacks below only serve a primitive that skipped -// it, such as one inside a component). Every primitive refuses to +// resolveVariables (the fallbacks below only serve a tree rendered without +// resolution, such as a test's raw tree). Every primitive refuses to // flex-shrink, so it keeps its size in a fixed-height column. Labels sit in // `data-fs-label` elements that truncate to one line — canvas_stress reads // their overflow as designed truncation. @@ -1026,8 +991,8 @@ const FALLBACK = { accent: '#2563EB', text: '#111827', secondary: '#6B7280', bor // and pressed layer the ink over the fill at the state's opacity (focus adds // the ring, 2px at a 2px gap so it meets only the backdrop, spec change S9); // disabled draws the token pair when the design system has it, else today's -// 0.5. Resolution (applyControlDefaults) hands over `stateStyle`; a node it -// skipped (inside a component) uses the fallback. +// 0.5. Resolution (applyControlDefaults) hands over `stateStyle`; a node in +// a tree rendered without resolution uses the fallback. const STATE_FALLBACK: StateStyle = { ring: FALLBACK.accent, onSurface: FALLBACK.text, surface: FALLBACK.surface, hover: STATE_LAYERS.hover, focus: STATE_LAYERS.focus, pressed: STATE_LAYERS.pressed }; @@ -1335,8 +1300,8 @@ function renderButton(node: SceneNode, rc: RenderCtx, attrs: string, item = fals if (name) attrs += ` aria-label="${escapeAttr(name)}" title="${escapeAttr(name)}"`; const h = buttonHeight(node); const words = text(node.label) ? labelHtml(text(node.label), '') : ''; - // Unthemed (a button inside a component skips resolveVariables): the - // primary look, so it is never an invisible white-on-transparent label. + // Unthemed (a raw tree that skipped resolveVariables): the primary look, + // so it is never an invisible white-on-transparent label. const fill = node.fill ?? (node.variant === 'secondary' || node.variant === 'ghost' ? 'transparent' : node.variant === 'destructive' ? FALLBACK.danger : FALLBACK.accent); const color = node.color ?? (fill === 'transparent' ? FALLBACK.accent : '#FFFFFF'); const glyph = iconHtml(node.icon, size === 'xs' ? 14 : size === 'sm' ? 16 : 20, color); @@ -1947,12 +1912,12 @@ export function isValidKeyframeName(name: string): name is keyof typeof KEYFRAME return name in KEYFRAME_LIBRARY; } -function buildRendererStylesheet(root: SceneNode, canvas?: Canvas): string { +function buildRendererStylesheet(root: SceneNode): string { const stackIds: string[] = []; const gridStackIds: string[] = []; const relativeIds = new Set(); const keyframes = new Set(); - collectRendererHints(root, [], canvas, stackIds, gridStackIds, relativeIds, keyframes); + collectRendererHints(root, [], stackIds, gridStackIds, relativeIds, keyframes); const parts: string[] = []; @@ -1995,31 +1960,25 @@ function buildRendererStylesheet(root: SceneNode, canvas?: Canvas): string { function collectRendererHints( node: SceneNode, ancestors: SceneNode[], - canvas: Canvas | undefined, stackIds: string[], gridStackIds: string[], relativeIds: Set, keyframes: Set, ): void { - // Resolve instances so responsive hints inside components are picked up - const resolved = node.type === 'instance' && node.componentId && canvas - ? resolveInstance(node, canvas) ?? node - : node; - - if (resolved.responsive === 'stack' && resolved.layout === 'horizontal') { - stackIds.push(resolved.id); + if (node.responsive === 'stack' && node.layout === 'horizontal') { + stackIds.push(node.id); } // Phase 26 slice A — a grid with responsive: "stack" collapses to a single // column on mobile (spans reset so tiles flow naturally). - if (resolved.responsive === 'stack' && resolved.layout === 'grid') { - gridStackIds.push(resolved.id); + if (node.responsive === 'stack' && node.layout === 'grid') { + gridStackIds.push(node.id); } - if (resolved.animation?.name && isValidKeyframeName(resolved.animation.name)) { - keyframes.add(resolved.animation.name); + if (node.animation?.name && isValidKeyframeName(node.animation.name)) { + keyframes.add(node.animation.name); } - if (resolved.position === 'absolute') { + if (node.position === 'absolute') { const hasPositionedAncestor = ancestors.some((a) => a.position === 'relative' || a.position === 'absolute'); if (!hasPositionedAncestor) { const container = findNearestContainer(ancestors); @@ -2029,10 +1988,10 @@ function collectRendererHints( } } - if (resolved.children) { - const nextAncestors = [...ancestors, resolved]; - for (const child of resolved.children) { - collectRendererHints(child, nextAncestors, canvas, stackIds, gridStackIds, relativeIds, keyframes); + if (node.children) { + const nextAncestors = [...ancestors, node]; + for (const child of node.children) { + collectRendererHints(child, nextAncestors, stackIds, gridStackIds, relativeIds, keyframes); } } } diff --git a/src/state-checks.ts b/src/state-checks.ts index 552b385..aa87c61 100644 --- a/src/state-checks.ts +++ b/src/state-checks.ts @@ -11,7 +11,7 @@ import { backdropBehind, composite, paintsNothing, parseAlpha, parseColor, reada import { OVERLAY_TYPES, STATE_LAYERS, STATEFUL_TYPES, isDisabled, modalActions, navActions, tabItems, tabsItems } from './primitives.js'; /** The renderer's fallbacks (renderer.ts FALLBACK), for props the resolver - * never set (a primitive inside a component). */ + * never set (a tree checked without resolution). */ const FALLBACK = { accent: '#2563EB', text: '#111827', secondary: '#6B7280', border: '#D1D5DB', surface: '#FFFFFF', danger: '#DC2626' } as const; /** A contained tab's active fill without a token (renderTabs). */ const TINT_FALLBACK = '#EFF4FF'; diff --git a/src/viewer.ts b/src/viewer.ts index 59617b6..bf18606 100644 --- a/src/viewer.ts +++ b/src/viewer.ts @@ -1,6 +1,6 @@ import { createServer, type IncomingMessage, type Server } from 'node:http'; import { getCanvas, listCanvases, archiveCanvas, unarchiveCanvas, deleteCanvas, ensureFresh, touchCanvas, type CanvasSummary } from './scene-graph.js'; -import { resolveVariables } from './variables.js'; +import { expandTree } from './expand.js'; import { renderToHtml } from './renderer.js'; import { getProject, listProjects, listWorkspaces, getCanvasTokens, getProjectDesignSystem, getWorkspaceDesignSystem } from './workspaces.js'; import { getRepoLocation, archiveRepoCanvas, deleteRepoCanvas, updateRepoCanvas } from './aggregate.js'; @@ -119,7 +119,7 @@ export async function startViewer(port: number): Promise { if (!canvas) { res.writeHead(404); res.end('Not found'); return; } // Phase 25 slice D — ?theme=dark renders the dark token layer. const theme = url.searchParams.get('theme') === 'dark' ? 'dark' as const : undefined; - const resolved = resolveVariables(canvas.root, getCanvasTokens(canvas), { theme }); + const resolved = expandTree(canvas.root, canvas, getCanvasTokens(canvas), { theme }).root; const defaultW = typeof canvas.root.width === 'number' ? canvas.root.width : 1440; const defaultH = typeof canvas.root.height === 'number' ? canvas.root.height : 900; const w = url.searchParams.has('w') ? parseInt(url.searchParams.get('w')!, 10) : defaultW; @@ -1775,7 +1775,10 @@ ${FAVICON_HTML} const chain = []; let el = target; while (el) { - chain.push(el.getAttribute('data-node-id')); + // A node inside a component instance renders as "/": + // the comment anchors on the instance, the node the canvas stores. + const id = el.getAttribute('data-node-id').split('/')[0]; + if (!chain.includes(id)) chain.push(id); el = el.parentElement && el.parentElement.closest('[data-node-id]'); } openPopover(chain, e); diff --git a/test/browser/test-one-tree-layout.ts b/test/browser/test-one-tree-layout.ts new file mode 100644 index 0000000..637bdd3 --- /dev/null +++ b/test/browser/test-one-tree-layout.ts @@ -0,0 +1,63 @@ +import '../env.js'; +// Phase 32 slice B (FR-B1): layout reads the one tree. snapshot_layout names a +// node inside an instance by its expanded id (`/`), so the +// same child in two instances has two ids, and canvas_stress names that node +// the same way. Both trees are built as the tools build them: snapshot_layout +// renders prepareRender's tree (expanded, then resolved); canvas_stress +// perturbs the raw expansion and resolves it. +// +// Usage: npx tsx test/browser/test-one-tree-layout.ts + +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { computeLayout, shutdown, type LayoutRect } from '../../src/screenshot.js'; +import { expandTree } from '../../src/expand.js'; +import { resolveVariables } from '../../src/variables.js'; +import { getCanvasTokens } from '../../src/workspaces.js'; +import { applyPerturbation, compareLayouts } from '../../src/stress.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 ids = (rects: LayoutRect[]): string[] => rects.flatMap((r) => [r.nodeId, ...ids(r.children ?? [])]); + +const canvas = createCanvas('one tree layout'); +const [page, card] = parseAndExecute(canvas.root, ` +page=I("document", {type: "frame", name: "page", layout: "horizontal", gap: 16, padding: 24, fill: "#FFFFFF", width: 800}) +card=I("document", {type: "component", name: "Card", layout: "vertical", padding: 16, gap: 8, fill: "#F3F4F6", width: 200}) +title=I(card, {type: "text", name: "title", content: "Quarterly revenue", fontSize: 16, color: "#111111"}) +`, canvas).map((r) => r.nodeId!); +const title = canvas.components[card].children![0].id; +const [a, b] = parseAndExecute(canvas.root, ` +a=I("${page}", {type: "instance", name: "card-a", componentId: "${card}"}) +b=I("${page}", {type: "instance", name: "card-b", componentId: "${card}"}) +`, canvas).map((r) => r.nodeId!); + +const w = 800; +const h = 400; +const tokens = getCanvasTokens(canvas); + +// snapshot_layout's tree. +const snapshot = ids(await computeLayout(renderToHtml(expandTree(canvas.root, canvas, tokens).root, w, h, canvas), undefined, 25, { width: w, height: h })); +check('snapshot_layout names the child in the first instance by its expanded id', snapshot.includes(`${a}/${title}`)); +check('…and in the second by another', snapshot.includes(`${b}/${title}`)); +check('…every rect id is unique', new Set(snapshot).size === snapshot.length); + +// canvas_stress's tree: the raw expansion, perturbed, then resolved. +const base = expandTree(canvas.root, canvas).root; +const render = (root: typeof base) => renderToHtml(resolveVariables(structuredClone(root), tokens), w, h, canvas); +const baseline = await computeLayout(render(base), undefined, 25, { width: w, height: h }); +const run = applyPerturbation('long-text', base); +check('canvas_stress touches the child in each instance under its expanded id', run.touched.includes(`${a}/${title}`) && run.touched.includes(`${b}/${title}`), run.touched.join(', ')); +check('…the same ids snapshot_layout gives', run.touched.every((id) => snapshot.includes(id))); +const perturbed = await computeLayout(render(run.root), undefined, 25, { width: w, height: h }); +const findings = compareLayouts(baseline, perturbed, run.touched, w); +check('…and any finding it raises names a node snapshot_layout knows', findings.every((f) => snapshot.includes(f.nodeId)), JSON.stringify(findings)); + +await shutdown(); +console.log(allPass ? '\nAll one-tree layout checks passed.' : '\nSome one-tree layout checks FAILED.'); +process.exit(allPass ? 0 : 1); diff --git a/test/browser/test-patterns-desktop-window.ts b/test/browser/test-patterns-desktop-window.ts index 72483b9..3ced60b 100644 --- a/test/browser/test-patterns-desktop-window.ts +++ b/test/browser/test-patterns-desktop-window.ts @@ -23,7 +23,7 @@ import { createCanvas } from '../../src/scene-graph.js'; import { evaluateCanvas } from '../../src/evaluate.js'; import { getVariables, resolveVariables, setVariables } from '../../src/variables.js'; import { renderToHtml } from '../../src/renderer.js'; -import { expandInstances } from '../../src/drift.js'; +import { expandTree } from '../../src/expand.js'; import { computeLayout, shutdown } from '../../src/screenshot.js'; import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from '../../src/stress.js'; import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from '../../src/design-language.js'; @@ -56,7 +56,7 @@ async function stressWarnings(canvas: Canvas): Promise { const h = canvas.root.height as number; const merged = getVariables(canvas); const layoutOf = (root: SceneNode) => computeLayout(renderToHtml(resolveVariables(structuredClone(root), merged), w, h, canvas), undefined, 25, { width: w, height: h }); - const base = expandInstances(canvas.root, canvas); + const base = expandTree(canvas.root, canvas).root; const baseline = await layoutOf(base); const warnings: string[] = []; for (const p of PERTURBATION_NAMES) { @@ -73,7 +73,7 @@ async function stressWarnings(canvas: Canvas): Promise { async function layoutRects(canvas: Canvas): Promise<{ nodeId: string; width: number }[]> { const w = canvas.root.width as number; const h = canvas.root.height as number; - const rects = await computeLayout(renderToHtml(resolveVariables(structuredClone(expandInstances(canvas.root, canvas)), getVariables(canvas)), w, h, canvas), undefined, 25, { width: w, height: h }); + const rects = await computeLayout(renderToHtml(resolveVariables(structuredClone(expandTree(canvas.root, canvas).root), getVariables(canvas)), w, h, canvas), undefined, 25, { width: w, height: h }); const out: { nodeId: string; width: number }[] = []; const walk = (r: { nodeId: string; width: number; children?: unknown[] }) => { out.push(r); (r.children as typeof r[] | undefined)?.forEach(walk); }; rects.forEach(walk); diff --git a/test/browser/test-patterns-desktop.ts b/test/browser/test-patterns-desktop.ts index 8ff3a59..ea067c3 100644 --- a/test/browser/test-patterns-desktop.ts +++ b/test/browser/test-patterns-desktop.ts @@ -32,7 +32,7 @@ import { createCanvas } from '../../src/scene-graph.js'; import { evaluateCanvas } from '../../src/evaluate.js'; import { getVariables, resolveVariables, setVariables } from '../../src/variables.js'; import { renderToHtml } from '../../src/renderer.js'; -import { expandInstances } from '../../src/drift.js'; +import { expandTree } from '../../src/expand.js'; import { computeLayout, shutdown, type LayoutRect } from '../../src/screenshot.js'; import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from '../../src/stress.js'; import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from '../../src/design-language.js'; @@ -93,7 +93,7 @@ function flat(rects: LayoutRect[]): LayoutRect[] { /** Warnings from a full stress run, as canvas_stress computes them, and the * nodes `many` and `empty` touched. */ async function stress(canvas: Canvas): Promise<{ warnings: string[]; touched: Record }> { - const base = expandInstances(canvas.root, canvas); + const base = expandTree(canvas.root, canvas).root; const baseline = await layoutOf(canvas, base); const warnings: string[] = []; const touched: Record = {}; @@ -132,7 +132,7 @@ for (const s of app) { // Tripled content scrolls inside its pane: the root keeps the artboard's // height and no row squashes to make room. const canvas = stamped(s.name, component); - const base = expandInstances(canvas.root, canvas); + const base = expandTree(canvas.root, canvas).root; const before = new Map(flat(await layoutOf(canvas, base)).map((r) => [r.nodeId, r])); const after = flat(await layoutOf(canvas, applyPerturbation('many', base, { type: 'desktop-app' }).root)); const root = after.find((r) => r.nodeId === canvas.root.id); @@ -156,7 +156,7 @@ for (const s of app) { const narrow = stamped(s.name, component, undefined, { width: 1024, height: 768 }); const narrowFindings = (await detailedFindings(narrow)).filter((f) => f.includes('desktop-app-')); check(`${s.name}: detailed mode raises no desktop-app finding at 1024×768`, narrowFindings.length === 0, narrowFindings.slice(0, 4).join(' | ')); - const past = flat(await layoutOf(narrow, expandInstances(narrow.root, narrow))).filter((r) => r.x + r.width > 1024 + 1); + const past = flat(await layoutOf(narrow, expandTree(narrow.root, narrow).root)).filter((r) => r.x + r.width > 1024 + 1); check(`${s.name}: nothing reaches past a 1024px window`, past.length === 0, past.slice(0, 4).map((r) => `${r.nodeId} ${r.x + r.width}`).join(' | ')); } @@ -174,7 +174,7 @@ for (const s of app) { return canvas; }; const manyWarnings = async (canvas: Canvas) => { - const base = expandInstances(canvas.root, canvas); + const base = expandTree(canvas.root, canvas).root; const run = applyPerturbation('many', base, { type: 'desktop-app' }); return compareLayouts(await layoutOf(canvas, base), await layoutOf(canvas, run.root), run.touched, 1440).filter((f) => f.severity === 'warning'); }; @@ -182,7 +182,7 @@ for (const s of app) { check('twin: the same pane with overflow hidden clips under many', (await manyWarnings(shellWith({ overflow: 'hidden' }, true))).some((f) => f.kind === 'clip' && f.nodeId === 'pane')); const rootHeight = async (canvas: Canvas) => { - const run = applyPerturbation('many', expandInstances(canvas.root, canvas), { type: 'desktop-app' }); + const run = applyPerturbation('many', expandTree(canvas.root, canvas).root, { type: 'desktop-app' }); return flat(await layoutOf(canvas, run.root)).find((r) => r.nodeId === canvas.root.id)?.height; }; check('with root overflow hidden the root keeps the window height', (await rootHeight(shellWith({ overflow: 'auto' }, true))) === 900); @@ -194,7 +194,7 @@ for (const s of app) { const canvas = stamped('dashboard-app', false); const table = flatNodes(canvas.root).find((n) => n.id === 'dba-table')!; if (overflow) table.overflow = overflow; - const base = expandInstances(canvas.root, canvas); + const base = expandTree(canvas.root, canvas).root; const before = new Map(flat(await layoutOf(canvas, base)).map((r) => [r.nodeId, r.height])); const after = flat(await layoutOf(canvas, applyPerturbation('many', base, { type: 'desktop-app' }).root)); return after.filter((r) => (before.get(r.nodeId) ?? 0) - r.height > 1).map((r) => r.nodeId); diff --git a/test/browser/test-patterns-mobile.ts b/test/browser/test-patterns-mobile.ts index ca96374..0f4d3d7 100644 --- a/test/browser/test-patterns-mobile.ts +++ b/test/browser/test-patterns-mobile.ts @@ -21,7 +21,7 @@ import { createCanvas } from '../../src/scene-graph.js'; import { evaluateCanvas } from '../../src/evaluate.js'; import { getVariables, resolveVariables } from '../../src/variables.js'; import { renderToHtml } from '../../src/renderer.js'; -import { expandInstances } from '../../src/drift.js'; +import { expandTree } from '../../src/expand.js'; import { computeLayout, shutdown } from '../../src/screenshot.js'; import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from '../../src/stress.js'; import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from '../../src/design-language.js'; @@ -45,7 +45,7 @@ async function stressWarnings(canvas: Canvas): Promise { const w = canvas.root.width as number; const h = canvas.root.height as number; const merged = getVariables(canvas); - const base = expandInstances(canvas.root, canvas); + const base = expandTree(canvas.root, canvas).root; const layoutOf = (root: typeof base) => computeLayout(renderToHtml(resolveVariables(structuredClone(root), merged), w, h, canvas), undefined, 25, { width: w, height: h }); const baseline = await layoutOf(base); diff --git a/test/browser/test-scaffold-system.ts b/test/browser/test-scaffold-system.ts index 90968eb..4cf0857 100644 --- a/test/browser/test-scaffold-system.ts +++ b/test/browser/test-scaffold-system.ts @@ -25,7 +25,7 @@ import { createCanvas, getCanvas } from '../../src/scene-graph.js'; import { generateDesignSystem } from '../../src/design-language.js'; import { setVariables, resolveVariables, getVariables } from '../../src/variables.js'; import { renderToHtml } from '../../src/renderer.js'; -import { expandInstances } from '../../src/drift.js'; +import { expandTree } from '../../src/expand.js'; import { computeLayout, takeScreenshot, shutdown } from '../../src/screenshot.js'; import { applyPerturbation, compareLayouts, PERTURBATION_NAMES, type PerturbationName } from '../../src/stress.js'; import type { Canvas, SceneNode } from '../../src/types.js'; @@ -104,7 +104,7 @@ for (const { name, kind, surface } of structures) { const w = typeof cv.root.width === 'number' ? cv.root.width : 1440; const h = typeof cv.root.height === 'number' ? cv.root.height : 900; const merged = getVariables(cv); - const base = expandInstances(cv.root, cv); + const base = expandTree(cv.root, cv).root; const baseline = await computeLayout( renderToHtml(resolveVariables(structuredClone(base), merged), w, h, cv), undefined, 25, { width: w, height: h }); diff --git a/test/e2e/test-mobile-rules-detailed.ts b/test/e2e/test-mobile-rules-detailed.ts index 8fa66ce..9c89900 100644 --- a/test/e2e/test-mobile-rules-detailed.ts +++ b/test/e2e/test-mobile-rules-detailed.ts @@ -291,7 +291,12 @@ I("document", { type: "frame", name: "Pinned", position: "fixed", bottom: 0, hei tokens.variables = { ...tokens.variables, spacing: { 'space-12': 60 } }; tokens.components = { pad: { id: 'pad', type: 'component', layout: 'vertical', children: [{ id: 'pad-sp', type: 'frame', height: '$space-12' }, { id: 'pad-t', type: 'text', content: 'Inside' }] } }; const tk = await safeArea(tokens, 'detailed'); - check('detailed reads a component as the screenshot draws it (its own $refs unresolved)', tk.some((i) => i.message.includes('top')), show(tk)); + // Phase 32 slice B: the screenshot resolves a component's own $refs, so its + // 60px spacer clears the top inset, and detailed mode reads the same. + check('detailed reads a component as the screenshot draws it (its $refs resolved: the spacer clears the inset)', !tk.some((i) => i.message.includes('top')), show(tk)); + tokens.variables = { ...tokens.variables, spacing: { 'space-12': 4 } }; + const tk4 = await safeArea(tokens, 'detailed'); + check('…twin: a 4px spacer leaves the content in the top inset', tk4.some((i) => i.message.includes('top')), show(tk4)); } console.log(allPass ? '\nAll detailed mobile checks passed.' : '\nSome detailed mobile checks FAILED.'); diff --git a/test/unit/test-components.ts b/test/unit/test-components.ts index 992e748..a173930 100644 --- a/test/unit/test-components.ts +++ b/test/unit/test-components.ts @@ -41,7 +41,9 @@ function buildShell(canvas: Canvas): SceneNode { result.overridableChildren.join(',') === 'Sidebar,Logo,ActiveNav', result.overridableChildren.join(',')); check('def registered on the canvas', !!canvas.components['cmp-shell'] && canvas.components['cmp-shell'].type === 'frame'); check('tree now holds an instance node', findNode(canvas.root, shell.id)?.node.type === 'instance'); - check('render is identical after promotion', render(canvas) === before); + // Inside the instance a node renders under its expanded id, "/" + // (Phase 32 slice B); with that prefix removed the markup is the same. + check('render is identical after promotion, ids aside', render(canvas).split(`"${shell.id}/`).join('"') === before); // Second instance with an override by child name. insertNode(canvas.root, canvas.root.id, { type: 'instance', componentId: 'cmp-shell', overrides: { ActiveNav: { content: 'Settings' } } }); diff --git a/test/unit/test-discoverability.ts b/test/unit/test-discoverability.ts index 953ee4e..a5ac9aa 100644 --- a/test/unit/test-discoverability.ts +++ b/test/unit/test-discoverability.ts @@ -464,6 +464,15 @@ const guidelines = readFileSync('docs/GUIDELINES.md', 'utf-8'); expect('state is in batch_design\'s property list', /checked, disabled, state, value/.test(indexSrc)); } +// ── Phase 32 slice B: findings inside a component instance ───────────────── +{ + // A finding there names the instance in nodeId and the inner node here. + for (const [label, src] of [['src/index.ts', indexSrc], ['README', readme], ['GUIDELINES', guidelines]] as const) { + expect(`innerNodeId documented in ${label}`, src.includes('innerNodeId')); + expect(`the expanded id form "/" documented in ${label}`, src.includes('/')); + } +} + let allPass = true; for (const c of checks) { if (!c.ok) allPass = false; diff --git a/test/unit/test-drift.ts b/test/unit/test-drift.ts index 1f7cf69..e7d7a1c 100644 --- a/test/unit/test-drift.ts +++ b/test/unit/test-drift.ts @@ -6,7 +6,8 @@ // Usage: npx tsx test/unit/test-drift.ts import '../env.js'; -import { computeStructuralDrift, extractInventory, expandInstances, isDataLike } from '../../src/drift.js'; +import { computeStructuralDrift, extractInventory, isDataLike } from '../../src/drift.js'; +import { expandTree } from '../../src/expand.js'; import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; @@ -188,14 +189,14 @@ check('structural: words survive', !isDataLike('STATUS') && !isDataLike('Rename' check('missing-text findings capped at 20 + summary', perString.length === 20 && !!summary && summary.detail.includes('10 more'), summary?.detail); } -// ── expandInstances sees through components ───────────────────────────────── +// ── expandTree sees through components ───────────────────────────────── { const shell: SceneNode = frame([text('Dashboard'), control('toggle')], { name: 'Shell' }); const canvas = { components: { 'cmp-shell': shell }, root: doc([{ id: 'inst-1', type: 'instance', componentId: 'cmp-shell' } as SceneNode]), } as unknown as Canvas; - const inv = extractInventory(expandInstances(canvas.root, canvas)); + const inv = extractInventory(expandTree(canvas.root, canvas).root); check('instance expanded into inventory', inv.texts.some((t) => t.display === 'Dashboard') && inv.controls.length === 1, JSON.stringify(inv.counts)); } diff --git a/test/unit/test-element-states.ts b/test/unit/test-element-states.ts index 2212d1e..fbf34cc 100644 --- a/test/unit/test-element-states.ts +++ b/test/unit/test-element-states.ts @@ -133,7 +133,7 @@ for (const s of ['rest', 'hover', 'focus', 'pressed'] as const) { check('P3: then $primary', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'focus' }], onlyPrimary), 'n').includes(ringCss('#B45309'))); check('P3: then #2563EB', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'focus' }], {}), 'n').includes(ringCss('#2563EB'))); const unresolved = tag(render([{ id: 'n', type: 'button', label: 'S', state: 'hover', color: '#FFFFFF', fill: '#000000' }], {}, false), 'n'); - check('P3: an unresolved node (inside a component) uses #2563EB and the constant layers', unresolved.includes(layer('#FFFFFF', 8)) && unresolved.includes('--fs-ring: #2563EB'), unresolved); + check('P3: an unresolved node (a tree rendered without resolution) uses #2563EB and the constant layers', unresolved.includes(layer('#FFFFFF', 8)) && unresolved.includes('--fs-ring: #2563EB'), unresolved); const tuned: DesignVariables = { ...SYSTEM, state: { ...SYSTEM.state, hover: 0.2, pressed: 0.3 } }; const h = tag(render([{ id: 'n', type: 'button', label: 'S', state: 'hover' }], tuned), 'n'); check('P3: a hover token of 0.2 layers at 20%', h.includes('#FFFFFF 20%'), h); diff --git a/test/unit/test-one-tree.ts b/test/unit/test-one-tree.ts new file mode 100644 index 0000000..8a273ba --- /dev/null +++ b/test/unit/test-one-tree.ts @@ -0,0 +1,158 @@ +import '../env.js'; +// Phase 32 slice B (FR-B1, FR-B2): the renderer and every rule read one tree, +// with instances expanded and then resolved. A disabled button inside an +// instance renders as it does outside one; a low-contrast text inside an +// instance is one error reported on the instance, with the inner node named +// and no fix; feedback on an inner node lands on the instance. +// +// Usage: npx tsx test/unit/test-one-tree.ts + +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { expandTree, storedId } from '../../src/expand.js'; +import { addFeedback } from '../../src/feedback.js'; +import type { Canvas, DesignVariables } 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}` : ''}`); +} + +/** A page holding one instance of a card (a button and a faint note) and, + * beside it, the same button outside any component. */ +function build(variables: DesignVariables, override: Record) { + const canvas = createCanvas('one tree'); + canvas.variables = variables; + const ops = parseAndExecute(canvas.root, ` +page=I("document", {type: "frame", name: "page", layout: "vertical", gap: 16, padding: 24, fill: "#FFFFFF", width: 800}) +card=I("document", {type: "component", name: "Card", layout: "vertical", padding: 16, gap: 8, fill: "#FFFFFF"}) +cta=I(card, {type: "button", name: "cta", label: "Save", variant: "primary"}) +note=I(card, {type: "text", name: "note", content: "A faint note", color: "#EEEEEE", fontSize: 14}) +`, canvas); + const page = ops[0].nodeId!; + const card = ops[1].nodeId!; + const def = canvas.components[card]; + const childId = (name: string) => def.children!.find((c) => c.name === name)!.id; + const [inst, outside] = parseAndExecute(canvas.root, ` +inst=I("${page}", {type: "instance", name: "card-1", componentId: "${card}", overrides: ${JSON.stringify({ cta: override })}}) +out=I("${page}", ${JSON.stringify({ type: 'button', name: 'outside', label: 'Save', variant: 'primary', ...override })}) +`, canvas).map((r) => r.nodeId!); + return { canvas, inst, outside, cta: childId('cta'), note: childId('note') }; +} + +/** The opening tag of the element a node id renders as, without the id. */ +function tagOf(html: string, id: string): string { + const at = html.indexOf(`data-node-id="${id}"`); + if (at < 0) return ''; + const start = html.lastIndexOf('<', at); + return html.slice(start, html.indexOf('>', at) + 1).replace(` data-node-id="${id}"`, ''); +} + +const PLAIN: DesignVariables = { colors: { accent: '#0F766E', 'bg-surface': '#FFFFFF', 'text-primary': '#111111' } }; +const STATE_TOKENS: DesignVariables = { ...PLAIN, state: { disabledContent: 0.38, disabledContainer: 0.12 } }; + +// ── FR-B1: a disabled button inside an instance renders as it does outside ── +for (const [label, vars] of [['without state tokens', PLAIN], ['with state tokens', STATE_TOKENS]] as const) { + const { canvas, inst, outside, cta } = build(vars, { disabled: true }); + const html = renderToHtml(canvas.root, 800, 600, canvas); + const inner = tagOf(html, `${inst}/${cta}`); + const out = tagOf(html, outside); + check(`disabled button inside an instance renders at all (${label})`, inner !== '' && out !== ''); + check(`…with the same markup and style as outside one (${label})`, inner === out, inner === out ? undefined : `\n inside: ${inner}\n outside: ${out}`); + check(`…in the design system's accent, not the fallback (${label})`, out.includes('#0F766E') && !inner.includes('#2563EB'), inner); +} + +// The same render, expanded by the caller first, is byte-identical. +{ + const { canvas } = build(PLAIN, { disabled: true }); + const viaRenderer = renderToHtml(canvas.root, 800, 600, canvas); + const viaHelper = renderToHtml(expandTree(canvas.root, canvas, canvas.variables).root, 800, 600, canvas); + check('rendering a raw tree equals rendering the expanded, resolved tree', viaRenderer === viaHelper); +} + +// Two instances of one component: distinct ids for the same child. +{ + const { canvas, inst, cta } = build(PLAIN, {}); + const page = canvas.root.children![0].id; + const [second] = parseAndExecute(canvas.root, `I("${page}", {type: "instance", name: "card-2", componentId: "${(canvas.root.children![0].children![0] as { componentId?: string }).componentId}"})`, canvas).map((r) => r.nodeId!); + const { root, owners } = expandTree(canvas.root, canvas); + const ids: string[] = []; + (function walk(n: typeof root) { ids.push(n.id); n.children?.forEach(walk); })(root); + check('two instances give one child two distinct ids', ids.includes(`${inst}/${cta}`) && ids.includes(`${second}/${cta}`)); + check('ids are unique across the expanded tree', new Set(ids).size === ids.length); + check('owners map each inner id to its instance', owners.get(`${inst}/${cta}`)?.id === inst && owners.get(`${second}/${cta}`)?.id === second); + check('the instance root keeps its own id and is not owned', ids.includes(inst) && !owners.has(inst)); + check('storedId gives the instance for an inner id', storedId(`${inst}/${cta}`) === inst && storedId(inst) === inst); +} + +// ── FR-B2: a finding inside an instance names it ──────────────────────────── +{ + const { canvas, inst, note } = build(PLAIN, {}); + const result = await evaluateCanvas(canvas, { mode: 'fast' }); + const contrast = result.issues.filter((i) => i.category === 'color' && i.severity === 'error' && (i.innerNodeId === `${inst}/${note}` || i.nodeId === `${inst}/${note}`)); + check('faint text inside an instance is one contrast error', contrast.length === 1, JSON.stringify(result.issues.filter((i) => i.category === 'color'))); + const issue = contrast[0]; + check('…with nodeId the instance', issue?.nodeId === inst, issue?.nodeId); + check('…innerNodeId the text\'s expanded id', issue?.innerNodeId === `${inst}/${note}`, issue?.innerNodeId); + check('…naming the instance and its component', !!issue?.message.includes('instance "card-1" of component "Card"'), issue?.message); + check('…and no fix', issue !== undefined && issue.fix === undefined); + const fixOps = result.issues.flatMap((i) => [i.fix?.op, ...(i.fixes ?? []).map((f) => f.op)]).filter((op): op is string => !!op); + check('no fix op names an expanded id (canvas_autofix stays applicable)', fixOps.every((op) => !op.includes(`${inst}/`)), fixOps.join(' | ')); + check('no finding keeps an expanded id as its nodeId', result.issues.every((i) => !i.nodeId.includes('/'))); +} + +// Without the instance, the same faint text outside is the same error, on itself. +{ + const canvas: Canvas = createCanvas('outside'); + parseAndExecute(canvas.root, ` +page=I("document", {type: "frame", layout: "vertical", padding: 24, fill: "#FFFFFF", width: 800}) +t=I(page, {type: "text", content: "A faint note", color: "#EEEEEE", fontSize: 14}) +`, canvas); + const result = await evaluateCanvas(canvas, { mode: 'fast' }); + const errors = result.issues.filter((i) => i.category === 'color' && i.severity === 'error'); + check('outside an instance the text is an error on itself, with no innerNodeId', errors.length === 1 && errors[0].innerNodeId === undefined); +} + +// ── FR-B2: feedback on an inner node lands on the instance ────────────────── +{ + const { canvas, inst, note } = build(PLAIN, {}); + const entry = addFeedback(canvas, { nodeId: `${inst}/${note}`, comment: 'too faint' }); + check('feedback on an expanded id is stored on the instance', entry.nodeId === inst, entry.nodeId); + check('…with the instance\'s snapshot', entry.node?.type === 'instance', JSON.stringify(entry.node)); + const throws = (nodeId: string) => { try { addFeedback(canvas, { nodeId, comment: 'x' }); return false; } catch { return true; } }; + check('an expanded id whose instance does not exist still throws', throws('nope/x')); + check('an id under a real instance that is not in its expansion throws', throws(`${inst}/ghost`)); + check('an id under a stored node that is not an instance throws', throws(`${canvas.root.children![0].id}/${note}`)); +} + +// ── edges the verify round found ──────────────────────────────────────────── +{ + // A stored icon whose id matches a component child's: each is its own origin, + // so the stored one keeps its autofix. + const canvas: Canvas = createCanvas('icon origins'); + canvas.components = { cmp: { id: 'cmp', type: 'component', name: 'Cmp', children: [{ id: 'ic', type: 'icon', icon: 'material:arrow-back' }] } }; + canvas.root.children = [ + { id: 'i1', name: 'i1', type: 'instance', componentId: 'cmp' }, + { id: 'ic', type: 'icon', icon: 'material:arrow-back' }, + ]; + const icons = (await evaluateCanvas(canvas, { mode: 'fast', categories: ['structure'] })).issues.filter((i) => i.message.includes('Unknown icon')); + check('a stored icon and a component icon with one id are two findings', icons.length === 2, JSON.stringify(icons.map((i) => i.nodeId))); + check('…the stored one keeps its fix', icons.some((i) => i.nodeId === 'ic' && !!i.fix), JSON.stringify(icons)); +} +{ + // A component holding an instance of itself expands once and stops. + const canvas: Canvas = createCanvas('recursive'); + canvas.components = { loop: { id: 'loop', type: 'component', name: 'Loop', children: [{ id: 't', type: 'text', content: 'Hi', color: '#111111' }, { id: 'again', type: 'instance', componentId: 'loop' }] } }; + canvas.root.children = [{ id: 'i1', name: 'i1', type: 'instance', componentId: 'loop' }]; + const { root } = expandTree(canvas.root, canvas); + const ids: string[] = []; + (function walk(n: typeof root) { ids.push(n.id); n.children?.forEach(walk); })(root); + check('a self-nesting component expands one level', ids.includes('i1/t') && ids.includes('i1/again') && !ids.some((id) => id.startsWith('i1/again/')), ids.join(', ')); + check('…and renders and evaluates without overflowing', renderToHtml(canvas.root, 400, 300, canvas).includes('i1/t') && (await evaluateCanvas(canvas, { mode: 'fast' })).overallScore >= 0); +} + +console.log(allPass ? '\nAll one-tree checks passed.' : '\nSome one-tree checks FAILED.'); +process.exit(allPass ? 0 : 1); diff --git a/test/unit/test-overlays.ts b/test/unit/test-overlays.ts index 378b2b9..1e4b30e 100644 --- a/test/unit/test-overlays.ts +++ b/test/unit/test-overlays.ts @@ -185,7 +185,7 @@ const modal = (extra: Partial = {}): SceneNode => ({ check('explicit fill wins; $token refs inside actions resolve', explicit.children![0].fill === '#000000' && explicit.children![0].actions![0].fill === TOKENS.danger); const noElevation = resolveVariables(canvasWith([modal()], app, TOKENS).root, { colors: TOKENS }); check('without $elevation.overlay no shadows are set (renderer fallback)', noElevation.children![0].shadows === undefined); - // Unthemed and inside a component (which skips resolveVariables): neutral fallbacks, never invisible. + // Unthemed, or a raw tree rendered without resolveVariables: neutral fallbacks, never invisible. const unthemed = layerOf(renderToHtml(canvasWith([modal(), { id: 'tip', name: 'tip', type: 'tooltip', text: 'x' }]).root, 1440, 900)); check('unthemed modal: white surface, grey border, dark text', /data-node-id="m"[^>]*background-color: #FFFFFF; border: 1px solid #D1D5DB/.test(unthemed)); check('unthemed tooltip: dark fill, light text', /data-node-id="tip"[^>]*background-color: #111827; color: #FFFFFF/.test(unthemed)); diff --git a/test/unit/test-state-checks.ts b/test/unit/test-state-checks.ts index fa5c110..eea78c4 100644 --- a/test/unit/test-state-checks.ts +++ b/test/unit/test-state-checks.ts @@ -149,10 +149,13 @@ const inspector = (): SceneNode[] => [panel([ f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go' }], { fill: '$bg' })], { colors: { bg: '#FFFFFF', 'focus-ring': '#1d4ed8' }, dark: { colors: { bg: '#0b1220', 'focus-ring': '#1e3a8a' } } }), FOCUS); check('R2: a dark-only failure is tagged dark', f.length === 1 && f[0].theme === 'dark' && /dark token layer/.test(f[0].suggestion ?? ''), show(f)); - // Inside a component: the ring falls back to #2563EB, reported on the instance. + // Inside a component: the ring is the design system's, as the render draws it + // (Phase 32 slice B: instances are expanded, then resolved), reported on the instance. const comp: SceneNode = { id: 'cc', type: 'frame', fill: '#2563EB', children: [{ id: 'cb1', type: 'button', label: 'Go' }] }; + f = of(await issues([panel([{ id: 'i1', name: 'i1', type: 'instance', componentId: 'cc' }])], { colors: { 'focus-ring': '#1d4ed8' } }, 'desktop-app', { cc: comp }), FOCUS); + check('R2: a target inside a component uses the design system\'s ring and reports the instance', f.length === 1 && ids(f[0]) === 'i1' && /#1d4ed8/i.test(f[0].message) && /instance "i1"/.test(f[0].message), show(f)); f = of(await issues([panel([{ id: 'i1', name: 'i1', type: 'instance', componentId: 'cc' }])], { colors: { 'focus-ring': '#000000' } }, 'desktop-app', { cc: comp }), FOCUS); - check('R2: a target inside a component uses #2563EB and reports the instance', f.length === 1 && ids(f[0]) === 'i1' && /#2563EB/.test(f[0].message), show(f)); + check('R2 twin: a ring that clears 3:1 inside a component passes (the fallback #2563EB no longer applies)', f.length === 0, show(f)); // Desktop-app only. for (const type of ['web', 'mobile'] as const) { @@ -377,10 +380,11 @@ for (const personality of PERSONALITY_NAMES) { check('V4 fix: a literal pair is reported once (no dark copy)', f.length === 1 && !f[0].theme, show(f)); f = of(await issues([{ id: 'tok', type: 'frame', fill: '$bg-primary', children: [{ id: 'tg', type: 'toggle', fill: '$bg-surface' }] }], sysD), BOUNDARY); check('V4 fix twin: a token pair that fails in both themes is reported per theme', f.length === 2 && f.some((i) => i.theme === 'dark'), show(f)); - // V4: inside an instance the suggestion says the tokens never reach it. + // V4, Phase 32 slice B: the design system reaches inside an instance, so a + // checkbox there draws $border-strong and passes, as it does outside. const compI: SceneNode = { id: 'cf', type: 'frame', children: [{ id: 'cbi', type: 'checkbox' }] }; f = of(await issues([panel([{ id: 'i9', name: 'Field', type: 'instance', componentId: 'cf' }])], sysD, 'desktop-app', { cf: compI }), BOUNDARY); - check('V4 fix: an instance finding\'s suggestion says the design system never reaches it', f.length > 0 && f.every((i) => /inside a component instance/.test(i.suggestion ?? '')), show(f)); + check('V4: a checkbox inside an instance draws the design system\'s $border-strong and passes', f.length === 0, show(f)); f = of(await issues([panel([{ id: 'cb', type: 'checkbox', stroke: '#EEEEEE' }])], sysD), BOUNDARY); check('V4 fix twin: a direct finding keeps the token suggestion', f.length > 0 && f.every((i) => /border-strong/.test(i.suggestion ?? '')), show(f)); // Out-of-contract values degrade instead of throwing. @@ -396,10 +400,10 @@ for (const personality of PERSONALITY_NAMES) { check('fix: a numeric fill paints nothing in the walk (no throw)', numeric.kind === 'color' && numeric.rgb.join(',') === '0,0,0', JSON.stringify(numeric)); // A grouped finding whose members sit inside instances names them. const comp: SceneNode = { id: 'cc', type: 'frame', children: [{ id: 'inner', type: 'button', label: 'Go' }] }; - // A component's button rings in #2563EB; on a #2563EB panel it shares the - // direct button's failing pair when the token ring is #2563EB too. + // A component's button rings in the token ring as the direct one does, so on + // a #2563EB panel with a #2563EB ring both share one failing pair. f = of(await issues([panel([{ id: 'direct', type: 'button', label: 'Go' }, { id: 'i1', name: 'Card', type: 'instance', componentId: 'cc' }], { fill: '#2563EB' })], { colors: { 'focus-ring': '#2563EB' } }, 'desktop-app', { cc: comp }), FOCUS); - check('fix: a group with members in an instance says so by name', f.some((i) => /some inside instances, listed by instance: "Card"/.test(i.message) && (i.nodeIds ?? []).includes('i1')), show(f)); + check('fix: a group with members in an instance says so by name', f.some((i) => /some inside instance "Card" of component "cc"/.test(i.message) && (i.nodeIds ?? []).includes('i1')), show(f)); const plain = of(await issues([panel([{ id: 'd1', type: 'button', label: 'Go' }, { id: 'd2', type: 'button', label: 'Go' }], { fill: '#2563EB' })], { colors: { 'focus-ring': '#2563EB' } }), FOCUS); check('fix twin: a group with no instance member says nothing of instances', plain.length === 1 && !/instance/.test(plain[0].message), show(plain)); } @@ -544,13 +548,17 @@ for (const personality of PERSONALITY_NAMES) { // ── 3b fixes ───────────────────────────────────────────────────────────── { const sysR = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; + // Phase 32 slice B: an instance whose root is the target is judged with the + // design system (it passes) and, when it fails, reported on its own id. let f = of(await issues([panel([{ id: 'i1', name: 'Box', type: 'instance', componentId: 'cb' }])], sysR, 'desktop-app', { cb: { id: 'cb', type: 'checkbox' } }), BOUNDARY); - check('3b: an instance whose root is the target gets the instance advice and note', f.length > 0 && f.every((i) => /inside a component instance/.test(i.suggestion ?? '') && /\(an instance — fix it in its component\)/.test(i.message)), show(f)); + check('3b: an instance whose root is the target draws $border-strong and passes', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'i1', name: 'Box', type: 'instance', componentId: 'cb' }])], sysR, 'desktop-app', { cb: { id: 'cb', type: 'checkbox', stroke: '$nope' } }), BOUNDARY); + check('3b: a failing instance root is reported on the instance itself, with no innerNodeId', f.length > 0 && f.every((i) => (i.nodeIds ?? [i.nodeId]).includes('i1') && i.innerNodeId === undefined), show(f)); f = of(await issues([panel([{ id: 'c1', type: 'checkbox', stroke: '$nope' }])], sysR), BOUNDARY); check('3b twin: the same checkbox placed directly keeps the token advice', f.length > 0 && f.every((i) => /border-strong/.test(i.suggestion ?? '') && !/instance/.test(i.message)), show(f)); const grad = { gradient: { type: 'linear', angle: 90, stops: [{ color: '#000000', position: 0 }, { color: '#FFFFFF', position: 1 }] } as SceneNode['gradient'], fill: undefined }; f = of(await issues([panel([{ id: 'ig', name: 'G', type: 'instance', componentId: 'gb' }], grad)], {}, 'desktop-app', { gb: { id: 'gb', type: 'frame', children: [{ id: 'gbb', type: 'button', label: 'x' }] } }), FOCUS); - check('3b: an info inside an instance keeps its "check by eye" advice and adds the instance one', f.length === 1 && f[0].severity === 'info' && /by eye/.test(f[0].suggestion ?? '') && /inside a component instance/.test(f[0].suggestion ?? ''), show(f)); + check('3b: an info inside an instance keeps its "check by eye" advice and names the instance', f.length === 1 && f[0].severity === 'info' && /by eye/.test(f[0].suggestion ?? '') && /inside instance "G" of component "gb"/.test(f[0].message), show(f)); f = of(await issues([panel([{ id: 'rd', type: 'radio', stroke: 'none' }, { id: 'tg', type: 'toggle', fill: 'none' }, { id: 'cb', type: 'checkbox', stroke: 'none' }])]), BOUNDARY); check('3b: a radio or toggle message never speaks of its fill; a checkbox does', f.filter((i) => /its fill/.test(i.message)).map((i) => i.nodeId).join(',') === 'cb' && f.length === 3, show(f)); f = of(await issues([panel([{ id: 'tb', type: 'tabs', variant: 'contained', fill: 'navy', items: [{ label: 'A', active: true }] }])]), FOCUS); diff --git a/test/unit/test-unknown-icons.ts b/test/unit/test-unknown-icons.ts index de3a977..74ea6bb 100644 --- a/test/unit/test-unknown-icons.ts +++ b/test/unit/test-unknown-icons.ts @@ -111,7 +111,8 @@ expect('material:a/b rejected', getIconSvg('material:a/b') === null); { id: 'i2', type: 'instance', componentId: 'btn' }, ], components); expect('component icon reported once', issues.length === 1, JSON.stringify(issues)); - expect('message points at the component definition', !!issues[0]?.message.includes('component definition')); + expect('message points at the component', !!issues[0]?.message.includes('of component "Btn": fix it in the component'), issues[0]?.message); + expect('…reported on the first instance, naming the inner node', issues[0]?.nodeId === 'i1' && issues[0]?.innerNodeId === 'i1/btn-icon', JSON.stringify(issues[0])); expect('no fix op for an id outside the canvas tree', !issues[0]?.fix); }