From a0d550a4026b9436f13a98285c9d27727315d326 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Tue, 17 Nov 2026 14:06:13 +0100 Subject: [PATCH 1/5] Pin the slice G contracts in the Phase 31 spec --- docs/specs/PHASE-31-SPEC.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 6cbf3ee..ef3787a 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -335,6 +335,24 @@ One profile ships, keyed by id so a second size is one table row later. Values i **Slice G: element states (FR-G1)** - `src/types.ts`: `state`. `src/renderer.ts`: state layers from the `state` tokens, the focus ring and the double ring. +**Slice G — contracts pinned before build (2026-11-17; frozen at the commit that adds this block).** No pre-freeze verifier: slice G adds no pass/fail rule; its one census change (P6) maps a prop onto the existing disabled exemption and depends on no earlier run. +- **Spec change S9 (Victor-approved, 2026-11-17): the focus ring has a gap, not an inner ring.** FR-G1's "1px inner ring in the fill color" draws nothing on a filled primitive. Focus is a 2px `$focus-ring` outline at a 2px offset on every primitive: the gap shows the backdrop, so the ring meets only the backdrop (what FR-H1 checks) and never a brand fill. It is the geometry the live `:focus-visible` rule already draws. A tab draws it inset (offset −2px), since the tablist clips its overflow. +- **P1: the prop.** `state?: 'rest' | 'hover' | 'focus' | 'pressed' | 'disabled'` on `SceneNode`. The effective state is `disabled` when `disabled === true` (whatever `state` says), else `state` when it is one of the five, else `rest` (an unknown value is ignored). One helper, `elementState`, in `src/primitives.ts`; `isDisabled(n)` is `elementState(n) === 'disabled'`. +- **P2: who takes it.** On the node: `button`, `link`, `text-input`, `nav-item`, `tree-row`, `menu-row`, `list-row`, `toggle`, `checkbox`, `radio`, `select`. On the item, for primitives that render several targets: `tabs.items[].state`, `tab-bar.items[].state`, `nav-bar` `leading.state` and `trailing[].state`, `modal.actions[].state`, `toast.action.state` (an item's `disabled: true` maps the same way). A `tabs` node's own `disabled` or `state: "disabled"` disables every tab. The modal's close button takes none (it has no object to carry it). Any other node ignores `state`: no render change, never a target. +- **P3: resolution.** `applyControlDefaults` gives every node of a P2 type a resolved `stateStyle` (an internal field, never authored or stored): `ring` = `$focus-ring`, else `$accent`, `$primary`, `#2563EB` (the chain FR-H1 names); `hover`, `focus`, `pressed` = the merged `state` token when it is a number in [0, 1], else the Material constant (`STATE_LAYERS`: 0.08 / 0.10 / 0.10); `disabledContent` and `disabledContainer` only when the merged `state` section sets either as a number in [0, 1], the other then taking its constant. A node the resolver skipped (inside a component) renders with ring `#2563EB`, the constant layers, and no disabled tokens. +- **P4: the render.** The element that carries the target's box (P2's node, or the item's slot) draws: + - `hover`, `focus`, `pressed`: a layer of the ink at the state's opacity over its fill, as `background-image: linear-gradient(L, L)` with `L = color-mix(in srgb, %, transparent)`, so it composites over the fill, or over the backdrop when the fill is transparent. The ink is the target's content color: `color` (the label) for button, link, text-input, the rows, select, a tab and a modal or toast action; the item's drawn color for a tab-bar item and a nav-bar action; `#FFFFFF` (the mark) for a checked checkbox and for a toggle (the knob); the `stroke` for an unchecked checkbox and a radio. + - `focus` also draws `outline: 2px solid ; outline-offset: 2px` (S9; a tab −2px). Every focusable primitive's `--fs-ring` (the live `:focus-visible` color) becomes the same `ring`, so live and static focus agree; captures never focus anything, so no screenshot changes. + - a `link` in `hover` or `pressed` also underlines its label (FR-B2). + - `disabled` with disabled tokens: the element renders at `opacity: disabledContent`; its container colors (the background and border of a button, a text-input's field, a select, a row's fill, a tab's fill, a modal or toast action) render through `color-mix(in srgb, P%, transparent)` with `P = min(100, disabledContainer / disabledContent × 100)` (100 when `disabledContent` is 0), so the container shows at `disabledContainer` and the content at `disabledContent`. A toggle, checkbox and radio are their own content: the whole control at `disabledContent`. No state layer, no ring. An authored `opacity` on a disabled node wins: it renders as authored, no container mix. + - `disabled` without disabled tokens: today's 0.5 element opacity (node `opacity` set by `applyControlDefaults` unless authored; an item gets `opacity: 0.5` inline, as a tab does today). + - `active`, `checked` and `expanded` combine: the layer sits over the active, checked or expanded fill. +- **P5: nothing else moves.** A canvas with no `state` prop and no disabled node renders the same pixels as before slice G; its HTML differs only in `--fs-ring` values. A canvas with disabled nodes and no `state` disabled tokens renders as before. Render never depends on type. +- **P6: disabled everywhere.** Every reader of `disabled` on a P2 target reads `isDisabled` instead: the 24px census (`checkUsability`'s targets, `desktopTargets`, `overlayTargets`, which now honours a modal or toast action's disabled state), `desktop-app-primary-count` (a disabled button and a disabled modal action are not primaries), and the renderer's `tabindex="-1" aria-disabled="true"`. The mobile touch census, which never exempted disabled targets, is unchanged. +- **P7: agent surfaces.** `batch_design`'s property list and every P2 primitive's line gain `state`; `INSTRUCTIONS`, GOTCHAS (states are a prop, screen states are variants), GUIDELINES (a "States sheet" paragraph: when to draw a state, what each looks like, that the evaluator needs none of them), README's primitive table, `test-discoverability.ts` if a list applies, and the VISION checklist. +- **P8: acceptance in this slice.** Fast tier: HTML assertions for each P2 target at each state, with a twin that must not show it (rest, a non-P2 node with `state`, an unknown value, `disabled: true` beating `state: "hover"`), the P3 fallbacks and P4's disabled arithmetic, and P6 with a twin per reader. Full tier: a `button` of each variant at each of the five states renders deterministically (two renders, identical pixels) and distinctly (every pair of states differs) in both themes of a generated design system; P5's pixels-unchanged claim on a stamped desktop-app realisation and a mobile one, against the same scene rendered before slice G. +- **P9: the inputs the render must cover** (hard rule 6, the verifier's list): every P2 node and item; each of the five states plus absent and unknown; `disabled: true` with each state; with and without `state` tokens, and with only one disabled token; an authored `opacity`; `active` / `checked` / `expanded` true and false; filled, transparent and unthemed (inside a component) fills; light and dark themes; `web`, `mobile` and `desktop-app` canvases; a modal and toast action, and a tab-bar and nav-bar item, each disabled. Census readers: fast and detailed `checkUsability`, `overlayTargets`, primary count. + **Slice H: state checks (FR-H1 to FR-H4)** - `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. From 5fbbbf376ce6c2262bcce2148aa3cfca5f6b0481 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Tue, 17 Nov 2026 15:38:35 +0100 Subject: [PATCH 2/5] Draw element states from state tokens (Phase 31 slice G) --- README.md | 2 + VISION.md | 2 +- docs/GUIDELINES.md | 17 +- docs/specs/PHASE-31-SPEC.md | 11 ++ src/design-language.ts | 8 +- src/desktop-app-rules.ts | 6 +- src/evaluate.ts | 16 +- src/index.ts | 31 ++-- src/primitives.ts | 40 ++++- src/renderer.ts | 237 +++++++++++++++++++++---- src/types.ts | 39 +++- src/variables.ts | 52 +++++- test-discoverability.ts | 28 +++ test-element-states-render.ts | 71 ++++++++ test-element-states.ts | 323 ++++++++++++++++++++++++++++++++++ 15 files changed, 800 insertions(+), 83 deletions(-) create mode 100644 test-element-states-render.ts create mode 100644 test-element-states.ts diff --git a/README.md b/README.md index e2d84fb..15a1b16 100644 --- a/README.md +++ b/README.md @@ -397,6 +397,8 @@ 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 (8 / 10 / 10%), focus adds a 2px `$focus-ring` at a 2px gap, and disabled renders in `$text-primary` at 38% (a drawn fill or border at 12%), or at 0.5 without state tokens. 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. Other node types ignore it. + #### Overlays Six overlays draw screen states: an open menu, a comment popover, a confirm dialog, a toast. Put each in a state variant (`canvas_add_variant` with `menu-open`, `comment-open`, `confirm-delete` or `toast`); coverage lists those states and never demands them. Wherever an overlay sits in the tree, it renders in one layer after the content, so a pane never clips it and a sticky bar never covers it. `x` / `y` are offsets from the root's top-left, not from the parent. Layers are fixed by kind, with no z-index property: `popover` and `menu` 400, the modal's scrim 500, `modal` and `drawer` 510, `toast` 600, `tooltip` 800. `anchor` names the node that opens an overlay; it is never rendered, and `desktop-app-overlay` checks that it names something clickable. Colours come from `$bg-surface`, `$border`, `$text-primary` and `$text-secondary`, depth from `$elevation.overlay`. diff --git a/VISION.md b/VISION.md index 63764a6..09ae048 100644 --- a/VISION.md +++ b/VISION.md @@ -571,7 +571,7 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 - [ ] Follow-up — the web scaffolds' tint tokens (`success-tint` and the rest) are seeded dark and survive a later light `apply_preset`, as `accent-tint` did before Phase 31 slice D stopped seeding it; derive them from the applied palette instead - [x] Slice E — overlays: one overlay layer at the root with a fixed ladder, and the `tooltip`, `popover`, `menu`, `modal`, `toast` and `drawer` primitives, with overlay screen states as variants - [x] Slice F — overlay rules: one modal, text-only tooltips, no large tables in modals, overlays inside the viewport, nothing under a scrim, and advisories on stacked toasts, error toasts and dangling anchors -- [ ] Slice G — element states: hover, focus, pressed and disabled as a primitive property, drawn from state tokens +- [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 - [ ] Slice H — state checks: focus rings, active indicators, disabled renders and control boundaries checked analytically on every interactive primitive, without being drawn - [ ] 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 diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index b068240..3cc7f84 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), and its screen states in [Overlays](#overlays-screen-states); the overlay rules and element states come in later slices 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); 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. 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). @@ -120,7 +120,7 @@ Build application screens from these primitives, never from hand-built frames: a - **`button` at `size: "xs"`** is the 24px icon button of a dense toolbar. An icon-only button (no `label`) takes `ariaLabel` as its accessible name: it renders `aria-label` and `title` and is never drawn. `xs`, like `sm`, is an error on a phone. - **`link`** `{ label, icon?, iconPosition?, external?, ariaLabel? }` is a standalone text action, at least 24 tall, and a measured target. Without a `label` it hugs its glyphs (14px wide, 30 with `external`) and takes `ariaLabel` as its name (rendered as `aria-label` and `title`). For a link inside a sentence, keep it in the `text` node: `links: [{ start, end }]` marks character ranges of its `content`, drawn underlined. Inline links are exempt from the 24px floor, as WCAG exempts them. A `text` node also takes `title`, rendered as a tooltip. -- **`text-input`** `{ value?, placeholder?, icon?, size?: "sm" | "md", rows?, error?, disabled? }` is a field (32 or 40 tall; `rows` makes it multi-line). Its border is its only boundary, so it uses `$border-strong` when the design system has one. `error` turns the border `$danger` and draws an icon and the message below the field, so the error is never colour alone. +- **`text-input`** `{ value?, placeholder?, icon?, size?: "sm" | "md", rows?, error?, disabled?, state? }` is a field (32 or 40 tall; `rows` makes it multi-line). Its border is its only boundary, so it uses `$border-strong` when the design system has one. `error` turns the border `$danger` and draws an icon and the message below the field, so the error is never colour alone. - **`nav-item`** `{ label, icon?, count?, dotColor?, active?, depth?: 0 | 1, collapsed? }` is a 32px sidebar row that spans its sidebar. `active` draws three cues: an `$accent-tint` fill, a 2px `$accent` bar, and a heavier label (and `aria-current`). `collapsed` is the 32×32 rail form, with its label as the accessible name. `dotColor` is an identity dot for a project or label: it is never counted as a competing accent, though the same colour used anywhere else still is. - **`tabs`** `{ items: [{ label, count?, active?, disabled? }], variant?: "line" | "contained", size?: "sm" | "md" }` is one tablist (32 or 40 tall). Each tab is its own target. The active tab gets an underline indicator (`line`) or an `$accent-tint` fill (`contained`, from the node's `fill`) and a heavier label. - **`tree-row`** `{ label, depth, expanded?, icon?, active? }` is a 32px row indented 16px per level. `expanded: true` / `false` draws an open / closed chevron; a leaf leaves it out and keeps the slot, so labels align. @@ -154,6 +154,19 @@ A modal's close button and actions (32 tall) and a toast's action (24 tall) are On a canvas whose root declares a `safeArea` or pins a `tab-bar` (a phone), a centred modal, a default toast and a drawer keep clear of them: the modal stays 16px past the insets and pinned chrome, the toast sits 16px above the tab bar or home indicator, and the drawer's padding grows past them, so the safe-area rules skip those three when that clearance covers the insets they judge by (on a phone root without a `safeArea` or pinned chrome they are still checked). A popover, a menu, a tooltip, and a modal or toast you place with `x` / `y` are checked like any positioned content. A `fullPage` capture grows the page, but the overlay layer stays the artboard: a scrim dims the first screen only. +### Element states (a property, not a variant) + +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. + +- **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 (Material 3's 8%, 10% and 10% without them): a filled primary lightens, a ghost or secondary button tints, a row tints over its active fill. 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 toggle it is the knob's (white). +- **Focus** also draws a 2px `$focus-ring` outline at a 2px gap, so the ring meets only the backdrop, never a brand fill; without a `$focus-ring` token it is `$accent`, then `$primary`, then `#2563EB`. A tab and a tab-bar item draw it inside their box, since the tablist and a floating bar clip. The live viewer's keyboard focus draws the same ring. +- **Disabled.** With the state tokens (`generate_design_system` writes them), a disabled target renders in `$text-primary`: its content at `disabledContent` (38%) and a drawn fill or border at `disabledContainer` (12%), so a disabled primary reads as a grey version of itself on light and dark. Without them it renders at today's 0.5 opacity in its own colours. An authored `opacity` wins over both. `disabled: true` means disabled whatever `state` says, and a `tabs` node's own `disabled` (or `state: "disabled"`) disables every tab. +- **Disabled is the same fact either way.** `state: "disabled"` leaves the tab order (`tabindex="-1"`, `aria-disabled`) and leaves the 24px census and the primary count exactly as `disabled: true` does. The mobile 44px census, which never exempted a disabled target, still measures it. +- **`active`, `checked` and `expanded` combine with `state`**: a hovered active nav-item keeps its tint, bar and weight under the layer. + ### Lists that lead with a mark are not tables (every type) A list whose every row starts with a mark (an icon, a dot, or a small image) is navigation, not data: a sidebar of projects with an identity dot, a name and a count. Table detection skips it, so `coverage` never asks for an empty or loading state for your navigation, and `canvas_stress` perturbs its labels as ordinary text. A table with a text header row still detects, even when every data row leads with an avatar. diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index ef3787a..2818fdc 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -353,6 +353,17 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **P8: acceptance in this slice.** Fast tier: HTML assertions for each P2 target at each state, with a twin that must not show it (rest, a non-P2 node with `state`, an unknown value, `disabled: true` beating `state: "hover"`), the P3 fallbacks and P4's disabled arithmetic, and P6 with a twin per reader. Full tier: a `button` of each variant at each of the five states renders deterministically (two renders, identical pixels) and distinctly (every pair of states differs) in both themes of a generated design system; P5's pixels-unchanged claim on a stamped desktop-app realisation and a mobile one, against the same scene rendered before slice G. - **P9: the inputs the render must cover** (hard rule 6, the verifier's list): every P2 node and item; each of the five states plus absent and unknown; `disabled: true` with each state; with and without `state` tokens, and with only one disabled token; an authored `opacity`; `active` / `checked` / `expanded` true and false; filled, transparent and unthemed (inside a component) fills; light and dark themes; `web`, `mobile` and `desktop-app` canvases; a modal and toast action, and a tab-bar and nav-bar item, each disabled. Census readers: fast and detailed `checkUsability`, `overlayTargets`, primary count. +**Slice G — as built (recorded 2026-11-17; read this before slice H).** S9 held; P4's disabled clause changed by S10. +- **Spec change S10 (Victor-approved, 2026-11-17): disabled renders in the on-surface colour.** P4 drew a disabled target in its own colours at the token opacities, so a filled primary's white label at 38% over a 12% blue nearly vanished on a light page. With the token pair, a disabled target now renders in `$text-primary` (Material's onSurface, the source of the 38% and 12%): its content colours (`color`, `secondaryColor`, `iconColor`, `badgeColor`, and `dotColor` when set) become it, a drawn fill or stroke takes it at the container share (solid on a toggle, checkbox or radio, which the one opacity dims), and the element renders at `opacity: disabledContent`. The checkbox mark and the toggle knob stay white. `StateStyle` gains `onSurface` (`$text-primary`, else `#111827`). Without the pair the render is P4's: 0.5 in the target's own colours. +- **Q1: P5 was proved by comparison, not by a permanent pixel test.** 337 scenes (every structure on every type, unthemed and under two personalities, in both themes; every P2 type enabled and disabled, themed, colours-only and unresolved) rendered on a0d550a and on the build, compared as HTML with `--fs-ring` values and random root ids normalised: 333 identical; three differ only by Q2's attributes; one is the intended token render of a disabled tab. A golden render would break on every later renderer change, so the permanent tests assert instead that a canvas with no `state` draws no layer, ring or state opacity. +- **Q2: a disabled `button` and the four controls leave the tab order** (`tabindex="-1"`, `aria-disabled`), as the slice B primitives already did (P6's renderer reader). HTML only; no pixel moves. +- **Q3: a tab-bar item draws its ring inset too**, as a tab does (S9): a floating tab bar clips its pill. +- **Q4: a disabled `tabs` node now dims its tabs.** Before slice G its node opacity was set but never drawn, so it rendered as enabled; each tab now renders disabled (0.5 without tokens). A pixel change only on canvases holding a disabled `tabs` node. +- **Q5: items in the 24px census.** A `tab-bar` item or `nav-bar` action with a disabled state is skipped by the web and desktop-app census (`primitiveTargets` reports it, `pointerTargets` reads it); the mobile 44px census ignores the flag, as P6 says. +- **Q6: layer percentages are rounded to two decimals** (`Math.round(x × 10000) / 100`), as is the container share (0.12 / 0.38 → 31.58%). Slice H's analytical model must round the same way to agree with the render. +- **Q7: the modal close button** carries the modal's resolved ring colour (it takes no state, P2). +- **Q8: tests.** `test-element-states.ts` (fast) and `test-element-states-render.ts` (full: four button variants × five states, two renders each, both themes, plus a frame twin); `test-discoverability.ts` checks each surface's element-states paragraph names every `STATEFUL_TYPES` entry and the state names. + **Slice H: state checks (FR-H1 to FR-H4)** - `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. diff --git a/src/design-language.ts b/src/design-language.ts index e8e700e..fb92f5e 100644 --- a/src/design-language.ts +++ b/src/design-language.ts @@ -15,6 +15,7 @@ import { generateColorSystem } from './color-system.js'; import { generateTypeScale, generateSpaceScale, type RatioName } from './scales.js'; import type { DesignVariables, ShadowSpec } from './types.js'; +import { STATE_LAYERS } from './primitives.js'; import { DEVICE_PROFILES, DEFAULT_DEVICE, deviceProfile, WINDOW_PROFILES, DEFAULT_WINDOW, windowProfile, type SurfaceType } from './surfaces.js'; export type PersonalityName = 'technical' | 'editorial' | 'soft' | 'data-dense'; @@ -165,10 +166,9 @@ export interface DesignSystemOptions { device?: string; } -/** Phase 31 FR-A8 — Material 3's current state-layer and disabled - * opacities (Flutter gen_defaults token files; an older M3 set used 0.12 for - * focus and pressed). */ -export const STATE_LAYERS = { hover: 0.08, focus: 0.10, pressed: 0.10, disabledContent: 0.38, disabledContainer: 0.12 } as const; +/** Phase 31 FR-A8 — Material 3's state-layer and disabled opacities; defined + * in primitives.ts (the renderer's fallback reads them without a cycle). */ +export { STATE_LAYERS }; /** Where a generated system's type pivot came from. */ export function typeBase(personalityName: PersonalityName, opts: DesignSystemOptions = {}): { size: number; source: 'explicit' | 'personality' | 'mobile' | 'desktop-app' } { diff --git a/src/desktop-app-rules.ts b/src/desktop-app-rules.ts index 1d42209..3a8691c 100644 --- a/src/desktop-app-rules.ts +++ b/src/desktop-app-rules.ts @@ -4,7 +4,7 @@ import type { EvaluationIssue } from './evaluate.js'; import type { LayoutRect } from './screenshot.js'; import type { SceneNode } from './types.js'; -import { CLICKABLE_PRIMITIVES, DESKTOP_APP_PRIMITIVES, OVERLAY_TYPES, MENU_MIN_WIDTH, modalActions, modalWidth, tabsItems } from './primitives.js'; +import { CLICKABLE_PRIMITIVES, DESKTOP_APP_PRIMITIVES, OVERLAY_TYPES, MENU_MIN_WIDTH, isDisabled, modalActions, modalWidth, tabsItems } from './primitives.js'; import { fontPx, paddingSides, proseWords } from './mobile-rules.js'; import { extractInventory } from './drift.js'; import { shapeHash } from './shape-hash.js'; @@ -593,10 +593,10 @@ export function checkPrimaryCount(ctx: DesktopContext): EvaluationIssue[] { const add = (pane: SceneNode, node: SceneNode, label: string) => byPane.set(pane, [...(byPane.get(pane) ?? []), { node, label }]); for (const n of parentOf.keys()) { if (n.type === 'modal') { - for (const a of modalActions(n)) if (a.variant === 'primary') add(n, n, String(a.label).trim()); + for (const a of modalActions(n)) if (a.variant === 'primary' && !isDisabled(a)) add(n, n, String(a.label).trim()); continue; } - if (!isPrimary(n) || n.disabled === true || repeated(n)) continue; + if (!isPrimary(n) || isDisabled(n) || repeated(n)) continue; add(paneOf(n, parentOf), n, String(n.label ?? n.ariaLabel ?? nameOf(n))); } for (const [pane, buttons] of byPane) { diff --git a/src/evaluate.ts b/src/evaluate.ts index 5038f99..b63d5e6 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -12,7 +12,7 @@ import { getIconSvg, parseIconRef } from './icons.js'; import { storedGenre } from './genre.js'; import { relaxedByPreset, relaxedByGenre, canonicalGenre, genreRulesets, activeRulesets, composeRulesets, resolveSurface, deviceProfile, DEVICE_PROFILES, DEFAULT_DEVICE, MOBILE_RULES, DESKTOP_APP_RULES, DEFAULT_WINDOW, WINDOW_PROFILES, windowProfile, type SurfaceType } from './surfaces.js'; import { checkArtboard, checkHandbuiltTargets, checkOneColumn, checkSafeAreaDetailed, checkSafeAreaFast, checkTabBars, checkTypeFloor, paddingSides, type MobileContext } from './mobile-rules.js'; -import { CHROME_EDGE, FAB_SIZE, NAV_ACTION, TAPPABLE_PRIMITIVES, CLICKABLE_PRIMITIVES, CONTROL_OWNERS, LIST_ROW_HEIGHT, MENU_ROW_HEIGHT, NAV_ITEM_HEIGHT, PROPERTY_ROW_HEIGHT, buttonBox, desktopTargets, overlayTargets, effectivePosition, listRowMinHeight, navActions, pinsBottom, tabItemBox, tabItems } from './primitives.js'; +import { CHROME_EDGE, FAB_SIZE, NAV_ACTION, TAPPABLE_PRIMITIVES, CLICKABLE_PRIMITIVES, CONTROL_OWNERS, LIST_ROW_HEIGHT, MENU_ROW_HEIGHT, NAV_ITEM_HEIGHT, PROPERTY_ROW_HEIGHT, buttonBox, desktopTargets, overlayTargets, effectivePosition, isDisabled, STATEFUL_TYPES, listRowMinHeight, navActions, pinsBottom, tabItemBox, tabItems } from './primitives.js'; // --- Types --- @@ -1985,7 +1985,7 @@ function mobileTarget( * doesn't fix is left undefined and not judged. */ function primitiveTargets( node: SceneNode, parentOf: Map, rootWidth: number, -): Array<{ what: string; w?: number; h: number; fix: string }> { +): Array<{ what: string; w?: number; h: number; fix: string; disabled?: boolean }> { if (node.type === 'button') { const b = buttonBox(node); return [{ what: 'button', ...b, fix: 'Use size "md" (44px) or "lg" (52px) — "sm" is for pointer surfaces — and drop any smaller height.' }]; @@ -1996,11 +1996,13 @@ function primitiveTargets( } if (node.type === 'tab-bar') { const box = tabItemBox(node, rootWidth); - const items = tabItems(node).map((it, i) => ({ what: `tab "${it?.label ?? i + 1}"`, ...box, fix: 'Widen the tab bar (drop its width) or move a destination out of it.' })); + // Slice G (P6) — an item's own disabled state; the 24px census skips it, + // the mobile touch census (which never exempted disabled targets) does not. + const items = tabItems(node).map((it, i) => ({ what: `tab "${it?.label ?? i + 1}"`, ...box, fix: 'Widen the tab bar (drop its width) or move a destination out of it.', disabled: isDisabled(it) })); return node.variant === 'fab' ? [...items, { what: 'tab-bar FAB', w: FAB_SIZE, h: FAB_SIZE, fix: '' }] : items; } if (node.type === 'nav-bar') { - return navActions(node).map((a) => ({ what: `nav-bar action "${a.label ?? a.icon ?? 'back'}"`, w: NAV_ACTION, h: NAV_ACTION, fix: '' })); + return navActions(node).map((a) => ({ what: `nav-bar action "${a.label ?? a.icon ?? 'back'}"`, w: NAV_ACTION, h: NAV_ACTION, fix: '', disabled: isDisabled(a) })); } return []; } @@ -2031,7 +2033,9 @@ export function pointerTargets(entries: NodeEntry[], rootWidth: number): Pointer }; const targets: PointerTarget[] = []; for (const { node } of entries) { - const disabled = node.disabled === true; + // Slice G (P2) — `state` counts only on the types that take it: a + // tab-bar or nav-bar node ignores its own state (its items carry theirs). + const disabled = node.disabled === true || (STATEFUL_TYPES.has(node.type) && isDisabled(node)); if (CONTROL_TYPES.has(node.type)) { const def = CONTROL_DEFAULT_SIZE[node.type]; let w = typeof node.width === 'number' ? node.width : def.w; @@ -2061,7 +2065,7 @@ export function pointerTargets(entries: NodeEntry[], rootWidth: number): Pointer targets.push({ node, what: node.type, w, h, disabled }); } else if (TAPPABLE_PRIMITIVES.has(node.type)) { for (const t of primitiveTargets(node, parentOf, rootWidth)) { - targets.push({ node, what: t.what, w: t.w ?? Infinity, h: t.h, disabled }); + targets.push({ node, what: t.what, w: t.w ?? Infinity, h: t.h, disabled: disabled || t.disabled === true }); } } else if (CLICKABLE_PRIMITIVES.has(node.type)) { // Phase 31 slice B — the desktop-app vocabulary, each by its own box diff --git a/src/index.ts b/src/index.ts index 6bd7be8..1c229b4 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. +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. 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,6 +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 design system has state tokens, 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 24px census, not a primary); 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.', @@ -563,7 +564,7 @@ Concatenate bindings: U(header+"/childId", {...}) Returns { ok, nodeIds, results }: nodeIds maps each bound variable to the node ID it created (e.g. { "header": "n_a1b2" }) — record it and use those IDs to target nodes in later calls (bindings only live within a single call). results lists each op's outcome in order. If the call wrote a fontFamily nothing can serve yet (not cached, not registered, not system/generic), an extra "Font warnings" content item names it — cache-only check, no network, so it can't catch everything set_fonts/network resolution would. Node types: frame, text, rectangle, ellipse, image, icon, path, component, instance, toggle, checkbox, radio, select, chart, skeleton, status-bar, home-indicator, nav-bar, tab-bar, button, list-row, sheet, link, text-input, nav-item, tabs, tree-row, menu-row, property-row, divider, tooltip, popover, menu, modal, toast, drawer -Properties: fill, gradient, stroke, strokeWidth, strokeStyle, borderTop, borderRight, borderBottom, borderLeft, cornerRadius, width, height, minWidth, minHeight, maxWidth, layout ("horizontal"|"vertical"|"grid"), gap (0 = flush, never flagged as off-scale), rowGap, gridColumns, gridColumn, gridRow, padding, alignItems, justifyContent, fontSize, fontFamily, fontWeight, color, content, textAlign, lineHeight, letterSpacing (px), textDecoration, textTransform ("uppercase" etc. — don't bake casing into content), textOverflow ("ellipsis" — designed single-line truncation for labels that must survive hostile-length content; canvas_stress reports clips behind it as info, not warnings), tabularNums (fixed-width digits so number columns align — table scaffolds and chart ticks carry it by default), fontVariationSettings (variable-font axes, e.g. '"wght" 650'), src, objectFit, opacity, shadow, shadows (plural wins — a \`shadow\` written where \`shadows\` is set is ignored, and the op result carries a warning saying so), blur, backdropBlur, backdropFilter, overflow, wrap, position ("absolute"|"relative"|"fixed"|"sticky"), x, y, bottom, right, icon, iconSize, iconColor, iconStyle, checked, disabled, value, pulse, d, viewBox, strokeLinecap, strokeLinejoin, strokeDasharray, animation, transition (object, or the string "$motion." referencing a motion token), kind, series, segments, innerRatio, centerValue, centerLabel, sparkKind, xDomain, yDomain, curve, gridlines, xLabels, yLabels, componentId, overrides, safeArea ({ top, bottom }, document root only — insets the renderer adds to the root's top/bottom padding; canvas_create type "mobile" writes the device's), responsive, and the mobile primitives' props: time, appearance, title, subtitle, leading, trailing, largeTitle, items, variant, fab, label, iconPosition, size, divider, detent, grabber, secondaryColor, badgeColor, and the desktop-app primitives' props: ariaLabel, external, links, count, dotColor, active, depth, collapsed, expanded, shortcut, destructive, submenu, labelWidth, placeholder, rows, error, orientation, inset, and the overlays' props: text, anchor, closeLabel, actions, tone, action, scrim +Properties: fill, gradient, stroke, strokeWidth, strokeStyle, borderTop, borderRight, borderBottom, borderLeft, cornerRadius, width, height, minWidth, minHeight, maxWidth, layout ("horizontal"|"vertical"|"grid"), gap (0 = flush, never flagged as off-scale), rowGap, gridColumns, gridColumn, gridRow, padding, alignItems, justifyContent, fontSize, fontFamily, fontWeight, color, content, textAlign, lineHeight, letterSpacing (px), textDecoration, textTransform ("uppercase" etc. — don't bake casing into content), textOverflow ("ellipsis" — designed single-line truncation for labels that must survive hostile-length content; canvas_stress reports clips behind it as info, not warnings), tabularNums (fixed-width digits so number columns align — table scaffolds and chart ticks carry it by default), fontVariationSettings (variable-font axes, e.g. '"wght" 650'), src, objectFit, opacity, shadow, shadows (plural wins — a \`shadow\` written where \`shadows\` is set is ignored, and the op result carries a warning saying so), blur, backdropBlur, backdropFilter, overflow, wrap, position ("absolute"|"relative"|"fixed"|"sticky"), x, y, bottom, right, icon, iconSize, iconColor, iconStyle, checked, disabled, state, value, pulse, d, viewBox, strokeLinecap, strokeLinejoin, strokeDasharray, animation, transition (object, or the string "$motion." referencing a motion token), kind, series, segments, innerRatio, centerValue, centerLabel, sparkKind, xDomain, yDomain, curve, gridlines, xLabels, yLabels, componentId, overrides, safeArea ({ top, bottom }, document root only — insets the renderer adds to the root's top/bottom padding; canvas_create type "mobile" writes the device's), responsive, and the mobile primitives' props: time, appearance, title, subtitle, leading, trailing, largeTitle, items, variant, fab, label, iconPosition, size, divider, detent, grabber, secondaryColor, badgeColor, and the desktop-app primitives' props: ariaLabel, external, links, count, dotColor, active, depth, collapsed, expanded, shortcut, destructive, submenu, labelWidth, placeholder, rows, error, orientation, inset, and the overlays' props: text, anchor, closeLabel, actions, tone, action, scrim Charts: { type: "chart", kind: "line"|"bar"|"donut"|"sparkline", series: [{ data: [210, 450, 648], stroke: "$accent", strokeDasharray?: "6 4", area?, points?, highlight?: [2] (a lone index 2 works too; null clears it; an entry that isn't an index into data renders no emphasis and the op result warns), barGradient? }], yDomain?: [0, 2700], curve?: "smooth", gridlines?: 4, xLabels?: ["Jan", ..., "Dec"] (spread evenly; one per bar on a bar chart centres each under its bar; tick labels keep their size at any chart width, so width: "100%" is safe; an x label wider than its slot (its bar, or halfway to the nearest labelled tick) truncates with an ellipsis, so on a narrow chart keep labels short and leave line-chart ticks empty ("") to give them room), yLabels? } — the node does ALL the value→coordinate math (multi-series in one node; x = data index, a shorter series stops early against a longer one; domains auto from data, bars floor at 0). Dash the projected/forecast series, solid the actuals; highlight: [i] renders those bars solid over muted siblings (the selected-day treatment) and barGradient fades the muted bars inside the SVG. DONUT: kind "donut" + segments: [{ value, color: "$chart-1", label? }] + innerRatio? + centerValue/centerLabel — data-bound slices from 12 o\'clock clockwise, center figure rendered tabular; compose the legend yourself from frames + $chart-* dots. SPARKLINE: kind "sparkline" (+ sparkKind "bar"|"line") — axis-free mini-trend for KPI cards, latest point emphasized by default (override with series.highlight). NEVER hand-compute path d-strings, absolutely-position tick labels, fake a donut with conic gradients, or hand-place sparkline bars. @@ -584,20 +585,20 @@ Positioning: position "fixed" pins to the screen (the root's width × height is Mobile primitives (phone screens — they carry their own sizes, hit areas, and colours from $accent / $border / $bg-surface / $text-primary / $text-secondary / $danger, neutral fallbacks unthemed; NEVER hand-build them from frames): - status-bar { time?: "9:41", appearance?: "dark"|"light" } and home-indicator { appearance? } — device chrome, pinned (fixed) top / bottom by default, sized from the root's safeArea (47 / 34 without one). No children. - - nav-bar { title, leading?: { icon?: "chevron-left", label? }, trailing?: [{ icon } | { label }] (max 2), largeTitle? } — 44 tall (96 with largeTitle), in flow; every action is a 44×44 target. - - tab-bar { items: [{ icon, label, active?, badge? }], variant?: "standard"|"floating"|"fab", fab?: { icon } } — pinned to the bottom by default, 49 + the bottom inset (16 more for "fab", whose raised 56px centre action is not a tab). 2–5 labeled tabs. - - button { label?, icon?, iconPosition?: "leading"|"trailing", variant?: "primary"|"secondary"|"ghost"|"destructive", size?: "xs"|"sm"|"md"|"lg" (24/32/44/52), ariaLabel?, disabled? } — an icon-only button (no label) takes ariaLabel as its accessible name (aria-label + title, never drawn); xs is the 24px icon button of a dense toolbar and an ERROR on a phone, like sm — md (the default) meets the 44px phone floor; sm is for pointer surfaces and is an ERROR on a mobile canvas. Icon-only is square; width: "100%" for a full-width CTA. - - list-row { title, subtitle?, leading?: { icon } | { initials } | { image }, trailing?: { text } | { chevron: true } | { toggle: boolean } | { badge }, divider? } — 44 tall (56 with a subtitle), spans its list; repeated rows count as reuse. + - nav-bar { title, leading?: { icon?: "chevron-left", label?, state? }, trailing?: [{ icon } | { label }, each with state?] (max 2), largeTitle? } — 44 tall (96 with largeTitle), in flow; every action is a 44×44 target. + - tab-bar { items: [{ icon, label, active?, badge?, state? }], variant?: "standard"|"floating"|"fab", fab?: { icon } } — pinned to the bottom by default, 49 + the bottom inset (16 more for "fab", whose raised 56px centre action is not a tab). 2–5 labeled tabs. + - button { label?, icon?, iconPosition?: "leading"|"trailing", variant?: "primary"|"secondary"|"ghost"|"destructive", size?: "xs"|"sm"|"md"|"lg" (24/32/44/52), ariaLabel?, disabled?, state? } — an icon-only button (no label) takes ariaLabel as its accessible name (aria-label + title, never drawn); xs is the 24px icon button of a dense toolbar and an ERROR on a phone, like sm — md (the default) meets the 44px phone floor; sm is for pointer surfaces and is an ERROR on a mobile canvas. Icon-only is square; width: "100%" for a full-width CTA. + - list-row { title, subtitle?, leading?: { icon } | { initials } | { image }, trailing?: { text } | { chevron: true } | { toggle: boolean } | { badge }, divider?, state? } — 44 tall (56 with a subtitle), spans its list; repeated rows count as reuse. - sheet { detent?: "medium"|"large"|"auto", grabber?: true, padding, gap, children } — a bottom sheet over a scrim, pinned, padded past the home indicator; its children scroll inside it. The renderer reserves room for pinned chrome: the root's top/bottom padding is raised to at least the pinned status-bar / tab-bar / home-indicator height, so content never starts or ends under it. Labels truncate to one line with an ellipsis (canvas_stress reports that as designed truncation). Desktop-app primitives (application screens — canvas_create type "desktop-app"; on the 24/32/40/48 density ladder, colours from $accent / $accent-tint / $border / $border-strong / $text-primary / $text-secondary / $danger, neutral fallbacks unthemed; NEVER hand-build them from frames — a hand-built frame is not a measured target): - - link { label, icon?, iconPosition?, external?, ariaLabel? } — a standalone text action, at least 24 tall, measured as a pointer target. With no label it hugs its glyphs (14px wide, 30 with external) and takes ariaLabel as its name (aria-label + title). A text node can hold INLINE links instead: links: [{ start, end }] character ranges of its content, drawn underlined (inline links are exempt from the 24px floor, as WCAG exempts them). - - text-input { value?, placeholder?, icon?, size?: "sm"|"md" (32/40), rows? (a multi-line field), error? (a message), disabled? } — its border ($border-strong when the design system has it) is its only boundary; error draws an icon and the message below and colours the border $danger. - - nav-item { label, icon?, count?, dotColor? (an identity dot — never counted as an accent), active?, depth?: 0|1, collapsed? } — 32 tall, spans its sidebar; active draws an $accent-tint fill, a 2px $accent bar and a heavier label (aria-current); collapsed is the 32×32 rail form, its label the accessible name. - - tabs { items: [{ label, count?, active?, disabled? }], variant?: "line"|"contained", size?: "sm"|"md" (32/40) } — one tablist; each tab is its own pointer target; the active tab gets an indicator (line) or an $accent-tint fill (contained) and a heavier label. - - tree-row { label, depth, expanded? (absent for a leaf), icon?, active? } — 32 tall, indents 16 per level, a chevron when expanded is set. - - menu-row { label, icon?, shortcut?, checked?, destructive?, disabled?, submenu? } — 32 tall; the shortcut right-aligns in a muted kbd style, destructive uses $danger, submenu adds a chevron. + - link { label, icon?, iconPosition?, external?, ariaLabel?, state? } — a standalone text action, at least 24 tall, measured as a pointer target. With no label it hugs its glyphs (14px wide, 30 with external) and takes ariaLabel as its name (aria-label + title). A text node can hold INLINE links instead: links: [{ start, end }] character ranges of its content, drawn underlined (inline links are exempt from the 24px floor, as WCAG exempts them). + - text-input { value?, placeholder?, icon?, size?: "sm"|"md" (32/40), rows? (a multi-line field), error? (a message), disabled?, state? } — its border ($border-strong when the design system has it) is its only boundary; error draws an icon and the message below and colours the border $danger. + - nav-item { label, icon?, count?, dotColor? (an identity dot — never counted as an accent), active?, depth?: 0|1, collapsed?, state? } — 32 tall, spans its sidebar; active draws an $accent-tint fill, a 2px $accent bar and a heavier label (aria-current); collapsed is the 32×32 rail form, its label the accessible name. + - tabs { items: [{ label, count?, active?, disabled?, state? }], variant?: "line"|"contained", size?: "sm"|"md" (32/40) } — one tablist; each tab is its own pointer target; the active tab gets an indicator (line) or an $accent-tint fill (contained) and a heavier label. + - tree-row { label, depth, expanded? (absent for a leaf), icon?, active?, state? } — 32 tall, indents 16 per level, a chevron when expanded is set. + - menu-row { label, icon?, shortcut?, checked?, destructive?, disabled?, submenu?, state? } — 32 tall; the shortcut right-aligns in a muted kbd style, destructive uses $danger, submenu adds a chevron. - property-row { label, labelWidth? (96), children: [one value] } — an inspector row: muted label column, then its single child (a control, a text-input, a button, a text); a control that is its only target (nothing clickable beside it) is measured by the row's box. Its label names a control directly inside it; with a blank label only text inside the row itself does (a sibling row's text does not count). - divider { orientation?: "horizontal"|"vertical", inset? } — a 1px $border hairline; vertical ones separate panes. Not a target. Of these, only property-row renders children; link, text-input, nav-item, tabs, tree-row, menu-row and divider draw their own anatomy and drop any children you give them (of the overlays below, popover, menu, modal and drawer render children; tooltip and toast do not). @@ -607,11 +608,13 @@ Overlays (screen states — put one in a state variant made with canvas_add_vari - tooltip { text, x, y } — inverted ($text-primary fill), wraps at 240px; text only, never children. - popover { x, y, size?: "xs"|"sm"|"md"|"lg" (192/320/480/640, default 320) or width, children } — a panel (vertical, padding 12 by default; layout / gap / padding apply as on a frame): a comment box, a filter form. - menu { x, y, children: menu-row and divider nodes } — padding 4, at least 192 wide, hugs its rows. - - modal { title, size?: "sm"|"md"|"lg" (480/640/960, default md), actions?: [{ label, variant? }], closeLabel?, children } — centred over its own full scrim (x / y place its top-left instead); a header with the title and a close button named "Close" (closeLabel renames it); the body holds the children (vertical, gap 12) and scrolls when tall; actions render right-aligned as 32px buttons, an action with no variant as "secondary", the filled ones ("primary", "destructive") rightmost. A modal is a region of its own for the primary-count and wayfinding rules. - - toast { text, tone?: "neutral"|"success"|"warning"|"danger", action?: { label } } — bottom-centre, 24px above the artboard's bottom edge (x / y place it); the tone colours a leading glyph, the text stays $text-primary. + - modal { title, size?: "sm"|"md"|"lg" (480/640/960, default md), actions?: [{ label, variant?, state? }], closeLabel?, children } — centred over its own full scrim (x / y place its top-left instead); a header with the title and a close button named "Close" (closeLabel renames it); the body holds the children (vertical, gap 12) and scrolls when tall; actions render right-aligned as 32px buttons, an action with no variant as "secondary", the filled ones ("primary", "destructive") rightmost. A modal is a region of its own for the primary-count and wayfinding rules. + - toast { text, tone?: "neutral"|"success"|"warning"|"danger", action?: { label, state? } } — bottom-centre, 24px above the artboard's bottom edge (x / y place it); the tone colours a leading glyph, the text stays $text-primary. - drawer { size?: "sm"|"md" (320/480) or width, scrim?: false, children } — pinned to the right edge, full height, padding 16; scrim: true dims what is behind it. A modal's close button and actions and a toast's action are pointer targets (32 / 32 / 24 tall), sized for a pointer: on a phone use a sheet for a dialog. On a root with a safeArea or a pinned tab-bar, a centred modal, a default toast and a drawer keep clear of the insets and the tab bar. snapshot_layout lists every overlay under the root, and a modal (or a drawer with a scrim) carries its scrim's rect. +Element states (state?: "rest"|"hover"|"focus"|"pressed"|"disabled", default rest): on button, link, text-input, nav-item, tree-row, menu-row, list-row, toggle, checkbox, radio, select, and on the items of tabs, tab-bar, nav-bar (leading / trailing), modal (actions[]) and toast (action). Hover, focus and pressed layer the target's label colour over its fill (the state tokens' hover / focus / pressed, Material's 8 / 10 / 10% without them); focus adds a 2px $focus-ring outline at a 2px gap (inside the tab for a tab or tab-bar item); a link also underlines in hover and pressed; active, checked and expanded keep their fill under the layer. disabled (or disabled: true, which wins over any state) renders the whole target in $text-primary at the state tokens' disabledContent (38%), a drawn fill or border at disabledContainer (12%), when the design system has them, else at today's 0.5 opacity; an authored opacity wins. A tabs node's own state "disabled" disables every tab. Other node types ignore state. + Responsive layout (author desktop-first, adapt down): - responsive: "stack" — on a horizontal container, flips to vertical below 768px (multi-column layouts that should stack on mobile) - responsive: "wrap" — children wrap to the next line instead of overflowing (card grids, tag rows) diff --git a/src/primitives.ts b/src/primitives.ts index de53fc9..d9296ce 100644 --- a/src/primitives.ts +++ b/src/primitives.ts @@ -2,7 +2,7 @@ // renderer (which draws them) and the rules (which judge what it draws), so the // two can never disagree about a button's height or where a tab bar pins. -import type { SceneNode, TabItem, TabsItem } from './types.js'; +import type { ElementState, SceneNode, TabItem, TabsItem } from './types.js'; import { DEFAULT_DEVICE, DEVICE_PROFILES, usableSafeArea } from './surfaces.js'; export const BUTTON_HEIGHT = { xs: 24, sm: 32, md: 44, lg: 52 } as const; @@ -44,6 +44,34 @@ export const TEXT_INPUT_LINE = 20; * `divider` are not targets (a property-row's value is). */ export const CLICKABLE_PRIMITIVES = new Set([...TAPPABLE_PRIMITIVES, 'link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row']); +// Phase 31 slice G (FR-G1) — element states. +/** Phase 31 FR-A8 — Material 3's current state-layer and disabled + * opacities (Flutter gen_defaults token files; an older M3 set used 0.12 for + * focus and pressed). */ +export const STATE_LAYERS = { hover: 0.08, focus: 0.10, pressed: 0.10, disabledContent: 0.38, disabledContainer: 0.12 } as const; + +export const ELEMENT_STATES: readonly ElementState[] = ['rest', 'hover', 'focus', 'pressed', 'disabled']; + +/** The nodes that take `state` themselves (spec P2). Items of tabs, tab-bar, + * nav-bar, modal and toast take it on the item instead. */ +export const STATEFUL_TYPES = new Set([ + 'button', 'link', 'text-input', 'nav-item', 'tree-row', 'menu-row', 'list-row', + 'toggle', 'checkbox', 'radio', 'select', +]); + +/** The effective state of a node or an item: `disabled: true` wins, then a + * known `state`, else rest (an unknown value is ignored). */ +export function elementState(n: { state?: unknown; disabled?: unknown } | null | undefined): ElementState { + if (!n) return 'rest'; + if (n.disabled === true) return 'disabled'; + return typeof n.state === 'string' && (ELEMENT_STATES as readonly string[]).includes(n.state) ? n.state as ElementState : 'rest'; +} + +/** Disabled by `disabled: true` or `state: "disabled"`. */ +export function isDisabled(n: { state?: unknown; disabled?: unknown } | null | undefined): boolean { + return elementState(n) === 'disabled'; +} + /** Rows whose only target, a control directly inside them, is measured by * the row's box (no link, input or button beside it). */ export const CONTROL_OWNERS = new Set(['property-row', 'nav-item', 'menu-row', 'list-row']); @@ -95,11 +123,11 @@ export function overlayTargets(n: SceneNode): Array<{ what: string; w?: number; if (n.type === 'modal') { return [ { what: 'modal close button', w: MODAL_CONTROL, h: MODAL_CONTROL, disabled: false }, - ...modalActions(n).map((a) => ({ what: `modal action "${String(a.label).trim()}"`, h: MODAL_CONTROL, disabled: false })), + ...modalActions(n).map((a) => ({ what: `modal action "${String(a.label).trim()}"`, h: MODAL_CONTROL, disabled: isDisabled(a) })), ]; } if (n.type === 'toast' && n.action && typeof n.action === 'object' && hasText(n.action.label)) { - return [{ what: `toast action "${String(n.action.label).trim()}"`, h: TOAST_ACTION, disabled: false }]; + return [{ what: `toast action "${String(n.action.label).trim()}"`, h: TOAST_ACTION, disabled: isDisabled(n.action) }]; } return []; } @@ -202,7 +230,7 @@ export function desktopTargets(n: SceneNode): Array<{ what: string; w?: number; // The rendered height: these rows take an explicit `height` and ignore // `minHeight`, so the census does too (it must judge what renders). const h = (fallback: number) => (isNum(n.height) ? n.height : fallback); - const disabled = n.disabled === true; + const disabled = isDisabled(n); switch (n.type) { // A link never renders shorter than 24 (min-height), whatever its height. // A px width is its width; without a label and with no width (or "auto") @@ -218,7 +246,7 @@ export function desktopTargets(n: SceneNode): Array<{ what: string; w?: number; // The tablist's height comes from its size alone (the renderer ignores // `height`); a disabled tabs node disables every tab. const th = TABS_HEIGHT[n.size === 'sm' ? 'sm' : 'md']; - return tabsItems(n).map((it, i) => ({ what: `tab "${typeof it.label === 'string' ? it.label : i + 1}"`, h: th, disabled: disabled || it.disabled === true })); + return tabsItems(n).map((it, i) => ({ what: `tab "${typeof it.label === 'string' ? it.label : i + 1}"`, h: th, disabled: disabled || isDisabled(it) })); } default: return []; } @@ -236,7 +264,7 @@ export function tabItemBox(n: SceneNode, rootWidth: number): { w: number; h: num } /** The nav-bar actions that render: the back action and up to two trailing. */ -export function navActions(n: SceneNode): { icon?: string; label?: string }[] { +export function navActions(n: SceneNode): { icon?: string; label?: string; state?: ElementState; disabled?: boolean }[] { const trailing = Array.isArray(n.trailing) ? n.trailing.filter((a) => !!a && typeof a === 'object').slice(0, 2) : []; return [...(n.leading && typeof n.leading === 'object' ? [n.leading] : []), ...trailing]; } diff --git a/src/renderer.ts b/src/renderer.ts index 5d4e62f..b4a8a9c 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -1,4 +1,4 @@ -import type { Canvas, FontFace, SceneNode } from './types.js'; +import type { Canvas, ElementState, FontFace, SceneNode, StateStyle } from './types.js'; import { getIconSvg } from './icons.js'; import { aliasFamilyStack } from './fonts.js'; import { usableSafeArea } from './surfaces.js'; @@ -8,6 +8,7 @@ import { LINK_MIN_HEIGHT, LINK_ICON, LINK_EXTERNAL, NAV_ITEM_HEIGHT, TABS_HEIGHT, TREE_ROW_HEIGHT, TREE_INDENT, MENU_ROW_HEIGHT, PROPERTY_ROW_HEIGHT, PROPERTY_LABEL_WIDTH, tabsItems, textInputHeight, textInputRows, OVERLAY_TYPES, OVERLAY_Z, TOOLTIP_MAX_WIDTH, MENU_MIN_WIDTH, drawerWidth, modalActions, modalWidth, popoverWidth, + STATE_LAYERS, elementState, isDisabled, } from './primitives.js'; /** Build a `background: …` declaration from a node's `gradient`. @@ -660,7 +661,7 @@ function renderNode(node: SceneNode, rc: RenderCtx): string { // are pixel-identical: nothing is focused in a capture). The ring color // rides a CSS var on the control's own style, keeping one style attribute. if (node.type === 'toggle' || node.type === 'checkbox' || node.type === 'radio' || node.type === 'select') { - const focusAttr = `${dataAttr} tabindex="0" data-focusable`; + const focusAttr = isDisabled(node) ? `${dataAttr} tabindex="-1" aria-disabled="true"` : `${dataAttr} tabindex="0" data-focusable`; if (node.type === 'toggle') return renderToggle(node, focusAttr); if (node.type === 'checkbox') return renderCheckbox(node, focusAttr); if (node.type === 'radio') return renderRadio(node, focusAttr); @@ -891,11 +892,10 @@ function buildStyles(node: SceneNode, rc: RenderCtx): string { // apply. Shared bits: numeric width/height with control-appropriate defaults, // opacity passthrough (resolveVariables sets 0.5 for disabled). -/** Focus-ring color for a control: its strongest own color, accent-flavored - * when checked. Consumed by the [data-focusable]:focus-visible rule. */ -function focusRing(node: SceneNode): string { - const ring = (node.checked ? node.fill : undefined) ?? node.stroke ?? node.fill ?? '#2563EB'; - return `--fs-ring: ${ring}`; +/** A control's state (slice G): its own content, so one opacity; `ink` is + * what the control draws on its fill (the mark, the knob, the boundary). */ +function controlState(node: SceneNode, ink: string | undefined, whole = true): StateParts { + return stateParts(elementState(node), node.stateStyle, ink, { whole, authored: node.opacity }); } function controlSize(node: SceneNode, defW: number, defH: number): { w: number; h: number } { @@ -932,17 +932,19 @@ function renderSkeleton(node: SceneNode, dataAttr: string): string { } function renderToggle(node: SceneNode, dataAttr: string): string { + node = neutralised(node, true); const { w, h } = controlSize(node, 44, 24); const inset = Math.max(Math.round(h * 0.125), 2); const knob = h - inset * 2; const left = node.checked ? w - knob - inset : inset; + const st = controlState(node, '#FFFFFF'); const track = [ - focusRing(node), + ringVar(node.stateStyle), 'position: relative', 'flex-shrink: 0', `width: ${w}px`, `height: ${h}px`, `border-radius: ${h / 2}px`, `background-color: ${node.fill}`, 'transition: background-color 0.15s ease', - ...controlOpacity(node), + ...controlOpacity(node), ...st.css, ].join('; '); const knobStyle = [ 'position: absolute', `top: ${inset}px`, `left: ${left}px`, @@ -953,27 +955,31 @@ function renderToggle(node: SceneNode, dataAttr: string): string { } function renderCheckbox(node: SceneNode, dataAttr: string): string { + node = neutralised(node, true); const { w, h } = controlSize(node, 18, 18); const radius = node.cornerRadius !== undefined && typeof node.cornerRadius === 'number' ? node.cornerRadius : 4; + const st = controlState(node, node.checked ? '#FFFFFF' : node.stroke); const box = [ - focusRing(node), + ringVar(node.stateStyle), 'flex-shrink: 0', 'display: flex', 'align-items: center', 'justify-content: center', `width: ${w}px`, `height: ${h}px`, `border-radius: ${radius}px`, `border: 1.5px solid ${node.stroke}`, `background-color: ${node.fill}`, - ...controlOpacity(node), + ...controlOpacity(node), ...st.css, ].join('; '); const mark = node.checked ? (getIconSvg('check', Math.round(Math.min(w, h) * 0.78), '#FFFFFF') ?? '') : ''; return `${mark}`; } function renderRadio(node: SceneNode, dataAttr: string): string { + node = neutralised(node, true); const { w, h } = controlSize(node, 18, 18); + const st = controlState(node, node.stroke); const ring = [ - focusRing(node), + ringVar(node.stateStyle), 'flex-shrink: 0', 'display: flex', 'align-items: center', 'justify-content: center', `width: ${w}px`, `height: ${h}px`, 'border-radius: 50%', `border: 1.5px solid ${node.stroke}`, 'background-color: transparent', - ...controlOpacity(node), + ...controlOpacity(node), ...st.css, ].join('; '); const dotSize = Math.max(Math.round(Math.min(w, h) * 0.45), 4); const dot = node.checked @@ -983,19 +989,22 @@ function renderRadio(node: SceneNode, dataAttr: string): string { } function renderSelect(node: SceneNode, dataAttr: string): string { + node = neutralised(node); const width = node.width !== undefined ? cssLength(node.width) : 'fit-content'; const radius = node.cornerRadius !== undefined && typeof node.cornerRadius === 'number' ? node.cornerRadius : 8; const fontSize = typeof node.fontSize === 'number' ? node.fontSize : 14; const isPlaceholder = !node.value; const textColor = isPlaceholder ? '#9CA3AF' : node.color; + // A select's frame is a container: the disabled pair splits it from its text. + const st = controlState(node, node.color, false); const frame = [ - focusRing(node), + ringVar(node.stateStyle), 'display: flex', 'flex-direction: row', 'align-items: center', 'justify-content: space-between', 'gap: 8px', 'padding: 8px 12px', `width: ${width}`, ...(typeof node.height === 'number' ? [`height: ${node.height}px`] : []), `border-radius: ${radius}px`, `border: 1px solid ${node.stroke}`, `background-color: ${node.fill}`, - ...controlOpacity(node), + ...controlOpacity(node), ...st.css, ].join('; '); const label = `${escapeHtml(node.value ?? 'Select…')}`; const chevron = getIconSvg('chevron-down', Math.round(fontSize * 1.15), textColor) ?? ''; @@ -1013,6 +1022,106 @@ function renderSelect(node: SceneNode, dataAttr: string): string { const FALLBACK = { accent: '#2563EB', text: '#111827', secondary: '#6B7280', border: '#D1D5DB', surface: '#FFFFFF', danger: '#DC2626' } as const; +// ── Phase 31 slice G — element states (FR-G1, spec P3/P4) ───────────────── +// One target's state drawn on the element that carries its box: hover, focus +// and pressed layer the ink over the fill at the state's opacity (focus adds +// the ring, 2px at a 2px gap so it meets only the backdrop, spec change S9); +// disabled draws the token pair when the design system has it, else today's +// 0.5. Resolution (applyControlDefaults) hands over `stateStyle`; a node it +// skipped (inside a component) uses the fallback. + +const STATE_FALLBACK: StateStyle = { ring: FALLBACK.accent, onSurface: FALLBACK.text, hover: STATE_LAYERS.hover, focus: STATE_LAYERS.focus, pressed: STATE_LAYERS.pressed }; + +/** A 0–1 opacity as a CSS percentage, two decimals at most. */ +const pct = (x: number): number => Math.round(x * 10000) / 100; + +/** A colour at `p` percent over transparent. */ +const atPercent = (color: string, p: number): string => `color-mix(in srgb, ${color} ${p}%, transparent)`; + +/** The disabled token pair, when the design system sets it (spec P3). */ +function disabledPair(style: StateStyle | undefined): { content: number; container: number; on: string } | undefined { + if (style?.disabledContent === undefined || style.disabledContainer === undefined) return undefined; + return { content: style.disabledContent, container: style.disabledContainer, on: style.onSurface }; +} + +/** The share of the on-surface colour a drawn container takes, so that under + * the element's `opacity: content` it shows at `container`. */ +const containerShare = (p: { content: number; container: number }): number => + (p.content === 0 ? 100 : Math.min(100, pct(p.container / p.content))); + +interface StateParts { + /** Declarations for the target's box: the layer, the ring, the opacity. */ + css: string[]; + /** Maps a container colour (background, border): spec change S10 draws a + * disabled one in the on-surface colour at the container share. */ + container: (color: string | undefined) => string | undefined; + /** Maps a content colour (label, icon): on-surface when disabled (S10). */ + content: (color: string | undefined) => string | undefined; +} + +const identity = (c: string | undefined) => c; + +/** + * What a target in `state` adds to its box. `ink` is its content colour; + * `whole` marks a control that is its own content (toggle, checkbox, radio: + * its container is drawn solid and the one opacity dims it); `item` marks a + * target with no `opacity` of its own (an item, or a button built for a + * modal or toast action), which takes the 0.5 fallback inline; `authored` is + * the node's own opacity, which wins over the disabled pair; `inset` draws + * the ring inside (a clipped tab). A node renderer applies the colour + * mappers through `neutralised`; an item renderer calls them itself. + */ +function stateParts( + state: ElementState, style: StateStyle | undefined, ink: string | undefined, + opts: { whole?: boolean; item?: boolean; authored?: number; inset?: boolean } = {}, +): StateParts { + const st = style ?? STATE_FALLBACK; + const none = { container: identity, content: identity }; + if (state === 'rest') return { css: [], ...none }; + if (state === 'disabled') { + const pair = disabledPair(style); + // No tokens: today's render (a node's opacity is set by resolution). + if (!pair) return { css: opts.item ? ['opacity: 0.5'] : [], ...none }; + if (opts.authored !== undefined) return { css: [], ...none }; + const share = containerShare(pair); + return { + css: [`opacity: ${pair.content}`], + container: (c) => (c && c !== 'transparent' ? (opts.whole ? pair.on : atPercent(pair.on, share)) : c), + content: (c) => (c === undefined ? c : pair.on), + }; + } + const css: string[] = []; + if (ink) { + const layer = atPercent(ink, pct(st[state])); + css.push(`background-image: linear-gradient(${layer}, ${layer})`); + } + if (state === 'focus') css.push(`outline: 2px solid ${st.ring}`, `outline-offset: ${opts.inset ? -2 : 2}px`); + return { css, ...none }; +} + +/** Spec change S10 — a disabled node with the token pair (and no authored + * opacity) renders in the on-surface colour: its content colours become it, + * a drawn fill or stroke takes it at the container share (solid for a + * `whole` control). Any other node is returned as is. */ +function neutralised(node: SceneNode, whole = false): SceneNode { + if (elementState(node) !== 'disabled' || node.opacity !== undefined) return node; + const pair = disabledPair(node.stateStyle); + if (!pair) return node; + const { container, content } = stateParts('disabled', node.stateStyle, undefined, { whole }); + return { + ...node, + color: pair.on, secondaryColor: pair.on, iconColor: pair.on, badgeColor: pair.on, + ...(node.dotColor !== undefined ? { dotColor: content(node.dotColor) } : {}), + fill: container(node.fill), stroke: container(node.stroke), + }; +} + +/** The live :focus-visible ring colour, the same as the static one (P4). */ +const ringVar = (style: StateStyle | undefined): string => `--fs-ring: ${(style ?? STATE_FALLBACK).ring}`; + +/** A link's label underlines in hover and pressed (FR-B2). */ +const underlined = (state: ElementState): boolean => state === 'hover' || state === 'pressed'; + function renderPrimitive(node: SceneNode, rc: RenderCtx): string | undefined { const dataAttr = ` data-node-id="${node.id}" data-fs-primitive`; switch (node.type) { @@ -1098,19 +1207,22 @@ function renderHomeIndicator(node: SceneNode, rc: RenderCtx, dataAttr: string): return `
`; } -function navAction(action: { icon?: unknown; label?: unknown }, color: string, back: boolean): string { +function navAction(action: { icon?: unknown; label?: unknown; state?: unknown; disabled?: unknown }, own: string, back: boolean, style?: StateStyle): string { + const st = stateParts(elementState(action), style, own, { item: true }); + const color = st.content(own) ?? own; const glyph = iconHtml(action.icon ?? (back ? 'chevron-left' : undefined), 24, color); const words = text(action.label) ? labelHtml(text(action.label), 'font-size: 17px') : ''; return `
${glyph}${words}
`; } function renderNavBar(node: SceneNode, rc: RenderCtx, dataAttr: string): string { const action = node.iconColor ?? FALLBACK.accent; const leading = node.leading && typeof node.leading === 'object' ? node.leading : undefined; - const trailing = entries<{ icon?: unknown; label?: unknown }>(node.trailing).slice(0, 2); + const trailing = entries<{ icon?: unknown; label?: unknown; state?: unknown; disabled?: unknown }>(node.trailing).slice(0, 2); const title = text(node.title); const box = css([ ...positionStyles(node, rc), 'flex-shrink: 0', node.width !== undefined ? `width: ${cssLength(node.width)}` : 'width: 100%', @@ -1125,23 +1237,26 @@ function renderNavBar(node: SceneNode, rc: RenderCtx, dataAttr: string): string ? `
${labelHtml(title, 'font-size: 17px; font-weight: 600')}
` : ''; const row = `
` - + side('flex-start', leading ? navAction(leading, action, true) : '') + + side('flex-start', leading ? navAction(leading, action, true, node.stateStyle) : '') + centred - + side('flex-end', trailing.map((a) => navAction(a, action, false)).join('')) + '
'; + + side('flex-end', trailing.map((a) => navAction(a, action, false, node.stateStyle)).join('')) + ''; const large = node.largeTitle ? `
${labelHtml(title, 'font-size: 34px; font-weight: 700; letter-spacing: -0.4px')}
` : ''; return `${row}${large}`; } -function tabItem(item: { icon?: unknown; label?: unknown; active?: unknown; badge?: unknown }, node: SceneNode): string { - const color = item.active ? node.iconColor ?? FALLBACK.accent : node.color ?? FALLBACK.secondary; +function tabItem(item: { icon?: unknown; label?: unknown; active?: unknown; badge?: unknown; state?: unknown; disabled?: unknown }, node: SceneNode): string { + const own = item.active ? node.iconColor ?? FALLBACK.accent : node.color ?? FALLBACK.secondary; + // A floating bar clips its pill, so an item's ring is drawn inside (as a tab's). + const st = stateParts(elementState(item), node.stateStyle, own, { item: true, inset: true }); + const color = st.content(own) ?? own; const count = badgeText(item.badge); const badge = count - ? `${escapeHtml(count)}` + ? `${escapeHtml(count)}` : ''; const words = text(item.label); - return `
` + return `
` + `${iconHtml(item.icon, 24, color)}${badge}` + `${words ? labelHtml(words, 'font-size: 11px; font-weight: 500; line-height: 13px') : ''}
`; } @@ -1176,8 +1291,12 @@ function renderTabBar(node: SceneNode, rc: RenderCtx, dataAttr: string): string return `${row}
`; } -function renderButton(node: SceneNode, rc: RenderCtx, attrs: string): string { +/** `item`: a button built for a modal or toast action, which has no + * resolved opacity of its own (slice G's 0.5 fallback goes inline). */ +function renderButton(node: SceneNode, rc: RenderCtx, attrs: string, item = false): string { + node = neutralised(node); const size = node.size === 'xs' || node.size === 'sm' || node.size === 'lg' ? node.size : 'md'; + attrs = disabledAttrs(node, attrs); // Phase 31 FR-B1 — an accessible name (never rendered as text). const name = text(node.ariaLabel); if (name) attrs += ` aria-label="${escapeAttr(name)}" title="${escapeAttr(name)}"`; @@ -1189,8 +1308,9 @@ function renderButton(node: SceneNode, rc: RenderCtx, attrs: string): string { const color = node.color ?? (fill === 'transparent' ? FALLBACK.accent : '#FFFFFF'); const glyph = iconHtml(node.icon, size === 'xs' ? 14 : size === 'sm' ? 16 : 20, color); const radius = typeof node.cornerRadius === 'number' ? node.cornerRadius : size === 'xs' ? 6 : 8; + const st = stateParts(elementState(node), node.stateStyle, color, { item, authored: node.opacity }); const box = css([ - `--fs-ring: ${fill !== 'transparent' ? fill : color}`, + ringVar(node.stateStyle), ...positionStyles(node, rc), 'display: inline-flex', 'flex-shrink: 0', 'align-items: center', 'justify-content: center', 'gap: 8px', `height: ${h}px`, `min-height: ${h}px`, `min-width: ${h}px`, words ? (node.width !== undefined ? `width: ${cssLength(node.width)}` : 'width: fit-content') : `width: ${h}px`, @@ -1202,6 +1322,7 @@ function renderButton(node: SceneNode, rc: RenderCtx, attrs: string): string { node.stroke ? `border: 1px solid ${node.stroke}` : undefined, `color: ${color}`, `font-size: ${BUTTON_FONT[size]}px`, 'font-weight: 600', 'white-space: nowrap', node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ...st.css, ]); const parts = node.iconPosition === 'trailing' ? `${words}${glyph}` : `${glyph}${words}`; return `${parts}`; @@ -1240,7 +1361,9 @@ function listRowLeading(node: SceneNode): string { } function renderListRow(node: SceneNode, rc: RenderCtx, dataAttr: string): string { + node = neutralised(node); const position = effectivePosition(node); + const st = stateParts(elementState(node), node.stateStyle, node.color ?? FALLBACK.text, { authored: node.opacity }); const box = css([ ...positionStyles(node, rc), position ? undefined : 'position: relative', 'display: flex', 'flex-direction: row', 'align-items: center', 'gap: 12px', 'flex-shrink: 0', @@ -1248,6 +1371,7 @@ function renderListRow(node: SceneNode, rc: RenderCtx, dataAttr: string): string 'padding: 6px 16px', node.width !== undefined ? `width: ${cssLength(node.width)}` : 'align-self: stretch', node.fill ? `background-color: ${node.fill}` : undefined, `color: ${node.color ?? FALLBACK.text}`, node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ...st.css, ]); const subtitle = text(node.subtitle); const words = `
` @@ -1301,31 +1425,37 @@ function textWithLinks(node: SceneNode): string { /** A disabled primitive leaves the tab order and says so. */ function disabledAttrs(node: SceneNode, attrs: string): string { - return node.disabled ? `${attrs.replace(' tabindex="0" data-focusable', ' tabindex="-1"')} aria-disabled="true"` : attrs; + return isDisabled(node) ? `${attrs.replace(' tabindex="0" data-focusable', ' tabindex="-1"')} aria-disabled="true"` : attrs; } function renderLink(node: SceneNode, rc: RenderCtx, attrs: string): string { + node = neutralised(node); attrs = disabledAttrs(node, attrs); // Phase 31 S3 — an icon-only link's accessible name (never rendered as text). const name = text(node.ariaLabel); if (name) attrs += ` aria-label="${escapeAttr(name)}" title="${escapeAttr(name)}"`; const color = node.color ?? FALLBACK.accent; + const state = elementState(node); + const st = stateParts(state, node.stateStyle, color, { authored: node.opacity }); const glyph = iconHtml(node.icon, LINK_ICON, node.iconColor ?? color); const external = node.external ? iconHtml('external-link', LINK_EXTERNAL, node.iconColor ?? color) : ''; - const words = text(node.label) ? titledLabel(text(node.label), '') : ''; + const words = text(node.label) ? titledLabel(text(node.label), underlined(state) ? 'text-decoration: underline; text-underline-offset: 2px' : '') : ''; const box = css([ + ringVar(node.stateStyle), ...positionStyles(node, rc), 'display: inline-flex', 'flex-shrink: 0', 'align-items: center', 'gap: 4px', `min-height: ${LINK_MIN_HEIGHT}px`, typeof node.height === 'number' ? `height: ${node.height}px` : undefined, node.width !== undefined ? `width: ${cssLength(node.width)}` : 'max-width: 100%', `color: ${color}`, `font-size: ${typeof node.fontSize === 'number' ? node.fontSize : 14}px`, `font-weight: ${node.fontWeight ?? 500}`, 'cursor: pointer', node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ...st.css, ]); const body = node.iconPosition === 'trailing' ? `${words}${glyph}` : `${glyph}${words}`; return `${body}${external}
`; } function renderTextInput(node: SceneNode, rc: RenderCtx, dataAttr: string): string { + node = neutralised(node); const h = textInputHeight(node); const multi = textInputRows(node) > 1; // An error colours the boundary and its message: $danger by default @@ -1335,11 +1465,18 @@ function renderTextInput(node: SceneNode, rc: RenderCtx, dataAttr: string): stri const value = text(node.value); const shown = value || text(node.placeholder); const radius = typeof node.cornerRadius === 'number' ? node.cornerRadius : 6; + // The field carries the target's box; the disabled opacity sits on the + // wrapper with the error message (spec P4). + const state = elementState(node); + const st = stateParts(state, node.stateStyle, node.color ?? FALLBACK.text, { authored: node.opacity }); + const opacity = st.css.filter((d) => d.startsWith('opacity:')); const field = css([ + ringVar(node.stateStyle), 'display: flex', multi ? 'align-items: flex-start' : 'align-items: center', 'gap: 8px', 'box-sizing: border-box', `height: ${h}px`, `min-height: ${h}px`, multi ? 'padding: 6px 10px' : 'padding: 0 10px', 'width: 100%', `border: 1px solid ${border}`, `border-radius: ${radius}px`, `background-color: ${node.fill ?? FALLBACK.surface}`, `font-size: ${node.size === 'sm' ? 13 : 14}px`, 'line-height: 20px', + ...st.css.filter((d) => !d.startsWith('opacity:')), ]); const glyph = iconHtml(node.icon, 16, secondary); const words = shown @@ -1354,13 +1491,15 @@ function renderTextInput(node: SceneNode, rc: RenderCtx, dataAttr: string): stri const outer = css([ ...positionStyles(node, rc), 'display: flex', 'flex-direction: column', 'gap: 4px', 'flex-shrink: 0', rowWidth(node), node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ...opacity, ]); const ariaInvalid = error ? ' aria-invalid="true"' : ''; - const focus = node.disabled ? ' tabindex="-1" aria-disabled="true"' : ' tabindex="0" data-focusable'; + const focus = state === 'disabled' ? ' tabindex="-1" aria-disabled="true"' : ' tabindex="0" data-focusable'; return `${glyph}${words}${message}`; } function renderNavItem(node: SceneNode, rc: RenderCtx, attrs: string): string { + node = neutralised(node); attrs = disabledAttrs(node, attrs); const color = node.color ?? FALLBACK.text; const accent = node.iconColor ?? FALLBACK.accent; @@ -1374,7 +1513,9 @@ function renderNavItem(node: SceneNode, rc: RenderCtx, attrs: string): string { const dot = node.dotColor ? `` : ''; const glyph = iconHtml(node.icon, 16, node.active ? accent : node.secondaryColor ?? FALLBACK.secondary); const count = text(node.count); + const st = stateParts(elementState(node), node.stateStyle, color, { authored: node.opacity }); const box = css([ + ringVar(node.stateStyle), ...positionStyles(node, rc), node.position ? undefined : 'position: relative', 'display: flex', 'align-items: center', 'gap: 8px', 'flex-shrink: 0', 'box-sizing: border-box', `height: ${typeof node.height === 'number' ? node.height : NAV_ITEM_HEIGHT}px`, @@ -1384,6 +1525,7 @@ function renderNavItem(node: SceneNode, rc: RenderCtx, attrs: string): string { node.fill ? `background-color: ${node.fill}` : undefined, `color: ${color}`, 'font-size: 13px', `font-weight: ${node.active ? 600 : 500}`, 'cursor: pointer', node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ...st.css, ]); if (node.collapsed) return `${bar}${glyph || dot}`; const tail = count ? `${escapeHtml(count)}` : ''; @@ -1394,24 +1536,31 @@ function renderTabs(node: SceneNode, rc: RenderCtx, dataAttr: string): string { const h = TABS_HEIGHT[node.size === 'sm' ? 'sm' : 'md']; const accent = node.iconColor ?? FALLBACK.accent; const line = node.variant !== 'contained'; + // A disabled tabs node disables every tab (spec P2). + const hostDisabled = isDisabled(node); const tabs = tabsItems(node).map((it) => { const label = text(it.label); const count = text(it.count); const active = it.active === true; + const state = hostDisabled ? 'disabled' : elementState(it); + const ink = active ? node.color ?? FALLBACK.text : node.secondaryColor ?? FALLBACK.secondary; + // The tablist clips its overflow, so a tab's ring is drawn inside (S9). + const st = stateParts(state, node.stateStyle, ink, { item: true, inset: true }); // A tab keeps its width until the tablist runs out, then shrinks so its // label truncates (never past its padding). const tab = css([ + ringVar(node.stateStyle), 'position: relative', 'display: flex', 'align-items: center', 'gap: 6px', 'flex: 0 1 auto', 'min-width: 0', 'height: 100%', line ? 'padding: 0 12px' : 'padding: 0 10px', !line ? `margin: 4px 0; height: ${h - 8}px; border-radius: 6px` : undefined, - !line && active ? `background-color: ${node.fill ?? '#EFF4FF'}` : undefined, - `color: ${active ? node.color ?? FALLBACK.text : node.secondaryColor ?? FALLBACK.secondary}`, - `font-weight: ${active ? 600 : 500}`, 'cursor: pointer', it.disabled ? 'opacity: 0.5' : undefined, + !line && active ? `background-color: ${st.container(node.fill ?? '#EFF4FF')}` : undefined, + `color: ${st.content(ink)}`, + `font-weight: ${active ? 600 : 500}`, 'cursor: pointer', ...st.css, ]); const indicator = line && active - ? `
` + ? `
` : ''; - const badge = count ? `${escapeHtml(count)}` : ''; - const focus = it.disabled ? ' tabindex="-1" aria-disabled="true"' : ' tabindex="0" data-focusable'; + const badge = count ? `${escapeHtml(count)}` : ''; + const focus = state === 'disabled' ? ' tabindex="-1" aria-disabled="true"' : ' tabindex="0" data-focusable'; return `
${titledLabel(label, '')}${badge}${indicator}
`; }).join(''); const box = css([ @@ -1423,19 +1572,23 @@ function renderTabs(node: SceneNode, rc: RenderCtx, dataAttr: string): string { } function renderTreeRow(node: SceneNode, rc: RenderCtx, attrs: string): string { + node = neutralised(node); attrs = disabledAttrs(node, attrs); const depth = typeof node.depth === 'number' && node.depth > 0 ? Math.floor(node.depth) : 0; const secondary = node.secondaryColor ?? FALLBACK.secondary; if (typeof node.expanded === 'boolean') attrs += ` aria-expanded="${node.expanded}"`; if (node.active) attrs += ' aria-selected="true"'; const chevron = typeof node.expanded === 'boolean' ? iconHtml(node.expanded ? 'chevron-down' : 'chevron-right', 14, secondary) : ''; + const st = stateParts(elementState(node), node.stateStyle, node.color ?? FALLBACK.text, { authored: node.opacity }); const box = css([ + ringVar(node.stateStyle), ...positionStyles(node, rc), 'display: flex', 'align-items: center', 'gap: 6px', 'flex-shrink: 0', 'box-sizing: border-box', `height: ${typeof node.height === 'number' ? node.height : TREE_ROW_HEIGHT}px`, rowWidth(node), `padding: 0 8px 0 ${8 + depth * TREE_INDENT}px`, 'border-radius: 6px', node.fill ? `background-color: ${node.fill}` : undefined, `color: ${node.color ?? FALLBACK.text}`, 'font-size: 13px', `font-weight: ${node.active ? 600 : 400}`, 'cursor: pointer', node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ...st.css, ]); const slot = `${chevron}`; const glyph = iconHtml(node.icon, 16, node.active ? node.iconColor ?? FALLBACK.accent : secondary); @@ -1443,6 +1596,7 @@ function renderTreeRow(node: SceneNode, rc: RenderCtx, attrs: string): string { } function renderMenuRow(node: SceneNode, rc: RenderCtx, attrs: string): string { + node = neutralised(node); const secondary = node.secondaryColor ?? FALLBACK.secondary; const color = node.color ?? (node.destructive ? FALLBACK.danger : FALLBACK.text); attrs = disabledAttrs(node, attrs); @@ -1456,11 +1610,14 @@ function renderMenuRow(node: SceneNode, rc: RenderCtx, attrs: string): string { ? `${titledLabel(text(node.shortcut), '')}` : ''; const chevron = node.submenu ? `${iconHtml('chevron-right', 14, secondary)}` : ''; + const st = stateParts(elementState(node), node.stateStyle, color, { authored: node.opacity }); const box = css([ + ringVar(node.stateStyle), ...positionStyles(node, rc), 'display: flex', 'align-items: center', 'gap: 8px', 'flex-shrink: 0', 'box-sizing: border-box', `height: ${typeof node.height === 'number' ? node.height : MENU_ROW_HEIGHT}px`, rowWidth(node), 'padding: 0 8px', 'border-radius: 6px', node.fill ? `background-color: ${node.fill}` : undefined, `color: ${color}`, 'font-size: 13px', 'cursor: pointer', node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ...st.css, ]); const checkSlot = typeof node.checked === 'boolean' ? `${check}` : ''; return `${checkSlot}${glyph}${titledLabel(text(node.label), '')}${shortcut}${chevron}`; @@ -1602,6 +1759,7 @@ function actionButton(node: SceneNode, a: NonNullable[numb id: node.id, type: 'button', size: 'sm', label: String(a.label).trim(), variant, maxWidth: 240, fill, color: a.color ?? (filled ? '#FFFFFF' : variant === 'ghost' ? FALLBACK.accent : node.color ?? FALLBACK.text), ...(stroke ? { stroke } : {}), + state: a.state, disabled: a.disabled, stateStyle: node.stateStyle, }; } @@ -1623,8 +1781,8 @@ function renderModal(node: SceneNode, rc: RenderCtx, attrs: string): string { ]); const close = renderButton({ id: node.id, type: 'button', size: 'sm', icon: 'x', variant: 'ghost', fill: 'transparent', - color: node.secondaryColor ?? FALLBACK.secondary, ariaLabel: text(node.closeLabel) || 'Close', - }, rc, ' tabindex="0" data-focusable data-fs-modal-close'); + color: node.secondaryColor ?? FALLBACK.secondary, ariaLabel: text(node.closeLabel) || 'Close', stateStyle: node.stateStyle, + }, rc, ' tabindex="0" data-focusable data-fs-modal-close', true); const header = `
${title ? titledLabel(title, 'font-size: 16px; font-weight: 600; line-height: 24px') : ''}
${close}
`; const actions = modalActions(node); const [pt, pr, pb, pl] = node.padding !== undefined ? paddingCss(node.padding) : ['8px', '20px', actions.length ? '8px' : '20px', '20px']; @@ -1635,7 +1793,7 @@ function renderModal(node: SceneNode, rc: RenderCtx, attrs: string): string { `padding: ${pt} ${pr} ${pb} ${pl}`, ])}">${renderChildren(node, rc)}`; const footer = actions.length - ? `
${actions.map((a) => renderButton(actionButton(node, a), rc, ' tabindex="0" data-focusable')).join('')}
` + ? `
${actions.map((a) => renderButton(actionButton(node, a), rc, ' tabindex="0" data-focusable', true)).join('')}
` : ''; return `${scrimHtml(node)}${header}${body}${footer}`; } @@ -1658,7 +1816,10 @@ function renderToast(node: SceneNode, rc: RenderCtx, attrs: string): string { const glyph = `${iconHtml(TONE_ICON[tone], 16, node.iconColor ?? TONE_FALLBACK[tone])}`; const message = `${escapeHtml(text(node.text))}`; const action = label - ? renderButton({ id: node.id, type: 'button', size: 'xs', label, variant: 'ghost', fill: 'transparent', color: node.action?.color ?? FALLBACK.accent, maxWidth: 160 }, rc, ' tabindex="0" data-focusable') + ? renderButton({ + id: node.id, type: 'button', size: 'xs', label, variant: 'ghost', fill: 'transparent', color: node.action?.color ?? FALLBACK.accent, maxWidth: 160, + state: node.action?.state, disabled: node.action?.disabled, stateStyle: node.stateStyle, + }, rc, ' tabindex="0" data-focusable', true) : ''; return `${glyph}${message}${action}`; } diff --git a/src/types.ts b/src/types.ts index 3bac742..09288bc 100644 --- a/src/types.ts +++ b/src/types.ts @@ -18,23 +18,43 @@ export type NodeType = 'frame' | 'text' | 'rectangle' | 'ellipse' | 'image' | 'i // tooltip), positioned by authored x/y in root coordinates. | 'tooltip' | 'popover' | 'menu' | 'modal' | 'toast' | 'drawer'; +/** Phase 31 slice G (FR-G1) — an element state, drawn by the renderer from + * the `state` tokens: rest (the default), hover, focus, pressed, disabled. + * `disabled: true` means "disabled" whatever `state` says. */ +export type ElementState = 'rest' | 'hover' | 'focus' | 'pressed' | 'disabled'; + /** Phase 30 slice D — one `nav-bar` action: an icon or a text label. */ -export interface NavAction { icon?: string; label?: string } +export interface NavAction { icon?: string; label?: string; state?: ElementState; disabled?: boolean } /** Phase 30 slice D — one `tab-bar` item. */ -export interface TabItem { icon: string; label: string; active?: boolean; badge?: string | number } +export interface TabItem { icon: string; label: string; active?: boolean; badge?: string | number; state?: ElementState; disabled?: boolean } /** Phase 31 slice B — one `tabs` item (its own type: unlike a tab-bar item * it has no icon). */ -export interface TabsItem { label: string; count?: string | number; active?: boolean; disabled?: boolean } +export interface TabsItem { label: string; count?: string | number; active?: boolean; disabled?: boolean; state?: ElementState } /** Phase 31 slice E — one `modal` action. No variant renders "secondary"; * the filled ones (primary, destructive) render rightmost. Colours default by * variant as a button's do; explicit ones win. */ -export interface ModalAction { label: string; variant?: 'primary' | 'secondary' | 'ghost' | 'destructive'; fill?: string; color?: string; stroke?: string } +export interface ModalAction { label: string; variant?: 'primary' | 'secondary' | 'ghost' | 'destructive'; fill?: string; color?: string; stroke?: string; state?: ElementState; disabled?: boolean } /** Phase 31 slice E — a `toast`'s action (a ghost text button). */ -export interface ToastAction { label: string; color?: string } +export interface ToastAction { label: string; color?: string; state?: ElementState; disabled?: boolean } + +/** Phase 31 slice G — what resolution hands the renderer for an element + * state (spec P3). Internal: set on the resolved clone, never authored or + * stored. The disabled pair is present only when the design system sets it. */ +export interface StateStyle { + ring: string; + /** The on-surface colour a disabled target with the token pair renders in + * (spec change S10: `$text-primary`, Material's onSurface). */ + onSurface: string; + hover: number; + focus: number; + pressed: number; + disabledContent?: number; + disabledContainer?: number; +} /** Phase 31 slice B — an inline link inside a `text` node's content: * character offsets [start, end). */ @@ -231,6 +251,13 @@ export interface SceneNode { // fill / stroke / color override them. checked?: boolean; disabled?: boolean; + /** Phase 31 slice G (FR-G1) — the element state the renderer draws on a + * clickable primitive or control (a states sheet, a screenshot). The + * evaluator never needs it. Other node types ignore it. */ + state?: ElementState; + /** Internal (slice G, P3): resolved state colours and opacities. Set by + * resolveVariables on its clone; never author it. */ + stateStyle?: StateStyle; /** select only: the displayed value; absent renders a muted placeholder. */ value?: string; /** skeleton only: set false to opt a block out of the live-viewer pulse. @@ -308,7 +335,7 @@ export interface SceneNode { subtitle?: string; /** nav-bar: the back action `{ icon?, label? }`; list-row: `{ icon }` | * `{ initials }` | `{ image }`. */ - leading?: { icon?: string; label?: string; initials?: string; image?: string }; + leading?: { icon?: string; label?: string; initials?: string; image?: string; state?: ElementState; disabled?: boolean }; /** nav-bar: up to two actions; list-row: one accessory. */ trailing?: NavAction[] | ListRowTrailing; /** nav-bar: the 96px large-title form. */ diff --git a/src/variables.ts b/src/variables.ts index d6ddabc..be24454 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -1,4 +1,5 @@ -import type { Canvas, DesignVariables, SceneNode, ShadowSpec } from './types.js'; +import type { Canvas, DesignVariables, SceneNode, ShadowSpec, StateStyle } from './types.js'; +import { STATE_LAYERS, STATEFUL_TYPES } from './primitives.js'; export function resolveVariables(node: SceneNode, variables: DesignVariables, opts?: { theme?: 'light' | 'dark' }): SceneNode { // Phase 25 slice D — dark is a sparse override layer: merge it over colors @@ -120,8 +121,53 @@ function deepResolve(node: SceneNode, variables: DesignVariables): SceneNode { // Explicit fill / stroke / color on the node always wins. const CONTROL_FALLBACK = { accent: '#2563EB', border: '#D1D5DB', surface: '#FFFFFF', text: '#111827' } as const; +// Phase 31 slice G (spec P2, P3) — every node that draws an element state +// gets its ring colour and layer opacities resolved here, so the renderer +// never reads tokens. Items of tabs / tab-bar / nav-bar / modal / toast use +// their host's. +const STATE_HOSTS = new Set([...STATEFUL_TYPES, 'tabs', 'tab-bar', 'nav-bar', 'modal', 'toast']); +// The nodes whose own `state: "disabled"` disables them (a tabs node's +// disables every tab). +const STATE_ON_NODE = new Set([...STATEFUL_TYPES, 'tabs']); + +/** An opacity token: a number in [0, 1], else undefined. */ +function unit(x: unknown): number | undefined { + return typeof x === 'number' && Number.isFinite(x) && x >= 0 && x <= 1 ? x : undefined; +} + +/** Whether the design system sets either disabled opacity (spec P3). */ +function hasDisabledTokens(v: DesignVariables): boolean { + return unit(v.state?.disabledContent) !== undefined || unit(v.state?.disabledContainer) !== undefined; +} + +export function resolveStateStyle(v: DesignVariables): StateStyle { + const c = v.colors ?? {}; + const s = v.state ?? {}; + const out: StateStyle = { + // FR-H1's chain: the renderer and the check never disagree. + ring: c['focus-ring'] ?? c.accent ?? c.primary ?? CONTROL_FALLBACK.accent, + onSurface: c['text-primary'] ?? CONTROL_FALLBACK.text, + hover: unit(s.hover) ?? STATE_LAYERS.hover, + focus: unit(s.focus) ?? STATE_LAYERS.focus, + pressed: unit(s.pressed) ?? STATE_LAYERS.pressed, + }; + if (hasDisabledTokens(v)) { + out.disabledContent = unit(s.disabledContent) ?? STATE_LAYERS.disabledContent; + out.disabledContainer = unit(s.disabledContainer) ?? STATE_LAYERS.disabledContainer; + } + return out; +} + +/** Without disabled tokens a disabled node renders at today's 0.5 opacity + * (unless authored); with them the renderer draws the token pair (P4). */ +function legacyDisabled(node: SceneNode, v: DesignVariables): void { + const disabled = node.disabled === true || (STATE_ON_NODE.has(node.type) && node.state === 'disabled'); + if (disabled && node.opacity === undefined && !hasDisabledTokens(v)) node.opacity = 0.5; +} + function applyControlDefaults(node: SceneNode, v: DesignVariables): void { const t = node.type; + if (STATE_HOSTS.has(t)) node.stateStyle = resolveStateStyle(v); if (t === 'skeleton') { // Phase 24 slice B — loading placeholder: a themed canvas picks up its // own border tone (or an explicit `skeleton` token); unthemed canvases @@ -139,7 +185,7 @@ function applyControlDefaults(node: SceneNode, v: DesignVariables): void { // Without the token the render is unchanged. const boundary = v.colors?.['border-strong'] ?? border; - if (node.disabled && node.opacity === undefined) node.opacity = 0.5; + legacyDisabled(node, v); if (t === 'toggle') { // fill = track color; the knob is always white. @@ -181,7 +227,7 @@ function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { // surface (12%), so it reads on a dark palette as well as a light one. const tint = c['accent-tint'] ?? mixHex(accent, surface, 0.12) ?? '#EFF4FF'; const set = (key: K, value: SceneNode[K]) => { if (node[key] === undefined) node[key] = value; }; - if (node.disabled && node.opacity === undefined) node.opacity = 0.5; + legacyDisabled(node, v); switch (node.type) { // Phase 31 slice B — the desktop-app vocabulary. diff --git a/test-discoverability.ts b/test-discoverability.ts index 1931048..51c6ec0 100644 --- a/test-discoverability.ts +++ b/test-discoverability.ts @@ -436,6 +436,34 @@ const guidelines = readFileSync('docs/GUIDELINES.md', 'utf-8'); expect('the issue `rule` field is documented in src/index.ts and GUIDELINES', /"rule" field/.test(indexSrc) && /`rule` field/.test(guidelines)); } +// ── Phase 31 slice G: element states are surfaced where agents look ────────── +// The state names and every node type that takes `state` (STATEFUL_TYPES, +// live import) appear on each surface, so a new stateful type cannot ship +// undocumented. +{ + const { ELEMENT_STATES, STATEFUL_TYPES } = await import('./src/primitives.js'); + // Each surface's own element-states paragraph, up to its blank line. + const paragraph = (src: string, marker: string) => { + const at = src.indexOf(marker); + if (at < 0) return ''; + const end = src.indexOf('\n\n', at); + return src.slice(at, end < 0 ? undefined : end); + }; + for (const [label, src, marker] of [ + ['src/index.ts', indexSrc, 'Element states (state?:'], + ['GUIDELINES', guidelines, '- **Who takes it.**'], + ['README', readme, '**Element states.**'], + ] as const) { + const para = paragraph(src, marker); + expect(`the element-states paragraph exists in ${label}`, para.length > 0); + const missing = ELEMENT_STATES.filter((st: string) => st !== 'rest' && !src.includes(`"${st}"`)); + expect(`every element state named in ${label}`, missing.length === 0, missing.join(', ')); + const untyped = [...STATEFUL_TYPES].filter((t) => !para.includes(t)); + expect(`every stateful node type listed under element states in ${label}`, untyped.length === 0, untyped.join(', ')); + } + expect('state is in batch_design\'s property list', /checked, disabled, state, value/.test(indexSrc)); +} + let allPass = true; for (const c of checks) { if (!c.ok) allPass = false; diff --git a/test-element-states-render.ts b/test-element-states-render.ts new file mode 100644 index 0000000..a13d8b8 --- /dev/null +++ b/test-element-states-render.ts @@ -0,0 +1,71 @@ +// Phase 31 slice G (FR-G1 acceptance, spec P8) — a `button` of each variant +// at each of the five states renders deterministically (two renders, the +// same pixels) and distinctly (every pair of states differs) in both themes +// of a generated design system. The capture is a small window around the +// button, so the focus ring (outside the box, S9) is in the frame. PNG bytes +// stand in for pixels: the encoder is lossless and deterministic, so equal +// bytes mean equal pixels and different bytes different ones. +// Needs Chrome. Run with: npx tsx test-element-states-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 { takeScreenshot, shutdown } from './src/screenshot.js'; +import type { 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}${extra ? ` — ${extra}` : ''}`); +} + +const SYSTEM = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; +const STATES: ElementState[] = ['rest', 'hover', 'focus', 'pressed', 'disabled']; +const VARIANTS = ['primary', 'secondary', 'ghost', 'destructive'] as const; +const W = 200; +const H = 96; + +function html(variant: string, state: ElementState, theme: 'light' | 'dark'): string { + const root: SceneNode = { + id: 'root', type: 'frame', width: W, height: H, fill: '$bg-primary', layout: 'vertical', alignItems: 'center', justifyContent: 'center', + children: [{ id: 'b', type: 'button', label: 'Save', size: 'sm', variant: variant as SceneNode['variant'], state }], + }; + return renderToHtml(resolveVariables(root, SYSTEM, { theme }), W, H); +} + +const shot = (h: string) => takeScreenshot(h, { width: W, height: H, scale: 1 }); + +for (const theme of ['light', 'dark'] as const) { + for (const variant of VARIANTS) { + const shots: string[] = []; + let stable = true; + for (const state of STATES) { + const h = html(variant, state, theme); + const [a, b] = [await shot(h), await shot(h)]; + if (a !== b) stable = false; + shots.push(a); + } + check(`${theme} ${variant}: each state renders the same pixels twice`, stable); + const same: string[] = []; + for (let i = 0; i < STATES.length; i++) { + for (let j = i + 1; j < STATES.length; j++) if (shots[i] === shots[j]) same.push(`${STATES[i]}=${STATES[j]}`); + } + check(`${theme} ${variant}: every pair of states differs`, same.length === 0, same.join(', ')); + } +} + +// Twin: a node that takes no state renders the same pixels in every state. +{ + const frame = (state: ElementState) => renderToHtml(resolveVariables({ + id: 'root', type: 'frame', width: W, height: H, fill: '$bg-primary', layout: 'vertical', alignItems: 'center', justifyContent: 'center', + children: [{ id: 'f', type: 'frame', width: 80, height: 32, fill: '$accent', cornerRadius: 8, state }], + }, SYSTEM), W, H); + const base = await shot(frame('rest')); + const all = await Promise.all(STATES.slice(1).map((s) => shot(frame(s)))); + check('twin: a frame with state renders as at rest', all.every((s) => s === base)); +} + +await shutdown(); +console.log(allPass ? '\nALL PASS' : '\nSOME FAILED'); +process.exit(allPass ? 0 : 1); diff --git a/test-element-states.ts b/test-element-states.ts new file mode 100644 index 0000000..94d8cd9 --- /dev/null +++ b/test-element-states.ts @@ -0,0 +1,323 @@ +// Phase 31 slice G (FR-G1, spec P1–P9) — element states as a property. The +// renderer draws hover / focus / pressed as a layer of the ink over the fill, +// focus adds a 2px ring at a 2px gap (S9), disabled draws the token pair in +// the on-surface colour (S10) or today's 0.5 without tokens; the 24px census, +// primary count and the overlays' targets read `state: "disabled"` as +// disabled. Every asserted presence has a twin that must not show it. +// Fast tier: HTML assertions, no Chrome. +// +// Usage: npx tsx test-element-states.ts + +import './test-env.js'; +import { renderToHtml } from './src/renderer.js'; +import { resolveVariables } from './src/variables.js'; +import { evaluateCanvas, pointerTargets } from './src/evaluate.js'; +import { generateDesignSystem } from './src/design-language.js'; +import { elementState, isDisabled, desktopTargets, overlayTargets, STATE_LAYERS } from './src/primitives.js'; +import type { Canvas, DesignVariables, SceneNode } from './src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +const SYSTEM = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; +const C = SYSTEM.colors!; +const RING = C['focus-ring']; +const ON = C['text-primary']; +const COLORS_ONLY: DesignVariables = { colors: { ...C } }; + +function render(children: SceneNode[], vars: DesignVariables = SYSTEM, resolve = true): string { + const root: SceneNode = { id: 'root', type: 'frame', layout: 'vertical', gap: 8, padding: 16, fill: '#FFFFFF', children }; + return renderToHtml(resolve ? resolveVariables(root, vars) : root, 900, 600); +} + +/** From a node's element to the next node's element (its own markup, items included). */ +function chunk(html: string, id: string): string { + const at = html.indexOf(`data-node-id="${id}"`); + if (at < 0) return ''; + const start = html.lastIndexOf('<', at); + const next = html.indexOf('data-node-id="', at + 10); + return html.slice(start, next < 0 ? undefined : html.lastIndexOf('<', next)); +} + +/** The opening tag of a node's own element. */ +function tag(html: string, id: string): string { + const c = chunk(html, id); + return c.slice(0, c.indexOf('>') + 1); +} + +const layer = (ink: string, p: number) => `linear-gradient(color-mix(in srgb, ${ink} ${p}%, transparent), color-mix(in srgb, ${ink} ${p}%, transparent))`; +const ringCss = (ring: string, offset = 2) => `outline: 2px solid ${ring}; outline-offset: ${offset}px`; + +// ── P1: the effective state ────────────────────────────────────────────── +check('P1: no state is rest', elementState({}) === 'rest'); +for (const s of ['rest', 'hover', 'focus', 'pressed', 'disabled'] as const) check(`P1: state "${s}" is ${s}`, elementState({ state: s }) === s); +check('P1: an unknown state is rest', elementState({ state: 'active' }) === 'rest' && elementState({ state: 3 }) === 'rest' && elementState({ state: 'Hover' }) === 'rest'); +check('P1: disabled: true beats state hover', elementState({ state: 'hover', disabled: true }) === 'disabled'); +check('P1: disabled: false keeps the state', elementState({ state: 'pressed', disabled: false }) === 'pressed'); +check('P1: isDisabled reads both spellings', isDisabled({ disabled: true }) && isDisabled({ state: 'disabled' }) && !isDisabled({ state: 'focus' }) && !isDisabled(undefined)); + +// ── P4: each node type, each layer state, with its ink ────────────────── +/** Each P2 node type, the element id its state lands on (the node's own, + * except a text-input's, whose field carries it), and its ink once resolved. */ +const NODES: Array<{ node: SceneNode; ink: (n: SceneNode) => string; field?: boolean }> = [ + { node: { id: 'n', type: 'button', label: 'Save' }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'button', label: 'Cancel', variant: 'secondary' }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'link', label: 'Docs' }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'text-input', placeholder: 'Search' }, ink: (n) => n.color!, field: true }, + { node: { id: 'n', type: 'nav-item', label: 'Inbox' }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'nav-item', label: 'Inbox', active: true }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'tree-row', label: 'src', expanded: true }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'menu-row', label: 'Rename', checked: true }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'menu-row', label: 'Delete', destructive: true }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'list-row', title: 'Wi-Fi' }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'select', value: 'One' }, ink: (n) => n.color! }, + { node: { id: 'n', type: 'toggle' }, ink: () => '#FFFFFF' }, + { node: { id: 'n', type: 'toggle', checked: true }, ink: () => '#FFFFFF' }, + { node: { id: 'n', type: 'checkbox', checked: true }, ink: () => '#FFFFFF' }, + { node: { id: 'n', type: 'checkbox' }, ink: (n) => n.stroke! }, + { node: { id: 'n', type: 'radio', checked: true }, ink: (n) => n.stroke! }, +]; +const PCT = { hover: 8, focus: 10, pressed: 10 } as const; + +for (const { node, ink, field } of NODES) { + const label = `${node.type}${node.variant ? `/${node.variant}` : ''}${node.checked ? ' checked' : ''}${node.active ? ' active' : ''}${node.destructive ? ' destructive' : ''}`; + const resolved = resolveVariables(node, SYSTEM); + const own = (html: string) => (field ? chunk(html, 'n').match(/]*role="textbox"[^>]*>/)?.[0] ?? '' : tag(html, 'n')); + const rest = own(render([node])); + check(`P4: ${label} at rest draws no layer and no ring`, rest.length > 0 && !rest.includes('linear-gradient(color-mix') && !rest.includes('outline:'), rest.slice(0, 200)); + for (const s of ['hover', 'focus', 'pressed'] as const) { + const t = own(render([{ ...node, state: s }])); + const hasLayer = t.includes(layer(ink(resolved), PCT[s])); + const hasRing = t.includes(ringCss(RING)); + check(`P4: ${label} ${s} layers its ink at ${PCT[s]}%${s === 'focus' ? ' and draws the ring' : ''}`, hasLayer && hasRing === (s === 'focus'), t.slice(0, 400)); + } +} + +// The same states on a node that takes none change nothing (P2). +for (const n of [ + { id: 'n', type: 'frame', width: 40, height: 40, fill: '#EEEEEE' }, + { id: 'n', type: 'text', content: 'Hello' }, + { id: 'n', type: 'property-row', label: 'Name' }, + { id: 'n', type: 'divider' }, +] as SceneNode[]) { + const base = render([n]); + const same = ['hover', 'focus', 'pressed', 'disabled'].every((s) => render([{ ...n, state: s as SceneNode['state'] }]) === base); + check(`P2: a ${n.type} ignores state`, same); +} + +// Unknown state renders as rest; disabled: true beats a hover state. +check('P1: an unknown state renders as rest', render([{ id: 'n', type: 'button', label: 'S', state: 'glow' as SceneNode['state'] }]) === render([{ id: 'n', type: 'button', label: 'S' }])); +{ + const t = tag(render([{ id: 'n', type: 'button', label: 'S', state: 'hover', disabled: true }]), 'n'); + check('P1: disabled: true with state hover renders disabled, no layer', t.includes('opacity: 0.38') && !t.includes('linear-gradient(color-mix'), t); +} + +// A link underlines its label in hover and pressed only. +for (const s of ['rest', 'hover', 'focus', 'pressed'] as const) { + const c = chunk(render([{ id: 'n', type: 'link', label: 'Docs', state: s }]), 'n'); + const under = /data-fs-label[^>]*text-decoration: underline/.test(c); + check(`P4: a link ${s === 'hover' || s === 'pressed' ? 'underlines' : 'does not underline'} in ${s}`, under === (s === 'hover' || s === 'pressed')); +} + +// ── P3: ring and opacities ─────────────────────────────────────────────── +{ + const noRing = { ...SYSTEM, colors: { ...C } }; + delete noRing.colors!['focus-ring']; + const accent = noRing.colors!.accent ?? noRing.colors!.primary; + check('P3: the ring is $focus-ring', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'focus' }]), 'n').includes(ringCss(RING))); + check('P3: without $focus-ring the ring is the accent', !!accent && accent !== RING && tag(render([{ id: 'n', type: 'button', label: 'S', state: 'focus' }], noRing), 'n').includes(ringCss(accent!))); + const onlyPrimary: DesignVariables = { colors: { primary: '#B45309' } }; + check('P3: then $primary', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'focus' }], onlyPrimary), 'n').includes(ringCss('#B45309'))); + check('P3: then #2563EB', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'focus' }], {}), 'n').includes(ringCss('#2563EB'))); + const unresolved = tag(render([{ id: 'n', type: 'button', label: 'S', state: 'hover', color: '#FFFFFF', fill: '#000000' }], {}, false), 'n'); + check('P3: an unresolved node (inside a component) uses #2563EB and the constant layers', unresolved.includes(layer('#FFFFFF', 8)) && unresolved.includes('--fs-ring: #2563EB'), unresolved); + const tuned: DesignVariables = { ...SYSTEM, state: { ...SYSTEM.state, hover: 0.2, pressed: 0.3 } }; + const h = tag(render([{ id: 'n', type: 'button', label: 'S', state: 'hover' }], tuned), 'n'); + check('P3: a hover token of 0.2 layers at 20%', h.includes('#FFFFFF 20%'), h); + check('P3: a pressed token of 0.3 layers at 30%', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'pressed' }], tuned), 'n').includes('#FFFFFF 30%')); + const bad: DesignVariables = { ...SYSTEM, state: { hover: 1.5, focus: -0.1, pressed: Number.NaN } }; + check('P3: out-of-range layer tokens fall back to the constants', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'hover' }], bad), 'n').includes('#FFFFFF 8%') + && tag(render([{ id: 'n', type: 'button', label: 'S', state: 'focus' }], bad), 'n').includes('#FFFFFF 10%') + && tag(render([{ id: 'n', type: 'button', label: 'S', state: 'pressed' }], bad), 'n').includes('#FFFFFF 10%')); + // The live :focus-visible ring is the same colour on every focusable primitive. + const all = render([ + { id: 'a', type: 'button', label: 'S' }, { id: 'b', type: 'link', label: 'L' }, { id: 'c', type: 'nav-item', label: 'N' }, + { id: 'd', type: 'tree-row', label: 'T' }, { id: 'e', type: 'menu-row', label: 'M' }, { id: 'f', type: 'checkbox' }, + { id: 'g', type: 'toggle', checked: true }, { id: 'h', type: 'radio' }, { id: 'i', type: 'select' }, + ]); + const rings = [...all.matchAll(/--fs-ring: ([^;"]+)/g)].map((m) => m[1]); + check('P4: every focusable primitive carries --fs-ring = the ring', rings.length >= 9 && rings.every((r) => r === RING), JSON.stringify(rings)); + const tin = render([{ id: 'n', type: 'text-input', placeholder: 'x' }]); + check('P4: a text-input field carries --fs-ring = the ring', /role="textbox"[^>]*--fs-ring: /.test(tin) && tin.includes(`--fs-ring: ${RING}`)); +} + +// ── P4: disabled ───────────────────────────────────────────────────────── +{ + const share = Math.round((0.12 / 0.38) * 10000) / 100; // 31.58 + const t = tag(render([{ id: 'n', type: 'button', label: 'Save', state: 'disabled' }]), 'n'); + check('S10: a disabled button with tokens renders at 0.38 in the on-surface colour', t.includes('opacity: 0.38') && t.includes(`color: ${ON}`) && t.includes(`background-color: color-mix(in srgb, ${ON} ${share}%, transparent)`), t); + check('P6: a disabled button leaves the tab order', t.includes('tabindex="-1"') && t.includes('aria-disabled="true"') && !t.includes('data-focusable')); + const sec = tag(render([{ id: 'n', type: 'button', label: 'Cancel', variant: 'secondary', disabled: true }]), 'n'); + check('S10: a disabled secondary keeps its transparent fill and draws its border in the on-surface share', sec.includes('background-color: transparent') && sec.includes(`border: 1px solid color-mix(in srgb, ${ON} ${share}%, transparent)`), sec); + const rest = tag(render([{ id: 'n', type: 'button', label: 'Save' }]), 'n'); + check('S10 twin: an enabled button keeps its own colours', !rest.includes('opacity:') && !rest.includes('color-mix') && !rest.includes(`color: ${ON}`), rest); + + const legacy = tag(render([{ id: 'n', type: 'button', label: 'Save', state: 'disabled' }], COLORS_ONLY), 'n'); + check('P4: without disabled tokens a disabled button renders at 0.5 in its own colours', legacy.includes('opacity: 0.5') && !legacy.includes('color-mix') && !legacy.includes(`color: ${ON};`), legacy); + const legacyFlag = tag(render([{ id: 'n', type: 'button', label: 'Save', disabled: true }], COLORS_ONLY), 'n'); + check('P5: disabled: true without tokens renders exactly as state disabled', legacyFlag === legacy); + + const one: DesignVariables = { ...SYSTEM, state: { disabledContent: 0.5 } }; + const o = tag(render([{ id: 'n', type: 'button', label: 'Save', disabled: true }], one), 'n'); + check('P3: one disabled token pulls in the other\'s constant (0.12 / 0.5 = 24%)', o.includes('opacity: 0.5') && o.includes(`color-mix(in srgb, ${ON} 24%, transparent)`), o); + const onlyContainer: DesignVariables = { ...SYSTEM, state: { disabledContainer: 0.2 } }; + check('P3: the container token alone pairs with the 0.38 constant', tag(render([{ id: 'n', type: 'button', label: 'S', disabled: true }], onlyContainer), 'n').includes(`color-mix(in srgb, ${ON} 52.63%, transparent)`)); + const zero: DesignVariables = { ...SYSTEM, state: { disabledContent: 0, disabledContainer: 0.12 } }; + check('P4: disabledContent 0 draws the container at 100%', tag(render([{ id: 'n', type: 'button', label: 'S', disabled: true }], zero), 'n').includes(`color-mix(in srgb, ${ON} 100%, transparent)`)); + const over: DesignVariables = { ...SYSTEM, state: { disabledContent: 0.2, disabledContainer: 0.6 } }; + check('P4: a container token above the content caps at 100%', tag(render([{ id: 'n', type: 'button', label: 'S', disabled: true }], over), 'n').includes(`color-mix(in srgb, ${ON} 100%, transparent)`)); + const authored = tag(render([{ id: 'n', type: 'button', label: 'Save', disabled: true, opacity: 0.7 }]), 'n'); + check('P4: an authored opacity wins over the pair', authored.includes('opacity: 0.7') && !authored.includes('opacity: 0.38') && !authored.includes('color-mix'), authored); + + const box = tag(render([{ id: 'n', type: 'checkbox', checked: true, disabled: true }]), 'n'); + check('S10: a disabled checkbox is drawn whole in the on-surface colour at 0.38', box.includes('opacity: 0.38') && box.includes(`background-color: ${ON}`) && box.includes(`border: 1.5px solid ${ON}`) && !box.includes('color-mix'), box); + const tg = tag(render([{ id: 'n', type: 'toggle', state: 'disabled' }]), 'n'); + check('S10: a disabled toggle track is the on-surface colour at 0.38', tg.includes('opacity: 0.38') && tg.includes(`background-color: ${ON}`), tg); + const sel = tag(render([{ id: 'n', type: 'select', value: 'A', disabled: true }]), 'n'); + check('S10: a disabled select splits its frame (container share) from its text', sel.includes('opacity: 0.38') && sel.includes(`color-mix(in srgb, ${ON} ${share}%, transparent)`), sel); + + const ti = chunk(render([{ id: 'n', type: 'text-input', value: 'abc', error: 'Bad', disabled: true }]), 'n'); + const outer = ti.slice(0, ti.indexOf('>') + 1); + const fieldTag = ti.match(/]*role="textbox"[^>]*>/)?.[0] ?? ''; + check('S10: a disabled text-input dims the wrapper and draws its field in the on-surface share', outer.includes('opacity: 0.38') && !fieldTag.includes('opacity') && fieldTag.includes(`color-mix(in srgb, ${ON} ${share}%, transparent)`) && fieldTag.includes('tabindex="-1"'), ti.slice(0, 600)); + + const nav = chunk(render([{ id: 'n', type: 'nav-item', label: 'Inbox', active: true, dotColor: '#16A34A', state: 'disabled' }]), 'n'); + check('S10: a disabled active nav-item draws its bar, dot and tint in the on-surface colour', !nav.includes(C.accent) && !nav.includes('#16A34A') && nav.includes(`background-color: ${ON}`) && nav.includes('opacity: 0.38'), nav.slice(0, 600)); + const navNoDot = chunk(render([{ id: 'n', type: 'nav-item', label: 'Inbox', state: 'disabled' }]), 'n'); + check('S10 twin: a disabled nav-item with no dot grows no dot', !navNoDot.includes('border-radius: 50%')); +} + +// ── P2: items ──────────────────────────────────────────────────────────── +{ + const tabs = (items: SceneNode['items'], extra: Partial = {}, vars: DesignVariables = SYSTEM) => + [...chunk(render([{ id: 'n', type: 'tabs', items, ...extra }], vars), 'n').matchAll(/
]*>/g)].map((m) => m[0]); + const t = tabs([{ label: 'A', active: true }, { label: 'B', state: 'hover' }, { label: 'C', state: 'focus' }, { label: 'D', state: 'disabled' }, { label: 'E' }]); + check('P2: a hovered tab layers its ink; its neighbours do not', t[1]?.includes('linear-gradient(color-mix') && !t[0]?.includes('linear-gradient') && !t[4]?.includes('linear-gradient'), JSON.stringify(t)); + check('S9: a focused tab draws its ring inset', !!t[2]?.includes(ringCss(RING, -2)) && !t[2]?.includes('outline-offset: 2px')); + check('P2: a tab with state disabled leaves the tab order at 0.38', !!t[3]?.includes('tabindex="-1"') && !!t[3]?.includes('opacity: 0.38') && !t[4]?.includes('opacity')); + const legacyTabs = tabs([{ label: 'A', disabled: true }, { label: 'B' }], {}, COLORS_ONLY); + check('P4: a disabled tab without tokens keeps today\'s 0.5', !!legacyTabs[0]?.includes('opacity: 0.5') && !legacyTabs[1]?.includes('opacity')); + const hostOff = tabs([{ label: 'A' }, { label: 'B' }], { state: 'disabled' }); + check('P2: a tabs node with state disabled disables every tab', hostOff.length === 2 && hostOff.every((x) => x.includes('tabindex="-1"') && x.includes('opacity: 0.38'))); + const hostOffLegacy = tabs([{ label: 'A' }, { label: 'B' }], { disabled: true }, COLORS_ONLY); + check('P2: a disabled tabs node without tokens dims every tab to 0.5', hostOffLegacy.every((x) => x.includes('opacity: 0.5'))); + + const bar = chunk(render([{ id: 'n', type: 'tab-bar', items: [{ icon: 'house', label: 'Home', active: true }, { icon: 'search', label: 'Find', state: 'pressed' }, { icon: 'user', label: 'Me', state: 'disabled' }] }]), 'n'); + check('P2: a pressed tab-bar item layers its ink at 10%', /10%, transparent\), color-mix/.test(bar), bar.slice(0, 300)); + check('P2: a disabled tab-bar item renders at 0.38', bar.includes('opacity: 0.38')); + const barRest = chunk(render([{ id: 'n', type: 'tab-bar', items: [{ icon: 'house', label: 'Home', active: true }, { icon: 'search', label: 'Find' }] }]), 'n'); + check('P2 twin: a tab-bar with no item state draws neither', !barRest.includes('linear-gradient(color-mix') && !barRest.includes('opacity')); + const focusBar = chunk(render([{ id: 'n', type: 'tab-bar', items: [{ icon: 'house', label: 'Home', state: 'focus' }, { icon: 'search', label: 'Find' }] }]), 'n'); + check('S9: a focused tab-bar item draws its ring inset', focusBar.includes(ringCss(RING, -2))); + + const nb = chunk(render([{ id: 'n', type: 'nav-bar', title: 'T', leading: { icon: 'chevron-left', state: 'hover' }, trailing: [{ icon: 'plus', state: 'focus' }, { label: 'Edit', disabled: true }] }]), 'n'); + check('P2: nav-bar actions take hover, focus (ring outside) and disabled', nb.includes('8%, transparent') && nb.includes(ringCss(RING)) && nb.includes('opacity: 0.38'), nb.slice(0, 300)); + + const modal = render([{ id: 'n', type: 'modal', title: 'Delete?', actions: [{ label: 'Cancel', state: 'hover' }, { label: 'Delete', variant: 'destructive', state: 'disabled' }] }]); + // The actions render under the modal with no node id of their own (slice E L2). + const actionTags = [...modal.matchAll(/
]*>/g)].map((m) => m[0]); + check('P2: a hovered modal action layers its ink', actionTags.some((x) => x.includes('8%, transparent') && x.includes('tabindex="0"'))); + check('P2: a disabled modal action is on-surface at 0.38 and out of the tab order', actionTags.some((x) => x.includes('opacity: 0.38') && x.includes('tabindex="-1"') && x.includes(`color: ${ON}`))); + const modalLegacy = render([{ id: 'n', type: 'modal', title: 'Delete?', actions: [{ label: 'Delete', variant: 'destructive', disabled: true }] }], COLORS_ONLY); + check('P4: a disabled modal action without tokens renders at 0.5 inline', /
]*opacity: 0\.5/.test(modalLegacy)); + const close = [...modal.matchAll(/]*data-fs-modal-close[^>]*>/g)].map((m) => m[0])[0] ?? ''; + check('P2: the modal close button takes no state and carries the ring colour', !close.includes('linear-gradient') && close.includes(`--fs-ring: ${RING}`), close); + + const toast = render([{ id: 'n', type: 'toast', text: 'Saved', action: { label: 'Undo', state: 'focus' } }]); + check('P2: a focused toast action draws the ring', toast.includes(ringCss(RING))); + const toastOff = render([{ id: 'n', type: 'toast', text: 'Saved', action: { label: 'Undo', disabled: true } }]); + check('P2: a disabled toast action renders at 0.38', toastOff.includes('opacity: 0.38') && toastOff.includes('tabindex="-1"')); +} + +// ── P5: a canvas with no state draws no state ──────────────────────────── +{ + const plain = render([ + { id: 'a', type: 'button', label: 'S' }, { id: 'b', type: 'link', label: 'L' }, { id: 'c', type: 'nav-item', label: 'N', active: true }, + { id: 'd', type: 'tabs', items: [{ label: 'A', active: true }, { label: 'B' }] }, { id: 'e', type: 'text-input', placeholder: 'x' }, + { id: 'f', type: 'checkbox', checked: true }, { id: 'g', type: 'modal', title: 'M', actions: [{ label: 'OK', variant: 'primary' }] }, + ]); + check('P5: no state prop, no layer, no ring, no state opacity', !plain.includes('linear-gradient(color-mix') && !/outline: 2px solid/.test(plain.replace('[data-focusable]:focus-visible { outline: 2px solid var(--fs-ring, #2563EB); outline-offset: 2px; }', '')) && !plain.includes('opacity: 0.38')); +} + +// ── P6: the census readers ─────────────────────────────────────────────── +function canvasOf(type: 'web' | 'desktop-app' | 'mobile', children: SceneNode[]): Canvas { + const w = type === 'mobile' ? 390 : 1440; + return { + id: 'c', name: 'c', projectId: 'p', components: {}, variables: {}, createdAt: '', lastModified: '', + root: { id: 'document', type: 'document', name: 'Document', width: w, height: 900, fill: '#FFFFFF', layout: 'vertical', padding: 40, children }, + metadata: { surface: type === 'web' ? { type } : type === 'mobile' ? { type, device: 'iphone-390' } : { type, device: 'window-1440' } }, + } as Canvas; +} +async function floorFindings(type: 'web' | 'desktop-app', children: SceneNode[]) { + const r = await evaluateCanvas(canvasOf(type, children), { mode: 'fast', categories: ['usability'] }); + return r.issues.filter((i) => /24px floor/.test(i.message)); +} + +for (const type of ['web', 'desktop-app'] as const) { + const small = (extra: Partial): SceneNode => ({ id: 'b', name: 'b', type: 'button', icon: 'x', ariaLabel: 'Close', size: 'xs', width: 20, height: 20, ...extra }); + check(`P6 ${type}: an undersized button warns`, (await floorFindings(type, [small({})])).length === 1); + check(`P6 ${type}: with state disabled it is not measured`, (await floorFindings(type, [small({ state: 'disabled' })])).length === 0); + check(`P6 ${type}: with state hover it still is`, (await floorFindings(type, [small({ state: 'hover' })])).length === 1); + const row = (extra: Partial): SceneNode => ({ id: 'r', name: 'r', type: 'nav-item', label: 'Inbox', height: 20, ...extra }); + check(`P6 ${type}: a 20px nav-item warns; state disabled skips it`, (await floorFindings(type, [row({})])).length === 1 && (await floorFindings(type, [row({ state: 'disabled' })])).length === 0); +} + +{ + const tabsT = desktopTargets({ id: 't', type: 'tabs', items: [{ label: 'A', state: 'disabled' }, { label: 'B', state: 'hover' }, { label: 'C', disabled: true }] }); + check('P6: desktopTargets reads a tab\'s state disabled', tabsT.map((t) => t.disabled).join() === 'true,false,true'); + const hostT = desktopTargets({ id: 't', type: 'tabs', state: 'disabled', items: [{ label: 'A' }, { label: 'B' }] }); + check('P6: a tabs node with state disabled disables every target', hostT.every((t) => t.disabled)); + check('P6: desktopTargets reads a row\'s state disabled', desktopTargets({ id: 'm', type: 'menu-row', label: 'X', state: 'disabled' })[0].disabled && !desktopTargets({ id: 'm', type: 'menu-row', label: 'X', state: 'pressed' })[0].disabled); + const modalT = overlayTargets({ id: 'm', type: 'modal', title: 'T', actions: [{ label: 'A', state: 'disabled' }, { label: 'B' }, { label: 'C', disabled: true }] }); + check('P6: overlayTargets reads a modal action\'s disabled state; the close button stays live', modalT.map((t) => t.disabled).join() === 'false,true,false,true', JSON.stringify(modalT)); + check('P6: overlayTargets reads a toast action\'s state', overlayTargets({ id: 't', type: 'toast', text: 'x', action: { label: 'Undo', state: 'disabled' } })[0].disabled + && !overlayTargets({ id: 't', type: 'toast', text: 'x', action: { label: 'Undo' } })[0].disabled); + + const entry = (node: SceneNode) => [{ node, parent: null, depth: 0 }]; + const bar: SceneNode = { id: 'tb', type: 'tab-bar', items: [{ icon: 'house', label: 'A', state: 'disabled' }, { icon: 'search', label: 'B' }] }; + check('P6: the 24px census skips a disabled tab-bar item', pointerTargets(entry(bar) as never, 1440).map((t) => t.disabled).join() === 'true,false'); + const barOff: SceneNode = { ...bar, state: 'disabled', items: [{ icon: 'house', label: 'A' }, { icon: 'search', label: 'B' }] }; + check('P2: a tab-bar node ignores its own state (its tabs stay in the census)', pointerTargets(entry(barOff) as never, 1440).every((t) => !t.disabled)); + check('P2 twin: a tab-bar node with disabled: true still disables its tabs', pointerTargets(entry({ ...barOff, state: undefined, disabled: true }) as never, 1440).every((t) => t.disabled)); + const nb: SceneNode = { id: 'nb', type: 'nav-bar', leading: { icon: 'chevron-left', disabled: true }, trailing: [{ icon: 'plus' }, { icon: 'x', state: 'disabled' }] }; + check('P6: the 24px census skips a disabled nav-bar action', pointerTargets(entry(nb) as never, 1440).map((t) => t.disabled).join() === 'true,false,true'); + check('P2: a nav-bar node ignores its own state', pointerTargets(entry({ id: 'nb2', type: 'nav-bar', state: 'disabled', trailing: [{ icon: 'plus' }] }) as never, 1440).every((t) => !t.disabled)); + check('P2: a frame with state disabled is no target', pointerTargets(entry({ id: 'f', type: 'frame', state: 'disabled', width: 10, height: 10 }) as never, 1440).length === 0); +} + +// Mobile's 44px census never exempted disabled targets, and still does not. +{ + const r = await evaluateCanvas(canvasOf('mobile', [{ id: 'b', name: 'b', type: 'button', label: 'Go', size: 'sm', state: 'disabled' }]), { mode: 'fast', categories: ['usability'] }); + check('P6: the mobile touch census still measures a disabled sm button', r.issues.some((i) => i.rule === 'mobile-touch-target' && i.nodeId === 'b')); +} + +// Primary count: a disabled primary is not a primary. +{ + const count = async (children: SceneNode[]) => + (await evaluateCanvas(canvasOf('desktop-app', children), { mode: 'fast', categories: ['structure'] })).issues.filter((i) => i.rule === 'desktop-app-primary-count').length; + const p = (id: string, extra: Partial = {}): SceneNode => ({ id, name: id, type: 'button', label: id, size: 'sm', ...extra }); + check('P6: two primaries in one pane raise the info', (await count([p('One'), p('Two')])) === 1); + check('P6: one of them with state disabled does not', (await count([p('One'), p('Two', { state: 'disabled' })])) === 0); + check('P6 twin: one of them with state hover still does', (await count([p('One'), p('Two', { state: 'hover' })])) === 1); + const modal = (a: SceneNode['actions']): SceneNode => ({ id: 'm', name: 'm', type: 'modal', title: 'M', actions: a }); + check('P6: two primary modal actions raise the info', (await count([modal([{ label: 'A', variant: 'primary' }, { label: 'B', variant: 'primary' }])])) === 1); + check('P6: one disabled modal primary does not', (await count([modal([{ label: 'A', variant: 'primary' }, { label: 'B', variant: 'primary', state: 'disabled' }])])) === 0); +} + +check('the constants are Material 3\'s', JSON.stringify(STATE_LAYERS) === JSON.stringify({ hover: 0.08, focus: 0.10, pressed: 0.10, disabledContent: 0.38, disabledContainer: 0.12 })); + +console.log(allPass ? '\nALL PASS' : '\nSOME FAILED'); +process.exit(allPass ? 0 : 1); From 6896c88cc3bf38faac006bb5b0f35af1ada115c5 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Tue, 17 Nov 2026 16:43:53 +0100 Subject: [PATCH 3/5] Fix the slice G verify round 1 findings --- README.md | 32 +++---- VISION.md | 1 + docs/GUIDELINES.md | 36 +++++--- docs/specs/PHASE-31-SPEC.md | 2 + src/evaluate.ts | 2 + src/index.ts | 8 +- src/renderer.ts | 110 +++++++++++++++--------- src/types.ts | 4 + src/variables.ts | 15 ++-- test-element-states.ts | 167 +++++++++++++++++++++++++++++++++++- 10 files changed, 296 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index 15a1b16..fd07378 100644 --- a/README.md +++ b/README.md @@ -358,10 +358,10 @@ Phone screens are built from seven primitives that carry their own sizes, 44px h |---|---|---| | `status-bar` | `time`, `appearance` | Device chrome pinned to the top, as tall as the root's `safeArea.top` (47 without one) | | `home-indicator` | `appearance` | The home pill pinned to the bottom, as tall as `safeArea.bottom` (34) | -| `nav-bar` | `title`, `leading`, `trailing` (≤2), `largeTitle` | 44 tall (96 large), in flow; every action a 44×44 target | -| `tab-bar` | `items: [{ icon, label, active?, badge? }]`, `variant` (`standard` / `floating` / `fab`), `fab` | Pinned to the bottom, 49 + the inset; 2–5 labeled tabs; `fab` adds a raised 56px centre action | -| `button` | `label`, `icon`, `iconPosition`, `variant`, `size` (`xs` 24 / `sm` 32 / `md` 44 / `lg` 52), `ariaLabel`, `disabled` | `md` meets the phone floor; `sm` and `xs` are mobile errors by design. An icon-only button takes `ariaLabel` as its accessible name (`aria-label` and `title`, never drawn) | -| `list-row` | `title`, `subtitle`, `leading`, `trailing` (`text` / `chevron` / `toggle` / `badge`), `divider` | 44 tall (56 with a subtitle); repeated rows count as reuse | +| `nav-bar` | `title`, `leading`, `trailing` (≤2), `largeTitle`; each action takes `state` | 44 tall (96 large), in flow; every action a 44×44 target | +| `tab-bar` | `items: [{ icon, label, active?, badge?, state? }]`, `variant` (`standard` / `floating` / `fab`), `fab` | Pinned to the bottom, 49 + the inset; 2–5 labeled tabs; `fab` adds a raised 56px centre action | +| `button` | `label`, `icon`, `iconPosition`, `variant`, `size` (`xs` 24 / `sm` 32 / `md` 44 / `lg` 52), `ariaLabel`, `disabled`, `state` | `md` meets the phone floor; `sm` and `xs` are mobile errors by design. An icon-only button takes `ariaLabel` as its accessible name (`aria-label` and `title`, never drawn) | +| `list-row` | `title`, `subtitle`, `leading`, `trailing` (`text` / `chevron` / `toggle` / `badge`), `divider`, `state` | 44 tall (56 with a subtitle); repeated rows count as reuse | | `sheet` | `detent`, `grabber`, children | A bottom sheet over a scrim, padded past the home indicator | `fill`, `stroke`, `color`, `iconColor`, `secondaryColor` (list-row subtitle and trailing) and `badgeColor` (badges) override the token defaults. @@ -386,18 +386,18 @@ Application screens (`type: "desktop-app"`) are built from eight primitives on t | Type | Key props | What it is | |---|---|---| -| `link` | `label`, `icon`, `iconPosition`, `external`, `ariaLabel` | A standalone text action, at least 24 tall. With no `label` it hugs its glyphs (14px wide, 30 with `external`) and needs an `ariaLabel` (rendered as `aria-label` and `title`). A `text` node can hold inline links instead: `links: [{ start, end }]` character ranges of its content, drawn underlined and exempt from the 24px floor | -| `text-input` | `value`, `placeholder`, `icon`, `size` (`sm` 32 / `md` 40), `rows`, `error` (a message), `disabled` | A field whose border (`$border-strong` when the design system has it) is its only boundary; `error` draws an icon and the message below and turns the border `$danger` | -| `nav-item` | `label`, `icon`, `count`, `dotColor`, `active`, `depth` (0 / 1), `collapsed` | A 32px sidebar row. `active` draws an `$accent-tint` fill, a 2px `$accent` bar and a heavier label; `collapsed` is the 32×32 rail form, with the label as its accessible name; `dotColor` is an identity dot, never counted as an accent | -| `tabs` | `items: [{ label, count?, active?, disabled? }]`, `variant` (`line` / `contained`), `size` (`sm` 32 / `md` 40) | One tablist; each tab is its own target. The active tab gets an indicator (`line`) or an `$accent-tint` fill (`contained`) | -| `tree-row` | `label`, `depth`, `expanded` (absent for a leaf), `icon`, `active` | A 32px row indented 16px per level, with a chevron when `expanded` is set | -| `menu-row` | `label`, `icon`, `shortcut`, `checked`, `destructive`, `disabled`, `submenu` | A 32px menu item; the shortcut right-aligns in a muted `kbd` style, `destructive` uses `$danger` | +| `link` | `label`, `icon`, `iconPosition`, `external`, `ariaLabel`, `state` | A standalone text action, at least 24 tall. With no `label` it hugs its glyphs (14px wide, 30 with `external`) and needs an `ariaLabel` (rendered as `aria-label` and `title`). A `text` node can hold inline links instead: `links: [{ start, end }]` character ranges of its content, drawn underlined and exempt from the 24px floor | +| `text-input` | `value`, `placeholder`, `icon`, `size` (`sm` 32 / `md` 40), `rows`, `error` (a message), `disabled`, `state` | A field whose border (`$border-strong` when the design system has it) is its only boundary; `error` draws an icon and the message below and turns the border `$danger` | +| `nav-item` | `label`, `icon`, `count`, `dotColor`, `active`, `depth` (0 / 1), `collapsed`, `state` | A 32px sidebar row. `active` draws an `$accent-tint` fill, a 2px `$accent` bar and a heavier label; `collapsed` is the 32×32 rail form, with the label as its accessible name; `dotColor` is an identity dot, never counted as an accent | +| `tabs` | `items: [{ label, count?, active?, disabled?, state? }]`, `variant` (`line` / `contained`), `size` (`sm` 32 / `md` 40) | One tablist; each tab is its own target. The active tab gets an indicator (`line`) or an `$accent-tint` fill (`contained`) | +| `tree-row` | `label`, `depth`, `expanded` (absent for a leaf), `icon`, `active`, `state` | A 32px row indented 16px per level, with a chevron when `expanded` is set | +| `menu-row` | `label`, `icon`, `shortcut`, `checked`, `destructive`, `disabled`, `submenu`, `state` | A 32px menu item; the shortcut right-aligns in a muted `kbd` style, `destructive` uses `$danger` | | `property-row` | `label`, `labelWidth` (96), one child | An inspector row: a muted label column, then its value (a control, a `text-input`, a `button`, a text). A control that is its only target is measured by the row's box. The row's `label` names a control directly inside it; with a blank label only text inside the row itself does (a sibling row's text does not count). The other desktop-app primitives drop any children | | `divider` | `orientation` (`horizontal` / `vertical`), `inset` | A 1px `$border` hairline; vertical dividers separate panes | `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 (8 / 10 / 10%), focus adds a 2px `$focus-ring` at a 2px gap, and disabled renders in `$text-primary` at 38% (a drawn fill or border at 12%), or at 0.5 without state tokens. 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. 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. `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 @@ -408,8 +408,8 @@ Six overlays draw screen states: an open menu, a comment popover, a confirm dial | `tooltip` | `text`, `x`, `y` | A short hint, inverted, wrapping at 240px; never renders children | | `popover` | `x`, `y`, `size` (`xs` 192 / `sm` 320 / `md` 480 / `lg` 640), children | A panel (vertical, 12px padding by default) for a comment box or a filter form | | `menu` | `x`, `y`, children (`menu-row`s, `divider`s) | A menu at least 192 wide, hugging its rows | -| `modal` | `title`, `size` (`sm` 480 / `md` 640 / `lg` 960), `actions: [{ label, variant? }]`, `closeLabel`, children | Centred over its own full scrim, with a close button named "Close"; actions right-aligned, the filled one (`primary` or `destructive`) rightmost, an action with no variant `secondary` | -| `toast` | `text`, `tone` (`neutral` / `success` / `warning` / `danger`), `action: { label }` | Bottom-centre, 24px above the artboard's edge; the tone colours a leading glyph | +| `modal` | `title`, `size` (`sm` 480 / `md` 640 / `lg` 960), `actions: [{ label, variant?, state? }]`, `closeLabel`, children | Centred over its own full scrim, with a close button named "Close"; actions right-aligned, the filled one (`primary` or `destructive`) rightmost, an action with no variant `secondary` | +| `toast` | `text`, `tone` (`neutral` / `success` / `warning` / `danger`), `action: { label, state? }` | Bottom-centre, 24px above the artboard's edge; the tone colours a leading glyph | | `drawer` | `size` (`sm` 320 / `md` 480), `scrim`, children | A panel pinned to the right edge at full height | ``` @@ -1221,12 +1221,12 @@ I("parent", { type: "checkbox", checked: true }) I("parent", { type: "radio" }) I("parent", { type: "select", value: "Administrator", width: 220 }) I("parent", { type: "select" }) # renders a muted "Select…" placeholder -I("parent", { type: "toggle", checked: true, disabled: true }) # 50% opacity +I("parent", { type: "toggle", checked: true, disabled: true }) # 38% in $text-primary with disabled state tokens, else 50% ``` Colors default from the design system — `$accent` (falling back to `$primary`) for active states, `$border` for outlines, `$bg-surface` / `$text-primary` for the select — with neutral fallbacks on unthemed canvases. Explicit `fill` / `stroke` / `color` override. Defaults: toggle 44×24, checkbox/radio 18×18, select `fit-content` (give it a `width` for form layouts). -All four controls are keyboard-focusable in the live viewer (`tabindex="0"`, an accent-derived `:focus-visible` ring) — that's a live-viewer-only affordance and never changes a screenshot, since nothing is focused in a static capture. `canvas_evaluate`'s `usability` category checks the things the renderer can't guarantee on its own: hit-target size, label association, and honest action copy — see the categories table below. +All four controls are keyboard-focusable in the live viewer (`tabindex="0"`, a `:focus-visible` ring in `$focus-ring`, else `$accent`). A live focus never changes a capture, since nothing is focused in one; to draw the ring in a screenshot, set `state: "focus"` (see Element states above). `canvas_evaluate`'s `usability` category checks the things the renderer can't guarantee on its own: hit-target size, label association, and honest action copy — see the categories table below. ## SVG Paths @@ -1258,7 +1258,7 @@ Built-in keyframe names: `fadeIn`, `slideUp`, `slideDown`, `scaleIn`. All end at `animation`: `{ name, duration?: 300ms, delay?: 0ms, easing?: "ease-out", iteration?: 1 | "infinite" }`. Easing is whitelisted: `ease`, `ease-in`, `ease-out`, `ease-in-out`, `linear` (anything else falls back to `ease-out`). -`transition`: `{ property?: "all", duration, easing?: "ease", delay?: 0ms }`. Transitions only fire on state change, so they're inert until interactive states exist in the renderer — included today so a future hover/focus PR has a place to land. +`transition`: `{ property?: "all", duration, easing?: "ease", delay?: 0ms }`. Transitions only fire on a live state change (hover or focus in the viewer); a static `state` render has nothing to animate. ## Components diff --git a/VISION.md b/VISION.md index 09ae048..2666f43 100644 --- a/VISION.md +++ b/VISION.md @@ -572,6 +572,7 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 - [x] Slice E — overlays: one overlay layer at the root with a fixed ladder, and the `tooltip`, `popover`, `menu`, `modal`, `toast` and `drawer` primitives, with overlay screen states as variants - [x] Slice F — overlay rules: one modal, text-only tooltips, no large tables in modals, overlays inside the viewport, nothing under a scrim, and advisories on stacked toasts, error toasts and dangling anchors - [x] Slice G — element states: hover, focus, pressed and disabled as a primitive property (and on the items of tabs, tab-bar, nav-bar, modal and toast), drawn from state tokens; focus is a 2px ring at a 2px gap, disabled renders in the on-surface colour, and `state: "disabled"` counts as disabled in the 24px census and the primary count +- [ ] Follow-up — a disabled control inside a component instance renders undimmed, because instances render after variable resolution (`resolveInstance`); resolve instance subtrees too, so `disabled` and `state` dim inside components as they do outside - [ ] Slice H — state checks: focus rings, active indicators, disabled renders and control boundaries checked analytically on every interactive primitive, without being drawn - [ ] 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 diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 3cc7f84..23cc51e 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -119,12 +119,12 @@ Mobile keeps its own 44px rule (`mobile-touch-target`), which has no spacing exc Build application screens from these primitives, never from hand-built frames: a frame is not a measured target, and none of the app rules can see it. They sit on the 24 / 32 / 40 / 48 density ladder and take their colours from `$accent`, `$accent-tint`, `$border`, `$border-strong`, `$text-primary`, `$text-secondary` and `$danger` (neutral fallbacks unthemed; `fill`, `stroke`, `color`, `iconColor`, `secondaryColor` override). Labels truncate to one line with an ellipsis and keep their full text as a `title`, so `canvas_stress` reports a designed truncation, not a clip. - **`button` at `size: "xs"`** is the 24px icon button of a dense toolbar. An icon-only button (no `label`) takes `ariaLabel` as its accessible name: it renders `aria-label` and `title` and is never drawn. `xs`, like `sm`, is an error on a phone. -- **`link`** `{ label, icon?, iconPosition?, external?, ariaLabel? }` is a standalone text action, at least 24 tall, and a measured target. Without a `label` it hugs its glyphs (14px wide, 30 with `external`) and takes `ariaLabel` as its name (rendered as `aria-label` and `title`). For a link inside a sentence, keep it in the `text` node: `links: [{ start, end }]` marks character ranges of its `content`, drawn underlined. Inline links are exempt from the 24px floor, as WCAG exempts them. A `text` node also takes `title`, rendered as a tooltip. +- **`link`** `{ label, icon?, iconPosition?, external?, ariaLabel?, state? }` is a standalone text action, at least 24 tall, and a measured target. Without a `label` it hugs its glyphs (14px wide, 30 with `external`) and takes `ariaLabel` as its name (rendered as `aria-label` and `title`). For a link inside a sentence, keep it in the `text` node: `links: [{ start, end }]` marks character ranges of its `content`, drawn underlined. Inline links are exempt from the 24px floor, as WCAG exempts them. A `text` node also takes `title`, rendered as a tooltip. - **`text-input`** `{ value?, placeholder?, icon?, size?: "sm" | "md", rows?, error?, disabled?, state? }` is a field (32 or 40 tall; `rows` makes it multi-line). Its border is its only boundary, so it uses `$border-strong` when the design system has one. `error` turns the border `$danger` and draws an icon and the message below the field, so the error is never colour alone. -- **`nav-item`** `{ label, icon?, count?, dotColor?, active?, depth?: 0 | 1, collapsed? }` is a 32px sidebar row that spans its sidebar. `active` draws three cues: an `$accent-tint` fill, a 2px `$accent` bar, and a heavier label (and `aria-current`). `collapsed` is the 32×32 rail form, with its label as the accessible name. `dotColor` is an identity dot for a project or label: it is never counted as a competing accent, though the same colour used anywhere else still is. -- **`tabs`** `{ items: [{ label, count?, active?, disabled? }], variant?: "line" | "contained", size?: "sm" | "md" }` is one tablist (32 or 40 tall). Each tab is its own target. The active tab gets an underline indicator (`line`) or an `$accent-tint` fill (`contained`, from the node's `fill`) and a heavier label. -- **`tree-row`** `{ label, depth, expanded?, icon?, active? }` is a 32px row indented 16px per level. `expanded: true` / `false` draws an open / closed chevron; a leaf leaves it out and keeps the slot, so labels align. -- **`menu-row`** `{ label, icon?, shortcut?, checked?, destructive?, disabled?, submenu? }` is a 32px menu item. The shortcut right-aligns in a muted `kbd` style, `destructive` uses `$danger`, `submenu` adds a chevron, and `checked` reserves a check slot. +- **`nav-item`** `{ label, icon?, count?, dotColor?, active?, depth?: 0 | 1, collapsed?, state? }` is a 32px sidebar row that spans its sidebar. `active` draws three cues: an `$accent-tint` fill, a 2px `$accent` bar, and a heavier label (and `aria-current`). `collapsed` is the 32×32 rail form, with its label as the accessible name. `dotColor` is an identity dot for a project or label: it is never counted as a competing accent, though the same colour used anywhere else still is. +- **`tabs`** `{ items: [{ label, count?, active?, disabled?, state? }], variant?: "line" | "contained", size?: "sm" | "md" }` is one tablist (32 or 40 tall). Each tab is its own target. The active tab gets an underline indicator (`line`) or an `$accent-tint` fill (`contained`, from the node's `fill`) and a heavier label. +- **`tree-row`** `{ label, depth, expanded?, icon?, active?, state? }` is a 32px row indented 16px per level. `expanded: true` / `false` draws an open / closed chevron; a leaf leaves it out and keeps the slot, so labels align. +- **`menu-row`** `{ label, icon?, shortcut?, checked?, destructive?, disabled?, submenu?, state? }` is a 32px menu item. The shortcut right-aligns in a muted `kbd` style, `destructive` uses `$danger`, `submenu` adds a chevron, and `checked` reserves a check slot. - **`property-row`** `{ label, labelWidth? }` with one child is an inspector row: a muted label column (96px by default) and the value (a control, a `text-input`, a `button`, a text). Every row's value starts at the same edge. The row's `label` names a control directly inside it; with a blank label only text inside the row itself does, and otherwise the control gets the usability warning "has no text label" (a sibling row's text does not count). A control that is its only target (directly inside, nothing clickable beside it) is measured by the row's 32px box. Only `property-row` renders children; the other desktop-app primitives draw their own anatomy and drop any children you give them. - **`divider`** `{ orientation?: "horizontal" | "vertical", inset? }` is a 1px `$border` hairline; vertical dividers separate panes. Not a target. @@ -146,8 +146,8 @@ The six overlays take their colours from `$bg-surface`, `$border`, `$text-primar - **`tooltip`** `{ text, x, y }` is a short hint, inverted (`$text-primary` fill, `$bg-surface` text, so light on a dark theme), wrapping at 240px. Text only: it never renders children. - **`popover`** `{ x, y, size?: "xs" | "sm" | "md" | "lg", children }` is a panel 192 / 320 / 480 / 640 wide (320 by default; a numeric `width` wins), vertical with 12px padding by default; `layout`, `gap` and `padding` apply as on a frame. A comment box or a filter form. - **`menu`** `{ x, y, children }` holds `menu-row`s and `divider`s: 4px padding, at least 192 wide, hugging its rows. -- **`modal`** `{ title, size?: "sm" | "md" | "lg", actions?: [{ label, variant? }], closeLabel?, children }` is 480 / 640 / 960 wide (640 by default), centred over its own scrim, which always covers the artboard (`x` / `y` place the modal's top-left instead). It is never taller than the artboard less 64px (less the insets on a phone). Its header holds the title and a close button named "Close" (`closeLabel` renames it). The body holds the children (vertical, 12px gap) and scrolls when tall, between the header and the actions. `actions` render right-aligned as 32px buttons; an action with no variant renders `secondary`, and the filled ones (`primary`, `destructive`) render rightmost. For a delete confirmation: `actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }]`. -- **`toast`** `{ text, tone?: "neutral" | "success" | "warning" | "danger", action?: { label } }` sits bottom-centre, 24px above the artboard's bottom edge (`x` / `y` place its top-left instead); it hugs its text up to 480px. The tone colours a leading glyph (`$success`, `$warning`, `$danger`, neutral `$text-secondary`; `iconColor` overrides); the text stays `$text-primary`. `danger` renders `role="alert"`. +- **`modal`** `{ title, size?: "sm" | "md" | "lg", actions?: [{ label, variant?, state? }], closeLabel?, children }` is 480 / 640 / 960 wide (640 by default), centred over its own scrim, which always covers the artboard (`x` / `y` place the modal's top-left instead). It is never taller than the artboard less 64px (less the insets on a phone). Its header holds the title and a close button named "Close" (`closeLabel` renames it). The body holds the children (vertical, 12px gap) and scrolls when tall, between the header and the actions. `actions` render right-aligned as 32px buttons; an action with no variant renders `secondary`, and the filled ones (`primary`, `destructive`) render rightmost. For a delete confirmation: `actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }]`. +- **`toast`** `{ text, tone?: "neutral" | "success" | "warning" | "danger", action?: { label, state? } }` sits bottom-centre, 24px above the artboard's bottom edge (`x` / `y` place its top-left instead); it hugs its text up to 480px. The tone colours a leading glyph (`$success`, `$warning`, `$danger`, neutral `$text-secondary`; `iconColor` overrides); the text stays `$text-primary`. `danger` renders `role="alert"`. - **`drawer`** `{ size?: "sm" | "md", scrim?, children }` is a 320 / 480 panel pinned to the right edge at full height, 16px padding; `scrim: true` dims what is behind it. A modal's close button and actions (32 tall) and a toast's action (24 tall) are pointer targets. They are sized for a pointer, so on a phone use a `sheet` for a dialog. A modal and a drawer are panes: navigation and primary buttons inside them are judged apart from the page behind. @@ -161,12 +161,22 @@ An **element state** belongs to one target: hover, focus, pressed or disabled. I 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. - **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 (Material 3's 8%, 10% and 10% without them): a filled primary lightens, a ghost or secondary button tints, a row tints over its active fill. 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 toggle it is the knob's (white). +- **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). - **Focus** also draws a 2px `$focus-ring` outline at a 2px gap, so the ring meets only the backdrop, never a brand fill; without a `$focus-ring` token it is `$accent`, then `$primary`, then `#2563EB`. A tab and a tab-bar item draw it inside their box, since the tablist and a floating bar clip. The live viewer's keyboard focus draws the same ring. -- **Disabled.** With the state tokens (`generate_design_system` writes them), a disabled target renders in `$text-primary`: its content at `disabledContent` (38%) and a drawn fill or border at `disabledContainer` (12%), so a disabled primary reads as a grey version of itself on light and dark. Without them it renders at today's 0.5 opacity in its own colours. An authored `opacity` wins over both. `disabled: true` means disabled whatever `state` says, and a `tabs` node's own `disabled` (or `state: "disabled"`) disables every tab. +- **Disabled.** When the `state` tokens set `disabledContent` or `disabledContainer` (`generate_design_system` writes both; a lone one takes the other's Material value, 0.38 or 0.12), a disabled target renders in `$text-primary`: its content at `disabledContent` and a drawn fill or border at `disabledContainer`, so a disabled primary reads as a grey version of itself on light and dark. A check mark, a toggle knob and a badge numeral take `$bg-surface`, so they show on that grey. A fill that paints nothing stays clear. When neither is set it renders at 0.5 opacity in its own colours, as it did before element states existed. An authored `opacity` wins over both. A truthy `disabled` means disabled whatever `state` says (`disabled: false` with `state: "disabled"` is disabled too), and a `tabs` node's own `disabled` (or `state: "disabled"`) disables every tab. `state: "rest"` is the default and changes nothing. - **Disabled is the same fact either way.** `state: "disabled"` leaves the tab order (`tabindex="-1"`, `aria-disabled`) and leaves the 24px census and the primary count exactly as `disabled: true` does. The mobile 44px census, which never exempted a disabled target, still measures it. - **`active`, `checked` and `expanded` combine with `state`**: a hovered active nav-item keeps its tint, bar and weight under the layer. +A states sheet for a toolbar button, a tablist and a sidebar row: + +``` +I(row, { type: "button", label: "Save", size: "sm", state: "hover" }) +I(row, { type: "button", label: "Save", size: "sm", state: "focus" }) +I(row, { type: "button", label: "Save", size: "sm", state: "disabled" }) +I(col, { type: "tabs", items: [{ label: "Issues", active: true }, { label: "Layout", state: "hover" }, { label: "History", state: "disabled" }] }) +I(col, { type: "nav-item", label: "Inbox", active: true, state: "hover" }) +``` + ### Lists that lead with a mark are not tables (every type) A list whose every row starts with a mark (an icon, a dot, or a small image) is navigation, not data: a sidebar of projects with an identity dot, a name and a count. Table detection skips it, so `coverage` never asks for an empty or loading state for your navigation, and `canvas_stress` perturbs its labels as ordinary text. A table with a text header row still detects, even when every data row leads with an avatar. @@ -179,10 +189,10 @@ Build phone screens from the mobile primitives, not hand-built frames. Each one |---|---|---| | `status-bar` | `time` (`"9:41"`), `appearance` (`"dark"` glyphs for a light screen, `"light"` for a dark one; default `color`) | Device chrome, pinned (`fixed`) to the top, as tall as the root's `safeArea.top` (47 without one) | | `home-indicator` | `appearance` | The 134×5 pill, pinned to the bottom, as tall as `safeArea.bottom` (34) | -| `nav-bar` | `title`, `leading` (`{ icon?, label? }`, icon defaults to `chevron-left`), `trailing` (up to two `{ icon }` / `{ label }`), `largeTitle` | 44 tall in flow (96 with `largeTitle`: the 44px action row plus a 52px row holding a 34px bold title); every action is a 44×44 target | -| `tab-bar` | `items: [{ icon, label, active?, badge? }]`, `variant` (`standard` / `floating` / `fab`), `fab: { icon }` | Pinned to the bottom, 49 plus the bottom inset (`safeArea.bottom`, 34 without one); `floating` is an inset pill; `fab` adds a raised 56px centre action (16px more box), which is not a tab | -| `button` | `label`, `icon`, `iconPosition`, `variant` (`primary` / `secondary` / `ghost` / `destructive`), `size` (`xs` 24 / `sm` 32 / `md` 44 / `lg` 52), `ariaLabel`, `disabled` | Never narrower than tall; icon-only is square; `width: "100%"` for a full-width CTA. `xs` and `sm` are for pointer surfaces and are errors on a phone; an icon-only button takes `ariaLabel` as its accessible name | -| `list-row` | `title`, `subtitle`, `leading` (`{ icon }` / `{ initials }` / `{ image }`), `trailing` (`{ text }` / `{ chevron: true }` / `{ toggle: true }` / `{ badge }`), `divider` | 44 tall (56 with a subtitle), spanning its list. Repeated rows count as reuse | +| `nav-bar` | `title`, `leading` (`{ icon?, label?, state? }`, icon defaults to `chevron-left`), `trailing` (up to two `{ icon }` / `{ label }`, each with `state?`), `largeTitle` | 44 tall in flow (96 with `largeTitle`: the 44px action row plus a 52px row holding a 34px bold title); every action is a 44×44 target | +| `tab-bar` | `items: [{ icon, label, active?, badge?, state? }]`, `variant` (`standard` / `floating` / `fab`), `fab: { icon }` | Pinned to the bottom, 49 plus the bottom inset (`safeArea.bottom`, 34 without one); `floating` is an inset pill; `fab` adds a raised 56px centre action (16px more box), which is not a tab | +| `button` | `label`, `icon`, `iconPosition`, `variant` (`primary` / `secondary` / `ghost` / `destructive`), `size` (`xs` 24 / `sm` 32 / `md` 44 / `lg` 52), `ariaLabel`, `disabled`, `state` | Never narrower than tall; icon-only is square; `width: "100%"` for a full-width CTA. `xs` and `sm` are for pointer surfaces and are errors on a phone; an icon-only button takes `ariaLabel` as its accessible name | +| `list-row` | `title`, `subtitle`, `leading` (`{ icon }` / `{ initials }` / `{ image }`), `trailing` (`{ text }` / `{ chevron: true }` / `{ toggle: true }` / `{ badge }`), `divider`, `state` | 44 tall (56 with a subtitle), spanning its list. Repeated rows count as reuse | | `sheet` | `detent` (`medium` / `large` / `auto`), `grabber` (default true), `padding`, `gap`, children | A bottom sheet over a dimmed scrim, padded past the home indicator; its children scroll inside it | **Pinning.** `position: "fixed"` pins a node to the screen: the root's width × height is the viewport, and content taller than it scrolls. `y` / `bottom` measure from the screen's top / bottom, `x` / `right` from the root's edges. A fixed node with no `x`, `right` or `width` spans the root's column; with no `y` or `bottom` it sticks to the top. `position: "sticky"` sticks at its `y` (or `bottom`) while its container scrolls. The chrome primitives default to fixed; override their `position` only for a deliberate composition (a `status-bar` set to `absolute` lets a full-bleed hero image run under it). The renderer raises the root's top and bottom padding to at least the reach of any pinned `status-bar`, `tab-bar` or `home-indicator`, so content never starts or ends under chrome. A fixed node inside a frame with `blur`, `backdropBlur`, `backdropFilter` or a slideUp / slideDown / scaleIn `animation` pins to that frame instead (CSS), so keep pinned bars out of them. `fullPage` captures grow to the content, so a bottom-pinned bar lands at the end of the image. diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 2818fdc..436c7d6 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -363,6 +363,8 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **Q6: layer percentages are rounded to two decimals** (`Math.round(x × 10000) / 100`), as is the container share (0.12 / 0.38 → 31.58%). Slice H's analytical model must round the same way to agree with the render. - **Q7: the modal close button** carries the modal's resolved ring colour (it takes no state, P2). - **Q8: tests.** `test-element-states.ts` (fast) and `test-element-states-render.ts` (full: four button variants × five states, two renders each, both themes, plus a frame twin); `test-discoverability.ts` checks each surface's element-states paragraph names every `STATEFUL_TYPES` entry and the state names. +- **Verify round 1 fixes** (each proved red on 5fbbbf3 and green on the fix, with its nearest keep-cases unchanged; F2 also checked against a0d550a). (F1) S10's white check mark, toggle knob and badge numerals vanished on the near-white dark-theme on-surface: a mark drawn on a disabled container now takes the surface colour (`StateStyle.surface`: `$bg-surface`, else `$surface`, else `#FFFFFF`); enabled and tokenless marks stay white. (F2) `disabled` lost its pre-slice truthiness (`disabled: "true"` stopped dimming), and an overlay or any other non-P2 node with `disabled: true` lost its 0.5 on a canvas with the token pair: resolution sets 0.5 for a truthy `disabled` (or a P2 node's `state: "disabled"`) unless the node is a P2 type that draws the pair, and the renderer reads a truthy `disabled` as disabled; the census keeps `disabled === true`, as before. Against a0d550a the only render differences left are the new `state: "disabled"` spelling and the pair on P2 types. (F3) a disabled text-input's error message took the border's container share (about 12% effective); it is content, so it takes the on-surface colour. (F4) a container spelled clear (`none`, a zero-alpha hex, `rgba()` or `hsla()`) took the on-surface share when disabled; it stays clear, while a translucent tint still takes the share. (F5) `state` joined `PRIMITIVE_COPY_PROPS`, so a states sheet's state props no longer dilute token adoption. Mutation testing (294 mutants, 76 survivors, about 22 equivalent) left the disabled paths of every type but the button, authored opacity, item inks, token resolution and host-style threading unasserted; tests now kill them (a representative 16 re-run, all killed). Dead code removed: `controlState`'s `whole` flag (the controls are neutralised first) and `tabs` in the legacy-opacity set (`renderTabs` never draws a node opacity). +- **Accepted as found (round 1):** a disabled control inside a component instance is not dimmed, because instances render unresolved (`resolveInstance` runs after resolution); it was so before slice G for `disabled: true`, and P5 keeps it (follow-up in VISION). A disabled toggle shows on and off by knob position only (Material's choice). The focus ring sits 4px outside the box, so a row flush against a clipping pane edge has its ring cut (S9's inset applies to tabs and tab-bar items only). A colour token aliased to another token (`accent: "$primary"`) reaches the ring unresolved, as everywhere else. Docs: the steward's nine edits and the cold reader's gaps (per-key token fallback, the radio's layer, `disabled: false` with `state: "disabled"`, no-fill targets, an example) are applied. **Slice H: state checks (FR-H1 to FR-H4)** - `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`. diff --git a/src/evaluate.ts b/src/evaluate.ts index b63d5e6..5a5b470 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -858,6 +858,8 @@ const PRIMITIVE_COPY_PROPS = new Set([ 'title', 'subtitle', 'label', 'time', 'variant', 'size', 'detent', 'appearance', 'iconPosition', // Phase 31 slice B — the desktop-app primitives' copy and enums. 'placeholder', 'value', 'shortcut', 'error', 'ariaLabel', 'count', 'orientation', + // Phase 31 slice G — the element state is an enum, not a style value. + 'state', ]); /** Spellings worth trying for an icon name that didn't resolve: Material diff --git a/src/index.ts b/src/index.ts index 1c229b4..6f9f4e6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 design system has state tokens, 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 24px census, not a primary); 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. 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.', @@ -579,7 +579,7 @@ Icons: two bundled sets render by name — use these instead of Unicode glyph st Components: I("parent", { type: "instance", componentId: "cmp-shell", overrides: { "": { content: "..." } } }) stamps a registered component (create_component promotes an existing subtree into one; overrides match def children by NAME). Instance-level props override the def root. -Input controls: toggle / checkbox / radio / select are real node types — I("parent", { type: "toggle", checked: true }), I("parent", { type: "select", value: "Admin", width: 200 }). Colors default from design tokens ($accent / $border / $bg-surface / $text-primary, neutral fallbacks when unthemed); fill / stroke / color override. NEVER fake a control from frames + ellipses. +Input controls: toggle / checkbox / radio / select are real node types — I("parent", { type: "toggle", checked: true }), I("parent", { type: "select", value: "Admin", width: 200 }). Colors default from design tokens ($accent / $border / $bg-surface / $text-primary, neutral fallbacks when unthemed); fill / stroke / color override; checked / disabled / state (see Element states below) set what they show. NEVER fake a control from frames + ellipses. Positioning: position "fixed" pins to the screen (the root's width × height is the viewport; content taller than it scrolls and the root grows to it), "sticky" sticks at its y (or bottom) while its container scrolls, "absolute" places against the nearest positioned ancestor. Offsets: x / y / bottom / right (px). A fixed node with no x, right or width spans the root's column; with no y or bottom it sticks to the top. The root grows with content taller than the artboard (a root child with height: "100%" fills what its siblings leave), so an absolute node with bottom set against the root measures from the end of the document, not the screen — use fixed to pin to the screen. A fixed node inside a frame with blur / backdropBlur / backdropFilter or a slideUp / slideDown / scaleIn animation pins to that frame instead of the screen (CSS), so keep pinned bars out of them. fullPage captures grow to the content, so a bottom-pinned bar captures at the end of the image. @@ -613,7 +613,7 @@ Overlays (screen states — put one in a state variant made with canvas_add_vari - drawer { size?: "sm"|"md" (320/480) or width, scrim?: false, children } — pinned to the right edge, full height, padding 16; scrim: true dims what is behind it. A modal's close button and actions and a toast's action are pointer targets (32 / 32 / 24 tall), sized for a pointer: on a phone use a sheet for a dialog. On a root with a safeArea or a pinned tab-bar, a centred modal, a default toast and a drawer keep clear of the insets and the tab bar. snapshot_layout lists every overlay under the root, and a modal (or a drawer with a scrim) carries its scrim's rect. -Element states (state?: "rest"|"hover"|"focus"|"pressed"|"disabled", default rest): on button, link, text-input, nav-item, tree-row, menu-row, list-row, toggle, checkbox, radio, select, and on the items of tabs, tab-bar, nav-bar (leading / trailing), modal (actions[]) and toast (action). Hover, focus and pressed layer the target's label colour over its fill (the state tokens' hover / focus / pressed, Material's 8 / 10 / 10% without them); focus adds a 2px $focus-ring outline at a 2px gap (inside the tab for a tab or tab-bar item); a link also underlines in hover and pressed; active, checked and expanded keep their fill under the layer. disabled (or disabled: true, which wins over any state) renders the whole target in $text-primary at the state tokens' disabledContent (38%), a drawn fill or border at disabledContainer (12%), when the design system has them, else at today's 0.5 opacity; an authored opacity wins. A tabs node's own state "disabled" disables every tab. Other node types ignore state. +Element states (state?: "rest"|"hover"|"focus"|"pressed"|"disabled", default rest): on button, link, text-input, nav-item, tree-row, menu-row, list-row, toggle, checkbox, radio, select, and on the items of tabs, tab-bar, nav-bar (leading / trailing), modal (actions[]) and toast (action). Hover, focus and pressed layer the target's label colour over its fill (the state tokens' hover / focus / pressed, Material's 8 / 10 / 10% without them); focus adds a 2px $focus-ring outline at a 2px gap (inside the tab for a tab or tab-bar item); a link also underlines in hover and pressed; active, checked and expanded keep their fill under the layer. disabled (or a truthy disabled, which wins over any state) renders the whole target in $text-primary at the state tokens' disabledContent (38%), a drawn fill or border at disabledContainer (12%), and a check mark, knob or badge numeral in $bg-surface, when the tokens set either disabled opacity (a lone one takes the other's Material value), else at 0.5 opacity in its own colours; an authored opacity wins. A disabled target leaves the tab order, the 24px census and the primary count (the phone's 44px census still measures it). A tabs node's own state "disabled" disables every tab. Other node types ignore state. Responsive layout (author desktop-first, adapt down): - responsive: "stack" — on a horizontal container, flips to vertical below 768px (multi-column layouts that should stack on mobile) @@ -977,7 +977,7 @@ server.tool( pressed: z.number().min(0).max(1).optional(), disabledContent: z.number().min(0).max(1).optional(), disabledContainer: z.number().min(0).max(1).optional(), - }).optional().describe('Element-state opacities (0–1): hover / focus / pressed are the share of the ink layered over a control\'s fill; disabledContent / disabledContainer are the opacities a disabled control renders at. generate_design_system writes Material 3\'s values (0.08 / 0.10 / 0.10 / 0.38 / 0.12).'), + }).optional().describe('Element-state opacities (0–1): hover / focus / pressed are the share of the ink layered over a control\'s fill; disabledContent is the opacity of a disabled target, drawn in $text-primary, and disabledContainer the opacity its drawn fill or border shows at; setting either switches disabled from the 0.5 fallback to this pair (a lone one takes the other\'s value). Unset or out-of-range values take Material\'s. generate_design_system writes Material 3\'s values (0.08 / 0.10 / 0.10 / 0.38 / 0.12).'), }).describe('Design variables to set'), }, async ({ canvasId, variables }) => { diff --git a/src/renderer.ts b/src/renderer.ts index b4a8a9c..9dfec31 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -8,7 +8,7 @@ import { LINK_MIN_HEIGHT, LINK_ICON, LINK_EXTERNAL, NAV_ITEM_HEIGHT, TABS_HEIGHT, TREE_ROW_HEIGHT, TREE_INDENT, MENU_ROW_HEIGHT, PROPERTY_ROW_HEIGHT, PROPERTY_LABEL_WIDTH, tabsItems, textInputHeight, textInputRows, OVERLAY_TYPES, OVERLAY_Z, TOOLTIP_MAX_WIDTH, MENU_MIN_WIDTH, drawerWidth, modalActions, modalWidth, popoverWidth, - STATE_LAYERS, elementState, isDisabled, + STATE_LAYERS, elementState, } from './primitives.js'; /** Build a `background: …` declaration from a node's `gradient`. @@ -653,15 +653,12 @@ function renderNode(node: SceneNode, rc: RenderCtx): string { // arrive pre-defaulted by resolveVariables (token-aware with neutral // fallbacks), so the builders just consume node.fill / stroke / color. if (node.type === 'skeleton') return renderSkeleton(node, dataAttr); - // Phase 27 slice C — controls are focusable in the live viewer, with an - // accent-derived focus ring (:focus-visible only, so static screenshots - // are pixel-identical: nothing is focused in a capture). - // Phase 27 slice C — controls are focusable in the live viewer, with an - // accent-derived focus ring (:focus-visible only, so static screenshots - // are pixel-identical: nothing is focused in a capture). The ring color - // rides a CSS var on the control's own style, keeping one style attribute. + // Phase 27 slice C — controls are focusable in the live viewer, with a + // :focus-visible ring (nothing is focused in a capture). Slice G: the ring + // colour is the resolved focus ring (a CSS var on the control's own style), + // and `state: "focus"` draws the same ring statically. if (node.type === 'toggle' || node.type === 'checkbox' || node.type === 'radio' || node.type === 'select') { - const focusAttr = isDisabled(node) ? `${dataAttr} tabindex="-1" aria-disabled="true"` : `${dataAttr} tabindex="0" data-focusable`; + const focusAttr = renderState(node) === 'disabled' ? `${dataAttr} tabindex="-1" aria-disabled="true"` : `${dataAttr} tabindex="0" data-focusable`; if (node.type === 'toggle') return renderToggle(node, focusAttr); if (node.type === 'checkbox') return renderCheckbox(node, focusAttr); if (node.type === 'radio') return renderRadio(node, focusAttr); @@ -892,10 +889,11 @@ function buildStyles(node: SceneNode, rc: RenderCtx): string { // apply. Shared bits: numeric width/height with control-appropriate defaults, // opacity passthrough (resolveVariables sets 0.5 for disabled). -/** A control's state (slice G): its own content, so one opacity; `ink` is - * what the control draws on its fill (the mark, the knob, the boundary). */ -function controlState(node: SceneNode, ink: string | undefined, whole = true): StateParts { - return stateParts(elementState(node), node.stateStyle, ink, { whole, authored: node.opacity }); +/** A control's state (slice G); `ink` is what the control draws on its fill + * (the mark, the knob, the boundary). Its disabled colours come from + * `neutralised`, called first. */ +function controlState(node: SceneNode, ink: string | undefined): StateParts { + return stateParts(renderState(node), node.stateStyle, ink, { authored: node.opacity }); } function controlSize(node: SceneNode, defW: number, defH: number): { w: number; h: number } { @@ -949,7 +947,7 @@ function renderToggle(node: SceneNode, dataAttr: string): string { const knobStyle = [ 'position: absolute', `top: ${inset}px`, `left: ${left}px`, `width: ${knob}px`, `height: ${knob}px`, 'border-radius: 50%', - 'background-color: #FFFFFF', 'box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25)', + `background-color: ${markOn(node)}`, 'box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25)', ].join('; '); return `
`; } @@ -966,7 +964,7 @@ function renderCheckbox(node: SceneNode, dataAttr: string): string { `border: 1.5px solid ${node.stroke}`, `background-color: ${node.fill}`, ...controlOpacity(node), ...st.css, ].join('; '); - const mark = node.checked ? (getIconSvg('check', Math.round(Math.min(w, h) * 0.78), '#FFFFFF') ?? '') : ''; + const mark = node.checked ? (getIconSvg('check', Math.round(Math.min(w, h) * 0.78), markOn(node)) ?? '') : ''; return `${mark}
`; } @@ -996,7 +994,7 @@ function renderSelect(node: SceneNode, dataAttr: string): string { const isPlaceholder = !node.value; const textColor = isPlaceholder ? '#9CA3AF' : node.color; // A select's frame is a container: the disabled pair splits it from its text. - const st = controlState(node, node.color, false); + const st = controlState(node, node.color); const frame = [ ringVar(node.stateStyle), 'display: flex', 'flex-direction: row', 'align-items: center', 'justify-content: space-between', @@ -1030,7 +1028,7 @@ const FALLBACK = { accent: '#2563EB', text: '#111827', secondary: '#6B7280', bor // 0.5. Resolution (applyControlDefaults) hands over `stateStyle`; a node it // skipped (inside a component) uses the fallback. -const STATE_FALLBACK: StateStyle = { ring: FALLBACK.accent, onSurface: FALLBACK.text, hover: STATE_LAYERS.hover, focus: STATE_LAYERS.focus, pressed: STATE_LAYERS.pressed }; +const STATE_FALLBACK: StateStyle = { ring: FALLBACK.accent, onSurface: FALLBACK.text, surface: FALLBACK.surface, hover: STATE_LAYERS.hover, focus: STATE_LAYERS.focus, pressed: STATE_LAYERS.pressed }; /** A 0–1 opacity as a CSS percentage, two decimals at most. */ const pct = (x: number): number => Math.round(x * 10000) / 100; @@ -1038,10 +1036,26 @@ const pct = (x: number): number => Math.round(x * 10000) / 100; /** A colour at `p` percent over transparent. */ const atPercent = (color: string, p: number): string => `color-mix(in srgb, ${color} ${p}%, transparent)`; +/** The state the renderer draws: a truthy `disabled` dims, as it did before + * slice G (the census keeps `disabled === true`). */ +function renderState(n: { state?: unknown; disabled?: unknown } | null | undefined): ElementState { + return n && n.disabled ? 'disabled' : elementState(n); +} + +/** A colour that paints nothing: the keywords, and a zero alpha in hex, rgb() + * or hsl() form. A disabled container keeps it clear. */ +function isClear(c: string | undefined): boolean { + if (!c) return true; + const v = c.trim().toLowerCase(); + return v === 'transparent' || v === 'none' + || /^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/.test(v) + || /^(?:rgba?|hsla?)\(.*[,/]\s*0*\.?0+%?\s*\)$/.test(v); +} + /** The disabled token pair, when the design system sets it (spec P3). */ -function disabledPair(style: StateStyle | undefined): { content: number; container: number; on: string } | undefined { +function disabledPair(style: StateStyle | undefined): { content: number; container: number; on: string; surface: string } | undefined { if (style?.disabledContent === undefined || style.disabledContainer === undefined) return undefined; - return { content: style.disabledContent, container: style.disabledContainer, on: style.onSurface }; + return { content: style.disabledContent, container: style.disabledContainer, on: style.onSurface, surface: style.surface }; } /** The share of the on-surface colour a drawn container takes, so that under @@ -1057,6 +1071,9 @@ interface StateParts { container: (color: string | undefined) => string | undefined; /** Maps a content colour (label, icon): on-surface when disabled (S10). */ content: (color: string | undefined) => string | undefined; + /** Maps a mark drawn on a filled container (a check, a knob, a badge + * numeral): the surface colour when disabled, so it shows on on-surface. */ + mark: (color: string | undefined) => string | undefined; } const identity = (c: string | undefined) => c; @@ -1076,7 +1093,7 @@ function stateParts( opts: { whole?: boolean; item?: boolean; authored?: number; inset?: boolean } = {}, ): StateParts { const st = style ?? STATE_FALLBACK; - const none = { container: identity, content: identity }; + const none = { container: identity, content: identity, mark: identity }; if (state === 'rest') return { css: [], ...none }; if (state === 'disabled') { const pair = disabledPair(style); @@ -1086,8 +1103,9 @@ function stateParts( const share = containerShare(pair); return { css: [`opacity: ${pair.content}`], - container: (c) => (c && c !== 'transparent' ? (opts.whole ? pair.on : atPercent(pair.on, share)) : c), + container: (c) => (isClear(c) ? c : opts.whole ? pair.on : atPercent(pair.on, share)), content: (c) => (c === undefined ? c : pair.on), + mark: () => pair.surface, }; } const css: string[] = []; @@ -1099,14 +1117,23 @@ function stateParts( return { css, ...none }; } +/** Drawn in the on-surface colour (S10): disabled, with the token pair, no + * authored opacity. True of the node before and after `neutralised`. */ +function isNeutral(node: SceneNode): boolean { + return renderState(node) === 'disabled' && node.opacity === undefined && !!disabledPair(node.stateStyle); +} + +/** A mark on a node's filled container: white, or the surface colour when + * the node is drawn in the on-surface colour. */ +const markOn = (node: SceneNode): string => (isNeutral(node) ? (node.stateStyle?.surface ?? FALLBACK.surface) : '#FFFFFF'); + /** Spec change S10 — a disabled node with the token pair (and no authored * opacity) renders in the on-surface colour: its content colours become it, * a drawn fill or stroke takes it at the container share (solid for a * `whole` control). Any other node is returned as is. */ function neutralised(node: SceneNode, whole = false): SceneNode { - if (elementState(node) !== 'disabled' || node.opacity !== undefined) return node; - const pair = disabledPair(node.stateStyle); - if (!pair) return node; + if (!isNeutral(node)) return node; + const pair = disabledPair(node.stateStyle)!; const { container, content } = stateParts('disabled', node.stateStyle, undefined, { whole }); return { ...node, @@ -1208,7 +1235,7 @@ function renderHomeIndicator(node: SceneNode, rc: RenderCtx, dataAttr: string): } function navAction(action: { icon?: unknown; label?: unknown; state?: unknown; disabled?: unknown }, own: string, back: boolean, style?: StateStyle): string { - const st = stateParts(elementState(action), style, own, { item: true }); + const st = stateParts(renderState(action), style, own, { item: true }); const color = st.content(own) ?? own; const glyph = iconHtml(action.icon ?? (back ? 'chevron-left' : undefined), 24, color); const words = text(action.label) ? labelHtml(text(action.label), 'font-size: 17px') : ''; @@ -1249,11 +1276,11 @@ function renderNavBar(node: SceneNode, rc: RenderCtx, dataAttr: string): string function tabItem(item: { icon?: unknown; label?: unknown; active?: unknown; badge?: unknown; state?: unknown; disabled?: unknown }, node: SceneNode): string { const own = item.active ? node.iconColor ?? FALLBACK.accent : node.color ?? FALLBACK.secondary; // A floating bar clips its pill, so an item's ring is drawn inside (as a tab's). - const st = stateParts(elementState(item), node.stateStyle, own, { item: true, inset: true }); + const st = stateParts(renderState(item), node.stateStyle, own, { item: true, inset: true }); const color = st.content(own) ?? own; const count = badgeText(item.badge); const badge = count - ? `${escapeHtml(count)}` + ? `${escapeHtml(count)}` : ''; const words = text(item.label); return `
` @@ -1308,7 +1335,7 @@ function renderButton(node: SceneNode, rc: RenderCtx, attrs: string, item = fals const color = node.color ?? (fill === 'transparent' ? FALLBACK.accent : '#FFFFFF'); const glyph = iconHtml(node.icon, size === 'xs' ? 14 : size === 'sm' ? 16 : 20, color); const radius = typeof node.cornerRadius === 'number' ? node.cornerRadius : size === 'xs' ? 6 : 8; - const st = stateParts(elementState(node), node.stateStyle, color, { item, authored: node.opacity }); + const st = stateParts(renderState(node), node.stateStyle, color, { item, authored: node.opacity }); const box = css([ ringVar(node.stateStyle), ...positionStyles(node, rc), 'display: inline-flex', 'flex-shrink: 0', 'align-items: center', 'justify-content: center', 'gap: 8px', @@ -1337,11 +1364,11 @@ function listRowTrailing(node: SceneNode): string { if (t.chevron) return `
${iconHtml('chevron-right', 18, secondary)}
`; if (typeof t.toggle === 'boolean') { const track = t.toggle ? node.iconColor ?? FALLBACK.accent : node.stroke ?? FALLBACK.border; - return `
`; + return `
`; } const count = badgeText(t.badge); if (count) { - return `${escapeHtml(count)}`; + return `${escapeHtml(count)}`; } return ''; } @@ -1363,7 +1390,7 @@ function listRowLeading(node: SceneNode): string { function renderListRow(node: SceneNode, rc: RenderCtx, dataAttr: string): string { node = neutralised(node); const position = effectivePosition(node); - const st = stateParts(elementState(node), node.stateStyle, node.color ?? FALLBACK.text, { authored: node.opacity }); + const st = stateParts(renderState(node), node.stateStyle, node.color ?? FALLBACK.text, { authored: node.opacity }); const box = css([ ...positionStyles(node, rc), position ? undefined : 'position: relative', 'display: flex', 'flex-direction: row', 'align-items: center', 'gap: 12px', 'flex-shrink: 0', @@ -1425,7 +1452,7 @@ function textWithLinks(node: SceneNode): string { /** A disabled primitive leaves the tab order and says so. */ function disabledAttrs(node: SceneNode, attrs: string): string { - return isDisabled(node) ? `${attrs.replace(' tabindex="0" data-focusable', ' tabindex="-1"')} aria-disabled="true"` : attrs; + return renderState(node) === 'disabled' ? `${attrs.replace(' tabindex="0" data-focusable', ' tabindex="-1"')} aria-disabled="true"` : attrs; } function renderLink(node: SceneNode, rc: RenderCtx, attrs: string): string { @@ -1435,7 +1462,7 @@ function renderLink(node: SceneNode, rc: RenderCtx, attrs: string): string { const name = text(node.ariaLabel); if (name) attrs += ` aria-label="${escapeAttr(name)}" title="${escapeAttr(name)}"`; const color = node.color ?? FALLBACK.accent; - const state = elementState(node); + const state = renderState(node); const st = stateParts(state, node.stateStyle, color, { authored: node.opacity }); const glyph = iconHtml(node.icon, LINK_ICON, node.iconColor ?? color); const external = node.external ? iconHtml('external-link', LINK_EXTERNAL, node.iconColor ?? color) : ''; @@ -1467,7 +1494,7 @@ function renderTextInput(node: SceneNode, rc: RenderCtx, dataAttr: string): stri const radius = typeof node.cornerRadius === 'number' ? node.cornerRadius : 6; // The field carries the target's box; the disabled opacity sits on the // wrapper with the error message (spec P4). - const state = elementState(node); + const state = renderState(node); const st = stateParts(state, node.stateStyle, node.color ?? FALLBACK.text, { authored: node.opacity }); const opacity = st.css.filter((d) => d.startsWith('opacity:')); const field = css([ @@ -1485,8 +1512,11 @@ function renderTextInput(node: SceneNode, rc: RenderCtx, dataAttr: string): stri : `${titledLabel(shown, `color: ${value ? node.color ?? FALLBACK.text : secondary}`)}`) : ''; const error = text(node.error); + // The message is content: under S10 it takes the on-surface colour, not + // the border's container share. + const tone = isNeutral(node) ? node.color ?? border : border; const message = error - ? `
${iconHtml('circle-alert', 14, border)}${titledLabel(error, '')}
` + ? `
${iconHtml('circle-alert', 14, tone)}${titledLabel(error, '')}
` : ''; const outer = css([ ...positionStyles(node, rc), 'display: flex', 'flex-direction: column', 'gap: 4px', 'flex-shrink: 0', rowWidth(node), @@ -1513,7 +1543,7 @@ function renderNavItem(node: SceneNode, rc: RenderCtx, attrs: string): string { const dot = node.dotColor ? `` : ''; const glyph = iconHtml(node.icon, 16, node.active ? accent : node.secondaryColor ?? FALLBACK.secondary); const count = text(node.count); - const st = stateParts(elementState(node), node.stateStyle, color, { authored: node.opacity }); + const st = stateParts(renderState(node), node.stateStyle, color, { authored: node.opacity }); const box = css([ ringVar(node.stateStyle), ...positionStyles(node, rc), node.position ? undefined : 'position: relative', @@ -1537,12 +1567,12 @@ function renderTabs(node: SceneNode, rc: RenderCtx, dataAttr: string): string { const accent = node.iconColor ?? FALLBACK.accent; const line = node.variant !== 'contained'; // A disabled tabs node disables every tab (spec P2). - const hostDisabled = isDisabled(node); + const hostDisabled = !!node.disabled || node.state === 'disabled'; const tabs = tabsItems(node).map((it) => { const label = text(it.label); const count = text(it.count); const active = it.active === true; - const state = hostDisabled ? 'disabled' : elementState(it); + const state = hostDisabled ? 'disabled' : renderState(it); const ink = active ? node.color ?? FALLBACK.text : node.secondaryColor ?? FALLBACK.secondary; // The tablist clips its overflow, so a tab's ring is drawn inside (S9). const st = stateParts(state, node.stateStyle, ink, { item: true, inset: true }); @@ -1579,7 +1609,7 @@ function renderTreeRow(node: SceneNode, rc: RenderCtx, attrs: string): string { if (typeof node.expanded === 'boolean') attrs += ` aria-expanded="${node.expanded}"`; if (node.active) attrs += ' aria-selected="true"'; const chevron = typeof node.expanded === 'boolean' ? iconHtml(node.expanded ? 'chevron-down' : 'chevron-right', 14, secondary) : ''; - const st = stateParts(elementState(node), node.stateStyle, node.color ?? FALLBACK.text, { authored: node.opacity }); + const st = stateParts(renderState(node), node.stateStyle, node.color ?? FALLBACK.text, { authored: node.opacity }); const box = css([ ringVar(node.stateStyle), ...positionStyles(node, rc), 'display: flex', 'align-items: center', 'gap: 6px', 'flex-shrink: 0', 'box-sizing: border-box', @@ -1610,7 +1640,7 @@ function renderMenuRow(node: SceneNode, rc: RenderCtx, attrs: string): string { ? `${titledLabel(text(node.shortcut), '')}` : ''; const chevron = node.submenu ? `${iconHtml('chevron-right', 14, secondary)}` : ''; - const st = stateParts(elementState(node), node.stateStyle, color, { authored: node.opacity }); + const st = stateParts(renderState(node), node.stateStyle, color, { authored: node.opacity }); const box = css([ ringVar(node.stateStyle), ...positionStyles(node, rc), 'display: flex', 'align-items: center', 'gap: 8px', 'flex-shrink: 0', 'box-sizing: border-box', diff --git a/src/types.ts b/src/types.ts index 09288bc..a18ede5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -49,6 +49,10 @@ export interface StateStyle { /** The on-surface colour a disabled target with the token pair renders in * (spec change S10: `$text-primary`, Material's onSurface). */ onSurface: string; + /** What a mark, knob or badge numeral drawn on a disabled container takes + * (`$bg-surface`), so it stays visible on the on-surface colour in both + * themes (Material's disabled checkbox mark). */ + surface: string; hover: number; focus: number; pressed: number; diff --git a/src/variables.ts b/src/variables.ts index be24454..8b3a3f5 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -126,9 +126,6 @@ const CONTROL_FALLBACK = { accent: '#2563EB', border: '#D1D5DB', surface: '#FFFF // never reads tokens. Items of tabs / tab-bar / nav-bar / modal / toast use // their host's. const STATE_HOSTS = new Set([...STATEFUL_TYPES, 'tabs', 'tab-bar', 'nav-bar', 'modal', 'toast']); -// The nodes whose own `state: "disabled"` disables them (a tabs node's -// disables every tab). -const STATE_ON_NODE = new Set([...STATEFUL_TYPES, 'tabs']); /** An opacity token: a number in [0, 1], else undefined. */ function unit(x: unknown): number | undefined { @@ -147,6 +144,7 @@ export function resolveStateStyle(v: DesignVariables): StateStyle { // FR-H1's chain: the renderer and the check never disagree. ring: c['focus-ring'] ?? c.accent ?? c.primary ?? CONTROL_FALLBACK.accent, onSurface: c['text-primary'] ?? CONTROL_FALLBACK.text, + surface: c['bg-surface'] ?? c.surface ?? CONTROL_FALLBACK.surface, hover: unit(s.hover) ?? STATE_LAYERS.hover, focus: unit(s.focus) ?? STATE_LAYERS.focus, pressed: unit(s.pressed) ?? STATE_LAYERS.pressed, @@ -158,11 +156,14 @@ export function resolveStateStyle(v: DesignVariables): StateStyle { return out; } -/** Without disabled tokens a disabled node renders at today's 0.5 opacity - * (unless authored); with them the renderer draws the token pair (P4). */ +/** A disabled node renders at today's 0.5 opacity (unless authored), except + * where the renderer draws the token pair instead (P4): a type that takes + * `state` on a canvas with disabled tokens. Truthiness matches the pre-slice + * check, so `disabled: "true"` still dims (P5). */ function legacyDisabled(node: SceneNode, v: DesignVariables): void { - const disabled = node.disabled === true || (STATE_ON_NODE.has(node.type) && node.state === 'disabled'); - if (disabled && node.opacity === undefined && !hasDisabledTokens(v)) node.opacity = 0.5; + const stateful = STATEFUL_TYPES.has(node.type); + const disabled = !!node.disabled || (stateful && node.state === 'disabled'); + if (disabled && node.opacity === undefined && !(stateful && hasDisabledTokens(v))) node.opacity = 0.5; } function applyControlDefaults(node: SceneNode, v: DesignVariables): void { diff --git a/test-element-states.ts b/test-element-states.ts index 94d8cd9..2de8ec5 100644 --- a/test-element-states.ts +++ b/test-element-states.ts @@ -19,7 +19,7 @@ import type { Canvas, DesignVariables, SceneNode } from './src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { if (!cond) allPass = false; - console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${!cond && extra ? ` — ${extra}` : ''}`); } const SYSTEM = generateDesignSystem('#2563EB', 'technical', { surface: 'desktop-app' }).variables; @@ -200,6 +200,171 @@ for (const s of ['rest', 'hover', 'focus', 'pressed'] as const) { check('S10 twin: a disabled nav-item with no dot grows no dot', !navNoDot.includes('border-radius: 50%')); } +// ── Verify round 1 fixes ──────────────────────────────────────────────── +{ + // F1: a mark, knob or badge numeral on a disabled container takes the surface + // colour, so it shows on the on-surface fill in a dark theme. + const dark = (n: SceneNode) => chunk(renderToHtml(resolveVariables({ id: 'root', type: 'frame', fill: '#000000', children: [n] }, SYSTEM, { theme: 'dark' }), 900, 600), 'n'); + const surfDark = { ...C, ...SYSTEM.dark!.colors }['bg-surface']; + const onDark = { ...C, ...SYSTEM.dark!.colors }['text-primary']; + check('F1: dark surface and on-surface differ (the fixture can tell them apart)', !!surfDark && surfDark !== onDark && surfDark !== '#FFFFFF'); + const cb = dark({ id: 'n', type: 'checkbox', checked: true, disabled: true }); + check('F1: a disabled checked checkbox draws its mark in the surface colour (dark)', cb.includes(`stroke="${surfDark}"`) && !cb.includes('stroke="#FFFFFF"'), cb.slice(0, 500)); + check('F1 twin: an enabled checkbox keeps a white mark (dark)', dark({ id: 'n', type: 'checkbox', checked: true }).includes('stroke="#FFFFFF"')); + const tg = dark({ id: 'n', type: 'toggle', checked: true, state: 'disabled' }); + check('F1: a disabled toggle knob is the surface colour (dark)', tg.includes(`border-radius: 50%; background-color: ${surfDark}`), tg); + check('F1 twin: an enabled toggle knob stays white', dark({ id: 'n', type: 'toggle', checked: true }).includes('border-radius: 50%; background-color: #FFFFFF')); + check('F1 twin: without tokens a disabled toggle knob stays white', chunk(render([{ id: 'n', type: 'toggle', disabled: true }], COLORS_ONLY), 'n').includes('border-radius: 50%; background-color: #FFFFFF')); + const lr = dark({ id: 'n', type: 'list-row', title: 'Inbox', trailing: { badge: 3 }, disabled: true }); + check('F1: a disabled list-row badge numeral is the surface colour', lr.includes(`color: ${surfDark}; font-size: 12px`), lr.slice(0, 900)); + const lrt = dark({ id: 'n', type: 'list-row', title: 'Wi-Fi', trailing: { toggle: true }, disabled: true }); + check('F1: a disabled list-row toggle knob is the surface colour', lrt.includes(`border-radius: 50%; background-color: ${surfDark}`)); + const tb = dark({ id: 'n', type: 'tab-bar', items: [{ icon: 'house', label: 'Home', badge: 5, state: 'disabled' }, { icon: 'search', label: 'Find', badge: 2 }] }); + check('F1: a disabled tab-bar item\'s badge numeral is the surface colour; an enabled one stays white', tb.includes(`color: ${surfDark}; font-size: 11px`) && tb.includes('color: #FFFFFF; font-size: 11px'), tb.slice(0, 900)); + + // F2: a truthy non-boolean disabled still dims (pre-slice behaviour); an + // overlay with disabled keeps its 0.5 when the design system has the pair. + for (const d of ['true', 1] as unknown[]) { + const t = tag(render([{ id: 'n', type: 'button', label: 'S', disabled: d as boolean }], COLORS_ONLY), 'n'); + check(`F2: disabled ${JSON.stringify(d)} still dims a button to 0.5 without tokens`, t.includes('opacity: 0.5'), t); + } + check('F2 twin: an enabled button has no opacity', !tag(render([{ id: 'n', type: 'button', label: 'S', disabled: false }], COLORS_ONLY), 'n').includes('opacity')); + for (const type of ['tooltip', 'popover', 'menu', 'modal', 'toast', 'drawer'] as const) { + const h = render([{ id: 'n', type, text: 'x', title: 'T', disabled: true }]); + check(`F2: a disabled ${type} keeps 0.5 on a canvas with the token pair`, tag(h, 'n').includes('opacity: 0.5')); + } + check('F2 twin: a disabled button on that canvas draws the pair, not 0.5', tag(render([{ id: 'n', type: 'button', label: 'S', disabled: true }]), 'n').includes('opacity: 0.38')); + + // F3: a disabled text-input's error message is content (on-surface), not the + // border's container share. + const ti = chunk(render([{ id: 'n', type: 'text-input', value: 'v', error: 'Bad', disabled: true }]), 'n'); + check('F3: a disabled text-input error message takes the on-surface colour', ti.includes(`line-height: 16px; color: ${ON}`) && !/line-height: 16px; color: color-mix/.test(ti), ti.slice(0, 900)); + const tiOn = chunk(render([{ id: 'n', type: 'text-input', value: 'v', error: 'Bad' }]), 'n'); + check('F3 twin: an enabled error message keeps the danger colour', tiOn.includes(`line-height: 16px; color: ${C.danger}`), tiOn.slice(0, 900)); + + // F4: a disabled container that paints nothing stays clear, whatever its spelling. + for (const f of ['transparent', 'none', 'rgba(0,0,0,0)', 'rgba(0, 0, 0, 0.0)', '#00000000', '#0000', 'hsla(0,0%,0%,0)', 'rgb(0 0 0 / 0%)']) { + const t = tag(render([{ id: 'n', type: 'button', label: 'S', variant: 'ghost', fill: f, state: 'disabled' }]), 'n'); + check(`F4: a disabled ghost with fill ${f} stays clear`, t.includes(`background-color: ${f}`), t); + } + for (const f of ['#2563EB1A', 'rgba(37,99,235,0.5)', 'rgb(10, 20, 30)', '#2563EB']) { + const t = tag(render([{ id: 'n', type: 'button', label: 'S', fill: f, state: 'disabled' }]), 'n'); + check(`F4 twin: a disabled button with fill ${f} takes the on-surface share`, t.includes(`background-color: color-mix(in srgb, ${ON}`), t); + } + + // F5: state is an enum, not a style value: it does not dilute token adoption. + const sheet = (st?: SceneNode['state']): Canvas => ({ + id: 'c', name: 'c', projectId: 'p', components: {}, createdAt: '', lastModified: '', variables: SYSTEM, + root: { id: 'document', type: 'document', width: 1440, height: 900, fill: '$bg-primary', layout: 'vertical', padding: 40, gap: 16, + children: Array.from({ length: 10 }, (_, i) => ({ id: `b${i}`, type: 'button', label: 'B', size: 'sm', fill: '$accent', color: '#FFFFFF', stroke: '#EEEEEE', ...(st ? { state: st } : {}) })) }, + metadata: { surface: { type: 'desktop-app', device: 'window-1440' } }, + } as Canvas); + const tokenWarn = async (st?: SceneNode['state']) => (await evaluateCanvas(sheet(st), { mode: 'fast' })).issues.filter((i) => /use design tokens/.test(i.message)).length; + check('F5: a states sheet\'s state props do not count against token adoption', (await tokenWarn('hover')) === (await tokenWarn())); +} + +// ── Verify round 1: mutation kills ────────────────────────────────────── +{ + const R = (n: SceneNode, v: DesignVariables = SYSTEM) => resolveVariables(n, v); + // A disabled node with no fill gains no background. + for (const type of ['menu-row', 'tree-row', 'nav-item', 'list-row'] as const) { + const t = tag(render([{ id: 'n', type, label: 'x', title: 'x', state: 'disabled' }]), 'n'); + check(`M: a disabled ${type} with no fill draws no background`, !t.includes('background-color'), t); + } + // An authored opacity wins on every node type, with and without the pair. + const OWN: SceneNode[] = [ + { id: 'n', type: 'button', label: 'S' }, { id: 'n', type: 'link', label: 'L' }, { id: 'n', type: 'nav-item', label: 'N' }, + { id: 'n', type: 'tree-row', label: 'T' }, { id: 'n', type: 'menu-row', label: 'M' }, { id: 'n', type: 'list-row', title: 'R' }, + { id: 'n', type: 'checkbox', checked: true }, { id: 'n', type: 'toggle' }, { id: 'n', type: 'radio' }, { id: 'n', type: 'select', value: 'A' }, + ]; + for (const n of OWN) for (const [vn, v] of [['pair', SYSTEM], ['no tokens', COLORS_ONLY]] as const) { + const t = tag(render([{ ...n, disabled: true, opacity: 0.7 }], v), 'n'); + check(`M: an authored opacity wins on a disabled ${n.type} (${vn})`, t.includes('opacity: 0.7') && !t.includes('opacity: 0.38') && !t.includes('opacity: 0.5') && !t.includes('color-mix'), t); + } + { + const ti = chunk(render([{ id: 'n', type: 'text-input', value: 'v', disabled: true, opacity: 0.7 }]), 'n'); + check('M: an authored opacity wins on a disabled text-input', ti.includes('opacity: 0.7') && !ti.includes('opacity: 0.38') && !ti.includes('color-mix')); + } + // Without tokens every disabled node and item dims to 0.5. + for (const n of OWN) { + const t = tag(render([{ ...n, state: 'disabled' }], COLORS_ONLY), 'n'); + check(`M: a ${n.type} with state disabled dims to 0.5 without tokens`, t.includes('opacity: 0.5') && !t.includes('color-mix'), t); + } + check('M: a disabled nav-bar action dims to 0.5 without tokens', chunk(render([{ id: 'n', type: 'nav-bar', title: 'T', trailing: [{ icon: 'plus', disabled: true }] }], COLORS_ONLY), 'n').includes('opacity: 0.5')); + check('M: a disabled tab-bar item dims to 0.5 without tokens', chunk(render([{ id: 'n', type: 'tab-bar', items: [{ icon: 'house', label: 'A', state: 'disabled' }, { icon: 'user', label: 'B' }] }], COLORS_ONLY), 'n').includes('opacity: 0.5')); + check('M: a disabled toast action dims to 0.5 without tokens', /
]*opacity: 0\.5/.test(render([{ id: 'n', type: 'toast', text: 'x', action: { label: 'Undo', state: 'disabled' } }], COLORS_ONLY))); + // state disabled leaves the tab order on every type. + for (const n of [...OWN, { id: 'n', type: 'link', label: 'L' }] as SceneNode[]) { + if (n.type === 'list-row') continue; // never focusable + const t = tag(render([{ ...n, state: 'disabled' }]), 'n'); + check(`M: a ${n.type} with state disabled leaves the tab order`, t.includes('tabindex="-1"') && t.includes('aria-disabled="true"') && !t.includes('data-focusable'), t); + } + { + const f = chunk(render([{ id: 'n', type: 'text-input', placeholder: 'x', state: 'disabled' }]), 'n').match(/]*role="textbox"[^>]*>/)?.[0] ?? ''; + check('M: a text-input with state disabled leaves the tab order', f.includes('tabindex="-1"') && !f.includes('data-focusable'), f); + } + // Disabled colours are the on-surface colour, per type. + for (const n of [{ id: 'n', type: 'link', label: 'L' }, { id: 'n', type: 'tree-row', label: 'T' }, { id: 'n', type: 'menu-row', label: 'M' }, { id: 'n', type: 'nav-item', label: 'N' }, { id: 'n', type: 'list-row', title: 'R' }] as SceneNode[]) { + const t = tag(render([{ ...n, state: 'disabled' }]), 'n'); + check(`M: a disabled ${n.type} draws its content in the on-surface colour`, t.includes(`color: ${ON}`) && t.includes('opacity: 0.38'), t); + } + const radio = tag(render([{ id: 'n', type: 'radio', checked: true, state: 'disabled' }]), 'n'); + check('M: a disabled radio draws its ring solid in the on-surface colour', radio.includes(`border: 1.5px solid ${ON}`) && !radio.includes('color-mix'), radio); + const dot = chunk(render([{ id: 'n', type: 'nav-item', label: 'N', dotColor: '#16A34A', state: 'disabled' }]), 'n'); + check('M: a disabled nav-item dot is exactly the on-surface colour', dot.includes(`border-radius: 50%; background-color: ${ON}`), dot.slice(0, 700)); + const shortcut = chunk(render([{ id: 'n', type: 'menu-row', label: 'Copy', shortcut: '⌘C', state: 'disabled' }]), 'n'); + check('M: a disabled menu-row shortcut takes the on-surface colour', /]*color: ([^;"]+)/.exec(shortcut)?.[1] === ON, shortcut.slice(0, 700)); + const share = Math.round((0.12 / 0.38) * 10000) / 100; + const tabsOff = chunk(render([{ id: 'n', type: 'tabs', items: [{ label: 'A', active: true, count: 3 }], state: 'disabled' }]), 'n'); + check('M: a disabled active tab draws label, indicator and badge in the on-surface colour', tabsOff.includes(`color: ${ON}`) && tabsOff.includes(`bottom: 0; height: 2px; border-radius: 1px; background-color: ${ON}`) + && tabsOff.includes(`border-radius: 8px; background-color: color-mix(in srgb, ${ON} ${share}%, transparent)`), tabsOff.slice(0, 900)); + const contained = chunk(render([{ id: 'n', type: 'tabs', variant: 'contained', items: [{ label: 'A', active: true, disabled: true }] }]), 'n'); + check('M: a disabled contained tab draws its fill in the on-surface share', contained.includes(`background-color: color-mix(in srgb, ${ON} ${share}%, transparent)`), contained.slice(0, 700)); + const barOff = chunk(render([{ id: 'n', type: 'tab-bar', items: [{ icon: 'house', label: 'A', badge: 2, disabled: true }] }]), 'n'); + check('M: a disabled tab-bar item draws its label and badge in the on-surface colour', barOff.includes(`gap: 2px; color: ${ON}`) && barOff.includes(`border-radius: 8px; background-color: ${ON}`), barOff.slice(0, 700)); + const navOff = chunk(render([{ id: 'n', type: 'nav-bar', title: 'T', trailing: [{ label: 'Edit', state: 'disabled' }] }]), 'n'); + check('M: a disabled nav-bar action draws in the on-surface colour', navOff.includes(`padding: 0 8px; color: ${ON}`), navOff.slice(0, 900)); + // Inks, exactly. + const nb = R({ id: 'n', type: 'nav-bar', title: 'T' }); + check('M: a hovered nav-bar action layers its own colour (iconColor)', chunk(render([{ id: 'n', type: 'nav-bar', title: 'T', trailing: [{ icon: 'plus', state: 'hover' }] }]), 'n').includes(layer(nb.iconColor!, 8))); + check('M: a hovered leading nav-bar action layers its own colour', chunk(render([{ id: 'n', type: 'nav-bar', title: 'T', leading: { icon: 'chevron-left', state: 'hover' } }]), 'n').includes(layer(nb.iconColor!, 8))); + const tbr = R({ id: 'n', type: 'tab-bar', items: [] }); + const bar = chunk(render([{ id: 'n', type: 'tab-bar', items: [{ icon: 'house', label: 'A', active: true, state: 'pressed' }, { icon: 'user', label: 'B', state: 'hover' }] }]), 'n'); + check('M: tab-bar items layer their own colour (active → iconColor, else color)', bar.includes(layer(tbr.iconColor!, 10)) && bar.includes(layer(tbr.color!, 8)), bar.slice(0, 900)); + const tabsR = R({ id: 'n', type: 'tabs', items: [] }); + const tb = chunk(render([{ id: 'n', type: 'tabs', items: [{ label: 'A', active: true, state: 'hover' }, { label: 'B', state: 'pressed' }] }]), 'n'); + check('M: tabs layer the label colour (active → color, else secondaryColor)', tb.includes(layer(tabsR.color!, 8)) && tb.includes(layer(tabsR.secondaryColor!, 10)), tb.slice(0, 900)); + const lk = R({ id: 'n', type: 'link', label: 'L' }); + check('M: a hovered link layers its label colour', tag(render([{ id: 'n', type: 'link', label: 'L', iconColor: '#000000', state: 'hover' }]), 'n').includes(layer(lk.color!, 8))); + check('M: the link underline sits 2px under the text', chunk(render([{ id: 'n', type: 'link', label: 'L', state: 'hover' }]), 'n').includes('text-decoration: underline; text-underline-offset: 2px')); + // Token resolution. + check('M: the ring prefers $accent over $primary', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'focus' }], { colors: { accent: '#111111', primary: '#222222' } }), 'n').includes(ringCss('#111111'))); + check('M: a focus token of 0.2 layers at 20%', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'focus' }], { ...SYSTEM, state: { focus: 0.2 } }), 'n').includes('#FFFFFF 20%')); + check('M: a hover token of exactly 1 layers at 100%', tag(render([{ id: 'n', type: 'button', label: 'S', state: 'hover' }], { ...SYSTEM, state: { hover: 1 } }), 'n').includes('#FFFFFF 100%')); + check('M: a lone out-of-range disabled token is no pair (0.5)', tag(render([{ id: 'n', type: 'button', label: 'S', disabled: true }], { ...SYSTEM, state: { disabledContent: 2 } }), 'n').includes('opacity: 0.5')); + const noText: DesignVariables = { colors: { accent: '#2563EB', 'bg-surface': '#FFFFFF' }, state: { disabledContent: 0.38, disabledContainer: 0.12 } }; + check('M: without $text-primary the on-surface colour is #111827', tag(render([{ id: 'n', type: 'button', label: 'S', disabled: true }], noText), 'n').includes('color: #111827')); + const noSurface: DesignVariables = { colors: { accent: '#2563EB', 'text-primary': '#222222', surface: '#FAFAFA' }, state: { disabledContent: 0.38, disabledContainer: 0.12 } }; + check('M: without $bg-surface the mark takes $surface', chunk(render([{ id: 'n', type: 'checkbox', checked: true, disabled: true }], noSurface), 'n').includes('stroke="#FAFAFA"')); + check('M: and with neither, #FFFFFF', chunk(render([{ id: 'n', type: 'checkbox', checked: true, disabled: true }], { colors: { 'text-primary': '#222222' }, state: { disabledContent: 0.38 } }), 'n').includes('stroke="#FFFFFF"')); + // Host styles reach the items (tuned tokens differ from the fallback). + const tuned: DesignVariables = { ...SYSTEM, colors: { ...C, 'focus-ring': '#B45309' }, state: { ...SYSTEM.state, hover: 0.2 } }; + check('M: a tab carries the host ring colour', chunk(render([{ id: 'n', type: 'tabs', items: [{ label: 'A' }] }], tuned), 'n').includes('--fs-ring: #B45309')); + check('M: a tab-bar item takes the host hover token', chunk(render([{ id: 'n', type: 'tab-bar', items: [{ icon: 'house', label: 'A', state: 'hover' }] }], tuned), 'n').includes(' 20%, transparent')); + check('M: a modal action takes the host ring', /
]*outline: 2px solid #B45309/.test(render([{ id: 'n', type: 'modal', title: 'M', actions: [{ label: 'OK', state: 'focus' }] }], tuned))); + check('M: a toast action takes the host hover token', render([{ id: 'n', type: 'toast', text: 'x', action: { label: 'Undo', state: 'hover' } }], tuned).includes(' 20%, transparent')); + // Fallbacks for an unresolved node. + check('M: an unresolved pressed node layers at 10%', tag(render([{ id: 'n', type: 'button', label: 'S', color: '#FFFFFF', fill: '#000000', state: 'pressed' }], {}, false), 'n').includes(layer('#FFFFFF', 10))); + check('M: an unresolved focused node layers at 10%', tag(render([{ id: 'n', type: 'button', label: 'S', color: '#FFFFFF', fill: '#000000', state: 'focus' }], {}, false), 'n').includes(layer('#FFFFFF', 10))); + check('M: an unresolved unchecked checkbox in hover draws no broken layer', !render([{ id: 'n', type: 'checkbox', state: 'hover' }], {}, false).includes('color-mix(in srgb, undefined')); +} + +// The census keeps disabled === true: a truthy string is still measured (pre-slice). +{ + const r = await evaluateCanvas(canvasOf('desktop-app', [{ id: 'b', name: 'b', type: 'button', icon: 'x', ariaLabel: 'X', size: 'xs', width: 20, height: 20, disabled: 'true' as unknown as boolean }]), { mode: 'fast', categories: ['usability'] }); + check('M: disabled "true" (a string) is still measured by the 24px census', r.issues.some((i) => /24px floor/.test(i.message))); +} + // ── P2: items ──────────────────────────────────────────────────────────── { const tabs = (items: SceneNode['items'], extra: Partial = {}, vars: DesignVariables = SYSTEM) => From ddada5e58576359a3e98ee91b7e3528cdc2a6175 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Tue, 17 Nov 2026 17:07:53 +0100 Subject: [PATCH 4/5] Read only a real alpha as clear in disabled containers --- docs/GUIDELINES.md | 2 +- docs/specs/PHASE-31-SPEC.md | 3 ++- src/index.ts | 4 ++-- src/renderer.ts | 13 +++++++++---- src/variables.ts | 2 +- test-element-states.ts | 4 +++- 6 files changed, 18 insertions(+), 10 deletions(-) diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 23cc51e..9cd29cb 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -163,7 +163,7 @@ Draw an element state only when a human should see it: a states sheet that shows - **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). - **Focus** also draws a 2px `$focus-ring` outline at a 2px gap, so the ring meets only the backdrop, never a brand fill; without a `$focus-ring` token it is `$accent`, then `$primary`, then `#2563EB`. A tab and a tab-bar item draw it inside their box, since the tablist and a floating bar clip. The live viewer's keyboard focus draws the same ring. -- **Disabled.** When the `state` tokens set `disabledContent` or `disabledContainer` (`generate_design_system` writes both; a lone one takes the other's Material value, 0.38 or 0.12), a disabled target renders in `$text-primary`: its content at `disabledContent` and a drawn fill or border at `disabledContainer`, so a disabled primary reads as a grey version of itself on light and dark. A check mark, a toggle knob and a badge numeral take `$bg-surface`, so they show on that grey. A fill that paints nothing stays clear. When neither is set it renders at 0.5 opacity in its own colours, as it did before element states existed. An authored `opacity` wins over both. A truthy `disabled` means disabled whatever `state` says (`disabled: false` with `state: "disabled"` is disabled too), and a `tabs` node's own `disabled` (or `state: "disabled"`) disables every tab. `state: "rest"` is the default and changes nothing. +- **Disabled.** When the `state` tokens set `disabledContent` or `disabledContainer` (`generate_design_system` writes both; a lone one takes the other's Material value, 0.38 or 0.12), a disabled target renders in `$text-primary`: its content at `disabledContent` and a drawn fill or border at `disabledContainer`, so a disabled primary reads as a grey version of itself on light and dark. A check mark, a toggle knob and a badge numeral take `$bg-surface`, so they show on that grey. A fill that paints nothing (`transparent`, `none`, a zero alpha) stays clear. When neither is set it renders at 0.5 opacity in its own colours, as it did before element states existed. An authored `opacity` wins over both. `disabled: true` means disabled whatever `state` says (`disabled: false` with `state: "disabled"` is disabled too), and a `tabs` node's own `disabled` (or `state: "disabled"`) disables every tab. `state: "rest"` is the default and changes nothing. - **Disabled is the same fact either way.** `state: "disabled"` leaves the tab order (`tabindex="-1"`, `aria-disabled`) and leaves the 24px census and the primary count exactly as `disabled: true` does. The mobile 44px census, which never exempted a disabled target, still measures it. - **`active`, `checked` and `expanded` combine with `state`**: a hovered active nav-item keeps its tint, bar and weight under the layer. diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 436c7d6..00dbd0c 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -363,7 +363,8 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **Q6: layer percentages are rounded to two decimals** (`Math.round(x × 10000) / 100`), as is the container share (0.12 / 0.38 → 31.58%). Slice H's analytical model must round the same way to agree with the render. - **Q7: the modal close button** carries the modal's resolved ring colour (it takes no state, P2). - **Q8: tests.** `test-element-states.ts` (fast) and `test-element-states-render.ts` (full: four button variants × five states, two renders each, both themes, plus a frame twin); `test-discoverability.ts` checks each surface's element-states paragraph names every `STATEFUL_TYPES` entry and the state names. -- **Verify round 1 fixes** (each proved red on 5fbbbf3 and green on the fix, with its nearest keep-cases unchanged; F2 also checked against a0d550a). (F1) S10's white check mark, toggle knob and badge numerals vanished on the near-white dark-theme on-surface: a mark drawn on a disabled container now takes the surface colour (`StateStyle.surface`: `$bg-surface`, else `$surface`, else `#FFFFFF`); enabled and tokenless marks stay white. (F2) `disabled` lost its pre-slice truthiness (`disabled: "true"` stopped dimming), and an overlay or any other non-P2 node with `disabled: true` lost its 0.5 on a canvas with the token pair: resolution sets 0.5 for a truthy `disabled` (or a P2 node's `state: "disabled"`) unless the node is a P2 type that draws the pair, and the renderer reads a truthy `disabled` as disabled; the census keeps `disabled === true`, as before. Against a0d550a the only render differences left are the new `state: "disabled"` spelling and the pair on P2 types. (F3) a disabled text-input's error message took the border's container share (about 12% effective); it is content, so it takes the on-surface colour. (F4) a container spelled clear (`none`, a zero-alpha hex, `rgba()` or `hsla()`) took the on-surface share when disabled; it stays clear, while a translucent tint still takes the share. (F5) `state` joined `PRIMITIVE_COPY_PROPS`, so a states sheet's state props no longer dilute token adoption. Mutation testing (294 mutants, 76 survivors, about 22 equivalent) left the disabled paths of every type but the button, authored opacity, item inks, token resolution and host-style threading unasserted; tests now kill them (a representative 16 re-run, all killed). Dead code removed: `controlState`'s `whole` flag (the controls are neutralised first) and `tabs` in the legacy-opacity set (`renderTabs` never draws a node opacity). +- **Verify round 1 fixes** (each proved red on 5fbbbf3 and green on the fix, with its nearest keep-cases unchanged; F2 also checked against a0d550a). (F1) S10's white check mark, toggle knob and badge numerals vanished on the near-white dark-theme on-surface: a mark drawn on a disabled container now takes the surface colour (`StateStyle.surface`: `$bg-surface`, else `$surface`, else `#FFFFFF`); enabled and tokenless marks stay white. (F2) `disabled` lost its pre-slice truthiness (`disabled: "true"` stopped dimming), and an overlay or any other non-P2 node with `disabled: true` lost its 0.5 on a canvas with the token pair: resolution sets 0.5 for a truthy `disabled` (or a P2 node's `state: "disabled"`) unless the node is a P2 type that draws the pair, and the renderer reads a truthy `disabled` as disabled; the census keeps `disabled === true`, as before. Against a0d550a the only render differences left are the new `state: "disabled"` spelling, the pair on P2 types, and Q4's disabled `tabs` node (its tabs now dim, 0.5 without tokens, and leave the tab order). The renderer reads a truthy `disabled`; the census and primary count read `disabled === true`, as before (`disabled` is typed boolean, so the split only shows on out-of-contract values). (F3) a disabled text-input's error message took the border's container share (about 12% effective); it is content, so it takes the on-surface colour. (F4) a container spelled clear (`none`, a zero-alpha hex, `rgba()` or `hsla()`) took the on-surface share when disabled; it stays clear, while a translucent tint still takes the share. (F5) `state` joined `PRIMITIVE_COPY_PROPS`, so a states sheet's state props no longer dilute token adoption. Mutation testing (294 mutants, 76 survivors, about 22 equivalent) left the disabled paths of every type but the button, authored opacity, item inks, token resolution and host-style threading unasserted; tests now kill them (a representative 16 re-run, all killed). Dead code removed: `controlState`'s `whole` flag (the controls are neutralised first) and `tabs` in the legacy-opacity set (`renderTabs` never draws a node opacity). +- **After verify round 2 (3b)** (proved red on 6896c88 and green on the fix; not re-verified by an agent). (a) F4's `isClear` read the last channel of an alpha-less `rgb()` / `hsl()` as an alpha, so an opaque `rgb(255, 165, 0)` or `rgb(0,0,0)` fill stayed unneutralised when disabled: the alpha is now the fourth comma argument or the value after a slash, and a colour without one is opaque. (b) The mark's surface colour falls back through `$bg-surface`, `$surface`, `$bg-primary`, `$background`, then `#FFFFFF`, so a dark palette with only `background` keeps its mark visible. (c) Wording: the docs said a truthy `disabled` leaves the census; they now say `disabled: true`. The `set_variables` describe text says a lone valid disabled token takes the other's value and two invalid ones leave the 0.5. Q1's count stands for its corpus, which held no disabled `tabs` node (Q4 covers that change). - **Accepted as found (round 1):** a disabled control inside a component instance is not dimmed, because instances render unresolved (`resolveInstance` runs after resolution); it was so before slice G for `disabled: true`, and P5 keeps it (follow-up in VISION). A disabled toggle shows on and off by knob position only (Material's choice). The focus ring sits 4px outside the box, so a row flush against a clipping pane edge has its ring cut (S9's inset applies to tabs and tab-bar items only). A colour token aliased to another token (`accent: "$primary"`) reaches the ring unresolved, as everywhere else. Docs: the steward's nine edits and the cold reader's gaps (per-key token fallback, the radio's layer, `disabled: false` with `state: "disabled"`, no-fill targets, an example) are applied. **Slice H: state checks (FR-H1 to FR-H4)** diff --git a/src/index.ts b/src/index.ts index 6f9f4e6..64e706b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -613,7 +613,7 @@ Overlays (screen states — put one in a state variant made with canvas_add_vari - drawer { size?: "sm"|"md" (320/480) or width, scrim?: false, children } — pinned to the right edge, full height, padding 16; scrim: true dims what is behind it. A modal's close button and actions and a toast's action are pointer targets (32 / 32 / 24 tall), sized for a pointer: on a phone use a sheet for a dialog. On a root with a safeArea or a pinned tab-bar, a centred modal, a default toast and a drawer keep clear of the insets and the tab bar. snapshot_layout lists every overlay under the root, and a modal (or a drawer with a scrim) carries its scrim's rect. -Element states (state?: "rest"|"hover"|"focus"|"pressed"|"disabled", default rest): on button, link, text-input, nav-item, tree-row, menu-row, list-row, toggle, checkbox, radio, select, and on the items of tabs, tab-bar, nav-bar (leading / trailing), modal (actions[]) and toast (action). Hover, focus and pressed layer the target's label colour over its fill (the state tokens' hover / focus / pressed, Material's 8 / 10 / 10% without them); focus adds a 2px $focus-ring outline at a 2px gap (inside the tab for a tab or tab-bar item); a link also underlines in hover and pressed; active, checked and expanded keep their fill under the layer. disabled (or a truthy disabled, which wins over any state) renders the whole target in $text-primary at the state tokens' disabledContent (38%), a drawn fill or border at disabledContainer (12%), and a check mark, knob or badge numeral in $bg-surface, when the tokens set either disabled opacity (a lone one takes the other's Material value), else at 0.5 opacity in its own colours; an authored opacity wins. A disabled target leaves the tab order, the 24px census and the primary count (the phone's 44px census still measures it). A tabs node's own state "disabled" disables every tab. Other node types ignore state. +Element states (state?: "rest"|"hover"|"focus"|"pressed"|"disabled", default rest): on button, link, text-input, nav-item, tree-row, menu-row, list-row, toggle, checkbox, radio, select, and on the items of tabs, tab-bar, nav-bar (leading / trailing), modal (actions[]) and toast (action). Hover, focus and pressed layer the target's label colour over its fill (the state tokens' hover / focus / pressed, Material's 8 / 10 / 10% without them); focus adds a 2px $focus-ring outline at a 2px gap (inside the tab for a tab or tab-bar item); a link also underlines in hover and pressed; active, checked and expanded keep their fill under the layer. disabled (or disabled: true, which wins over any state) renders the whole target in $text-primary at the state tokens' disabledContent (38%), a drawn fill or border at disabledContainer (12%), and a check mark, knob or badge numeral in $bg-surface, when the tokens set either disabled opacity (a lone one takes the other's Material value), else at 0.5 opacity in its own colours; an authored opacity wins. A disabled target leaves the tab order, the 24px census and the primary count (the phone's 44px census still measures it). A tabs node's own state "disabled" disables every tab. Other node types ignore state. Responsive layout (author desktop-first, adapt down): - responsive: "stack" — on a horizontal container, flips to vertical below 768px (multi-column layouts that should stack on mobile) @@ -977,7 +977,7 @@ server.tool( pressed: z.number().min(0).max(1).optional(), disabledContent: z.number().min(0).max(1).optional(), disabledContainer: z.number().min(0).max(1).optional(), - }).optional().describe('Element-state opacities (0–1): hover / focus / pressed are the share of the ink layered over a control\'s fill; disabledContent is the opacity of a disabled target, drawn in $text-primary, and disabledContainer the opacity its drawn fill or border shows at; setting either switches disabled from the 0.5 fallback to this pair (a lone one takes the other\'s value). Unset or out-of-range values take Material\'s. generate_design_system writes Material 3\'s values (0.08 / 0.10 / 0.10 / 0.38 / 0.12).'), + }).optional().describe('Element-state opacities (0–1): hover / focus / pressed are the share of the ink layered over a control\'s fill; disabledContent is the opacity of a disabled target, drawn in $text-primary, and disabledContainer the opacity its drawn fill or border shows at; setting either switches disabled from the 0.5 fallback to this pair (a lone valid one takes the other\'s Material value; with neither valid, disabled stays at 0.5). Unset or out-of-range hover / focus / pressed take Material\'s. generate_design_system writes Material 3\'s values (0.08 / 0.10 / 0.10 / 0.38 / 0.12).'), }).describe('Design variables to set'), }, async ({ canvasId, variables }) => { diff --git a/src/renderer.ts b/src/renderer.ts index 9dfec31..12e1fd0 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -1043,13 +1043,18 @@ function renderState(n: { state?: unknown; disabled?: unknown } | null | undefin } /** A colour that paints nothing: the keywords, and a zero alpha in hex, rgb() - * or hsl() form. A disabled container keeps it clear. */ + * or hsl() form (the fourth comma argument, or the value after a slash; a + * colour with no alpha is opaque). A disabled container keeps it clear. */ function isClear(c: string | undefined): boolean { if (!c) return true; const v = c.trim().toLowerCase(); - return v === 'transparent' || v === 'none' - || /^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/.test(v) - || /^(?:rgba?|hsla?)\(.*[,/]\s*0*\.?0+%?\s*\)$/.test(v); + if (v === 'transparent' || v === 'none' || /^#(?:[0-9a-f]{3}0|[0-9a-f]{6}00)$/.test(v)) return true; + const fn = /^(?:rgba?|hsla?)\((.*)\)$/.exec(v); + if (!fn) return false; + const slash = fn[1].split('/'); + const parts = fn[1].split(','); + const alpha = slash.length === 2 ? slash[1] : parts.length === 4 ? parts[3] : undefined; + return alpha !== undefined && /^\s*[+-]?0*(?:\.0*)?%?\s*$/.test(alpha) && /\d/.test(alpha); } /** The disabled token pair, when the design system sets it (spec P3). */ diff --git a/src/variables.ts b/src/variables.ts index 8b3a3f5..9b01be6 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -144,7 +144,7 @@ export function resolveStateStyle(v: DesignVariables): StateStyle { // FR-H1's chain: the renderer and the check never disagree. ring: c['focus-ring'] ?? c.accent ?? c.primary ?? CONTROL_FALLBACK.accent, onSurface: c['text-primary'] ?? CONTROL_FALLBACK.text, - surface: c['bg-surface'] ?? c.surface ?? CONTROL_FALLBACK.surface, + surface: c['bg-surface'] ?? c.surface ?? c['bg-primary'] ?? c.background ?? CONTROL_FALLBACK.surface, hover: unit(s.hover) ?? STATE_LAYERS.hover, focus: unit(s.focus) ?? STATE_LAYERS.focus, pressed: unit(s.pressed) ?? STATE_LAYERS.pressed, diff --git a/test-element-states.ts b/test-element-states.ts index 2de8ec5..2b68990 100644 --- a/test-element-states.ts +++ b/test-element-states.ts @@ -247,7 +247,8 @@ for (const s of ['rest', 'hover', 'focus', 'pressed'] as const) { const t = tag(render([{ id: 'n', type: 'button', label: 'S', variant: 'ghost', fill: f, state: 'disabled' }]), 'n'); check(`F4: a disabled ghost with fill ${f} stays clear`, t.includes(`background-color: ${f}`), t); } - for (const f of ['#2563EB1A', 'rgba(37,99,235,0.5)', 'rgb(10, 20, 30)', '#2563EB']) { + // An opaque colour whose last channel is 0 is not clear (3b: the alpha is the fourth argument or after a slash). + for (const f of ['#2563EB1A', 'rgba(37,99,235,0.5)', 'rgb(10, 20, 30)', '#2563EB', 'rgb(0,0,0)', 'rgb(255, 165, 0)', 'hsl(40, 100%, 0%)', 'rgb(0 0 0 / 0.5)', 'rgba(0,0,0,1)']) { const t = tag(render([{ id: 'n', type: 'button', label: 'S', fill: f, state: 'disabled' }]), 'n'); check(`F4 twin: a disabled button with fill ${f} takes the on-surface share`, t.includes(`background-color: color-mix(in srgb, ${ON}`), t); } @@ -346,6 +347,7 @@ for (const s of ['rest', 'hover', 'focus', 'pressed'] as const) { check('M: without $text-primary the on-surface colour is #111827', tag(render([{ id: 'n', type: 'button', label: 'S', disabled: true }], noText), 'n').includes('color: #111827')); const noSurface: DesignVariables = { colors: { accent: '#2563EB', 'text-primary': '#222222', surface: '#FAFAFA' }, state: { disabledContent: 0.38, disabledContainer: 0.12 } }; check('M: without $bg-surface the mark takes $surface', chunk(render([{ id: 'n', type: 'checkbox', checked: true, disabled: true }], noSurface), 'n').includes('stroke="#FAFAFA"')); + check('M: then $bg-primary / $background (a dark palette with no surface token keeps its mark visible)', chunk(render([{ id: 'n', type: 'checkbox', checked: true, disabled: true }], { colors: { 'text-primary': '#F3F7FE', background: '#111318' }, state: { disabledContent: 0.38, disabledContainer: 0.12 } }), 'n').includes('stroke="#111318"')); check('M: and with neither, #FFFFFF', chunk(render([{ id: 'n', type: 'checkbox', checked: true, disabled: true }], { colors: { 'text-primary': '#222222' }, state: { disabledContent: 0.38 } }), 'n').includes('stroke="#FFFFFF"')); // Host styles reach the items (tuned tokens differ from the fallback). const tuned: DesignVariables = { ...SYSTEM, colors: { ...C, 'focus-ring': '#B45309' }, state: { ...SYSTEM.state, hover: 0.2 } }; From 988088aae5aeef9bfe7f385ff50d7efdd7444c77 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Tue, 17 Nov 2026 17:17:33 +0100 Subject: [PATCH 5/5] Tidy slice G comments and keep the state resolver private --- src/renderer.ts | 3 ++- src/variables.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/renderer.ts b/src/renderer.ts index 12e1fd0..57810f7 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -993,7 +993,8 @@ function renderSelect(node: SceneNode, dataAttr: string): string { const fontSize = typeof node.fontSize === 'number' ? node.fontSize : 14; const isPlaceholder = !node.value; const textColor = isPlaceholder ? '#9CA3AF' : node.color; - // A select's frame is a container: the disabled pair splits it from its text. + // A select's frame is a container: `neutralised` (not whole) gave it the + // container share and its text the on-surface colour. const st = controlState(node, node.color); const frame = [ ringVar(node.stateStyle), diff --git a/src/variables.ts b/src/variables.ts index 9b01be6..82476f1 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -137,7 +137,8 @@ function hasDisabledTokens(v: DesignVariables): boolean { return unit(v.state?.disabledContent) !== undefined || unit(v.state?.disabledContainer) !== undefined; } -export function resolveStateStyle(v: DesignVariables): StateStyle { +/** The ring, the colours and the opacities a stateful node renders with. */ +function resolveStateStyle(v: DesignVariables): StateStyle { const c = v.colors ?? {}; const s = v.state ?? {}; const out: StateStyle = {