diff --git a/README.md b/README.md index fd07378..bd0bb70 100644 --- a/README.md +++ b/README.md @@ -397,7 +397,7 @@ Application screens (`type: "desktop-app"`) are built from eight primitives on t `fill`, `stroke`, `color`, `iconColor` and `secondaryColor` override the token defaults (`tabs.fill` is the contained variant's active background). A canvas that holds a `nav-item`, `tabs`, `tree-row`, `menu-row` or `property-row` must declare its type (`desktop-app-artboard`). -**Element states.** `state: "hover" | "focus" | "pressed" | "disabled"` on a `button`, `link`, `text-input`, `nav-item`, `tree-row`, `menu-row`, `list-row` or control (`toggle`, `checkbox`, `radio`, `select`; on the item for `tabs`, `tab-bar`, `nav-bar` actions, `modal` actions and a `toast` action) draws that state from the design system's state tokens: hover, focus and pressed layer the label colour over the fill, or over what is behind a target with no fill (8 / 10 / 10%), focus adds a 2px `$focus-ring` at a 2px gap (inside the box for a tab and a tab-bar item), and disabled renders in `$text-primary` at `disabledContent` 38% (a drawn fill or border at `disabledContainer` 12%) when the `state` tokens set either disabled opacity (a lone one takes the other's Material value), else at 0.5 in the target's own colours. An authored `opacity` wins. It is for a states sheet or a screenshot; the evaluator never needs a state drawn. `state: "disabled"` counts as disabled wherever `disabled: true` does: it leaves the tab order, the 24px census and the primary count (the phone's 44px census still measures a disabled target). Other node types ignore it. +**Element states.** `state: "hover" | "focus" | "pressed" | "disabled"` on a `button`, `link`, `text-input`, `nav-item`, `tree-row`, `menu-row`, `list-row` or control (`toggle`, `checkbox`, `radio`, `select`; on the item for `tabs`, `tab-bar`, `nav-bar` actions, `modal` actions and a `toast` action) draws that state from the design system's state tokens: hover, focus and pressed layer the label colour over the fill, or over what is behind a target with no fill (8 / 10 / 10%), focus adds a 2px `$focus-ring` at a 2px gap (inside the box for a tab and a tab-bar item), and disabled renders in `$text-primary` at `disabledContent` 38% (a drawn fill or border at `disabledContainer` 12%) when the `state` tokens set either disabled opacity (a lone one takes the other's Material value), else at 0.5 in the target's own colours. An authored `opacity` wins. It is for a states sheet or a screenshot; the evaluator never needs a state drawn: on a desktop-app canvas four rules compute each target's focus ring, active indicator, disabled look and boundary from the scene (`desktop-app-focus-visible`, `desktop-app-state-contrast`, `desktop-app-disabled`, `desktop-app-boundary`, in the rules table below). `state: "disabled"` counts as disabled wherever `disabled: true` does: it leaves the tab order, the 24px census and the primary count (the phone's 44px census still measures a disabled target). Other node types ignore it. #### Overlays @@ -929,6 +929,10 @@ Every result also carries a **`surface`** field: `{ type, device, source, rulesO | `desktop-app-truncation` | usability | warning / info | Desktop-app only: a truncating column header warns; a hand-built ellipsis with no `title` is an info. Detailed mode: a `tabs` node whose every label is cut warns, and an ellipsis leaving fewer than four characters is an info. | | `desktop-app-primary-count` | structure | info | Desktop-app only: two or more primary `button`s in one pane (any variant but `secondary`, `ghost` or `destructive` renders filled, so it counts; no variant included). A modal's `actions` with `variant: "primary"` count in the modal's pane. Primaries inside three or more same-shaped sibling frames, such as a card grid, don't count. | | `desktop-app-overlay` | usability | warning / info | Desktop-app only: warns on a second `modal`; a `tooltip` with children; inside a modal, a table of more than ten body rows or a frame with `overflow: "auto"` that renders wider than the modal or scrolls sideways; an overlay that leaves the viewport (the root's size, else the window's; a modal wider than the viewport less 32px in both modes, in fast mode a popover or menu with numeric `x`/`y`/`width`/`height` and a placed modal's sides, in detailed mode every rendered overlay); a `popover` or `menu` on a canvas with a modal or a scrimmed drawer, which renders under the scrim. Infos: a second `toast`, a `danger` toast, an `anchor` naming no node or nothing clickable. | +| `desktop-app-focus-visible` | color | error / info | Desktop-app only, in each theme: a focus ring (`$focus-ring`, else `$accent`) below 3:1 against the pixels it covers unfocused (the backdrop behind the target; a tab's own fill for its inset ring). One error per ring and backdrop, with `nodeIds` and `count`; a target whose backdrop or ring cannot be read is listed in one info. Disabled targets are skipped. | +| `desktop-app-state-contrast` | color | warning | Desktop-app only, in each theme: an active `nav-item`'s bar or an active line tab's underline below 3:1 against its active fill, at rest or in hover. | +| `desktop-app-boundary` | color | warning | Desktop-app only, in each theme: a `text-input` border, an unchecked `checkbox` or `radio` outline, or an unchecked `toggle` track below 3:1 against what is behind it. A border that draws nothing (`transparent`, an unresolved token) counts as invisible; a field whose own fill clears 3:1 passes. `$border-strong` clears it on `bg-primary` and `bg-surface`. | +| `desktop-app-disabled` | color | info | Desktop-app only, when the `state` tokens set the disabled opacities: targets whose disabled content would draw within 1.1:1 of their enabled content. On every type, text inside a disabled clickable primitive is exempt from the text-contrast error. | 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. @@ -946,7 +950,7 @@ Whenever the `coverage` category runs on a **base** canvas, the result also carr | Category | Weight | Checks | |----------|--------|--------| | `spacing` | 20 | Off-scale padding/gap values (`gap: 0`, a flush stack, is never flagged), plus spacing variety measured against the canvas's **declared** scale (`set_variables`/`generate_scale` spacing tokens) — only values *not* on that scale count toward sprawl, so a design built entirely from its own multi-step scale (framesmith's generated scale ships nine: `space-3xs`…`space-3xl`) isn't penalized for using it. No declared scale falls back to the old total-unique-values count, with a suggestion to declare one | -| `color` | 25 | WCAG AA contrast ratios for text against nearest background — checked in BOTH themes when a `dark` token layer exists (dark-run issues carry `theme: "dark"`, score takes the worse theme, and dark failures point at the dark layer instead of carrying a literal fix). WCAG-passing pairs that are perceptually weak by **APCA** get an info advisory (Lc vs ~75 body / ~60 large) — APCA is a candidate method, not a standard; it never blocks | +| `color` | 25 | WCAG AA contrast ratios for text against nearest background — checked in BOTH themes when a `dark` token layer exists (dark-run issues carry `theme: "dark"`, score takes the worse theme, and dark failures point at the dark layer instead of carrying a literal fix). WCAG-passing pairs that are perceptually weak by **APCA** get an info advisory (Lc vs ~75 body / ~60 large) — APCA is a candidate method, not a standard; it never blocks. On a desktop-app canvas it also carries the four element-state rules (`desktop-app-focus-visible`, `desktop-app-state-contrast`, `desktop-app-boundary`, `desktop-app-disabled`; see the rules table above), each judged in both themes. Text inside a disabled clickable primitive is exempt, on every type | | `typography` | 20 | Type-scale ratios (1.1–2.0; adjacent sizes both declared as typography tokens are pinned and skip the check), font-family count, weight variation — plus score-neutral craft advisories: measure (prose past ~75 characters per line; warning past 90), tracking (display text ≥28px without negative letter-spacing, autofixable), and tabular numerals (numeric table columns without `tabularNums`, autofixable) On a mobile canvas `mobile-type-floor` adds −10 per warning. | | `structure` | 15 | Tree depth, naming coverage, design-token usage %, component reuse, unknown icon names (an icon node, or a mobile primitive's icon prop — `button.icon`, `leading.icon`, nav-bar `trailing[].icon`, `tab-bar` `items[].icon` (required) and `fab.icon` — that resolves in neither set renders an empty slot: a directive-blocking warning, −10 structure score each; autofixable for icon nodes and `button.icon` when one spelling resolves) `mobile-artboard` adds −10 per warning, on every type. | | `consistency` | 20 | Frames missing `layout`, sibling overlap (detailed mode; positioned siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt, while a bar pinned to the top still counts) — plus score-neutral advisories: **token detachment** (a literal `fill`/`stroke`/`color`/`cornerRadius` that exactly equals a token's value flags with a mechanical `$ref` autofix; ambiguous matches list candidates and never guess) and **ad-hoc motion** (3+ distinct duration/easing combos with no motion tokens declared) | diff --git a/VISION.md b/VISION.md index 2666f43..7af0cfb 100644 --- a/VISION.md +++ b/VISION.md @@ -573,7 +573,8 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 - [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 -- [ ] Slice H — state checks: focus rings, active indicators, disabled renders and control boundaries checked analytically on every interactive primitive, without being drawn +- [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 - [ ] 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 _Full spec-driven breakdown in [`docs/specs/PHASE-31-SPEC.md`](docs/specs/PHASE-31-SPEC.md). Deliberately out of scope: porting the viewer's code, anchored overlay rendering, keyboard behaviour, narrow-window collapse, the command palette and bulk-selection variants, importer work, and desktop-app rules on web._ diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 9cd29cb..f6eecb9 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -75,7 +75,7 @@ None of these rules has a mechanical fix, so `canvas_autofix` never proposes one ## The desktop-app ruleset -A `desktop-app` canvas is judged as an application, not a page. Its vocabulary is in [Desktop-app vocabulary](#desktop-app-vocabulary) and its layouts in [Starting an application screen](#starting-an-application-screen-desktop-app-realisations), its screen states in [Overlays](#overlays-screen-states), and its element states in [Element states](#element-states-a-property-not-a-variant); the analytical state checks come in a later slice of Phase 31. Each finding from these rules names its rule in a `rule` field, and the `surface` report lists them in `rulesOn`. Only `desktop-app-artboard` runs on web and mobile; the other `desktop-app-*` rules run on desktop-app canvases only. Errors and warnings block the directive (the gate on presenting); infos never do. Fast mode is the loop; before presenting, also run `canvas_evaluate({ canvasId, mode: "detailed" })`, which measures rendered rows, column edges and truncation. Nodes inside a component instance are judged as rendered and reported on the instance. None of these rules has a mechanical fix, so `canvas_autofix` proposes none. +A `desktop-app` canvas is judged as an application, not a page. Its vocabulary is in [Desktop-app vocabulary](#desktop-app-vocabulary) and its layouts in [Starting an application screen](#starting-an-application-screen-desktop-app-realisations), its screen states in [Overlays](#overlays-screen-states), and its element states in [Element states](#element-states-a-property-not-a-variant), which the four state rules below check without your drawing them. Each finding from these rules names its rule in a `rule` field, and the `surface` report lists them in `rulesOn`. Only `desktop-app-artboard` runs on web and mobile; the other `desktop-app-*` rules run on desktop-app canvases only. Errors and warnings block the directive (the gate on presenting); infos never do. Fast mode is the loop; before presenting, also run `canvas_evaluate({ canvasId, mode: "detailed" })`, which measures rendered rows, column edges and truncation. Nodes inside a component instance are judged as rendered and reported on the instance. None of these rules has a mechanical fix, so `canvas_autofix` proposes none. Two terms the rules share. A **pane** is a frame that scrolls on its own (`overflow: "auto"`), a `modal`, a `drawer`, or the root; every node belongs to its nearest pane. App panes scroll independently, so give each navigation region (a rail, a sidebar, a list) its own pane. **Prose** is text of five or more words, where a word holds letters and no digits (figures and their units are not words). @@ -98,6 +98,14 @@ Two terms the rules share. A **pane** is a frame that scrolls on its own (`overf - **`desktop-app-overlay`** (usability). Overlays that cannot work as drawn. - **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). + +- **`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. +- **`desktop-app-boundary`** (color, **warning**). The only boundary of a control below 3:1 against what is behind it: a `text-input`'s border (with or without an `error`), the outline of an unchecked `checkbox` or `radio`, the track of an unchecked `toggle`. A translucent border is measured where it is drawn, over the control's own fill, and a border that draws nothing (`transparent`, `none`, a misspelt or unresolved `$token`) counts as invisible, not as absent. A field or checkbox whose own fill clears 3:1 against the backdrop passes whatever its border, since the fill shows the edge. A checked control is not measured, since its filled box, dot or track is the cue. These controls draw `$border-strong` when the design system has it, else `$border`. `$border-strong` clears 3:1 against `bg-primary` and `bg-surface` and `$border` usually does not, so a canvas without `$border-strong` warns here: add the token (`generate_design_system` writes it, or `set_variables`) rather than recolouring each node. A `select` is not measured. +- **`desktop-app-disabled`** (color, **info**). Runs only when the `state` tokens set a disabled opacity (a lone one takes the other's Material value). It is a prediction, so it covers every target, disabled or not: it lists the targets whose disabled content would draw within 1.1:1 of their enabled content, so disabled would look enabled (for example `state.disabledContent: 1` on a row whose label is already `$text-primary`). Lower `state.disabledContent`; Material uses 0.38. +- **On every type**, a `text` node inside a disabled target (any node that takes `state`, with `disabled: true` or `state: "disabled"`, or a disabled `tabs`) is exempt from the `color` category's text-contrast check, as WCAG exempts it. - "Inside a modal" means the modal is the node's nearest overlay ancestor: a popover inside a modal is lifted out, so a table in it is the popover's, not the modal's (the popover itself still gets the scrim warning). "Wider than the modal" compares with the modal's outer width. - The viewport is the root's numeric `width` and `height`, else the window's (1440×900). A modal wider than the viewport less 32px warns in both modes, since the render squeezes it to fit. - Detailed mode checks every rendered overlay's box. Fast mode has no render, so it boxes only what your numbers decide: a `popover` or `menu` with numeric `x`, `y`, `width` and `height` (its width as the render resolves it: shrunk to the viewport, held by a `minWidth`, a menu never under 192), and a placed `modal` with numeric `x` and `y` at its own width (its height is its content, so only detailed mode judges its bottom edge). A `tooltip` and a `toast` size to their text and a `drawer` is pinned to the right edge, so only detailed mode sees them leave the window. @@ -158,7 +166,7 @@ On a canvas whose root declares a `safeArea` or pins a `tab-bar` (a phone), a ce An **element state** belongs to one target: hover, focus, pressed or disabled. It is a property, `state: "hover" | "focus" | "pressed" | "disabled"` (default `"rest"`), and the renderer draws it from the design system's state tokens. A **screen state** (a menu open, a dialog up) changes what is on screen, and stays a variant ([Overlays](#overlays-screen-states)). -Draw an element state only when a human should see it: a states sheet that shows a button at rest, hovered, focused, pressed and disabled side by side, or a screenshot of a focused field. The evaluator never needs it drawn: it judges every target in every state from the scene alone. +Draw an element state only when a human should see it: a states sheet that shows a button at rest, hovered, focused, pressed and disabled side by side, or a screenshot of a focused field. The evaluator never needs it drawn. On a desktop-app canvas it computes each target's focus ring, active indicator, disabled look and boundary from the scene alone ([the four state rules](#the-desktop-app-ruleset)), in every theme, whatever `state` the node is in. - **Who takes it.** On the node: `button`, `link`, `text-input`, `nav-item`, `tree-row`, `menu-row`, `list-row` and the four controls (`toggle`, `checkbox`, `radio`, `select`). On the item, where one primitive draws several targets: each of `tabs.items[]` and `tab-bar.items[]`, a `nav-bar`'s `leading` and each `trailing[]` action, each of a `modal`'s `actions[]`, and a `toast`'s `action`. A modal's close button takes none. Any other node type ignores `state`: it changes nothing and makes nothing a target. - **Hover, focus, pressed** lay the target's label colour over its fill at the state tokens' `hover`, `focus` and `pressed` opacities, each read on its own (Material 3's 8%, 10% and 10% for any that is unset): a filled primary lightens, a row tints over its active fill, and a target with no fill (a ghost or secondary button, a link) tints what is behind it. A link also underlines in hover and pressed. On a checkbox the layer is the mark's colour (white) when checked and the border's when not; on a radio it is the ring's; on a toggle it is the knob's (white). @@ -349,7 +357,7 @@ Authoring rules: - **Start the look with one call — `generate_design_system`.** `generate_design_system({ seed: "#0E7490", personality: "technical", workspaceId })` writes the complete design language: the color system, a curated font pairing (real faces load from the first screenshot), typography **roles** (`$display` / `$heading` / `$title` / `$body` / `$label` / `$caption`, plus `$figures` with a mono face), a radius and density stance, `$elevation.flat|raised|floating|overlay` depth tokens (the dark layer re-states each depth so it reads on dark surfaces — reference as `shadow: "$elevation.raised"`), `$motion` defaults, and the element-state tokens: a `state` section of opacities (`hover` 0.08, `focus` 0.10, `pressed` 0.10 — the share of the ink over a control's fill — and `disabledContent` 0.38 / `disabledContainer` 0.12, Material 3's values; set them by hand with `set_variables({ state: { … } })`). The personality is **required** and is a real design stance: `technical` (crisp product tool), `editorial` (serif voice, generous air), `soft` (rounded, warm), `data-dense` (instrument-panel density). Same seed, different personality = visibly different product. The two generators below regenerate just one part. - **Don't hand-pick a type scale — generate one.** `generate_scale({ ratio: "major-third", workspaceId })` derives a full `text-xs`…`text-3xl` scale plus a paired `space-3xs`…`space-3xl` scale from a named ratio (`minor-second` 1.125, `major-second` 1.2, `minor-third` 1.25, `major-third` 1.333, `perfect-fourth` 1.5, `golden` 1.618 — or any number), with the craft defaults (line-height bands, display tracking) baked in and sizes pinned against the ratio check. Pass `fluid: {}` for Utopia-style `clamp()` sizes that interpolate between viewports instead of static px. - **Don't eyeball a palette from ten hexes — generate one.** `generate_color_system({ seed: "#2563EB", workspaceId })` derives OKLCH `primary-50`…`900` + a matched neutral ramp + status colors + the `bg-surface`/`text-primary`/`accent`/… semantic tokens the structures already speak, with every text/surface pair AA-clean by construction. Status colors (`success`/`warning`/`danger`) are tuned as TEXT — each is darkened from its hue's band until it clears AA (4.5:1) against white, so a `$danger` validation message is legible, not just legible-adjacent. It also derives the color range — a `$chart-1`…`$chart-6` categorical series palette and the `-tint` layer for chips/tiles/badges — see "Designing with character" below — and two control colors, each at 3:1 or more (WCAG 1.4.11) in both themes: `$focus-ring`, against every `bg-*` and `-tint` token, and `$border-strong`, against `bg-primary` and `bg-surface`, for a control whose border is its only boundary. `generate_design_system` writes them too. -- **It ships a dark theme too.** The dark mapping lands in a sparse `dark.colors` override layer alongside the light tokens (or set one by hand via `set_variables`, which also accepts `dark.elevation` for depth-token overrides) — status colors get a second, dark-specific pass here so they clear AA against the dark surface as well. Render it with `theme: "dark"` on `screenshot` / `screenshot_responsive` / `export`; `canvas_evaluate`'s `color` category then contrast-checks both themes automatically and scores the worse one — dark-run failures point at the dark token layer (a node literal would break light). Contrast is measured as rendered: translucent fills and text (`rgba` / `#RRGGBBAA`) composite over what is behind them, so a tinted selected or hover row is judged by its real color. WCAG 2.2 is the gate; **APCA** Lc values appear as info-only advisories on perceptually weak pairs (APCA is a candidate method, not a standard — it never blocks). +- **It ships a dark theme too.** The dark mapping lands in a sparse `dark.colors` override layer alongside the light tokens (or set one by hand via `set_variables`, which also accepts `dark.elevation` for depth-token overrides) — status colors get a second, dark-specific pass here so they clear AA against the dark surface as well. Render it with `theme: "dark"` on `screenshot` / `screenshot_responsive` / `export`; `canvas_evaluate`'s `color` category then contrast-checks both themes automatically and scores the worse one — dark-run failures point at the dark token layer (a node literal would break light). Contrast is measured as rendered: translucent fills and text (`rgba`, its alpha a fraction or a percent, or `#RRGGBBAA`) composite over what is behind them, so a tinted selected or hover row is judged by its real color. WCAG 2.2 is the gate; **APCA** Lc values appear as info-only advisories on perceptually weak pairs (APCA is a candidate method, not a standard — it never blocks). - **Give motion the same treatment as color and type.** Declare `motion` tokens via `set_variables` (`{ fast: { duration: 150, easing: "ease-out" } }`) and reference them as `transition: "$motion."` — ad-hoc duration/easing pairs sprawling across a canvas with no declared motion tokens get an advisory. Merge semantics are per-category: a project that only sets `colors` doesn't reset the workspace's `spacing`/`radius`/`typography`. A canvas that only overrides `colors.primary` keeps every other workspace color. diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 00dbd0c..0079903 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -371,6 +371,28 @@ One profile ships, keyed by id so a second size is one table row later. Values i - `src/evaluate.ts`: factor `checkColorContrast`'s layer walk (`:413-473`) into a shared helper; the analytical focus, active, disabled and boundary renders; the disabled exclusion in `checkColorContrast`. - A full-tier test that renders each state and compares the computed colors with the rendered ones, so the analytical model and the renderer cannot drift apart. +**Slice H — contracts pinned before build (2026-11-17; frozen at the commit that adds this block).** A pre-freeze verifier broke the draft on paper (FR-H1, H2 and H4 are pass/fail rules, and R9 is a gate over generated output): 12 findings, all folded in below. The one that would have failed the gate: an inset tab ring measured against the tab's focus layer fails every dark generated system (2.48 to 2.95), because `focus-ring` is picked against the plain backdrops (R3 now measures the pixels the ring covers when unfocused). +- **R1: one backdrop walk.** The color helpers (`parseColor`, `parseAlpha`, `contrastRatio`, `composite`, `rgbToHex`) move to a new `src/color-math.ts` (`evaluate.ts` re-exports the ones it exported), with the walk factored out of `checkColorContrast`: `backdropBehind(chain)` takes a node's ancestors nearest first and returns the composited backdrop, `gradient`, or `unreadable`. Its rules are today's: a `gradient` stops the walk (gradient); a fill of `transparent`, `none`, unset, or an unresolved `$token` paints nothing (the renderer emits it as invalid CSS) and the walk goes on; an unparseable fill stops it (unreadable); a translucent fill is a layer composited over what is behind it; no opaque fill means the white page. `checkColorContrast` calls it and its verdicts do not move (every existing contrast test stays green), with one correction on every reader: `parseAlpha` reads a percent alpha (`rgba(0, 0, 0, 50%)` is 0.5, not opaque, which `parseColor` already accepts), so a translucent fill spelled that way is composited instead of treated as solid. A colour `parseColor` rejects (space syntax, `#RGBA`, `hsl()`, a name) stays unreadable. For the state checks only, the walk also stops at an overlay (`tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer`): an opaque overlay fill is the backdrop, any other is `unreadable`, since the renderer lifts the overlay to the root and its tree parents are not behind it. +- **R2: one model, in `src/state-checks.ts`.** The four checks and the full-tier test read the same exported model, which computes from the resolved, instance-expanded tree what the renderer draws (slice G P4, S9, S10, Q6). Targets: every P2 node and item, plus the modal's close button; a target is disabled when `isDisabled` says so (a `tabs` node disables its tabs), as the census reads it. The ring is the target's `stateStyle.ring`, else `#2563EB` (the renderer's fallback for a node inside a component). Opacities are `stateStyle`'s, else `STATE_LAYERS`, each rounded as the render rounds it (Q6: `Math.round(x × 10000) / 100` percent). A layer is the ink composited source-over at that percent times the ink's own alpha (`color-mix` with `transparent` multiplies them: a `#ffffffde` ink at 8% is 6.96%); the on-surface colour, a ring, an indicator and a boundary carry their own alpha the same way. The ink is P4's: `color` for a button, link, text-input, the rows, a select and a modal or toast action; a tab's is `color` when active, else `secondaryColor`; a tab-bar item's is `iconColor` when active, else `color`; a nav-bar action's is `iconColor`; the modal close button's is `secondaryColor`. Every prop the model reads that is unset takes the renderer's own fallback for that primitive (a `text-input`'s `stroke` is `#DC2626` with an `error`, else `#D1D5DB`, its `fill` `#FFFFFF`; a modal, toast or tab-bar `fill` `#FFFFFF`; a contained tab's active fill `#EFF4FF`; the inks' fallbacks), since inside a component the resolver set none of them; a value the renderer would emit as invalid CSS (an unresolved `$token`, or unset where the renderer has no fallback, as a checkbox's `stroke`) draws nothing. A target's own `opacity` (a number in [0, 1]) composites the target as a group over its backdrop: its ring, indicator, fill and boundary pixels are each the group's pixel at that opacity over the backdrop. Ancestor opacity and `position` are not modelled (as in the text-contrast check). The model reads disabled as the census does (`isDisabled`, `disabled === true`); an out-of-contract truthy `disabled` the renderer dims is measured as enabled. Each check runs on the light tree and, when the merged tokens carry a dark color layer, on the dark tree too (resolved with `theme: "dark"`, expanded the same way), its findings tagged `theme: "dark"`. Fast and detailed mode compute the same thing; no rects are read. All four rule ids join `DESKTOP_APP_RULES`, category `color`, desktop-app only (only R6's exclusion reaches other types). +- **R3: `desktop-app-focus-visible` (FR-H1, error).** For every target not disabled: the ring (its alpha composited over the backdrop) against the backdrop the ring meets. An outset ring (every target but a tab and a tab-bar item) meets the backdrop behind the target: `backdropBehind` from the target's parent; for an item, from its host, where a host that draws its own fill counts first (a `nav-bar`'s `fill`, a `modal`'s or `toast`'s fill); a `tabs` node draws none, so its tabs start at its parent. An inset ring (a tab, a tab-bar item, S9 and Q3) covers the item's own edge: its rest fill (a contained tab's active fill, else none) over the host's backdrop (a `tab-bar` counts its own `fill`). Either way the ring is measured against the pixels it covers when the target is not focused, the change-of-contrast reading of WCAG 2.4.13 that FR-H1's "backdrop behind the primitive" names; the focus layer is part of the focused render and is not the reference (measured against it, every dark generated system's tab ring fails while the same ring clears 3:1 against every `bg-*` and `*-tint`, FR-A8). The contrast ratio, rounded to two decimals, below 3 fails. One error per distinct pair of ring and composited backdrop (as hex) per theme (a contained `tabs` node can add a second pair, its active tab's fill), its `nodeId` the first target, `nodeIds` every distinct node (an item reports its host), `count` the number of targets; the message names both colors and the ratio, the suggestion names `$focus-ring` (the dark layer's for a dark finding). A target whose backdrop is a gradient or unreadable, or whose ring does not parse, is left out; one info per theme lists them (`nodeIds`, `count`). +- **R4: `desktop-app-state-contrast` (FR-H2, warning).** Measured on the active primitives that draw an indicator mark: an `active` `nav-item` (its 2px bar in `iconColor`, else `#2563EB`), and each active tab of a `tabs` node whose `variant` is not `contained` (its 2px underline in the node's `iconColor`, else `#2563EB`). Disabled ones are skipped (they render in the on-surface colour, S10). The indicator, its alpha composited, is measured against the active fill over the backdrop behind the primitive (a nav-item's `fill`; a line tab has none, so the backdrop behind the `tabs` node), in rest, and in hover, with the hover layer of the ink over that fill. Either rounded ratio below 3 warns, one warning per primitive (per active tab, named by label), the message naming the failing state or states with their ratios. A `tree-row` and a contained tab draw no indicator mark (their active cue is the fill and the weight), so this rule has nothing to measure on them. A gradient or unreadable backdrop is skipped silently (R3 reports it). +- **R5: `desktop-app-disabled` (FR-H3, info).** Only where a target's `stateStyle` carries both disabled opacities (the design system sets them, S10) and the target has no authored `opacity`: for every target, disabled or not, the content it would draw disabled against the content it draws at rest, both composited over the backdrop behind it. Rest content is its ink over its rest fill (for a toggle the track fill, for an unchecked checkbox or a radio the stroke, for a checked checkbox the fill: a control is its own content). Disabled content is the on-surface colour (`stateStyle.onSurface`, its alpha carried) at `disabledContent` over that backdrop: the content is drawn inside a group at that opacity, so the container under an opaque on-surface colour does not change the pixel. The modal close button is never disabled and is not measured. A rounded ratio of 1.10 or less (the house threshold) means disabled looks the same as enabled. One info per theme listing those targets (`nodeIds`, `count`), naming `disabledContent` and the closest ratio, with the suggestion to lower `state.disabledContent`. +- **R6: the disabled exclusion (FR-H3, every type).** `checkColorContrast` skips a text node with an ancestor that is a disabled clickable primitive (a P2 node or a `tabs` node, by `isDisabled`): no error, no APCA info. The renderer draws no children inside a clickable primitive today, so on current renders the exclusion only removes findings on text the screenshot does not show. +- **R7: `desktop-app-boundary` (FR-H4, warning).** For a `text-input` (its `stroke`, with or without an `error`), an unchecked `checkbox` (its `stroke`), an unchecked `toggle` (its track, the `fill`) and an unchecked `radio` (its `stroke`), not disabled: the boundary colour against the backdrop behind the primitive (`backdropBehind` from its parent). A border is painted over the control's own fill (the background runs under it), so a translucent `stroke` composites over the `fill` (a text-input's, a checkbox's) over the backdrop. A rounded ratio below 3 warns, one warning per primitive, the suggestion naming `$border-strong`. A checked checkbox, toggle or radio is not measured (its fill or dot is the cue). ~~A boundary that draws nothing (R2: an unresolved `$token`, or a checkbox, radio or toggle with it unset; an unset text-input stroke draws its fallback and is measured) or that `parseColor` rejects, or a gradient or unreadable backdrop, is skipped silently.~~ *Amended by verify round 1 fix (c):* a boundary that draws nothing is measured as what shows there, and a `text-input` or `checkbox` whose own fill clears 3:1 passes; a boundary that `parseColor` rejects, a field fill it rejects, or a gradient or unreadable backdrop is skipped silently. Known false negatives, left for later (VISION): `select` is not in FR-H4, though its `$border` is its only boundary too; and FR-H2's "indicator by construction" does not hold for `tree-row` and the contained tab (R4). +- **R8: render versus model (full tier).** `test-state-model-render.ts` renders scenes holding a `button` of each variant, a `text-input`, a `checkbox`, a `toggle`, a `nav-item` and line and contained `tabs`, unthemed and under a generated system in both themes, on a panel fill, and reads pixels from the screenshot at device scale 1: the ring and the backdrop in its gap (outset) or just inside it (inset tab) in `focus`; the indicator and the fill beside it in rest and hover; the hover, focus and pressed fill of a button; a disabled toggle track and a disabled button container with the token pair; the boundary and the backdrop outside it. Each pixel matches the model's colour within 2/255 per channel; a ring's reference pixel is read from the rest render at the ring's position, as R3 measures it. Its twin: the same comparison against a model whose layer opacity is off by 0.05 must fail on a pair whose ink and fill differ strongly, so the tolerance cannot hide a drift. The dark preset's translucent `text-primary` (`#ffffffde`) is among the inks. +- **R9: the gate and its inputs (hard rule 6).** No generated system and no desktop-app realisation trips the new rules: (a) the slice D desktop gate (`test-patterns.ts` `desktopGate`, fast: the five themes, each personality × the three seeds, the inherited workspace system; `test-patterns-desktop.ts`, detailed) keeps its pass rule (zero desktop-app findings at any severity), which now covers the four ids, in both themes; (b) a fast test generates each personality × the three seeds and, in both themes, places every target (each P2 node, a contained and a line `tabs`, a `nav-item` active and not, checked and unchecked controls) on each `bg-*` token and on each `*-tint` token, and expects zero `desktop-app-focus-visible`, and on `bg-primary` and `bg-surface` (the backdrops FR-A8 promises) zero `desktop-app-state-contrast` and `desktop-app-boundary`, and zero `desktop-app-disabled` everywhere. The inputs the rules read: ring, backdrop chain (fills, gradient, `$token`, overlay, page), ink (`color`, `secondaryColor`, `iconColor`) and its alpha, the target's own `fill` and the host's, indicator colour, boundary (`stroke`, a toggle's `fill`) and `error`, `state` opacities, the disabled pair, `onSurface` and its alpha, authored `opacity`, `active`, `checked`, `variant`, `disabled` and `state: "disabled"` on node, item and `tabs` host, unset props and their renderer fallbacks, instance or not, theme. +- **R10: acceptance (FR-H1 to FR-H4, fast).** `test-state-checks.ts`: a `$focus-ring` at about 2.4:1 against an inspector panel holding several outset targets and a line `tabs` node gives one error whose `nodeIds` lists each of them, and at about 3.2:1 nothing; a `nav-item` whose indicator measures about 2.5:1 against its active fill warns, and the generated default passes in both themes; a disabled `button` under generated opacities raises nothing, and `state.disabledContent: 1` raises the info; a `text-input` whose `$border` is about 1.8:1 against its panel warns, and the generated system passes. Each pass has a twin that must fail, each failure a twin that must pass; the web and mobile types raise none of the four ids; R6 skips text under a disabled primitive on web, with a twin under an enabled one. +- **R11: agent surfaces.** The four rule ids on every surface slice C to F used for theirs: `INSTRUCTIONS`, the `canvas_evaluate` docstring, GOTCHAS where they shape behaviour, GUIDELINES (the desktop-app rules list and the element-states paragraph: the evaluator checks focus, active, disabled and boundaries itself), README, `test-discoverability.ts`'s rule list, and the VISION checklist. + +**Slice H — as built (recorded 2026-11-17).** The contracts held; no spec change. +- **T1: where the findings go.** The four rules feed the `color` category (`withRuleIssues`: each warning costs 10 points there, as every rule finding does in its category). They read the light tree with instances expanded (`mobileRoot`) and, with a dark layer, the dark-resolved tree expanded the same way. `reportOnInstances` now maps `nodeIds` to their instances too (a grouped finding names several nodes). +- **T2: the model's surface.** `src/state-checks.ts` exports `stateTargets` and the four pair builders (`focusPairs`, `indicatorPairs`, `disabledPairs`, `boundaryPairs`) plus `paint` and `layerAlpha`; the rules and `test-state-model-render.ts` read the same functions. A radio's boundary sits on the backdrop (the renderer draws its background `transparent`); a toggle's track is its fill. +- **T3: the gate.** R9(a) needed no change: the slice D desktop gate stays green with the four rules on. R9(b) lives in `test-state-checks.ts`, with a twin that breaks the tokens and finds each rule on the frame it was planted on. +- **T4: the render test** samples a pill's ring (the toggle) at its straight bottom edge: on the curved side the ring's antialiasing moves a pixel by up to 11/255, which is geometry, not the model. +- **Verify round 1 fixes** (on ac2f203; each proved red there and green on the fix, the nearest keep-cases unchanged). (a) A colour the model cannot read but the browser paints (a named colour, `hsl()`) was drawn as transparent: an inset tab ring over such a fill gave a false 1.00:1 error, and a named hover ink dropped the layer. Now an unreadable inset fill or active fill skips the target (R3's info, R4 silently), an unreadable hover ink keeps the rest verdict only, and any boundary over an unreadable field fill is skipped. (b) A non-string ring or fill threw (`startsWith`): `paintsNothing` reads any non-string as painting nothing, as the renderer's invalid CSS does. (c) **R7 changed:** a boundary that draws nothing (`transparent`, `none`, an unresolved or misspelt `$token`, a control's unset boundary inside a component) is measured as what shows there instead of skipped, since an invisible outline is the worst boundary; and, honouring FR-H4's own condition (a border needs 3:1 only when nothing else shows the field), a `text-input` or `checkbox` whose own fill clears 3:1 against the backdrop passes. (d) A dark finding that repeats the light one word for word (literal colours, which no theme changes) is dropped. (e) A finding on targets inside a component instance carries a suggestion saying the design system never reaches them, and a grouped finding's instance note names every instance (or says some members are inside). (f) Grouping is linear (it spread an array per member), and a group whose members name different authored rings prints the drawn hex. Mutation testing (350 mutants, 162 killed, 12 equivalent) left thresholds at exactly 3.00 and 1.10, the per-rule gates, the overlay and item backdrops, every type's ink and fill, a control's own content, grouping and the colour helpers' edges unasserted; tests now kill them. The render test now covers every button variant, an authored opacity, `disabledPairs` on a toggle and a modal's close button and actions (127 pixel checks). +- **After verify round 2 (3b)** (proved red on b094305 and green on the fix; not re-verified by an agent). (a) An instance whose component root is itself the target keeps the instance's id, which `owners` does not map, so its findings had no instance note and kept the token advice: `stateFindings` now reads the canvas's instance ids too and adds "(an instance — fix it in its component)". (b) The instance advice replaced an info's own suggestion ("check these rings by eye"); an info now keeps it and gains the instance sentence. (c) Wording: the unmeasured-ring info names a tab's own fill as a cause; a radio's or toggle's boundary message no longer speaks of a field fill; `INSTRUCTIONS` and GOTCHAS state the boundary changes. +- **Accepted as found (round 1):** an inset tab ring is measured against the tab's rest fill (R3), so a canvas that raises `state.focus` far above Material's 0.10 can hide a tab's ring under its own focus layer unflagged; at the default 0.10, about a third of dark generated tabs measure 2.3 to 3.0 against the focused layer (the S9 trade-off, made deliberately). `apply_preset` after `generate_design_system` can leave `$accent-tint` and `$border-strong` out of step with the preset's surfaces; the warnings it then raises are true (the slice D gate applies presets alone). + **Slice I: acceptance (FR-J1)** - `test-viewer-rebuild.ts` in the full tier, building the viewer canvases from the realisations and asserting FR-J1's numbers, the way `test-ridgeline.ts` pins Phase 30's re-run. diff --git a/src/color-math.ts b/src/color-math.ts new file mode 100644 index 0000000..0db233b --- /dev/null +++ b/src/color-math.ts @@ -0,0 +1,130 @@ +// Phase 31 slice H (spec R1) — the colour arithmetic the contrast checks +// share: parsing, WCAG luminance and ratio, source-over compositing, and the +// walk that finds what a node is painted over. The text-contrast check and +// the analytical state checks (state-checks.ts) read the same walk, so they +// never disagree about a backdrop. + +import type { SceneNode } from './types.js'; + +export type Rgb = [number, number, number]; + +export function parseColor(str: string): Rgb | null { + if (!str || typeof str !== 'string') return null; + // #RGB + let m = str.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i); + if (m) return [parseInt(m[1] + m[1], 16), parseInt(m[2] + m[2], 16), parseInt(m[3] + m[3], 16)]; + // #RRGGBB or #RRGGBBAA + m = str.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i); + if (m) return [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)]; + // rgb(r,g,b) / rgba(r,g,b,a) + m = str.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/); + if (m) return [+m[1], +m[2], +m[3]]; + return null; +} + +// Phase 12 — alpha channel for glow detection (a low-alpha colored shadow reads +// as a bloom). Handles #RRGGBBAA and rgba(), the alpha as a number or a +// percent (slice H: `rgba(0, 0, 0, 50%)` is 0.5); everything else is opaque. +export function parseAlpha(str: string): number { + if (!str || typeof str !== 'string') return 1; + const hex8 = str.match(/^#[0-9a-f]{6}([0-9a-f]{2})$/i); + if (hex8) return parseInt(hex8[1], 16) / 255; + const rgba = str.match(/rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*([\d.]+)(%?)\s*\)/i); + if (rgba) return Math.max(0, Math.min(1, parseFloat(rgba[1]) / (rgba[2] ? 100 : 1))); + return 1; +} + +function relativeLuminance(r: number, g: number, b: number): number { + const [rs, gs, bs] = [r / 255, g / 255, b / 255].map( + (c) => (c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)), + ); + return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs; +} + +export function contrastRatio(fg: Rgb, bg: Rgb): number { + const l1 = relativeLuminance(...fg); + const l2 = relativeLuminance(...bg); + const lighter = Math.max(l1, l2); + const darker = Math.min(l1, l2); + return (lighter + 0.05) / (darker + 0.05); +} + +/** A contrast ratio at the two decimals it is reported (and judged) at. */ +export const roundedRatio = (a: Rgb, b: Rgb): number => Math.round(contrastRatio(a, b) * 100) / 100; + +/** Source-over blend of `top` at `alpha` onto an opaque `base`. */ +export function composite(top: Rgb, alpha: number, base: Rgb): Rgb { + if (alpha >= 1) return top; + return [0, 1, 2].map((i) => Math.round(alpha * top[i] + (1 - alpha) * base[i])) as Rgb; +} + +export function rgbToHex([r, g, b]: Rgb): string { + return '#' + [r, g, b].map((c) => c.toString(16).padStart(2, '0')).join('').toLowerCase(); +} + +export const WHITE: Rgb = [255, 255, 255]; + +/** What a node is painted over: a composited colour (with the fills that made + * it, nearest first), a gradient, or something the walk cannot read. */ +export type Backdrop = + | { kind: 'color'; rgb: Rgb; layers: string[] } + | { kind: 'gradient' } + | { kind: 'unreadable' }; + +/** A fill that paints nothing: unset, the keywords, an unresolved $token or + * a value that is not a string (the renderer emits those as invalid CSS, so + * the browser draws nothing). */ +export function paintsNothing(fill: unknown): boolean { + return typeof fill !== 'string' || !fill || fill === 'transparent' || fill === 'none' || fill.startsWith('$'); +} + +/** A colour the model can draw: one that paints nothing, or one that parses. + * Anything else (a named colour, hsl()) still paints, so it cannot be skipped + * as transparent. */ +export const readable = (color: unknown): boolean => paintsNothing(color) || parseColor(color as string) !== null; + +/** + * The backdrop behind a node, from its ancestors nearest first. A gradient + * stops the walk; a fill that paints nothing is seen through; an unparseable + * fill stops it (unreadable); a translucent fill is a layer composited over + * what is behind it; with no opaque fill the white page shows. `stop`, when + * given, ends the walk at a node it returns a fill for (the state checks stop + * at an overlay, whose tree parents are not behind it): an opaque fill is the + * backdrop, anything else unreadable. `fillOf` reads a node's painted fill + * (default: its `fill`). + */ +export function backdropBehind( + chain: Iterable, + opts: { stop?: (n: SceneNode) => string | undefined | null; fillOf?: (n: SceneNode) => string | undefined } = {}, +): Backdrop { + const layers: string[] = []; + const fillOf = opts.fillOf ?? ((n: SceneNode) => n.fill); + for (const node of chain) { + const stop = opts.stop?.(node); + if (stop !== undefined && stop !== null) { + const rgb = parseColor(stop); + if (!rgb || paintsNothing(stop) || parseAlpha(stop) < 1) return { kind: 'unreadable' }; + layers.push(stop); + return finish(layers); + } + if (node.gradient) return { kind: 'gradient' }; + const fill = fillOf(node); + if (paintsNothing(fill)) continue; + // A fill we cannot parse (hsl(), a named color) still paints: stop here + // rather than measure against what is behind it. + if (!parseColor(fill!)) return { kind: 'unreadable' }; + const alpha = parseAlpha(fill!); + if (alpha > 0) layers.push(fill!); + if (alpha >= 1) break; + } + return finish(layers); +} + +function finish(layers: string[]): Backdrop { + const backmost = layers[layers.length - 1]; + let rgb: Rgb = backmost !== undefined && parseAlpha(backmost) >= 1 ? parseColor(backmost)! : WHITE; + for (let i = layers.length - 1; i >= 0; i--) { + if (parseAlpha(layers[i]) < 1) rgb = composite(parseColor(layers[i])!, parseAlpha(layers[i]), rgb); + } + return { kind: 'color', rgb, layers }; +} diff --git a/src/evaluate.ts b/src/evaluate.ts index 5a5b470..535d386 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -9,6 +9,8 @@ import { } from './desktop-app-rules.js'; import { extractInventory, expandInstances, 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'; import { storedGenre } from './genre.js'; import { relaxedByPreset, relaxedByGenre, canonicalGenre, genreRulesets, activeRulesets, composeRulesets, resolveSurface, deviceProfile, DEVICE_PROFILES, DEFAULT_DEVICE, MOBILE_RULES, DESKTOP_APP_RULES, DEFAULT_WINDOW, WINDOW_PROFILES, windowProfile, type SurfaceType } from './surfaces.js'; import { checkArtboard, checkHandbuiltTargets, checkOneColumn, checkSafeAreaDetailed, checkSafeAreaFast, checkTabBars, checkTypeFloor, paddingSides, type MobileContext } from './mobile-rules.js'; @@ -172,34 +174,9 @@ interface CheckResult { // --- Color utilities --- -export function parseColor(str: string): [number, number, number] | null { - if (!str || typeof str !== 'string') return null; - // #RGB - let m = str.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i); - if (m) return [parseInt(m[1] + m[1], 16), parseInt(m[2] + m[2], 16), parseInt(m[3] + m[3], 16)]; - // #RRGGBB or #RRGGBBAA - m = str.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i); - if (m) return [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)]; - // rgb(r,g,b) / rgba(r,g,b,a) - m = str.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/); - if (m) return [+m[1], +m[2], +m[3]]; - return null; -} - -function relativeLuminance(r: number, g: number, b: number): number { - const [rs, gs, bs] = [r / 255, g / 255, b / 255].map( - (c) => (c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)), - ); - return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs; -} - -export function contrastRatio(fg: [number, number, number], bg: [number, number, number]): number { - const l1 = relativeLuminance(...fg); - const l2 = relativeLuminance(...bg); - const lighter = Math.max(l1, l2); - const darker = Math.min(l1, l2); - return (lighter + 0.05) / (darker + 0.05); -} +// Phase 31 slice H — the parsing, ratio and compositing helpers live in +// color-math.ts (shared with the state checks); re-exported for callers. +export { contrastRatio, parseAlpha, parseColor } from './color-math.js'; // Phase 25 slice D — APCA (Accessible Perceptual Contrast Algorithm, // 0.0.98G-4g constants). ADVISORY ONLY: APCA sits outside the normative @@ -246,23 +223,6 @@ export function rgbToHsl(rgb: [number, number, number]): { h: number; s: number; return { h, s, l }; } -// Phase 12 — alpha channel for glow detection (a low-alpha colored shadow reads -// as a bloom). Handles #RRGGBBAA and rgba(); everything else is opaque. -export function parseAlpha(str: string): number { - if (!str || typeof str !== 'string') return 1; - const hex8 = str.match(/^#[0-9a-f]{6}([0-9a-f]{2})$/i); - if (hex8) return parseInt(hex8[1], 16) / 255; - const rgba = str.match(/rgba\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*([\d.]+)\s*\)/i); - if (rgba) return Math.max(0, Math.min(1, parseFloat(rgba[1]))); - return 1; -} - -/** Source-over blend of `top` at `alpha` onto an opaque `base`. */ -function composite(top: [number, number, number], alpha: number, base: [number, number, number]): [number, number, number] { - if (alpha >= 1) return top; - return [0, 1, 2].map((i) => Math.round(alpha * top[i] + (1 - alpha) * base[i])) as [number, number, number]; -} - // --- Tree walking --- function buildTreeContext(root: SceneNode): NodeEntry[] { @@ -421,6 +381,20 @@ function checkSpacing(entries: NodeEntry[], variables: DesignVariables): CheckRe return { score: Math.max(0, Math.min(100, Math.round(score))), issues }; } +/** A node and its ancestors, nearest first. */ +function* ancestors(from: SceneNode | null, parentOf: Map): Generator { + for (let n = from; n; n = parentOf.get(n) ?? null) yield n; +} + +/** Inside a clickable primitive that is disabled (a P2 node, or a `tabs` + * node, which disables every tab), as the census reads it. */ +function insideDisabledTarget(node: SceneNode, parentOf: Map): boolean { + for (const n of ancestors(parentOf.get(node) ?? null, parentOf)) { + if ((STATEFUL_TYPES.has(n.type) || n.type === 'tabs') && isDisabled(n)) return true; + } + return false; +} + function checkColorContrast(entries: NodeEntry[], theme?: 'dark'): CheckResult { const issues: EvaluationIssue[] = []; const textNodes = entries.filter((e) => e.node.type === 'text'); @@ -428,41 +402,23 @@ function checkColorContrast(entries: NodeEntry[], theme?: 'dark'): CheckResult { if (textNodes.length === 0) return { score: 100, issues }; let failCount = 0; + const parentOf = new Map(entries.map((e) => [e.node, e.parent] as const)); for (const { node, parent } of textNodes) { const fgStr = node.color ?? '#000000'; const fgRaw = parseColor(fgStr); if (!fgRaw) continue; - // Walk up collecting fills until an opaque one. Translucent fills - // (rgba / #RRGGBBAA) are layers the text sees THROUGH, so they composite - // over what is behind them instead of counting as solid paint. - const layers: string[] = []; - let onGradient = false; - let unreadable = false; - let current = parent; - while (current) { - if (current.gradient) { - onGradient = true; - break; - } - const see = current.fill === 'transparent' || current.fill === 'none'; - if (current.fill && !see && !current.fill.startsWith('$')) { - // A fill we cannot parse (hsl(), a named color) still paints: stop - // here and skip the check rather than measure against what is behind. - if (!parseColor(current.fill)) { - unreadable = true; - break; - } - const alpha = parseAlpha(current.fill); - if (alpha > 0) layers.push(current.fill); - if (alpha >= 1) break; - } - const parentEntry = entries.find((e) => e.node.children?.includes(current!)); - current = parentEntry?.node ?? null; - } + // Phase 31 FR-H3 (spec R6) — text inside a disabled clickable primitive + // is exempt from contrast, as WCAG exempts it, on every type. + if (insideDisabledTarget(node, parentOf)) continue; + + // Walk up collecting fills until an opaque one (color-math.ts). Translucent + // fills (rgba / #RRGGBBAA) are layers the text sees THROUGH, so they + // composite over what is behind them instead of counting as solid paint. + const backdrop = backdropBehind(ancestors(parent, parentOf)); - if (onGradient) { + if (backdrop.kind === 'gradient') { issues.push({ category: 'color', severity: 'info', @@ -472,14 +428,10 @@ function checkColorContrast(entries: NodeEntry[], theme?: 'dark'): CheckResult { }); continue; } - if (unreadable || layers.length === 0) continue; + if (backdrop.kind === 'unreadable' || backdrop.layers.length === 0) continue; - // No opaque fill behind the layers: they sit on the page, which renders white. - const backmost = layers[layers.length - 1]; - let bg: [number, number, number] = parseAlpha(backmost) >= 1 ? parseColor(backmost)! : [255, 255, 255]; - for (let i = layers.length - 1; i >= 0; i--) { - if (parseAlpha(layers[i]) < 1) bg = composite(parseColor(layers[i])!, parseAlpha(layers[i]), bg); - } + const { layers } = backdrop; + const bg = backdrop.rgb; const fg = composite(fgRaw, parseAlpha(fgStr), bg); const composited = layers.length > 1 || parseAlpha(layers[0]) < 1; const bgStr = composited ? `${layers[0]} (composited: ${rgbToHex(bg)})` : layers[0]; @@ -1220,10 +1172,6 @@ const BRAND_WORDMARKS = [ 'google', 'microsoft', 'apple', 'amazon', 'meta', 'netflix', 'stripe', ]; -function rgbToHex([r, g, b]: [number, number, number]): string { - return '#' + [r, g, b].map((c) => c.toString(16).padStart(2, '0')).join('').toLowerCase(); -} - // A hue in the indigo→violet→purple band with real saturation — the "AI purple" // tell. Floor 230 catches indigo-500 (#6366f1 ≈ h239); a considered blue like // #2563EB (≈ h221) or #3b82f6 (≈ h217) stays below it. @@ -2497,11 +2445,52 @@ function expandForRules(root: SceneNode, canvas: Canvas): { root: SceneNode; own /** 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[] { + 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; +} + function reportOnInstances(issues: EvaluationIssue[], owners: Map): EvaluationIssue[] { 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 (!owner) return i; - return { ...i, nodeId: owner.id, nodeName: owner.name, message: `${i.message} (inside instance "${owner.name ?? owner.id}" — fix it in its component)` }; + 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}` }; + } + 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)` }; }); } @@ -2582,13 +2571,20 @@ export async function evaluateCanvas( // themes; contrast is checked in BOTH, dark issues tagged. Score takes // the worse theme: a dark-only failure must hurt. const darkLayer = mergedTokens.dark?.colors; - if (darkLayer && Object.keys(darkLayer).length > 0) { - const darkEntries = buildTreeContext(resolveVariables(canvas.root, mergedTokens, { theme: 'dark' })); - const dark = checkColorContrast(darkEntries, 'dark'); - results.set('color', { score: Math.min(light.score, dark.score), issues: [...light.issues, ...dark.issues] }); - } else { - results.set('color', light); + const hasDark = !!darkLayer && Object.keys(darkLayer).length > 0; + const darkRoot = hasDark ? resolveVariables(canvas.root, mergedTokens, { theme: 'dark' }) : 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. + 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)) + : []; + results.set('color', withRuleIssues(color, reportOnInstances(states, owners))); } // Phase 25 slice A — detailed-mode layout is computed ONCE and shared by // the consistency and typography (measure) checks. diff --git a/src/index.ts b/src/index.ts index 64e706b..fb1fb6d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -85,7 +85,7 @@ Point-and-tell feedback: the user toggles Comment mode in the viewer and clicks Phone app screens: declare the medium. canvas_create({ type: "mobile" }) makes a phone screen — the device artboard (390×844 for the default device "iphone-390") with the root reserving the safe-area insets as safeArea: { top: 47, bottom: 34 } (the renderer adds them to the root's own top/bottom padding, and the root grows with long content keeping that padding past it, so in-flow content never sits under the status bar or home indicator). type: "web" (the default) is a web page; canvas_set_type changes or clears the declaration on an existing canvas (it never resizes or writes safeArea — its result's hint names the op that does). The type selects a ruleset and defaults, never the render: generate_design_system on a mobile canvas pivots the type scale on the device body size (17px; 16px for data-dense), and every evaluate result carries a "surface" report ({ type, device, source "declared" | "default", rulesOn, rulesOff, conflicts }) naming the rule ids the type + genre + preset rulesets turned on and off — a rule both enabled and disabled stays on (in rulesOn) and is listed in conflicts. Start a phone screen from a mobile realisation: apply_structure on a mobile canvas resolves the anatomy name to it — dashboard → dashboard-mobile, settings → settings-mobile, auth → auth-mobile, onboarding → onboarding-mobile, and the mobile-first feed → feed-mobile (a list of rows, pinned tab bar) and detail → detail-mobile (an item with a primary action pinned over the home indicator) — each built from the primitives and gated to pass the mobile ruleset in fast and detailed mode and canvas_stress CLEAN (unthemed and under every personality); stamp it after generate_design_system (the dark, light and material presets carry a 14–15px body that mobile-type-floor flags on a phone). Resolution reads the DECLARED type: an undeclared 390px canvas stamps the web structure, so declare type "mobile" first. Its placeholders include every copy field of its primitives, with prop the field's path (title, subtitle, label, trailing.text, leading.initials, leading.label, items[0].label — a path, not an op key: set a nested one by writing its whole object or array, siblings included). An anatomy with no mobile realisation (the other web pages such as pricing, catalogue or bento-grid; web-only components such as data-table) is refused with the list of those that have one; realisation: "web" stamps the web one anyway. Of the components, form-field, stat-card, empty-state, skeleton-card, skeleton-stat-card, kpi-card, status-chip and initials-avatar stamp on every type. Build phone screens from the mobile primitives (batch_design lists them): status-bar and home-indicator (device chrome), nav-bar, tab-bar, button, list-row, sheet — never hand-built frames — and pin bars with position "fixed" (the renderer reserves room for pinned chrome, so content never starts or ends under it). A mobile canvas runs the mobile ruleset; every finding names its rule in a "rule" field: mobile-touch-target (ERROR: a tap target below 44px — a control (its row counts only when the row is a horizontal frame holding that one tappable), a button (size "sm" is 32, "xs" 24), a list-row, each tab-bar tab and FAB, each nav-bar action; primitives are measured by their own box, inside instances too), mobile-safe-area (WARNING: content under the 47px status-bar or 34px home-indicator inset, or left under a pinned bar at the start or end of the scroll; with root safeArea or pinned chrome the renderer reserves the insets and only positioned content (absolute / fixed / sticky) and pinned bars are checked — padding ≥32px scales down on a phone, so clear a pinned bar with a spacer frame inside your content frame; detailed mode is authoritative), mobile-tab-bar (WARNING: a tab bar with fewer than 2 or more than 5 tabs, an unlabeled tab, or one not pinned to the bottom), mobile-type-floor (WARNING: text below 11px, $body below 16px, prose of 5+ words below 13px), mobile-handbuilt-target (info: an icon-shaped frame below 44px — rebuild it as a button), mobile-one-column (info: two or more side-by-side children each holding 8+ words), and on every type mobile-artboard (a mobile canvas 500px+ wide WARNS; an undeclared canvas narrower than 500px WARNS until canvas_set_type declares it either way). -Application screens: canvas_create({ type: "desktop-app" }) for a tool you work in — an editor, an admin console, a file browser, a viewer: persistent chrome, panes, dense controls, a current selection, in a browser tab or a native window. The test is what the user does: a page you read and scroll is "web", a tool you work in is "desktop-app". It gets the window artboard (1440×900 for the default device "window-1440", no insets); generate_design_system pivots its type on 14px (13 for data-dense); its ruleset turns OFF type-scale-ratio (the adjacent font-size ratio check — dense apps step 12/13/14 on purpose), and desktop-app-artboard (on every type) WARNS when a desktop-app canvas is narrower than 1024px, 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 (declared web gets an info); an undeclared canvas holding an overlay (tooltip, popover, menu, modal, toast, drawer) warns too, while web and mobile canvases may hold overlays freely. Build app screens from the desktop-app primitives (batch_design lists them): link, text-input, nav-item, tabs, tree-row, menu-row, property-row, divider, plus button size "xs" (24px) with ariaLabel for icon-only buttons and links — never hand-built frames, which no target rule can measure. A nav-item's dotColor is an identity dot and never counts as a competing accent. Start an app screen from a desktop-app realisation: apply_structure on a desktop-app canvas resolves the anatomy name to it — split-workbench → split-workbench-app, dashboard → dashboard-app, settings → settings-app, and three app-only anatomies: list-detail → list-detail-app (navigation, a searchable list, a detail pane with a "nothing selected" placeholder), editor-inspector → editor-inspector-app (a work area beside a 70/30 inspector of tabs and property-rows), browser → browser-app (a filter bar over an adaptive card grid); data-table → data-table-app (32px toolbar, header, rows and pager; stamp it into a pane at least 480px wide, not a 300px side panel) and skeleton-table → skeleton-table-app (its loading state). Each is built from the primitives and gated: > 95 with no warning, error, tell or desktop-app finding in fast and detailed mode under the presets, every personality and an inherited system, canvas_stress CLEAN at 1440, 1280 and 1024 wide, data-table stamped into a pane at least 480px wide clean too — so a fresh stamp is READY TO PRESENT unless coverage asks for a state. They fill the window: the stamp sets root overflow "hidden" (the root keeps the artboard height) and every pane is overflow "auto", so long content scrolls inside its pane — keep new content inside a pane, and never give a pane's direct child a fixed height or an overflow (the pane squashes it instead of scrolling). Coverage still asks for states: dashboard-app and data-table-app need "empty" + "loading", editor-inspector-app and settings-app (forms) need "error". toolbar, toggle-row, segmented-control and breadcrumb stay web-only (realisation: "web" forces one). On web and desktop-app every pointer target — the four controls and the clickable primitives (button, list-row, tab-bar tabs, nav-bar actions, link, text-input, nav-item, each tab of a tabs, tree-row, menu-row; inline text links are exempt) — meets the 24px WCAG 2.5.8 floor or its spacing exception (nothing else within a 24px circle around it): detailed mode runs that circle test (ERROR on failure), fast mode WARNS on anything under 24 and names detailed mode. The desktop-app ruleset (each finding carries its "rule"; canvas_evaluate lists them) adds: name every icon-only button and link (ariaLabel); mark exactly one current place — one active nav-item per pane — a frame with overflow "auto", so give a rail and a sidebar each their own (a parent may stay active over its active child), one active tab per tabs, one active row per tree; a dense type ladder (desktop-app-type-ladder, replacing type-scale-ratio: 12/13/14 steps are fine, nothing below 11px, prose ≥12px, $body ≥13px); table header rows as tall as their body rows; column headers never truncated; one primary button per pane (info); and frames shaped like small buttons are named as hand-built targets (info) — rebuild them as button or link; overlays that cannot work as drawn warn (desktop-app-overlay: a second modal, a tooltip with children, a table of more than 10 body rows or a sideways scroller inside a modal, an overlay leaving the viewport, a popover or menu under the scrim of a modal or a scrim: true drawer) and a second toast, a danger toast and an anchor naming nothing clickable are infos. Before presenting a desktop-app screen run mode "detailed" too: it measures rendered rows, column edges and truncation (a tablist whose every label is cut warns). Overlays (tooltip, popover, menu, modal, toast, drawer) are screen states: add a variant ("menu-open", "comment-open", "confirm-delete", "toast") with canvas_add_variant and insert the overlay there; wherever it sits in the tree it renders in one layer above all content, stacked by kind (no z-index exists), at x / y in ROOT coordinates; a modal and a drawer are panes of their own (one active nav-item, one primary — a modal's "primary" action counts). A menu or popover on a screen with a modal (or a drawer with scrim: true) renders under the scrim: put its content in the dialog, or design it open on a variant without one. Element states are a property, not a variant: state: "hover" | "focus" | "pressed" | "disabled" on a button, link, text-input, nav-item, tree-row, menu-row, list-row or control (on the item for tabs, tab-bar, nav-bar actions, modal actions and a toast action) draws that state from the design system's state tokens — for a states sheet or a screenshot; the evaluator never needs it drawn. +Application screens: canvas_create({ type: "desktop-app" }) for a tool you work in — an editor, an admin console, a file browser, a viewer: persistent chrome, panes, dense controls, a current selection, in a browser tab or a native window. The test is what the user does: a page you read and scroll is "web", a tool you work in is "desktop-app". It gets the window artboard (1440×900 for the default device "window-1440", no insets); generate_design_system pivots its type on 14px (13 for data-dense); its ruleset turns OFF type-scale-ratio (the adjacent font-size ratio check — dense apps step 12/13/14 on purpose), and desktop-app-artboard (on every type) WARNS when a desktop-app canvas is narrower than 1024px, 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 (declared web gets an info); an undeclared canvas holding an overlay (tooltip, popover, menu, modal, toast, drawer) warns too, while web and mobile canvases may hold overlays freely. Build app screens from the desktop-app primitives (batch_design lists them): link, text-input, nav-item, tabs, tree-row, menu-row, property-row, divider, plus button size "xs" (24px) with ariaLabel for icon-only buttons and links — never hand-built frames, which no target rule can measure. A nav-item's dotColor is an identity dot and never counts as a competing accent. Start an app screen from a desktop-app realisation: apply_structure on a desktop-app canvas resolves the anatomy name to it — split-workbench → split-workbench-app, dashboard → dashboard-app, settings → settings-app, and three app-only anatomies: list-detail → list-detail-app (navigation, a searchable list, a detail pane with a "nothing selected" placeholder), editor-inspector → editor-inspector-app (a work area beside a 70/30 inspector of tabs and property-rows), browser → browser-app (a filter bar over an adaptive card grid); data-table → data-table-app (32px toolbar, header, rows and pager; stamp it into a pane at least 480px wide, not a 300px side panel) and skeleton-table → skeleton-table-app (its loading state). Each is built from the primitives and gated: > 95 with no warning, error, tell or desktop-app finding in fast and detailed mode under the presets, every personality and an inherited system, canvas_stress CLEAN at 1440, 1280 and 1024 wide, data-table stamped into a pane at least 480px wide clean too — so a fresh stamp is READY TO PRESENT unless coverage asks for a state. They fill the window: the stamp sets root overflow "hidden" (the root keeps the artboard height) and every pane is overflow "auto", so long content scrolls inside its pane — keep new content inside a pane, and never give a pane's direct child a fixed height or an overflow (the pane squashes it instead of scrolling). Coverage still asks for states: dashboard-app and data-table-app need "empty" + "loading", editor-inspector-app and settings-app (forms) need "error". toolbar, toggle-row, segmented-control and breadcrumb stay web-only (realisation: "web" forces one). On web and desktop-app every pointer target — the four controls and the clickable primitives (button, list-row, tab-bar tabs, nav-bar actions, link, text-input, nav-item, each tab of a tabs, tree-row, menu-row; inline text links are exempt) — meets the 24px WCAG 2.5.8 floor or its spacing exception (nothing else within a 24px circle around it): detailed mode runs that circle test (ERROR on failure), fast mode WARNS on anything under 24 and names detailed mode. The desktop-app ruleset (each finding carries its "rule"; canvas_evaluate lists them) adds: name every icon-only button and link (ariaLabel); mark exactly one current place — one active nav-item per pane — a frame with overflow "auto", so give a rail and a sidebar each their own (a parent may stay active over its active child), one active tab per tabs, one active row per tree; a dense type ladder (desktop-app-type-ladder, replacing type-scale-ratio: 12/13/14 steps are fine, nothing below 11px, prose ≥12px, $body ≥13px); table header rows as tall as their body rows; column headers never truncated; one primary button per pane (info); and frames shaped like small buttons are named as hand-built targets (info) — rebuild them as button or link; overlays that cannot work as drawn warn (desktop-app-overlay: a second modal, a tooltip with children, a table of more than 10 body rows or a sideways scroller inside a modal, an overlay leaving the viewport, a popover or menu under the scrim of a modal or a scrim: true drawer) and a second toast, a danger toast and an anchor naming nothing clickable are infos. Before presenting a desktop-app screen run mode "detailed" too: it measures rendered rows, column edges and truncation (a tablist whose every label is cut warns). Overlays (tooltip, popover, menu, modal, toast, drawer) are screen states: add a variant ("menu-open", "comment-open", "confirm-delete", "toast") with canvas_add_variant and insert the overlay there; wherever it sits in the tree it renders in one layer above all content, stacked by kind (no z-index exists), at x / y in ROOT coordinates; a modal and a drawer are panes of their own (one active nav-item, one primary — a modal's "primary" action counts). A menu or popover on a screen with a modal (or a drawer with scrim: true) renders under the scrim: put its content in the dialog, or design it open on a variant without one. Element states are a property, not a variant: state: "hover" | "focus" | "pressed" | "disabled" on a button, link, text-input, nav-item, tree-row, menu-row, list-row or control (on the item for tabs, tab-bar, nav-bar actions, modal actions and a toast action) draws that state from the design system's state tokens — for a states sheet or a screenshot; the evaluator never needs it drawn: on a desktop-app canvas it computes every target's states itself, in both themes — desktop-app-focus-visible (ERROR: a focus ring below 3:1 against the pixels it covers unfocused; one error per ring and backdrop, its nodeIds every target that shares them — fix $focus-ring), desktop-app-state-contrast (WARNING: an active nav-item's bar or line tab's underline below 3:1 against its active fill, at rest or in hover), desktop-app-boundary (WARNING: a text-input border, an unchecked checkbox or radio outline, or an unchecked toggle track below 3:1 against what is behind it — a border that draws nothing (transparent, a misspelt $token) counts as invisible, a field whose own fill clears 3:1 passes; use $border-strong) and desktop-app-disabled (info: state tokens that make a disabled target look like its enabled self, within 1.1:1). Text inside a disabled clickable primitive is exempt from text contrast on every type. Gotchas (current sharp edges): - Row rules and accent bars are per-side borders — borderTop: { width: 1, color: "$border" } on each table row, borderLeft: { width: 3, color: "$primary" } for an accent edge (style "dashed"|"dotted" for forecast/draft outlines; strokeDasharray dashes SVG paths). Never fake hairlines with gap: 1 + background bleed-through. @@ -126,7 +126,7 @@ 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. 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); 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.', @@ -2155,7 +2155,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 typeof v === 'number' && Number.isFinite(v); +const label = (v: unknown, fallback: string): string => (typeof v === 'string' && v.trim() ? `"${v.trim()}"` : fallback); +const ownOpacity = (n: SceneNode): number | undefined => (isNum(n.opacity) && n.opacity >= 0 && n.opacity <= 1 ? n.opacity : undefined); + +/** A 0–1 opacity as the render writes it: a percentage at two decimals (Q6). */ +export const layerAlpha = (x: number): number => Math.round(x * 10000) / 100 / 100; + +/** `color` painted over an opaque `base`, its own alpha times `alpha` + * (`color-mix` with transparent multiplies them). A colour that paints + * nothing leaves the base; callers check `readable` first, since a colour + * that does not parse still paints. */ +export function paint(color: string | undefined, base: Rgb, alpha = 1): Rgb { + const rgb = color && !paintsNothing(color) ? parseColor(color) : null; + return rgb ? composite(rgb, alpha * parseAlpha(color!), base) : base; +} + +/** A pixel of an element drawn as a group at `opacity` over its backdrop. */ +const group = (pixel: Rgb, opacity: number | undefined, backdrop: Rgb): Rgb => + (opacity === undefined ? pixel : composite(pixel, opacity, backdrop)); + +/** An overlay's painted fill (the renderer's fallbacks): the backdrop walk + * stops there, since the overlay is lifted to the root (R1). */ +function overlayFill(n: SceneNode): string | undefined { + if (!OVERLAY_TYPES.has(n.type)) return undefined; + return n.fill ?? (n.type === 'tooltip' ? FALLBACK.text : FALLBACK.surface); +} + +function parentsOf(root: SceneNode): Map { + const out = new Map([[root, null]]); + (function walk(n: SceneNode) { for (const c of n.children ?? []) { out.set(c, n); walk(c); } })(root); + return out; +} + +function* chainFrom(n: SceneNode | null, parentOf: Map): Generator { + for (let c = n; c; c = parentOf.get(c) ?? null) yield c; +} + +/** The backdrop behind `n`'s box: its ancestors, from the parent up. */ +function behind(n: SceneNode, parentOf: Map): Backdrop { + return backdropBehind(chainFrom(parentOf.get(n) ?? null, parentOf), { stop: overlayFill }); +} + +/** The backdrop an item of `host` sits on: the host's own painted fill + * first (`hostFill`), then the host's ancestors. */ +function behindItem(host: SceneNode, hostFill: string | undefined, parentOf: Map): Backdrop { + return backdropBehind(chainFrom(host, parentOf), { + stop: (n) => (n === host && OVERLAY_TYPES.has(n.type) ? hostFill : overlayFill(n)), + fillOf: (n) => (n === host ? hostFill : n.fill), + }); +} + +/** A button's fill and label colour as renderButton draws them. */ +function buttonColors(n: { fill?: string; color?: string; variant?: string }): { fill: string; ink: string } { + const fill = n.fill ?? (n.variant === 'secondary' || n.variant === 'ghost' ? 'transparent' : n.variant === 'destructive' ? FALLBACK.danger : FALLBACK.accent); + return { fill, ink: n.color ?? (fill === 'transparent' ? FALLBACK.accent : '#FFFFFF') }; +} + +/** A P2 node's ink and own fill, as its renderer draws them (P4). */ +function nodeInkFill(n: SceneNode): { ink: string; fill?: string } { + switch (n.type) { + case 'button': return buttonColors(n); + case 'link': return { ink: n.color ?? FALLBACK.accent }; + case 'text-input': return { ink: n.color ?? FALLBACK.text, fill: n.fill ?? FALLBACK.surface }; + case 'menu-row': return { ink: n.color ?? (n.destructive ? FALLBACK.danger : FALLBACK.text), fill: n.fill }; + case 'toggle': return { ink: '#FFFFFF', fill: n.fill }; + case 'checkbox': return { ink: n.checked ? '#FFFFFF' : n.stroke ?? '', fill: n.fill }; + case 'radio': return { ink: n.stroke ?? '' }; + case 'select': return { ink: n.color ?? '', fill: n.fill }; + // nav-item, tree-row, list-row + default: return { ink: n.color ?? FALLBACK.text, fill: n.fill }; + } +} + +/** Every target in the tree, with what the model needs to draw it. */ +export function stateTargets(root: SceneNode): StateTarget[] { + const parentOf = parentsOf(root); + const out: StateTarget[] = []; + (function walk(n: SceneNode) { + const style = n.stateStyle; + if (STATEFUL_TYPES.has(n.type)) { + out.push({ node: n, what: n.type, kind: n.type, disabled: isDisabled(n), inset: false, ...nodeInkFill(n), opacity: ownOpacity(n), style, backdrop: behind(n, parentOf) }); + } else if (n.type === 'tabs') { + const contained = n.variant === 'contained'; + const backdrop = behind(n, parentOf); + tabsItems(n).forEach((it, i) => { + const active = it.active === true; + out.push({ + node: n, what: `tab ${label(it.label, String(i + 1))}`, kind: 'tab', disabled: isDisabled(n) || isDisabled(it), inset: true, + ink: active ? n.color ?? FALLBACK.text : n.secondaryColor ?? FALLBACK.secondary, + fill: contained && active ? n.fill ?? TINT_FALLBACK : undefined, style, backdrop, + }); + }); + } else if (n.type === 'tab-bar') { + const backdrop = behindItem(n, n.fill ?? FALLBACK.surface, parentOf); + tabItems(n).forEach((it, i) => { + out.push({ + node: n, what: `tab-bar item ${label(it.label, String(i + 1))}`, kind: 'tab-bar item', disabled: isDisabled(it), inset: true, + ink: it.active ? n.iconColor ?? FALLBACK.accent : n.color ?? FALLBACK.secondary, style, backdrop, + }); + }); + } else if (n.type === 'nav-bar') { + const backdrop = behindItem(n, n.fill, parentOf); + for (const a of navActions(n)) { + out.push({ node: n, what: `nav-bar action ${label(a.label ?? a.icon, 'back')}`, kind: 'nav-bar action', disabled: isDisabled(a), inset: false, ink: n.iconColor ?? FALLBACK.accent, style, backdrop }); + } + } else if (n.type === 'modal') { + const backdrop = behindItem(n, n.fill ?? FALLBACK.surface, parentOf); + out.push({ node: n, what: 'modal close button', kind: 'modal close', disabled: false, inset: false, ink: n.secondaryColor ?? FALLBACK.secondary, fill: 'transparent', style, backdrop }); + for (const a of modalActions(n)) { + const variant = a.variant ?? 'secondary'; + const filled = variant === 'primary' || variant === 'destructive'; + // As renderModal's actionButton builds them. + const fill = a.fill ?? (filled ? (variant === 'destructive' ? FALLBACK.danger : FALLBACK.accent) : 'transparent'); + const ink = a.color ?? (filled ? '#FFFFFF' : variant === 'ghost' ? FALLBACK.accent : n.color ?? FALLBACK.text); + out.push({ node: n, what: `modal action ${label(a.label, '')}`, kind: 'modal action', disabled: isDisabled(a), inset: false, ink, fill, style, backdrop }); + } + } else if (n.type === 'toast' && n.action && typeof n.action === 'object' && typeof n.action.label === 'string' && n.action.label.trim()) { + out.push({ + node: n, what: `toast action ${label(n.action.label, '')}`, kind: 'toast action', disabled: isDisabled(n.action), inset: false, + ink: n.action.color ?? FALLBACK.accent, fill: 'transparent', style, backdrop: behindItem(n, n.fill ?? FALLBACK.surface, parentOf), + }); + } + n.children?.forEach(walk); + })(root); + return out; +} + +/** R3 — what a focus ring draws and the pixels it covers unfocused. */ +export interface FocusPair { target: StateTarget; ring: string; ringPx?: Rgb; reference?: Rgb } + +export function focusPairs(targets: StateTarget[]): FocusPair[] { + return targets.filter((t) => !t.disabled).map((t) => { + const ring = t.style?.ring ?? FALLBACK.accent; + // An inset ring covers the item's own fill, which must be readable too. + if (t.backdrop.kind !== 'color' || paintsNothing(ring) || !parseColor(ring) || (t.inset && !readable(t.fill))) return { target: t, ring }; + // Outset: the ring sits in the gap past the box, over the backdrop. + // Inset: over the item's own rest fill (S9, Q3). Either way the reference + // is what those pixels show when the target is not focused. + const reference = t.inset ? paint(t.fill, t.backdrop.rgb) : t.backdrop.rgb; + const ringPx = group(paint(ring, reference), t.inset ? undefined : t.opacity, reference); + return { target: t, ring, ringPx, reference }; + }); +} + +/** R4 — an active primitive's indicator and the fill beside it. */ +export interface IndicatorPair { + node: SceneNode; + what: string; + indicator: string; + rest: { indicator: Rgb; fill: Rgb }; + /** Absent when the ink does not parse (its layer cannot be modelled). */ + hover?: { indicator: Rgb; fill: Rgb }; +} + +export function indicatorPairs(root: SceneNode): IndicatorPair[] { + const parentOf = parentsOf(root); + const out: IndicatorPair[] = []; + const pair = (node: SceneNode, what: string, indicator: string, fill: string | undefined, ink: string, opacity: number | undefined, backdrop: Backdrop) => { + if (backdrop.kind !== 'color' || paintsNothing(indicator) || !parseColor(indicator) || !readable(fill)) return; + const bd = backdrop.rgb; + const hover = layerAlpha(node.stateStyle?.hover ?? STATE_LAYERS.hover); + const rest = paint(fill, bd); + const at = (under: Rgb) => ({ indicator: group(paint(indicator, under), opacity, bd), fill: group(under, opacity, bd) }); + out.push({ node, what, indicator, rest: at(rest), ...(readable(ink) ? { hover: at(paint(ink, rest, hover)) } : {}) }); + }; + (function walk(n: SceneNode) { + if (n.type === 'nav-item' && n.active && !isDisabled(n)) { + pair(n, `nav-item ${label(n.label, n.id)}`, n.iconColor ?? FALLBACK.accent, n.fill, n.color ?? FALLBACK.text, ownOpacity(n), behind(n, parentOf)); + } else if (n.type === 'tabs' && n.variant !== 'contained' && !isDisabled(n)) { + const backdrop = behind(n, parentOf); + tabsItems(n).forEach((it, i) => { + if (it.active === true && !isDisabled(it)) pair(n, `tab ${label(it.label, String(i + 1))}`, n.iconColor ?? FALLBACK.accent, undefined, n.color ?? FALLBACK.text, undefined, backdrop); + }); + } + n.children?.forEach(walk); + })(root); + return out; +} + +/** R5 — the content a target draws at rest and would draw disabled. */ +export interface DisabledPair { target: StateTarget; rest: Rgb; disabled: Rgb } + +const WHOLE = new Set(['toggle', 'checkbox', 'radio']); + +export function disabledPairs(targets: StateTarget[]): DisabledPair[] { + const out: DisabledPair[] = []; + for (const t of targets) { + const s = t.style; + if (s?.disabledContent === undefined || s.disabledContainer === undefined) continue; + if (t.opacity !== undefined || t.kind === 'modal close' || t.backdrop.kind !== 'color') continue; + const bd = t.backdrop.rgb; + const n = t.node; + // A control is its own content: the track, the box or the ring. + const content = WHOLE.has(t.kind) ? (t.kind === 'toggle' || (t.kind === 'checkbox' && n.checked) ? n.fill : n.stroke) : t.ink; + if (paintsNothing(content) || !parseColor(content!) || !readable(t.fill) || !readable(s.onSurface)) continue; + const rest = WHOLE.has(t.kind) ? paint(content, bd) : paint(content, paint(t.fill, bd)); + out.push({ target: t, rest, disabled: paint(s.onSurface, bd, s.disabledContent) }); + } + return out; +} + +/** R7 — a boundary that is a control's only cue, and what is outside it. */ +export interface BoundaryPair { + node: SceneNode; + color: string; + boundary: Rgb; + /** The control's own fill as drawn, when it paints one. */ + field?: Rgb; + backdrop: Rgb; +} + +export function boundaryPairs(root: SceneNode): BoundaryPair[] { + const parentOf = parentsOf(root); + const out: BoundaryPair[] = []; + (function walk(n: SceneNode) { + const measured = !isDisabled(n) && (n.type === 'text-input' || ((n.type === 'checkbox' || n.type === 'toggle' || n.type === 'radio') && !n.checked)); + if (measured) { + // An unset text-input stroke draws its fallback; the controls' unset + // boundary is invalid CSS, which draws nothing. + const color = n.type === 'text-input' ? n.stroke ?? (typeof n.error === 'string' && n.error.trim() ? FALLBACK.danger : FALLBACK.border) : n.type === 'toggle' ? n.fill : n.stroke; + const backdrop = behind(n, parentOf); + // The field's own fill (a radio draws none; a toggle's fill is its track). + const fill = n.type === 'text-input' ? n.fill ?? FALLBACK.surface : n.type === 'checkbox' ? n.fill : undefined; + // A boundary that draws nothing (unset, an unresolved $token, + // transparent, none) is measured as what shows there: an invisible + // outline is the worst boundary, not one to skip. + if ((paintsNothing(color) || parseColor(color as string)) && backdrop.kind === 'color' && readable(fill)) { + const bd = backdrop.rgb; + const under = paint(fill, bd); + out.push({ + node: n, color: typeof color === 'string' && color ? color : 'none', + // A border is painted over the control's own fill (R7). + boundary: group(paint(color as string, under), ownOpacity(n), bd), + // WCAG 1.4.11 asks the border for 3:1 only when nothing else shows + // the field: a fill that clears the backdrop does. + ...(fill !== undefined && !paintsNothing(fill) ? { field: group(under, ownOpacity(n), bd) } : {}), + backdrop: bd, + }); + } + } + n.children?.forEach(walk); + })(root); + return out; +} + +// ── the rules ──────────────────────────────────────────────────────────── + +const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`; +const darkTag = (theme?: 'dark') => (theme === 'dark' ? { theme: 'dark' as const } : {}); +const inTheme = (theme?: 'dark') => (theme === 'dark' ? ' in the dark theme' : ''); + +function grouped(base: Omit, nodes: SceneNode[], count: number): EvaluationIssue { + const ids = [...new Set(nodes.map((n) => n.id))]; + return { ...base, nodeId: ids[0], nodeName: nodes[0].name, nodeIds: ids, count }; +} + +/** FR-H1 (R3) — `desktop-app-focus-visible`. */ +export function checkFocusVisible(targets: StateTarget[], theme?: 'dark'): EvaluationIssue[] { + const groups = new Map(); + const skipped: StateTarget[] = []; + for (const p of focusPairs(targets)) { + if (!p.ringPx || !p.reference) { skipped.push(p.target); continue; } + if (roundedRatio(p.ringPx, p.reference) >= NON_TEXT_MIN) continue; + const key = `${rgbToHex(p.ringPx)}|${rgbToHex(p.reference)}`; + const members = groups.get(key); + if (members) members.push(p); + else groups.set(key, [p]); + } + const issues: EvaluationIssue[] = []; + for (const members of groups.values()) { + const { ringPx, reference } = members[0]; + // Members share the drawn ring; name the authored one when they agree. + const authored = new Set(members.map((m) => m.ring)); + const ring = authored.size === 1 ? members[0].ring : rgbToHex(ringPx!); + const ratio = roundedRatio(ringPx!, reference!); + const whats = [...new Set(members.map((m) => m.target.what))]; + issues.push(grouped({ + category: 'color', rule: STATE_RULES.focus, severity: 'error', ...darkTag(theme), + message: `Focus ring ${ring} measures ${ratio.toFixed(2)}:1 against ${rgbToHex(reference!)}${inTheme(theme)} on ${plural(members.length, 'target')} (${whats.slice(0, 4).join(', ')}${whats.length > 4 ? ', …' : ''}). WCAG 1.4.11 needs 3:1 for a focus indicator, so keyboard users cannot see where they are.`, + suggestion: theme === 'dark' + ? `Fix it in the dark token layer: a dark.colors "focus-ring" that clears 3:1 against ${rgbToHex(reference!)} (generate_design_system picks one against every bg-* and *-tint).` + : `Set a $focus-ring that clears 3:1 against ${rgbToHex(reference!)}: set_variables({ colors: { "focus-ring": … } }) — generate_design_system picks one against every bg-* and *-tint.`, + }, members.map((m) => m.target.node), members.length)); + } + if (skipped.length) { + issues.push(grouped({ + category: 'color', rule: STATE_RULES.focus, severity: 'info', ...darkTag(theme), + message: `The focus ring of ${plural(skipped.length, 'target')} could not be measured${inTheme(theme)}: the backdrop (or a tab's own fill) is a gradient or a fill the checker cannot read, or the ring colour does not parse.`, + suggestion: 'Check these focus rings by eye in a focus state screenshot (state: "focus").', + }, skipped.map((t) => t.node), skipped.length)); + } + return issues; +} + +/** FR-H2 (R4) — `desktop-app-state-contrast`. */ +export function checkStateContrast(root: SceneNode, theme?: 'dark'): EvaluationIssue[] { + return indicatorPairs(root).flatMap((p) => { + const rest = roundedRatio(p.rest.indicator, p.rest.fill); + const hover = p.hover ? roundedRatio(p.hover.indicator, p.hover.fill) : undefined; + const failing = [rest < NON_TEXT_MIN ? `${rest.toFixed(2)}:1 at rest` : '', hover !== undefined && hover < NON_TEXT_MIN ? `${hover.toFixed(2)}:1 in hover` : ''].filter(Boolean); + if (!failing.length) return []; + return [{ + category: 'color', rule: STATE_RULES.active, severity: 'warning' as const, nodeId: p.node.id, nodeName: p.node.name, ...darkTag(theme), + message: `The active ${p.what}'s indicator ${p.indicator} measures ${failing.join(' and ')} against its active fill${inTheme(theme)}. WCAG 1.4.11 needs 3:1, and hover must not hide the selection.`, + suggestion: theme === 'dark' + ? 'Fix it in the dark token layer: a dark $accent (the indicator) or $accent-tint (the active fill) a step further apart.' + : 'Move $accent (the indicator) and $accent-tint (the active fill) further apart, or set iconColor / fill on the node.', + }]; + }); +} + +/** FR-H3 (R5) — `desktop-app-disabled`. */ +export function checkDisabledLook(targets: StateTarget[], theme?: 'dark'): EvaluationIssue[] { + const same = disabledPairs(targets).map((p) => ({ ...p, ratio: roundedRatio(p.rest, p.disabled) })).filter((p) => p.ratio <= SAME_LOOK_MAX); + if (!same.length) return []; + const closest = Math.min(...same.map((p) => p.ratio)); + const s = same[0].target.style!; + return [grouped({ + category: 'color', rule: STATE_RULES.disabled, severity: 'info', ...darkTag(theme), + message: `With state.disabledContent ${s.disabledContent} (disabledContainer ${s.disabledContainer}), ${plural(same.length, 'target')} would draw disabled content within ${SAME_LOOK_MAX}:1 of their enabled content${inTheme(theme)} (closest ${closest.toFixed(2)}:1): disabled would look enabled.`, + suggestion: 'Lower state.disabledContent with set_variables (Material uses 0.38), so a disabled control reads as unavailable.', + }, same.map((p) => p.target.node), same.length)]; +} + +/** FR-H4 (R7) — `desktop-app-boundary`. */ +export function checkBoundaries(root: SceneNode, theme?: 'dark'): EvaluationIssue[] { + return boundaryPairs(root).flatMap((p) => { + const ratio = roundedRatio(p.boundary, p.backdrop); + if (ratio >= NON_TEXT_MIN) return []; + if (p.field && roundedRatio(p.field, p.backdrop) >= NON_TEXT_MIN) return []; + const part = p.node.type === 'toggle' ? 'track' : p.node.type === 'text-input' ? 'border' : 'outline'; + return [{ + category: 'color', rule: STATE_RULES.boundary, severity: 'warning' as const, nodeId: p.node.id, nodeName: p.node.name, ...darkTag(theme), + message: `This ${p.node.type}'s ${part} ${p.color} measures ${ratio.toFixed(2)}:1 against ${rgbToHex(p.backdrop)}${inTheme(theme)}: nothing else shows the control's edge${p.node.type === 'text-input' || p.node.type === 'checkbox' ? ' (its fill does not stand out either)' : ''}, and WCAG 1.4.11 needs 3:1.`, + suggestion: theme === 'dark' + ? 'Fix it in the dark token layer: a dark $border-strong that clears 3:1 against the surface behind the control.' + : 'Use $border-strong for the boundary (generate_design_system writes one at 3:1 against bg-primary and bg-surface), or set a stronger stroke.', + }]; + }); +} + +/** The four checks on one theme's tree, each when its rule is on. */ +export function checkStates(root: SceneNode, ruleOn: (id: string) => boolean, theme?: 'dark'): EvaluationIssue[] { + const targets = stateTargets(root); + return [ + ...(ruleOn(STATE_RULES.focus) ? checkFocusVisible(targets, theme) : []), + ...(ruleOn(STATE_RULES.active) ? checkStateContrast(root, theme) : []), + ...(ruleOn(STATE_RULES.disabled) ? checkDisabledLook(targets, theme) : []), + ...(ruleOn(STATE_RULES.boundary) ? checkBoundaries(root, theme) : []), + ]; +} diff --git a/src/surfaces.ts b/src/surfaces.ts index cd73371..b8063cd 100644 --- a/src/surfaces.ts +++ b/src/surfaces.ts @@ -200,6 +200,11 @@ export const DESKTOP_APP_RULES: readonly string[] = [ 'desktop-app-truncation', 'desktop-app-primary-count', 'desktop-app-overlay', + // Phase 31 slice H — the element states, checked analytically (state-checks.ts). + 'desktop-app-focus-visible', + 'desktop-app-state-contrast', + 'desktop-app-disabled', + 'desktop-app-boundary', ]; /** Phase 31: default rules — they run unless an active ruleset disables them. diff --git a/test-desktop-app-rules.ts b/test-desktop-app-rules.ts index ce8cd41..6058946 100644 --- a/test-desktop-app-rules.ts +++ b/test-desktop-app-rules.ts @@ -292,20 +292,25 @@ const nav = (id: string, extra: Partial = {}): SceneNode => ({ id, na frame('users', [frame('head', cells('h', { textOverflow: 'ellipsis' }), { layout: 'horizontal', height: 40 }), ...[0, 1, 2].map((i) => frame(`r${i}`, cells(`r${i}`), { layout: 'horizontal', height: 32 }))]), frame('bar', [{ id: 'p1', name: 'p1', type: 'button', label: 'Save', variant: 'primary' }, { id: 'p2', name: 'p2', type: 'button', label: 'Publish', variant: 'primary' }], { layout: 'horizontal' }), { id: 'oops', name: 'oops', type: 'toast', text: 'Could not save', tone: 'danger' }, + // Slice H: a faint ring and border, a faint indicator, disabledContent 1. + { id: 'field', name: 'field', type: 'text-input', placeholder: 'Name' }, + { id: 'faint', name: 'faint', type: 'nav-item', label: 'Faint', active: true, fill: '#FFFFFF', iconColor: '#EEEEEE' }, ]; + const vars: Canvas['variables'] = { colors: { 'focus-ring': '#EEEEEE', border: '#EEEEEE' }, state: { disabledContent: 1 } }; const expected: Record = { 'desktop-app-target': 'usability', 'desktop-app-handbuilt-target': 'usability', 'desktop-app-icon-label': 'usability', 'desktop-app-current': 'usability', 'desktop-app-type-ladder': 'typography', 'desktop-app-row-rhythm': 'consistency', 'desktop-app-truncation': 'usability', 'desktop-app-primary-count': 'structure', 'desktop-app-overlay': 'usability', + 'desktop-app-focus-visible': 'color', 'desktop-app-state-contrast': 'color', 'desktop-app-disabled': 'color', 'desktop-app-boundary': 'color', }; check('the combined tree covers every registered desktop-app rule', JSON.stringify(Object.keys(expected).sort()) === JSON.stringify([...DESKTOP_APP_RULES].sort())); - const app = (await evaluateCanvas(canvasOf(everything), { mode: 'fast' })).issues; + const app = (await evaluateCanvas(canvasOf(everything, 'desktop-app', vars), { mode: 'fast' })).issues; for (const [rule, category] of Object.entries(expected)) { const f = app.filter((i) => i.rule === rule); check(`F9: ${rule} fires on desktop-app, under ${category}`, f.length > 0 && f.every((i) => i.category === category), show(f)); } for (const type of ['web', 'mobile'] as const) { - const r = (await evaluateCanvas(canvasOf(everything, type), { mode: 'fast' })).issues; + const r = (await evaluateCanvas(canvasOf(everything, type, vars), { mode: 'fast' })).issues; const leaked = r.filter((i) => i.rule?.startsWith('desktop-app-') && i.rule !== 'desktop-app-artboard'); check(`${type} runs none of the desktop-app rules but the artboard`, leaked.length === 0, show(leaked)); } diff --git a/test-state-checks.ts b/test-state-checks.ts new file mode 100644 index 0000000..a545bd1 --- /dev/null +++ b/test-state-checks.ts @@ -0,0 +1,561 @@ +// Phase 31 slice H (FR-H1 to FR-H4, spec R1 to R10) — the element states, +// checked without being drawn: the focus ring (desktop-app-focus-visible), the +// active indicator (desktop-app-state-contrast), disabled versus rest +// (desktop-app-disabled), the only-cue boundary (desktop-app-boundary), and +// FR-H3's text-contrast exclusion on every type. Every asserted pass has a +// twin that must fail, every failure a twin that must pass. R9(b): no +// generated system trips them on the backdrops it promises. Fast tier. +// +// Usage: npx tsx test-state-checks.ts + +import './test-env.js'; +import { evaluateCanvas, type EvaluationIssue } from './src/evaluate.js'; +import { backdropBehind, parseAlpha, parseColor, contrastRatio, rgbToHex } from './src/color-math.js'; +import { boundaryPairs, checkDisabledLook, checkFocusVisible, checkStates, disabledPairs, focusPairs, indicatorPairs, stateTargets, layerAlpha, paint } from './src/state-checks.js'; +import { resolveVariables } from './src/variables.js'; +import { generateDesignSystem, PERSONALITY_NAMES } from './src/design-language.js'; +import type { Canvas, DesignVariables, SceneNode } from './src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${!cond && extra ? ` — ${extra}` : ''}`); +} + +type Kind = 'web' | 'mobile' | 'desktop-app'; +const FOCUS = 'desktop-app-focus-visible'; +const ACTIVE = 'desktop-app-state-contrast'; +const DISABLED = 'desktop-app-disabled'; +const BOUNDARY = 'desktop-app-boundary'; +const STATE_IDS = [FOCUS, ACTIVE, DISABLED, BOUNDARY]; + +function canvasOf(children: SceneNode[], variables: DesignVariables = {}, type: Kind = 'desktop-app', components: Record = {}): Canvas { + return { + id: 'c', name: 'c', projectId: 'p', components, variables, createdAt: '', lastModified: '', + root: { id: 'document', type: 'document', name: 'Document', width: 1440, height: 900, fill: '#FFFFFF', layout: 'vertical', padding: 24, children }, + metadata: { surface: type === 'desktop-app' ? { type, device: 'window-1440' } : { type } }, + } as Canvas; +} +async function issues(children: SceneNode[], variables: DesignVariables = {}, type: Kind = 'desktop-app', components: Record = {}): Promise { + const r = await evaluateCanvas(canvasOf(children, variables, type, components), { mode: 'fast' }); + return r.issues; +} +const of = (all: EvaluationIssue[], rule: string) => all.filter((i) => i.rule === rule); +const show = (f: EvaluationIssue[]) => JSON.stringify(f.map((i) => `${i.severity}${i.theme ? `/${i.theme}` : ''}: ${i.message} [${(i.nodeIds ?? [i.nodeId]).join(',')}]`)); +const panel = (children: SceneNode[], extra: Partial = {}): SceneNode => + ({ id: 'panel', name: 'panel', type: 'frame', fill: '#FFFFFF', layout: 'vertical', gap: 8, padding: 16, width: 320, children, ...extra }); +const ids = (i: EvaluationIssue | undefined) => [...(i?.nodeIds ?? [])].sort().join(','); + +// ── R1: the shared walk and the percent alpha ───────────────────────────── +check('R1: a percent alpha is read', parseAlpha('rgba(0, 0, 0, 50%)') === 0.5 && parseAlpha('rgba(0,0,0,0.5)') === 0.5); +check('R1: an opaque colour is 1 (twin)', parseAlpha('#000') === 1 && parseAlpha('rgb(0, 0, 0)') === 1 && parseAlpha('rgba(0,0,0,100%)') === 1); +check('R1: #RRGGBBAA alpha', Math.abs(parseAlpha('#00000080') - 128 / 255) < 1e-9); +{ + const node = (fill?: string, extra: Partial = {}): SceneNode => ({ id: 'n', type: 'frame', fill, ...extra }); + const bd = (chain: SceneNode[]) => backdropBehind(chain); + const color = (b: ReturnType) => (b.kind === 'color' ? b.rgb.join(',') : b.kind); + check('R1: no fill is the white page', color(bd([node()])) === '255,255,255'); + check('R1: a $token, transparent and none are seen through', color(bd([node('$x'), node('transparent'), node('none'), node('#000000')])) === '0,0,0'); + check('R1: a translucent fill composites over the next', color(bd([node('rgba(0, 0, 0, 50%)'), node('#FFFFFF')])) === '128,128,128'); + check('R1: a gradient stops the walk', color(bd([node(undefined, { gradient: { type: 'linear', stops: [] } as SceneNode['gradient'] }), node('#000000')])) === 'gradient'); + check('R1: an unparseable fill is unreadable', color(bd([node('hsl(0, 0%, 0%)'), node('#000000')])) === 'unreadable'); + const stop = (n: SceneNode) => (n.type === 'modal' ? n.fill : undefined); + check('R1: the walk stops at an opaque overlay', color(backdropBehind([{ id: 'm', type: 'modal', fill: '#000000' }, node('#FFFFFF')], { stop })) === '0,0,0'); + check('R1: a translucent overlay is unreadable', color(backdropBehind([{ id: 'm', type: 'modal', fill: 'rgba(0,0,0,0.5)' }, node('#FFFFFF')], { stop })) === 'unreadable'); +} + +// ── R3 / FR-H1: desktop-app-focus-visible ───────────────────────────────── +// #8ea2ff is 2.40:1 on white, #7286ff 3.20:1. +const inspector = (): SceneNode[] => [panel([ + { id: 'b', type: 'button', label: 'Save', size: 'sm', fill: '#111111', color: '#FFFFFF' }, + { id: 'ti', type: 'text-input', placeholder: 'Name' }, + { id: 'cb', type: 'checkbox' }, + { id: 'ln', type: 'link', label: 'Docs' }, + { id: 'nv', type: 'nav-item', label: 'Home' }, + { id: 'tb', type: 'tabs', items: [{ label: 'Design', active: true }, { label: 'Layout' }] }, +])]; +{ + let f = of(await issues(inspector(), { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + const errors = f.filter((i) => i.severity === 'error'); + check('FR-H1: a 2.4:1 ring on the panel is ONE error', errors.length === 1, show(f)); + check('FR-H1: its nodeIds list every target on the panel', ids(errors[0]) === 'b,cb,ln,nv,tb,ti', show(f)); + check('FR-H1: its count is the targets (two tabs)', errors[0]?.count === 7, show(f)); + check('FR-H1: the message names the ring, the backdrop and the ratio', /#8ea2ff measures 2\.40:1 against #ffffff/.test(errors[0]?.message ?? ''), show(f)); + f = of(await issues(inspector(), { colors: { 'focus-ring': '#7286ff' } }), FOCUS); + check('FR-H1 twin: a 3.2:1 ring raises nothing', f.length === 0, show(f)); + f = of(await issues(inspector(), { colors: { accent: '#8ea2ff' } }), FOCUS); + check('R3: without $focus-ring the ring is $accent (the chain)', f.length === 1 && /#8ea2ff/.test(f[0].message), show(f)); + f = of(await issues(inspector(), { colors: { accent: '#7286ff', 'focus-ring': '#8ea2ff' } }), FOCUS); + check('R3 twin: $focus-ring wins over $accent', f.length === 1 && /#8ea2ff/.test(f[0].message), show(f)); + f = of(await issues(inspector()), FOCUS); + check('R3: unthemed, the #2563EB fallback clears white', f.length === 0, show(f)); + + // An outset ring meets the backdrop, never the target's own fill. + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go', fill: '#1d4ed8', color: '#FFFFFF' }])], { colors: { 'focus-ring': '#1d4ed8' } }), FOCUS); + check('R3: an outset ring is not measured against the target fill', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go', fill: '#FFFFFF', color: '#111111' }], { fill: '#1d4ed8' })], { colors: { 'focus-ring': '#1d4ed8' } }), FOCUS); + check('R3 twin: the same ring on a panel of its own colour errors', f.length === 1 && f[0].severity === 'error', show(f)); + + // An inset ring (a tab) covers the tab's own rest fill. + const contained = (variant: 'contained' | 'line') => [panel([{ id: 'tb', type: 'tabs', variant, fill: '#1e3a8a', items: [{ label: 'A', active: true }, { label: 'B' }] }])]; + f = of(await issues(contained('contained'), { colors: { 'focus-ring': '#1d4ed8' } }), FOCUS); + check('R3: a contained active tab\'s ring meets its fill', f.length === 1 && f[0].count === 1 && /tab "A"/.test(f[0].message), show(f)); + f = of(await issues(contained('line'), { colors: { 'focus-ring': '#1d4ed8' } }), FOCUS); + check('R3 twin: a line tab paints no fill, so the same ring passes', f.length === 0, show(f)); + // The focus layer is not the reference: a line tab whose ink layer would + // darken the backdrop does not move the verdict. + const tabsOnPanel = (ring: string) => issues([panel([{ id: 'tb', type: 'tabs', color: '#000000', items: [{ label: 'A', active: true }] }])], { colors: { 'focus-ring': ring }, state: { focus: 1 } }); + f = of(await tabsOnPanel('#7286ff'), FOCUS); + check('R3: a tab ring is measured against the unfocused pixels (a full focus layer ignored)', f.length === 0, show(f)); + + // Disabled targets draw no ring. + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go', disabled: true }, { id: 'b2', type: 'button', label: 'Go', state: 'disabled' }])], { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + check('R3: a disabled target is not measured (both spellings)', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go', disabled: false }])], { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + check('R3 twin: an enabled one is', f.length === 1, show(f)); + f = of(await issues([panel([{ id: 'tb', type: 'tabs', disabled: true, items: [{ label: 'A' }] }])], { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + check('R3: a disabled tabs node disables its tabs', f.length === 0, show(f)); + + // Own opacity dims the ring with the target. + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go', opacity: 0.4 }])], { colors: { 'focus-ring': '#1d4ed8' } }), FOCUS); + check('R2: a target\'s own opacity dims its ring', f.length === 1, show(f)); + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go', opacity: 1 }])], { colors: { 'focus-ring': '#1d4ed8' } }), FOCUS); + check('R2 twin: at opacity 1 the ring passes', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go' }])], { colors: { 'focus-ring': 'rgba(29, 78, 216, 30%)' } }), FOCUS); + check('R2: a percent-alpha ring composites (fails)', f.length === 1, show(f)); + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go' }])], { colors: { 'focus-ring': 'rgba(29, 78, 216, 100%)' } }), FOCUS); + check('R2 twin: at 100% it passes', f.length === 0, show(f)); + + // Unmeasurable: one info listing them. + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go' }], { fill: undefined, gradient: { type: 'linear', angle: 90, stops: [{ color: '#000000', position: 0 }, { color: '#FFFFFF', position: 1 }] } as SceneNode['gradient'] })]), FOCUS); + check('R3: a gradient backdrop is one info naming the target', f.length === 1 && f[0].severity === 'info' && ids(f[0]) === 'b', show(f)); + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'Go' }])], { colors: { 'focus-ring': 'hsl(220, 80%, 50%)' } }), FOCUS); + check('R3: an unparseable ring is the same info', f.length === 1 && f[0].severity === 'info', show(f)); + + // Items: modal actions and close report the modal; its fill is the backdrop. + const modal = (fill: string): SceneNode[] => [panel([], { fill: '#000000' }), { + id: 'm', name: 'm', type: 'modal', title: 'Delete?', fill, actions: [{ label: 'Cancel' }, { label: 'Delete', variant: 'destructive' }], + }]; + f = of(await issues(modal('#FFFFFF'), { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + check('R3: a modal\'s close and actions are measured on the modal fill', f.length === 1 && f[0].count === 3 && ids(f[0]) === 'm' && /#ffffff/.test(f[0].message), show(f)); + f = of(await issues(modal('rgba(255,255,255,0.6)'), { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + check('R3 twin: a translucent modal is unreadable (its tree parent is not behind it)', f.length === 1 && f[0].severity === 'info', show(f)); + f = of(await issues([panel([{ id: 'nb', type: 'nav-bar', title: 'T', fill: '#8ea2ff', leading: { label: 'Back' } }])], { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + check('R3: a nav-bar action meets the nav-bar fill', f.length === 1 && f[0].count === 1 && /measures 1\.00:1/.test(f[0].message), show(f)); + f = of(await issues([panel([{ id: 'ts', type: 'toast', text: 'Saved', fill: '#FFFFFF', action: { label: 'Undo', disabled: true } }])], { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + check('R3: a disabled toast action is not measured', f.length === 0, show(f)); + + // Dark theme: the dark layer is checked too, tagged. + 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. + 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': '#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)); + + // Desktop-app only. + for (const type of ['web', 'mobile'] as const) { + const all = await issues(inspector(), { colors: { 'focus-ring': '#8ea2ff', 'border-strong': '#c1c1c1' }, state: { disabledContent: 1 } }, type); + check(`R2: a ${type} canvas runs none of the four`, all.every((i) => !STATE_IDS.includes(i.rule ?? '')), show(all.filter((i) => STATE_IDS.includes(i.rule ?? '')))); + } +} + +// ── R4 / FR-H2: desktop-app-state-contrast ──────────────────────────────── +{ + const nav = (iconColor: string, extra: Partial = {}): SceneNode[] => [panel([{ id: 'nv', type: 'nav-item', label: 'Home', active: true, fill: '#EAF0FD', iconColor, ...extra }])]; + let f = of(await issues(nav('#7d91ff')), ACTIVE); + check('FR-H2: a 2.5:1 nav-item indicator warns', f.length === 1 && f[0].severity === 'warning' && /2\.50:1 at rest/.test(f[0].message), show(f)); + f = of(await issues(nav('#1e3a8a')), ACTIVE); + check('FR-H2 twin: a strong indicator passes', f.length === 0, show(f)); + // Hover only: an indicator lighter than the fill gets closer under a dark layer. + const hoverOnly = indicatorPairs(resolveVariables(nav('#FFFFFF', { fill: '#5b6b8c', color: '#FFFFFF' })[0], {}))[0]; + const rest = contrastRatio(hoverOnly.rest.indicator, hoverOnly.rest.fill); + const hover = contrastRatio(hoverOnly.hover!.indicator, hoverOnly.hover!.fill); + check('R4: the hover layer is the ink over the fill (white ink lightens)', hover < rest, `${rest} ${hover}`); + f = of(await issues(nav('#FFFFFF', { fill: '#6d7a95', color: '#FFFFFF' }), { state: { hover: 0.3 } }), ACTIVE); + check('R4: a hover-only failure warns naming hover', f.length === 1 && /in hover/.test(f[0].message) && !/at rest/.test(f[0].message), show(f)); + f = of(await issues(nav('#FFFFFF', { fill: '#6d7a95', color: '#FFFFFF' }), { state: { hover: 0 } }), ACTIVE); + check('R4 twin: with no hover layer it passes', f.length === 0, show(f)); + f = of(await issues(nav('#7d91ff', { active: false })), ACTIVE); + check('R4: an inactive nav-item draws no indicator', f.length === 0, show(f)); + f = of(await issues(nav('#7d91ff', { disabled: true })), ACTIVE); + check('R4: a disabled active nav-item is skipped', f.length === 0, show(f)); + const tabs = (variant: 'line' | 'contained', iconColor = '#c9d6f2'): SceneNode[] => [panel([{ id: 'tb', type: 'tabs', variant, iconColor, items: [{ label: 'One', active: true }, { label: 'Two' }] }])]; + f = of(await issues(tabs('line')), ACTIVE); + check('R4: a line tab underline at 1.4:1 warns, naming the tab', f.length === 1 && /tab "One"/.test(f[0].message), show(f)); + f = of(await issues(tabs('line', '#1e3a8a')), ACTIVE); + check('R4 twin: a strong underline passes', f.length === 0, show(f)); + f = of(await issues(tabs('contained')), ACTIVE); + check('R4: a contained tab draws no indicator mark', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'tr', type: 'tree-row', label: 'src', depth: 0, active: true, iconColor: '#c9d6f2', icon: 'folder' }])]), ACTIVE); + check('R4: a tree-row draws no indicator mark', f.length === 0, show(f)); +} + +// ── R5 / FR-H3: desktop-app-disabled, and the disabled exclusion (R6) ────── +{ + const sys = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; + let all = await issues([panel([{ id: 'b', type: 'button', label: 'Save', disabled: true }], { fill: '$bg-surface' })], sys); + check('FR-H3: a disabled button at the generated opacities raises nothing', all.filter((i) => STATE_IDS.includes(i.rule ?? '') || (i.category === 'color' && i.severity !== 'info')).length === 0, show(all.filter((i) => i.category === 'color'))); + const withContent = (c: number): DesignVariables => ({ ...sys, state: { ...sys.state, disabledContent: c } }); + let f = of(await issues([panel([{ id: 'nv', type: 'nav-item', label: 'Home' }, { id: 'b', type: 'button', label: 'Save' }], { fill: '$bg-surface' })], withContent(1)), DISABLED); + check('FR-H3: disabledContent 1 raises the info (the dark copy says the same, so it is dropped)', f.length === 1 && f[0].severity === 'info' && !f[0].theme, show(f)); + check('R5: it names the on-surface targets, not the white-label primary', ids(f[0]) === 'nv', show(f)); + f = of(await issues([panel([{ id: 'nv', type: 'nav-item', label: 'Home' }], { fill: '$bg-surface' })], withContent(0.38)), DISABLED); + check('FR-H3 twin: 0.38 raises nothing', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'nv', type: 'nav-item', label: 'Home', opacity: 0.9 }], { fill: '$bg-surface' })], withContent(1)), DISABLED); + check('R5: an authored opacity is not the tokens\' render', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'nv', type: 'nav-item', label: 'Home' }])], { colors: { ...sys.colors } }), DISABLED); + check('R5: no disabled tokens, no info (the 0.5 render)', f.length === 0, show(f)); + // The modal close button is never disabled and never measured. + const tgs = stateTargets(resolveVariables({ id: 'r', type: 'frame', fill: '#FFFFFF', children: [{ id: 'm', type: 'modal', title: 'x' }] }, withContent(1))); + check('R5: the modal close button is not measured', disabledPairs(tgs).every((p) => p.target.kind !== 'modal close') && tgs.some((t) => t.kind === 'modal close')); + + // R6 on web: text under a disabled clickable primitive is exempt. + const textUnder = (disabled: boolean): SceneNode[] => [panel([{ id: 'b', type: 'button', label: 'x', disabled, children: [{ id: 't', type: 'text', content: 'faint', color: '#EEEEEE' }] }])]; + all = await issues(textUnder(true), {}, 'web'); + check('R6: text inside a disabled primitive raises no contrast error (web)', !all.some((i) => i.category === 'color' && i.nodeId === 't'), show(all.filter((i) => i.category === 'color'))); + all = await issues(textUnder(false), {}, 'web'); + check('R6 twin: inside an enabled one it errors', all.some((i) => i.category === 'color' && i.nodeId === 't' && i.severity === 'error'), show(all.filter((i) => i.category === 'color'))); + all = await issues([panel([{ id: 'tb', type: 'tabs', state: 'disabled', items: [{ label: 'A' }], children: [{ id: 't', type: 'text', content: 'faint', color: '#EEEEEE' }] }])], {}, 'mobile'); + check('R6: a disabled tabs node exempts its text (mobile)', !all.some((i) => i.category === 'color' && i.nodeId === 't'), show(all.filter((i) => i.category === 'color'))); + all = await issues([panel([{ id: 'f', type: 'frame', disabled: true, children: [{ id: 't', type: 'text', content: 'faint', color: '#EEEEEE' }] }])], {}, 'web'); + check('R6 twin: a disabled frame is not a target, its text still errors', all.some((i) => i.category === 'color' && i.nodeId === 't'), show(all.filter((i) => i.category === 'color'))); +} + +// ── R7 / FR-H4: desktop-app-boundary ────────────────────────────────────── +{ + let f = of(await issues([panel([{ id: 'ti', type: 'text-input', placeholder: 'Name' }])], { colors: { border: '#c1c1c1' } }), BOUNDARY); + check('FR-H4: a text-input on a 1.8:1 $border warns', f.length === 1 && f[0].severity === 'warning' && /1\.80:1/.test(f[0].message), show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', placeholder: 'Name' }])], { colors: { border: '#c1c1c1', 'border-strong': '#767676' } }), BOUNDARY); + check('FR-H4 twin: $border-strong at 4.5:1 passes', f.length === 0, show(f)); + const controls = (checked: boolean): SceneNode[] => [panel([ + { id: 'cb', type: 'checkbox', checked }, { id: 'rd', type: 'radio', checked }, { id: 'tg', type: 'toggle', checked }, + ])]; + f = of(await issues(controls(false), { colors: { border: '#c1c1c1', accent: '#c1c1c1' } }), BOUNDARY); + check('R7: an unchecked checkbox, radio and toggle each warn', f.map((i) => i.nodeId).sort().join(',') === 'cb,rd,tg', show(f)); + f = of(await issues(controls(true), { colors: { border: '#c1c1c1', accent: '#c1c1c1' } }), BOUNDARY); + check('R7 twin: checked ones are not measured', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', disabled: true }])], { colors: { border: '#c1c1c1' } }), BOUNDARY); + check('R7: a disabled text-input is not measured', f.length === 0, show(f)); + // A translucent border composites over the field fill, not the panel. + const translucent = (fill: string) => [panel([{ id: 'ti', type: 'text-input', fill, stroke: 'rgba(255, 255, 255, 0.5)' }])]; + f = of(await issues(translucent('#000000')), BOUNDARY); + check('R7: a translucent border over a black field is grey, 3.95:1 against the white panel (passes)', f.length === 0, show(f)); + f = of(await issues(translucent('#FFFFFF')), BOUNDARY); + check('R7 twin: over a white field the same border vanishes (warns)', f.length === 1 && /1\.00:1/.test(f[0].message), show(f)); + const over = boundaryPairs(resolveVariables(translucent('#000000')[0], {}))[0]; + check('R7: the boundary pixel is the stroke over the field fill', over?.boundary.join(',') === '128,128,128', JSON.stringify(over)); + // Inside a component: an unset text-input stroke draws its #D1D5DB fallback; + // an unset checkbox stroke draws nothing. + const raw: SceneNode = { id: 'r', type: 'frame', fill: '#FFFFFF', children: [{ id: 'ti', type: 'text-input' }, { id: 'cb', type: 'checkbox' }] }; + const pairs = boundaryPairs(raw); + check('R7: an unresolved text-input is measured at its fallback', pairs[0]?.node.id === 'ti' && pairs[0].color === '#D1D5DB', JSON.stringify(pairs)); + check('V4 fix: an unresolved checkbox draws no outline and is measured as the backdrop', pairs[1]?.node.id === 'cb' && pairs[1].boundary.join(',') === '255,255,255', JSON.stringify(pairs)); + const errored = boundaryPairs({ id: 'r', type: 'frame', children: [{ id: 'ti', type: 'text-input', error: 'Required' }] }); + check('R7: with an error the fallback is #DC2626', errored[0]?.color === '#DC2626', JSON.stringify(errored)); + check('R7: a select is not measured (not in FR-H4)', boundaryPairs({ id: 'r', type: 'frame', children: [{ id: 's', type: 'select', stroke: '#EEEEEE' }] }).length === 0); +} + +// ── R2: the model's arithmetic ──────────────────────────────────────────── +check('R2: layer percent rounds as the render (Q6)', layerAlpha(0.123456) === 0.1235 && layerAlpha(0.08) === 0.08); +check('R2: an ink alpha multiplies the layer (#ffffffde at 8% is 6.96%)', paint('#ffffffde', [0, 0, 0], 0.08).join(',') === '18,18,18', paint('#ffffffde', [0, 0, 0], 0.08).join(',')); +check('R2: a token paints nothing', paint('$x', [1, 2, 3]).join(',') === '1,2,3'); +{ + const t = stateTargets({ id: 'r', type: 'frame', children: [ + { id: 'tb', type: 'tabs', variant: 'contained', items: [{ label: 'A', active: true }, { label: 'B' }] }, + { id: 'bar', type: 'tab-bar', items: [{ icon: 'home', label: 'Home', active: true }, { icon: 'cog', label: 'S' }] }, + { id: 'ma', type: 'modal', title: 'm', actions: [{ label: 'Go', variant: 'primary' }, { label: 'No', variant: 'ghost' }] }, + ] }); + const byWhat = (w: string) => t.find((x) => x.what === w); + check('R2: a contained active tab fills #EFF4FF unthemed, inactive none', byWhat('tab "A"')?.fill === '#EFF4FF' && byWhat('tab "B"')?.fill === undefined); + check('R2: tab inks: active color, else secondary (fallbacks)', byWhat('tab "A"')?.ink === '#111827' && byWhat('tab "B"')?.ink === '#6B7280'); + check('R2: tab-bar item inks: active accent, else color', byWhat('tab-bar item "Home"')?.ink === '#2563EB' && byWhat('tab-bar item "S"')?.ink === '#6B7280'); + check('R2: tabs and tab-bar items are inset, a modal action outset', !!byWhat('tab "A"')?.inset && !!byWhat('tab-bar item "Home"')?.inset && byWhat('modal action "Go"')?.inset === false); + check('R2: modal action colours as actionButton draws them', byWhat('modal action "Go"')?.ink === '#FFFFFF' && byWhat('modal action "Go"')?.fill === '#2563EB' && byWhat('modal action "No"')?.ink === '#2563EB'); + const ring = focusPairs(t).find((p) => p.target.what === 'tab "A"'); + check('R3: an inset ring\'s reference is the item fill over the backdrop', ring?.reference?.join(',') === parseColor('#EFF4FF')!.join(','), JSON.stringify(ring)); +} + +// ── R9(b): the generated systems on the backdrops they promise ──────────── +const SEEDS = ['#166534', '#2563EB', '#B45309']; +const targetsOn = (key: string): SceneNode => ({ + id: `bd-${key}`, type: 'frame', fill: `$${key}`, layout: 'vertical', gap: 8, padding: 16, width: 360, + children: [ + { id: `${key}-b1`, type: 'button', label: 'Save', size: 'sm' }, + { id: `${key}-b2`, type: 'button', label: 'Cancel', size: 'sm', variant: 'secondary' }, + { id: `${key}-b3`, type: 'button', label: 'More', size: 'sm', variant: 'ghost' }, + { id: `${key}-b4`, type: 'button', label: 'Delete', size: 'sm', variant: 'destructive' }, + { id: `${key}-ln`, type: 'link', label: 'Docs' }, + { id: `${key}-ti`, type: 'text-input', placeholder: 'Search' }, + { id: `${key}-te`, type: 'text-input', value: 'x', error: 'Required' }, + { id: `${key}-n1`, type: 'nav-item', label: 'Home', active: true }, + { id: `${key}-n2`, type: 'nav-item', label: 'Inbox' }, + { id: `${key}-tr`, type: 'tree-row', label: 'src', depth: 0, active: true, icon: 'folder' }, + { id: `${key}-mr`, type: 'menu-row', label: 'Copy', shortcut: '⌘C' }, + { id: `${key}-lr`, type: 'list-row', title: 'Row' }, + { id: `${key}-tl`, type: 'tabs', items: [{ label: 'One', active: true }, { label: 'Two' }] }, + { id: `${key}-tc`, type: 'tabs', variant: 'contained', items: [{ label: 'One', active: true }, { label: 'Two' }] }, + { id: `${key}-c0`, type: 'checkbox' }, { id: `${key}-c1`, type: 'checkbox', checked: true }, + { id: `${key}-r0`, type: 'radio' }, { id: `${key}-r1`, type: 'radio', checked: true }, + { id: `${key}-g0`, type: 'toggle' }, { id: `${key}-g1`, type: 'toggle', checked: true }, + { id: `${key}-se`, type: 'select', value: 'One' }, + ], +}); +for (const personality of PERSONALITY_NAMES) { + for (const seed of SEEDS) { + const sys = generateDesignSystem(seed, personality, { surface: 'desktop-app' }).variables; + const keys = Object.keys(sys.colors!).filter((k) => /^bg-|-tint$/.test(k)); + const all = await issues(keys.map(targetsOn), sys); + const where = (i: EvaluationIssue) => (i.nodeIds ?? [i.nodeId]).map((id) => id.split('-').slice(0, -1).join('-').replace(/^bd-/, '')); + const focus = of(all, FOCUS); + check(`R9(b) ${personality} ${seed}: no focus-ring finding on any bg-* or *-tint, either theme`, focus.length === 0, show(focus)); + const promised = (i: EvaluationIssue) => where(i).some((k) => k === 'bg-primary' || k === 'bg-surface'); + const active = of(all, ACTIVE).filter(promised); + check(`R9(b) ${personality} ${seed}: no indicator finding on bg-primary / bg-surface`, active.length === 0, show(active)); + const boundary = of(all, BOUNDARY).filter(promised); + check(`R9(b) ${personality} ${seed}: no boundary finding on bg-primary / bg-surface`, boundary.length === 0, show(boundary)); + const disabled = of(all, DISABLED); + check(`R9(b) ${personality} ${seed}: no disabled-look finding anywhere`, disabled.length === 0, show(disabled)); + check(`R9(b) ${personality} ${seed}: both themes ran`, !!sys.dark?.colors && Object.keys(sys.dark.colors).length > 0); + } +} + +{ + // R9(b) twin: the same scene trips the rules once the tokens are broken, and + // the findings land on the frames the filter reads. + const sys = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; + const c = sys.colors!; + const broken: DesignVariables = { ...sys, colors: { ...c, 'focus-ring': c['bg-primary'], 'border-strong': c['bg-surface'], accent: c['accent-tint'] }, state: { ...sys.state, disabledContent: 1 } }; + const all = await issues(['bg-primary', 'bg-surface'].map(targetsOn), broken); + const on = (rule: string, key: string) => of(all, rule).some((i) => (i.nodeIds ?? [i.nodeId]).some((id) => id.startsWith(`${key}-`))); + check('R9(b) twin: a broken ring is found on bg-primary', on(FOCUS, 'bg-primary'), show(of(all, FOCUS))); + check('R9(b) twin: a broken boundary is found on bg-surface', on(BOUNDARY, 'bg-surface'), show(of(all, BOUNDARY))); + check('R9(b) twin: a broken indicator is found', of(all, ACTIVE).length > 0, show(of(all, ACTIVE))); + check('R9(b) twin: disabledContent 1 is found', of(all, DISABLED).length > 0, show(of(all, DISABLED))); +} + +// ── Verify round 1 fixes ────────────────────────────────────────────────── +{ + // An inset ring over a fill that does not parse (a named colour still + // paints) cannot be measured: the info, never an error against the backdrop. + const navyTabs = (fill: string) => [panel([{ id: 'tb', type: 'tabs', variant: 'contained', fill, items: [{ label: 'A', active: true }] }])]; + let f = of(await issues(navyTabs('navy'), { colors: { 'focus-ring': '#FFFFFF' } }), FOCUS); + check('fix: a contained tab with a named fill is unmeasurable (info)', f.length === 1 && f[0].severity === 'info', show(f)); + f = of(await issues(navyTabs('#FFFFFF'), { colors: { 'focus-ring': '#FFFFFF' } }), FOCUS); + check('fix twin: the same tab with a hex fill errors', f.length === 1 && f[0].severity === 'error', show(f)); + // A named hover ink: the rest verdict still stands, hover is not modelled. + f = of(await issues([panel([{ id: 'nv', type: 'nav-item', label: 'Home', active: true, fill: '#EAF0FD', iconColor: '#7d91ff', color: 'black' }])]), ACTIVE); + check('fix: a named ink still gets the rest verdict, not a hover one', f.length === 1 && /at rest/.test(f[0].message) && !/in hover/.test(f[0].message), show(f)); + f = of(await issues([panel([{ id: 'nv', type: 'nav-item', label: 'Home', active: true, fill: 'lavender', iconColor: '#7d91ff' }])]), ACTIVE); + check('fix twin: a named active fill skips the pair', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', fill: 'white', stroke: 'rgba(0,0,0,0.1)' }])]), BOUNDARY); + check('fix: a translucent border over a named field fill is skipped', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', fill: '#FFFFFF', stroke: 'rgba(0,0,0,0.1)' }])]), BOUNDARY); + check('fix twin: over a hex field fill it warns', f.length === 1, show(f)); + // V1: an explicit transparent / none boundary is invisible, so it warns + // unless the control's own fill shows the edge. + f = of(await issues([panel([{ id: 'ti', type: 'text-input', stroke: 'transparent', fill: '#FFFFFF' }, { id: 'rd', type: 'radio', stroke: 'none' }, { id: 'tg', type: 'toggle', fill: 'transparent' }])]), BOUNDARY); + check('fix: a transparent / none boundary warns at 1.00:1', f.map((i) => i.nodeId).sort().join(',') === 'rd,tg,ti' && f.every((i) => /1\.00:1/.test(i.message)), show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', stroke: 'transparent', fill: '#1F2937' }])]), BOUNDARY); + check('fix twin: a transparent border on a dark field passes (the fill is the edge)', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', stroke: '$missing' }, { id: 'cb', type: 'checkbox', stroke: '$missing' }, { id: 'tg', type: 'toggle', fill: '$missing' }])]), BOUNDARY); + check('V4 fix: a typo\'d token boundary draws nothing, so it warns', f.map((i) => i.nodeId).sort().join(',') === 'cb,tg,ti', show(f)); + // V4: a field whose fill clears the backdrop is shown by its fill. + f = of(await issues([panel([{ id: 'ti', type: 'text-input', fill: '#111827', color: '#FFFFFF', stroke: '#D1D5DB' }, { id: 'cb', type: 'checkbox', fill: '#111827', stroke: '#D1D5DB' }])]), BOUNDARY); + check('V4 fix: a dark-filled field with a faint border passes (the fill is the edge)', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', fill: '#969696', stroke: '#D1D5DB' }])]), BOUNDARY); + check('V4 fix twin: a fill at 2.96:1 does not show the field (warns)', f.length === 1, show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', fill: '#949494', stroke: '#D1D5DB' }])]), BOUNDARY); + check('V4 fix: a fill at 3.03:1 shows it (the boundary)', f.length === 0, show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', fill: '#F3F4F6', stroke: 'transparent' }])]), BOUNDARY); + check('V4 fix: a ghost field (faint fill, no border) warns', f.length === 1, show(f)); + // V4: a literal control on a literal frame says the same in both themes: + // one finding, not a dark copy pointing at the dark layer. + const sysD = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; + f = of(await issues([{ id: 'lit', type: 'frame', fill: '#FFFFFF', children: [{ id: 'tg', type: 'toggle', fill: '#E5E7EB' }] }], sysD), BOUNDARY); + 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. + 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)); + 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. + // (A numeric colour token already throws in checkConsistency, before slice + // H, so the state model is driven directly here.) + let threw = false; + let infos: EvaluationIssue[] = []; + try { + infos = checkFocusVisible(stateTargets({ id: 'r', type: 'frame', fill: '#FFFFFF', children: [{ id: 'b', type: 'button', label: 'Go', stateStyle: { ring: 7 as unknown as string, onSurface: '#111111', surface: '#FFFFFF', hover: 0.08, focus: 0.1, pressed: 0.1 } }] })); + } catch { threw = true; } + check('fix: a numeric ring does not throw (the info)', !threw && infos.length === 1 && infos[0].severity === 'info', show(infos)); + const numeric = backdropBehind([{ id: 'n', type: 'frame', fill: 5 as unknown as string }, { id: 'm', type: 'frame', fill: '#000000' }]); + 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. + 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)); + 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)); +} + + +// ── Mutation round: boundaries, gates, inks, the walk ──────────────────── +{ + const W = '#FFFFFF'; + // Exact thresholds: 3.00 passes (a raw 2.997 rounds to it), 2.99 fails. + const ringOn = async (ring: string) => of(await issues([panel([{ id: 'b', type: 'button', label: 'Go' }])], { colors: { 'focus-ring': ring } }), FOCUS); + check('M: a ring at a raw 2.997:1 rounds to 3.00 and passes', (await ringOn('#9191bf')).length === 0); + check('M twin: a ring at 2.99:1 fails', (await ringOn('#9191c0')).length === 1); + const borderOn = async (stroke: string) => of(await issues([panel([{ id: 'ti', type: 'text-input', stroke }])]), BOUNDARY); + check('M: a border at a raw 2.997:1 passes, at 2.99 warns', (await borderOn('#9191bf')).length === 0 && (await borderOn('#9191c0')).length === 1); + const barOn = async (iconColor: string) => of(await issues([panel([{ id: 'nv', type: 'nav-item', label: 'H', active: true, fill: W, iconColor, color: W }])], { state: { hover: 0 } }), ACTIVE); + check('M: an indicator at a raw 2.997:1 passes, at 2.99 warns', (await barOn('#9191bf')).length === 0 && (await barOn('#9191c0')).length === 1); + // Disabled look: #111111 content at 0.956 is 1.10:1 (info), at 0.955 1.11:1 (silent). + const look = async (c: number) => of(await issues([panel([{ id: 'nv', type: 'nav-item', label: 'H', color: '#111111' }], { fill: W })], { colors: { 'text-primary': '#111111' }, state: { disabledContent: c, disabledContainer: 0.12 } }), DISABLED); + const at110 = await look(0.956); + check('M: a disabled look at exactly 1.10:1 is the info', at110.length === 1 && /closest 1\.10:1/.test(at110[0].message), show(at110)); + check('M twin: at 1.11:1 it is silent', (await look(0.955)).length === 0); + + // Each rule answers only to its own id. + const sysG = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; + const broken = resolveVariables({ id: 'r', type: 'frame', fill: '#FFFFFF', children: [ + { id: 'b', type: 'button', label: 'Go' }, { id: 'ti', type: 'text-input' }, + { id: 'nv', type: 'nav-item', label: 'H', active: true, fill: '#FFFFFF', iconColor: '#F0F0F0' }, + ] }, { ...sysG, colors: { ...sysG.colors, 'focus-ring': '#F8F8F8', 'border-strong': '#F8F8F8', 'text-primary': '#111111' }, state: { ...sysG.state, disabledContent: 1 } }); + const all4 = [FOCUS, ACTIVE, DISABLED, BOUNDARY]; + for (const rule of all4) { + const got = new Set(checkStates(broken, (id) => id === rule).map((i) => i.rule)); + check(`M: with only ${rule} on, only it reports`, got.size === 1 && got.has(rule), [...got].join(',')); + const without = new Set(checkStates(broken, (id) => id !== rule).map((i) => i.rule)); + check(`M twin: with ${rule} off, the other three report`, !without.has(rule) && without.size === 3, [...without].join(',')); + } + + // The grouping key: two backdrops, two errors; one node with two tabs listed once. + let f = of(await issues([panel([{ id: 'b1', type: 'button', label: 'A' }]), { id: 'p2', type: 'frame', fill: '#F0F0F0', children: [{ id: 'b2', type: 'button', label: 'B' }] }], { colors: { 'focus-ring': '#DDDDDD' } }), FOCUS); + check('M: two backdrops give two errors', f.length === 2 && f.every((i) => i.count === 1), show(f)); + f = of(await issues([panel([{ id: 'tb', type: 'tabs', items: [{ label: 'A', active: true }, { label: 'B' }, { label: 'C' }] }, { id: 'b', type: 'button', label: 'x' }, { id: 'l', type: 'link', label: 'y' }, { id: 'n', type: 'nav-item', label: 'z' }, { id: 'c', type: 'checkbox' }])], { colors: { 'focus-ring': '#DDDDDD' } }), FOCUS); + check('M: one tabs node is listed once, its tabs counted each', f.length === 1 && f[0].count === 7 && (f[0].nodeIds ?? []).filter((i) => i === 'tb').length === 1 && f[0].nodeId === 'tb', show(f)); + check('M: the message names four kinds then an ellipsis, plural targets', /on 7 targets \(tab "A", tab "B", tab "C", button, …\)/.test(f[0]?.message ?? ''), f[0]?.message); + f = of(await issues([panel([{ id: 'b', type: 'button', label: 'x' }])], { colors: { 'focus-ring': '#DDDDDD' } }), FOCUS); + check('M: one target reads singular', /on 1 target \(button\)\./.test(f[0]?.message ?? ''), f[0]?.message); + + // Backdrops of overlays and item hosts. + const inPopover = resolveVariables({ id: 'r', type: 'frame', fill: '#000000', children: [{ id: 'po', type: 'popover', fill: '#FAFAFA', children: [{ id: 'b', type: 'button', label: 'Go' }] }] }, {}); + check('M: a target in a popover sits on the popover fill, not the page behind', focusPairs(stateTargets(inPopover))[0].reference?.join(',') === '250,250,250'); + const inMenu = { id: 'r', type: 'frame', fill: '#000000', children: [{ id: 'mn', type: 'menu', children: [{ id: 'mr', type: 'menu-row', label: 'Copy' }] }] } as SceneNode; + check('M: an unfilled menu draws its #FFFFFF fallback behind its rows', focusPairs(stateTargets(inMenu))[0].reference?.join(',') === '255,255,255'); + const inDrawer = { id: 'r', type: 'frame', fill: '#000000', children: [{ id: 'dr', type: 'drawer', fill: '$x', children: [{ id: 'b', type: 'button', label: 'Go' }] }] } as SceneNode; + check('M: a drawer whose fill paints nothing is unreadable', stateTargets(inDrawer)[0].backdrop.kind === 'unreadable'); + const bar = (fill?: string) => stateTargets({ id: 'r', type: 'frame', fill: '#000000', children: [{ id: 'tb', type: 'tab-bar', ...(fill ? { fill } : {}), items: [{ icon: 'home', label: 'H' }, { icon: 'x', label: 'X', disabled: true }] }] } as SceneNode); + const barBd = (fill?: string) => { const b = bar(fill)[0].backdrop; return b.kind === 'color' ? b.rgb.join(',') : b.kind; }; + check('M: a tab-bar with no fill draws #FFFFFF behind its items', barBd() === '255,255,255'); + check('M: a translucent tab-bar fill composites over its ancestors', barBd('rgba(255, 255, 255, 0.5)') === '128,128,128'); + check('M: a disabled tab-bar item is disabled, the other not', bar()[1].disabled && !bar()[0].disabled && bar()[0].inset); + const nb = stateTargets({ id: 'r', type: 'frame', fill: '#000000', children: [{ id: 'nb', type: 'nav-bar', title: 't', leading: { label: 'Back' }, trailing: [{ icon: 'x', state: 'disabled' }] }] } as SceneNode); + check('M: a nav-bar with no fill puts its actions on the page behind (#000000)', nb[0].backdrop.kind === 'color' && nb[0].backdrop.rgb.join(',') === '0,0,0' && nb[0].ink === '#2563EB' && !nb[0].inset); + check('M: a disabled nav-bar action is disabled', nb[1].disabled && !nb[0].disabled); + const md = stateTargets({ id: 'r', type: 'frame', children: [{ id: 'm', type: 'modal', title: 't', actions: [{ label: 'Go', variant: 'primary', disabled: true }, { label: 'No' }, { label: 'Bye', variant: 'destructive' }] }] } as SceneNode); + const mWhat = (w: string) => md.find((t) => t.what === w)!; + check('M: the modal close button: secondary ink, transparent, never disabled', mWhat('modal close button').ink === '#6B7280' && mWhat('modal close button').fill === 'transparent' && !mWhat('modal close button').disabled); + check('M: a default modal action is secondary (text ink, transparent)', mWhat('modal action "No"').ink === '#111827' && mWhat('modal action "No"').fill === 'transparent'); + check('M: a destructive action fills #DC2626 with white ink', mWhat('modal action "Bye"').fill === '#DC2626' && mWhat('modal action "Bye"').ink === '#FFFFFF'); + check('M: a disabled modal action is disabled', mWhat('modal action "Go"').disabled && !mWhat('modal action "No"').disabled); + const ts = stateTargets({ id: 'r', type: 'frame', children: [{ id: 't', type: 'toast', text: 'x', action: { label: 'Undo' } }, { id: 't2', type: 'toast', text: 'y', action: { label: ' ' } }] } as SceneNode); + check('M: a toast action: accent ink, transparent fill, on the toast; a blank one is none', ts.length === 1 && ts[0].ink === '#2563EB' && ts[0].fill === 'transparent' && ts[0].backdrop.kind === 'color' && ts[0].backdrop.rgb.join(',') === '255,255,255'); + f = of(await issues([panel([{ id: 'ts', type: 'toast', text: 'Saved', fill: '#FFFFFF', action: { label: 'Undo' } }])], { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + check('M twin: an enabled toast action is measured', f.length === 1, show(f)); + + // The P4 inks and fills of every node type, unresolved (the renderer's fallbacks). + const kinds = stateTargets({ id: 'r', type: 'frame', children: [ + { id: 'bp', type: 'button', label: 'a' }, { id: 'bs', type: 'button', label: 'a', variant: 'secondary' }, { id: 'bg', type: 'button', label: 'a', variant: 'ghost' }, { id: 'bd', type: 'button', label: 'a', variant: 'destructive' }, + { id: 'ln', type: 'link', label: 'a' }, { id: 'ti', type: 'text-input' }, { id: 'mr', type: 'menu-row', label: 'a' }, { id: 'md', type: 'menu-row', label: 'a', destructive: true }, + { id: 'tg', type: 'toggle', fill: '#123456' }, { id: 'c0', type: 'checkbox', stroke: '#222222' }, { id: 'c1', type: 'checkbox', checked: true, stroke: '#222222' }, { id: 'rd', type: 'radio', stroke: '#333333' }, + { id: 'se', type: 'select', color: '#444444', fill: '#555555' }, { id: 'tr', type: 'tree-row', label: 'a' }, { id: 'lr', type: 'list-row', title: 'a', fill: '#666666' }, + ] } as SceneNode); + const k = (id: string) => kinds.find((t) => t.node.id === id)!; + const row = (id: string) => `${k(id).ink}|${k(id).fill ?? '-'}`; + const expected: Record = { + bp: '#FFFFFF|#2563EB', bs: '#2563EB|transparent', bg: '#2563EB|transparent', bd: '#FFFFFF|#DC2626', ln: '#2563EB|-', ti: '#111827|#FFFFFF', + mr: '#111827|-', md: '#DC2626|-', tg: '#FFFFFF|#123456', c0: '#222222|-', c1: '#FFFFFF|-', rd: '#333333|-', se: '#444444|#555555', tr: '#111827|-', lr: '#111827|#666666', + }; + const wrong = Object.entries(expected).filter(([id, want]) => row(id) !== want).map(([id, want]) => `${id}: ${row(id)} ≠ ${want}`); + check('M: every node type\'s ink and fill are the renderer\'s', wrong.length === 0, wrong.join('; ')); + + // disabledPairs: a control is its own content. + const ctl = resolveVariables({ id: 'r', type: 'frame', fill: '#FFFFFF', children: [ + { id: 'tg', type: 'toggle', fill: '#000000' }, { id: 'c0', type: 'checkbox', stroke: '#000000', fill: '#FFFFFF' }, { id: 'c1', type: 'checkbox', checked: true, fill: '#000000', stroke: '#FFFFFF' }, { id: 'rd', type: 'radio', stroke: '#000000', fill: '#FFFFFF' }, + { id: 'bt', type: 'button', label: 'x', fill: '#FFFFFF', color: '#000000' }, + ] }, { colors: { 'text-primary': '#000000' }, state: { disabledContent: 1, disabledContainer: 0.12 } }); + const dp = disabledPairs(stateTargets(ctl)); + const dIds = dp.map((p) => `${p.target.node.id}:${p.rest.join(',')}`).sort().join(' '); + check('M: a toggle, an unchecked checkbox, a checked checkbox and a radio are their own content', dIds === 'bt:0,0,0 c0:0,0,0 c1:0,0,0 rd:0,0,0 tg:0,0,0', dIds); + check('M: with on-surface #000 at 1 all five look enabled (the info lists them)', checkDisabledLook(stateTargets(ctl)).at(0)?.count === 5); + const ctlOpacity = resolveVariables({ id: 'r', type: 'frame', children: [{ id: 'a', type: 'nav-item', label: 'x', opacity: 1 }, { id: 'b', type: 'nav-item', label: 'x', opacity: 0 }, { id: 'c', type: 'nav-item', label: 'x' }] }, { state: { disabledContent: 1 } }); + check('M: an authored opacity of 1 or 0 is authored (skipped); none is not', disabledPairs(stateTargets(ctlOpacity)).map((p) => p.target.node.id).join(',') === 'c'); + + // indicatorPairs: disabled hosts and items, fallback indicator, own opacity. + const tabsAt = (extra: Partial, item: object = {}) => indicatorPairs({ id: 'r', type: 'frame', fill: '#FFFFFF', children: [{ id: 't', type: 'tabs', items: [{ label: 'A', active: true, ...item }], ...extra }] } as SceneNode); + check('M: a disabled tabs host and a disabled active tab draw no indicator', tabsAt({ disabled: true }).length === 0 && tabsAt({}, { disabled: true }).length === 0 && tabsAt({}).length === 1); + check('M: an unset tabs indicator is #2563EB', tabsAt({})[0].indicator === '#2563EB'); + const navAt = (opacity?: number) => indicatorPairs({ id: 'r', type: 'frame', fill: '#FFFFFF', children: [{ id: 'n', type: 'nav-item', label: 'x', active: true, ...(opacity !== undefined ? { opacity } : {}) }] } as SceneNode)[0]; + check('M: an unset nav-item bar is #2563EB on its (absent) fill', navAt().indicator === '#2563EB' && navAt().rest.fill.join(',') === '255,255,255'); + check('M: a nav-item at opacity 0.3 draws its bar faded', navAt(0.3).rest.indicator.join(',') !== navAt().rest.indicator.join(',')); + + // boundaryPairs: a blank error is no error; own opacity fades the border. + check('M: a whitespace error keeps the #D1D5DB fallback', boundaryPairs({ id: 'r', type: 'frame', children: [{ id: 't', type: 'text-input', error: ' ' }] } as SceneNode)[0].color === '#D1D5DB'); + const faded = boundaryPairs({ id: 'r', type: 'frame', fill: '#FFFFFF', children: [{ id: 't', type: 'text-input', stroke: '#000000', opacity: 0.4 }] } as SceneNode)[0]; + check('M: a text-input at opacity 0.4 draws a lighter border', faded.boundary.join(',') === '153,153,153', faded.boundary.join(',')); + const track = boundaryPairs({ id: 'r', type: 'frame', fill: '#FFFFFF', children: [{ id: 'g', type: 'toggle', fill: '#000000' }, { id: 'rd', type: 'radio', stroke: '#000000', fill: '#FF0000' }] } as SceneNode); + check('M: a toggle\'s boundary is its track; a radio\'s ring ignores its (dot) fill', track[0].boundary.join(',') === '0,0,0' && !track[0].field && track[1].boundary.join(',') === '0,0,0' && !track[1].field); + + // Twins the first round lacked. + f = of(await issues([panel([{ id: 'tb', type: 'tabs', items: [{ label: 'A' }] }])], { colors: { 'focus-ring': '#8ea2ff' } }), FOCUS); + check('M twin: an enabled tabs node is measured', f.length === 1, show(f)); + f = of(await issues([panel([{ id: 'nv', type: 'nav-item', label: 'x', active: true, iconColor: '#c9d6f2', icon: 'folder' }])]), ACTIVE); + check('M twin: a nav-item with the tree-row\'s faint colours does warn', f.length === 1, show(f)); + f = of(await issues([panel([{ id: 'ti', type: 'text-input', stroke: '#EEEEEE' }])]), BOUNDARY); + check('M twin: a text-input with the select\'s faint stroke warns', f.length === 1, show(f)); + + // color-math edges. + check('M: a percent alpha over 100% clamps to 1', parseAlpha('rgba(0,0,0,150%)') === 1); + const stop = (fill: string) => backdropBehind([{ id: 'o', type: 'modal' }], { stop: () => fill }).kind; + check('M: a stop that paints nothing or does not parse is unreadable', stop('transparent') === 'unreadable' && stop('hsl(0,0%,0%)') === 'unreadable' && stop('#000000') === 'color'); + const fo = backdropBehind([{ id: 'a', type: 'frame', fill: '#FFFFFF' }], { fillOf: () => '#000000' }); + check('M: fillOf is honoured', fo.kind === 'color' && fo.rgb.join(',') === '0,0,0'); + const clear = backdropBehind([{ id: 'a', type: 'frame', fill: 'rgba(0,0,0,0)' }, { id: 'b', type: 'frame', fill: '#000000' }]); + check('M: a zero-alpha fill adds no layer', clear.kind === 'color' && clear.layers.join() === '#000000'); + const two = backdropBehind([{ id: 'a', type: 'frame', fill: 'rgba(255,255,255,0.5)' }, { id: 'b', type: 'frame', fill: 'rgba(0,0,0,0.5)' }, { id: 'c', type: 'frame', fill: '#FFFFFF' }]); + check('M: two translucent layers composite back to front', two.kind === 'color' && two.rgb.join(',') === '192,192,192', two.kind === 'color' ? two.rgb.join(',') : two.kind); + check('M: rgbToHex pads', rgbToHex([0, 10, 255]) === '#000aff'); + + // A dark-layer canvas with an instance: nodeIds map to the instance once. + const comp: SceneNode = { id: 'cc', type: 'frame', fill: '#2563EB', children: [{ id: 'x1', type: 'button', label: 'a' }, { id: 'x2', type: 'button', label: 'b' }] }; + f = of(await issues([panel([{ id: 'inst', name: 'Bar', type: 'instance', componentId: 'cc' }])], { colors: { bg: '#FFFFFF' }, dark: { colors: { bg: '#000000' } } }, 'desktop-app', { cc: comp }), FOCUS); + check('M: an instance\'s grouped targets report the instance once, with its note', f.length === 1 && (f[0].nodeIds ?? []).join(',') === 'inst' && /inside instance "Bar"/.test(f[0].message), show(f)); +} + + +// ── 3b fixes ───────────────────────────────────────────────────────────── +{ + const sysR = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; + 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)); + 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)); + 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); + check('3b: the unmeasured info names a tab\'s own fill as a cause', /or a tab's own fill/.test(f[0]?.message ?? ''), show(f)); +} + +console.log(allPass ? '\nAll state-check tests passed.' : '\nSOME TESTS FAILED'); +process.exit(allPass ? 0 : 1); diff --git a/test-state-model-render.ts b/test-state-model-render.ts new file mode 100644 index 0000000..b4082de --- /dev/null +++ b/test-state-model-render.ts @@ -0,0 +1,225 @@ +// Phase 31 slice H (spec R8) — the analytical state model against the +// renderer's pixels. Each scene is rendered at device scale 1; the colours the +// model computes (state-checks.ts) for a focus ring and the pixels it covers +// unfocused, an active indicator and its fill in rest and hover, a button's +// hover / focus / pressed fill, a disabled toggle track and button container +// with the token pair, and a boundary with the backdrop outside it, must each +// match the rendered pixel within 2/255 per channel, unthemed and under a +// generated system in both themes (and the dark preset's translucent ink). +// Twin: a model whose layer opacity is 0.05 off must fail the same compare. +// Needs Chrome. Run with: npx tsx test-state-model-render.ts + +import './test-env.js'; +import { renderToHtml } from './src/renderer.js'; +import { resolveVariables } from './src/variables.js'; +import { generateDesignSystem } from './src/design-language.js'; +import { withPage, shutdown } from './src/screenshot.js'; +import { boundaryPairs, disabledPairs, focusPairs, indicatorPairs, layerAlpha, paint, stateTargets } from './src/state-checks.js'; +import type { Rgb } from './src/color-math.js'; +import type { DesignVariables, ElementState, SceneNode } from './src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${!cond && extra ? ` — ${extra}` : ''}`); +} + +const W = 640; +const H = 720; +const TOLERANCE = 2; + +interface Rect { left: number; top: number; right: number; bottom: number } + +/** Render, then read each named element's rect and the pixels at `points`. */ +async function sample(html: string, points: (rects: Record) => Array<[number, number]>): Promise { + return withPage(async (page) => { + await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 }); + await page.setContent(html, { waitUntil: 'domcontentloaded' }); + const rects: Record = await page.evaluate(`(() => { + const out = {}; + const put = (key, el) => { const r = el.getBoundingClientRect(); out[key] = { left: r.left, top: r.top, right: r.right, bottom: r.bottom }; }; + document.querySelectorAll('[data-node-id]').forEach((el) => put(el.getAttribute('data-node-id'), el)); + document.querySelectorAll('[role=tab]').forEach((el, i) => put('tab' + i, el)); + document.querySelectorAll('[role=textbox]').forEach((el, i) => put('field' + i, el)); + document.querySelectorAll('[data-node-id="m"] [data-focusable]').forEach((el, i) => put('m' + i, el)); + return out; + })()`); + const png = Buffer.from(await page.screenshot({ type: 'png' })).toString('base64'); + const pts = points(rects).map(([x, y]) => [Math.round(x), Math.round(y)]); + return page.evaluate(`(async () => { + const img = new Image(); + img.src = 'data:image/png;base64,${png}'; + await img.decode(); + const c = document.createElement('canvas'); + c.width = img.width; c.height = img.height; + const ctx = c.getContext('2d', { willReadFrequently: true }); + ctx.drawImage(img, 0, 0); + return ${JSON.stringify(pts)}.map(([x, y]) => Array.from(ctx.getImageData(x, y, 1, 1).data.slice(0, 3))); + })()`) as Promise; + }); +} + +const off = (a: Rgb, b: Rgb) => Math.max(...a.map((v, i) => Math.abs(v - b[i]))); +const hex = (c: Rgb) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`; +function same(name: string, model: Rgb | undefined, pixel: Rgb) { + check(name, !!model && off(model, pixel) <= TOLERANCE, `model ${model ? hex(model) : 'none'}, pixel ${hex(pixel)}`); +} + +const SYSTEM = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; +const THEMES: Array<{ name: string; vars: DesignVariables; theme?: 'dark' }> = [ + { name: 'unthemed', vars: {} }, + { name: 'generated light', vars: SYSTEM }, + { name: 'generated dark', vars: SYSTEM, theme: 'dark' }, +]; + +/** One scene: a panel of targets, each element in `state`. */ +function scene(state: ElementState, opts: { panelFill?: string; navInk?: string } = {}): SceneNode { + return { + id: 'root', type: 'frame', width: W, height: H, fill: '#FFFFFF', layout: 'vertical', padding: 16, + children: [{ + id: 'panel', type: 'frame', fill: opts.panelFill ?? '$bg-surface', layout: 'vertical', gap: 14, padding: 16, width: 360, + children: [ + { id: 'b', type: 'button', label: 'Save', size: 'sm', state }, + { id: 'nv', type: 'nav-item', label: 'Home', active: true, state, ...(opts.navInk ? { color: opts.navInk } : {}) }, + { id: 'tl', type: 'tabs', items: [{ label: 'Design', active: true, state }, { label: 'Layout' }] }, + { id: 'tc', type: 'tabs', variant: 'contained', items: [{ label: 'All', active: true, state }, { label: 'Starred' }] }, + { id: 'ti', type: 'text-input', placeholder: 'Search', width: 200 }, + { id: 'cb', type: 'checkbox' }, + { id: 'tg', type: 'toggle', state }, + { id: 'b2', type: 'button', label: 'Cancel', size: 'sm', variant: 'secondary', state }, + { id: 'b3', type: 'button', label: 'More', size: 'sm', variant: 'ghost', state }, + { id: 'b4', type: 'button', label: 'Delete', size: 'sm', variant: 'destructive', state }, + { id: 'bo', type: 'button', label: 'Faded', size: 'sm', opacity: 0.5, state }, + ], + }], + }; +} + +const resolved = (state: ElementState, vars: DesignVariables, theme?: 'dark', opts?: Parameters[1]) => + resolveVariables(scene(state, opts), vars, theme ? { theme } : {}); +const htmlOf = (root: SceneNode) => renderToHtml(root, W, H); +const mid = (r: Rect) => (r.top + r.bottom) / 2; + +for (const t of THEMES) { + const rest = resolved('rest', t.vars, t.theme); + const targets = stateTargets(rest); + const find = (id: string, what?: string) => targets.find((x) => x.node.id === id && (!what || x.what === what))!; + + // ── focus: the ring, and the unfocused pixels it covers ── + const ring = focusPairs(targets); + const ringOf = (id: string, what?: string) => ring.find((p) => p.target.node.id === id && (!what || p.target.what === what))!; + const at = (r: Record) => [ + [r.b.right + 3, mid(r.b)], // outset ring, centre of 2px at a 2px gap + [r.tab0.left + 1, mid(r.tab0)], // a line tab's inset ring + [r.tab2.left + 1, mid(r.tab2)], // a contained active tab's inset ring + [(r.tg.left + r.tg.right) / 2, r.tg.bottom + 3], // a pill: its straight bottom edge + ] as Array<[number, number]>; + const focused = await sample(htmlOf(resolved('focus', t.vars, t.theme)), at); + const unfocused = await sample(htmlOf(rest), at); + same(`${t.name}: a button's outset ring`, ringOf('b').ringPx, focused[0]); + same(`${t.name}: the pixels it covers unfocused (the backdrop)`, ringOf('b').reference, unfocused[0]); + same(`${t.name}: a line tab's inset ring`, ringOf('tl', 'tab "Design"').ringPx, focused[1]); + same(`${t.name}: what it covers unfocused`, ringOf('tl', 'tab "Design"').reference, unfocused[1]); + same(`${t.name}: a contained active tab's inset ring`, ringOf('tc', 'tab "All"').ringPx, focused[2]); + same(`${t.name}: what it covers unfocused (the tab fill)`, ringOf('tc', 'tab "All"').reference, unfocused[2]); + same(`${t.name}: a toggle's outset ring`, ringOf('tg').ringPx, focused[3]); + + // ── active: the indicator and its fill, rest and hover ── + const ind = indicatorPairs(rest); + const nav = ind.find((p) => p.node.id === 'nv')!; + const tab = ind.find((p) => p.node.id === 'tl')!; + const marks = (r: Record) => [ + [r.nv.left + 1, mid(r.nv)], [r.nv.right - 8, r.nv.top + 3], + [(r.tab0.left + r.tab0.right) / 2, r.tab0.bottom - 1], [(r.tab0.left + r.tab0.right) / 2, r.tab0.top + 3], + ] as Array<[number, number]>; + for (const state of ['rest', 'hover'] as const) { + const px = await sample(htmlOf(resolved(state, t.vars, t.theme)), marks); + same(`${t.name} ${state}: the nav-item bar`, nav[state]!.indicator, px[0]); + same(`${t.name} ${state}: the nav-item fill beside it`, nav[state]!.fill, px[1]); + same(`${t.name} ${state}: the line tab underline`, tab[state]!.indicator, px[2]); + same(`${t.name} ${state}: the line tab fill above it`, tab[state]!.fill, px[3]); + } + + // ── every button variant: its layer in hover, focus and pressed, its ring ── + const BUTTONS = ['b', 'b2', 'b3', 'b4'] as const; + for (const state of ['hover', 'focus', 'pressed'] as const) { + const px = await sample(htmlOf(resolved(state, t.vars, t.theme)), (r) => BUTTONS.map((id) => [r[id].left + 4, mid(r[id])] as [number, number])); + BUTTONS.forEach((id, i) => { + const btn = find(id); + const bd = btn.backdrop.kind === 'color' ? btn.backdrop.rgb : ([255, 255, 255] as Rgb); + same(`${t.name}: button ${btn.node.variant ?? 'primary'}'s ${state} fill`, paint(btn.ink, paint(btn.fill, bd), layerAlpha(btn.style?.[state] ?? 0)), px[i]); + }); + } + const rings = await sample(htmlOf(resolved('focus', t.vars, t.theme)), (r) => [...BUTTONS, 'bo'].map((id) => [r[id].right + 3, mid(r[id])] as [number, number])); + [...BUTTONS, 'bo'].forEach((id, i) => same(`${t.name}: ${id}'s ring${id === 'bo' ? ' at its own opacity 0.5' : ''}`, ringOf(id).ringPx, rings[i])); + + // ── the boundary and the backdrop outside it ── + const bounds = boundaryPairs(rest); + const field = bounds.find((p) => p.node.id === 'ti')!; + const box = bounds.find((p) => p.node.id === 'cb')!; + const track = bounds.find((p) => p.node.id === 'tg')!; + const edge = await sample(htmlOf(rest), (r) => [[r.field0.left, mid(r.field0)], [r.field0.left - 3, mid(r.field0)], [r.cb.left, mid(r.cb)], [r.tg.right - 4, mid(r.tg)]]); + same(`${t.name}: a text-input border`, field.boundary, edge[0]); + same(`${t.name}: the backdrop outside it`, field.backdrop, edge[1]); + same(`${t.name}: a checkbox outline`, box.boundary, edge[2]); + same(`${t.name}: a toggle track`, track.boundary, edge[3]); +} + +// ── disabled with the token pair: a toggle track, a button container ── +for (const theme of [undefined, 'dark'] as const) { + const name = theme ? 'generated dark' : 'generated light'; + const root = resolved('disabled', SYSTEM, theme); + const tg = stateTargets(root).find((x) => x.node.id === 'tg')!; + const b = stateTargets(root).find((x) => x.node.id === 'b')!; + const s = tg.style!; + const bdOf = (x: typeof tg) => (x.backdrop.kind === 'color' ? x.backdrop.rgb : ([255, 255, 255] as Rgb)); + const [trackPx, containerPx] = await sample(htmlOf(root), (r) => [[r.tg.right - 4, mid(r.tg)], [r.b.left + 4, mid(r.b)]]); + const pair = disabledPairs(stateTargets(resolved('rest', SYSTEM, theme))).find((p) => p.target.node.id === 'tg')!; + same(`${name}: a disabled toggle track is disabledPairs' disabled content`, pair.disabled, trackPx); + const [restTrack] = await sample(htmlOf(resolved('rest', SYSTEM, theme)), (r) => [[r.tg.right - 4, mid(r.tg)]]); + same(`${name}: the rest track is disabledPairs' rest content`, pair.rest, restTrack); + same(`${name}: a disabled toggle track (on-surface at disabledContent)`, paint(s.onSurface, bdOf(tg), s.disabledContent!), trackPx); + // The container takes the on-surface colour at its share, inside the group. + const share = Math.min(100, Math.round((s.disabledContainer! / s.disabledContent!) * 10000) / 100); + same(`${name}: a disabled button container (on-surface at disabledContainer)`, paint(s.onSurface, bdOf(b), (share / 100) * s.disabledContent!), containerPx); +} + +// ── a modal's close button and actions (items reported by the modal) ── +for (const t of THEMES) { + const modal = (state: ElementState): SceneNode => ({ + id: 'root', type: 'frame', width: W, height: H, fill: '#FFFFFF', + children: [{ id: 'm', type: 'modal', title: 'Delete project?', size: 'sm', actions: [{ label: 'Cancel', state }, { label: 'Delete', variant: 'destructive', state }] }], + }); + const root = (state: ElementState) => resolveVariables(modal(state), t.vars, t.theme ? { theme: t.theme } : {}); + const targets = stateTargets(root('rest')); + const ring = focusPairs(targets); + const close = ring.find((p) => p.target.kind === 'modal close')!; + const cancel = ring.find((p) => p.target.what === 'modal action "Cancel"')!; + const del = targets.find((x) => x.what === 'modal action "Delete"')!; + // The close button takes no state, so its ring is checked on the actions. + const focused = await sample(htmlOf(root('focus')), (r) => [[r.m1.left - 3, mid(r.m1)], [r.m2.left + 4, mid(r.m2)]]); + same(`${t.name}: a modal action's ring meets the modal fill`, cancel.ringPx, focused[0]); + const bd = del.backdrop.kind === 'color' ? del.backdrop.rgb : ([255, 255, 255] as Rgb); + same(`${t.name}: a destructive modal action's focus fill`, paint(del.ink, paint(del.fill, bd), layerAlpha(del.style?.focus ?? 0)), focused[1]); + const [restClose] = await sample(htmlOf(root('rest')), (r) => [[r.m0.right + 3, mid(r.m0)]]); + same(`${t.name}: what the close button's ring covers (the modal fill)`, close.reference, restClose); +} + +// ── the dark preset's translucent ink, and the twin ── +{ + const root = resolveVariables(scene('hover', { panelFill: '#121212', navInk: '#ffffffde' }), {}); + const nav = indicatorPairs(root).find((p) => p.node.id === 'nv')!; + const [px] = await sample(htmlOf(root), (r) => [[r.nv.right - 8, r.nv.top + 3]]); + same('a #ffffffde ink\'s hover layer (alpha × percent)', nav.hover!.fill, px); + + const light = resolveVariables(scene('hover'), {}); + const target = stateTargets(light).find((x) => x.node.id === 'nv')!; + const bd = target.backdrop.kind === 'color' ? target.backdrop.rgb : ([255, 255, 255] as Rgb); + const [hoverPx] = await sample(htmlOf(light), (r) => [[r.nv.right - 8, r.nv.top + 3]]); + const drifted = paint(target.ink, paint(target.fill, bd), layerAlpha(0.08) + 0.05); + check('twin: a model 0.05 off in layer opacity fails the compare', off(drifted, hoverPx) > TOLERANCE, `drifted ${hex(drifted)}, pixel ${hex(hoverPx)}`); +} + +await shutdown(); +console.log(allPass ? '\nAll state model render tests passed.' : '\nSOME TESTS FAILED'); +process.exit(allPass ? 0 : 1);