From 0082b0b4a70b9cc74e8084c5709b72a3c29622bf Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Fri, 13 Nov 2026 18:44:12 +0100 Subject: [PATCH 1/4] Add the desktop-app vocabulary: links, inputs, navigation and menus Phase 31 slice B. Eight primitives on the 24/32/40 ladder (link, text-input, nav-item, tabs, tree-row, menu-row, property-row, divider), a 24px button with an accessible name, inline text links and text titles. The new targets join the 24px census, identity dots never count as accents, and a canvas holding a desktop-app primitive must declare its type. --- README.md | 21 ++- VISION.md | 2 +- docs/GUIDELINES.md | 24 ++- docs/specs/PHASE-31-SPEC.md | 13 ++ src/desktop-app-rules.ts | 48 +++++- src/evaluate.ts | 37 ++++- src/index.ts | 23 ++- src/primitives.ts | 70 ++++++++- src/renderer.ts | 235 +++++++++++++++++++++++++++++- src/stress.ts | 9 ++ src/structures.ts | 27 +++- src/types.ts | 66 ++++++++- src/variables.ts | 62 +++++++- test-desktop-primitives-render.ts | 122 ++++++++++++++++ test-desktop-primitives.ts | 208 ++++++++++++++++++++++++++ test-pointer-targets.ts | 9 ++ 16 files changed, 925 insertions(+), 51 deletions(-) create mode 100644 test-desktop-primitives-render.ts create mode 100644 test-desktop-primitives.ts diff --git a/README.md b/README.md index c7db08a..ebc3c88 100644 --- a/README.md +++ b/README.md @@ -310,7 +310,7 @@ R("nodeId", { type: "text", content: "Replaced" }) **Returns** `{ ok, nodeIds, results }`. `nodeIds` maps each bound variable to the node ID it created — e.g. `{ "header": "n_a1b2" }` — so you can target those nodes in later calls (bindings only live within a single call). `results` lists each op's outcome in order; an op that succeeded but will not fully take effect carries a `warning` (a `shadow` beside an active `shadows`, a chart `highlight` entry outside the series data). If the call wrote a `fontFamily` nothing can serve yet (not cached, registered, or system/generic), a `Font warnings` content item names it — a cache-only check with no network call, so it's a heads-up, not exhaustive. -**Node types:** `frame`, `text`, `rectangle`, `ellipse`, `image`, `icon`, `path`, `component`, `instance`, `toggle`, `checkbox`, `radio`, `select`, `chart`, `skeleton` (loading-placeholder block — token-derived neutral fill; pulses subtly in the live viewer, always static in screenshots/exports so diffs stay deterministic; `pulse: false` opts a block out), and the mobile primitives `status-bar`, `home-indicator`, `nav-bar`, `tab-bar`, `button`, `list-row`, `sheet` (see [Mobile primitives](#mobile-primitives)) +**Node types:** `frame`, `text`, `rectangle`, `ellipse`, `image`, `icon`, `path`, `component`, `instance`, `toggle`, `checkbox`, `radio`, `select`, `chart`, `skeleton` (loading-placeholder block — token-derived neutral fill; pulses subtly in the live viewer, always static in screenshots/exports so diffs stay deterministic; `pulse: false` opts a block out), the mobile primitives `status-bar`, `home-indicator`, `nav-bar`, `tab-bar`, `button`, `list-row`, `sheet` (see [Mobile primitives](#mobile-primitives)), and the desktop-app primitives `link`, `text-input`, `nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`, `divider` (see [Desktop-app primitives](#desktop-app-primitives)) **Properties:** `fill`, `gradient`, `stroke`, `strokeWidth`, `strokeStyle`, `borderTop`, `borderRight`, `borderBottom`, `borderLeft`, `cornerRadius`, `width`, `height`, `minWidth`, `minHeight`, `maxWidth`, `layout` (`"horizontal"` | `"vertical"` | `"grid"`), `gap`, `rowGap`, `gridColumns`, `gridColumn`, `gridRow`, `padding`, `alignItems`, `justifyContent`, `fontSize`, `fontFamily`, `fontWeight`, `color`, `content`, `textAlign`, `lineHeight`, `letterSpacing` (px), `textDecoration`, `textTransform`, `textOverflow` (`"ellipsis"` — designed single-line truncation; `canvas_stress` reports clips behind it as info), `tabularNums`, `fontVariationSettings`, `src`, `objectFit`, `opacity`, `shadow` (CSS string, or `"$elevation."` referencing an elevation token), `shadows`, `blur`, `backdropBlur`, `backdropFilter`, `overflow`, `wrap`, `position` (`"absolute"` | `"relative"` | `"fixed"` | `"sticky"`), `x`, `y`, `bottom`, `right`, `icon`, `iconSize`, `iconColor`, `iconStyle`, `checked`, `disabled`, `value`, `d`, `viewBox`, `strokeLinecap`, `strokeLinejoin`, `strokeDasharray`, `animation`, `transition` (object, or `"$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 and bottom padding; `canvas_create` with `type: "mobile"` writes the device's), `name` (a readable label — `find_nodes` and component overrides match on it), `pulse` (skeleton only), `responsive` (`"stack"` | `"wrap"`) @@ -360,7 +360,7 @@ Phone screens are built from seven primitives that carry their own sizes, 44px h | `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` (`sm` 32 / `md` 44 / `lg` 52), `disabled` | `md` meets the phone floor; `sm` is a mobile error by design | +| `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 | | `sheet` | `detent`, `grabber`, children | A bottom sheet over a scrim, padded past the home indicator | @@ -380,6 +380,23 @@ I("document", { type: "home-indicator" }) The mobile ruleset judges them (see [`canvas_evaluate`](#canvas_evaluate)); [GUIDELINES](docs/GUIDELINES.md#mobile-vocabulary-primitives-and-pinning) has the pinned-CTA-bar idiom. +#### Desktop-app primitives + +Application screens (`type: "desktop-app"`) are built from eight primitives on the 24 / 32 / 40 / 48 density ladder, coloured from `$accent`, `$accent-tint`, `$border`, `$border-strong`, `$text-primary`, `$text-secondary` and `$danger` (neutral fallbacks unthemed). Labels truncate to one line with an ellipsis and keep their full text as a `title`. On web and desktop-app canvases each one except `property-row` and `divider` is a pointer target held to the 24px floor; a hand-built frame is not. + +| Type | Key props | What it is | +|---|---|---| +| `link` | `label`, `icon`, `iconPosition`, `external` | A standalone text action, at least 24 tall. 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`, `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` | +| `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 sole control inside it is measured by the row's box | +| `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`). + ### `find_nodes` Find nodes by what they are — property values, text content, or name — instead of hand-tracking ids. Read-only; the query twin of `replace_matching_properties`. diff --git a/VISION.md b/VISION.md index 81cb23d..5fb1ded 100644 --- a/VISION.md +++ b/VISION.md @@ -562,7 +562,7 @@ _Full spec-driven breakdown in [`docs/specs/PHASE-30-SPEC.md`](docs/specs/PHASE- Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 with zero findings: the viewer has a 17px Back link and 21 click targets that are plain spans, but the web hit-target rule only measures form controls. Meanwhile page rules misfired on the app: the sidebar project list read as a data table, the dense 13/14px type steps failed the scale ratio, and the projects' identity dots counted as competing accents. framesmith judges an application as if it were a marketing page, and has no words for what makes it an application. This phase adds a third type, `desktop-app` (a tool you work in, in a browser or a native window), with the vocabulary, rules, layouts, overlays and element states an app needs. Acceptance is literal: the viewer itself rebuilt as canvases, CLEAN, with every click target a primitive. - [x] Slice A — the type: `desktop-app` with a 1440×900 window profile, a ruleset that switches off the type-scale ratio, the WCAG 2.5.8 spacing exception on the 24px floor (web and desktop-app; mobile keeps its 44px rule) and navigation lists that never read as tables (every type), evaluate and import results an agent can read (repeated findings fold, keeping every fix), type-aware generation with state and control-color tokens, and the baseline canvases committed as fixtures -- [ ] Slice B — vocabulary: a 24px `button` with an accessible name, `link`, `text-input`, `nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row` and `divider`, plus identity dots that never count as accents (moved here from slice A: it keys on `nav-item`) +- [x] Slice B — vocabulary: a 24px `button` with an accessible name, `link`, `text-input`, `nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row` and `divider`, plus identity dots that never count as accents (moved here from slice A: it keys on `nav-item`) - [ ] Slice C — app rules: every click target measured, hand-built targets named, icon-only actions named, one current item per navigation group, a dense type ladder, row rhythm, honest truncation, one primary per region, and the declaration matching the window - [ ] Slice D — panes: resolution for any number of types and six desktop-app realisations (workbench, list-detail, editor-inspector, browser, dashboard, settings) under the pattern gate - [ ] 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 diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 79f4dac..bbb144a 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -75,22 +75,40 @@ 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. Today its ruleset does two things; the app rules, the app vocabulary, overlays and element states come in later slices of Phase 31. +A `desktop-app` canvas is judged as an application, not a page. Today its ruleset does two things, and its vocabulary is in [Desktop-app vocabulary](#desktop-app-vocabulary); the app rules, layouts, overlays and element states come in later slices of Phase 31. - **`type-scale-ratio` is off.** On web and mobile, adjacent font sizes must step by a ratio between 1.1 and 2.0, and a pair outside that warns with `rule: "type-scale-ratio"`. Dense apps step 12 / 13 / 14 on purpose, so the desktop-app ruleset turns that rule off; it is listed in the `surface` report's `rulesOff`. Pinned typography tokens still skip the check on every type. -- **`desktop-app-artboard`** (structure, warning; a base rule, so it runs on every type). A desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for. Resize the root to the window (`U("document", { width: 1440, height: 900 })`), or declare the type the canvas really is. +- **`desktop-app-artboard`** (structure; a base rule, so it runs on every type). + - A desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for, **warns**. Resize the root to the window (`U("document", { width: 1440, height: 900 })`), or declare the type the canvas really is. + - A canvas that holds a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) must say what it is: never declared **warns** until `canvas_set_type` declares it either way; declared `mobile` **warns** (those primitives are built for a pointer and a dense window, not a phone); declared `web` gets an **info**. Primitives inside a component instance count, and the finding names the first one found. There are no desktop-app realisations yet: `apply_structure` on a desktop-app canvas refuses every page anatomy and names the types it is realised on — `realisation: "web"`, plus `"mobile"` for the six mobile anatomies — so `realisation: "web"` stamps the web `split-workbench`, `dashboard` or `settings` onto it. Component scaffolds that stamp on every type stamp as usual. ### The 24px floor (web and desktop-app) -On web and desktop-app canvases every pointer target is measured against WCAG 2.5.8's 24px floor: the four controls (toggle, checkbox, radio, select) and the clickable primitives (`button`, `list-row`, each `tab-bar` tab and the FAB, each `nav-bar` action). A lone control first grows to its padded row, two levels up, as before; a disabled target is neither measured nor in anyone's way; nodes inside a component instance are judged as rendered and reported on the instance. What is still below 24px passes only by WCAG's **spacing exception**: a 24px circle centred on it must reach no other target's box and no other undersized target's circle (circles that only touch pass; a target nested inside another is not its neighbour). Spacing needs rendered positions, so: +On web and desktop-app canvases every pointer target is measured against WCAG 2.5.8's 24px floor: the four controls (toggle, checkbox, radio, select) and the clickable primitives (`button`, `list-row`, each `tab-bar` tab and the FAB, each `nav-bar` action, and the [desktop-app vocabulary](#desktop-app-vocabulary): `link`, `text-input`, `nav-item`, each tab of a `tabs` node, `tree-row`, `menu-row`). Inline text links and `divider`s are not targets. A lone control first grows to its padded row, two levels up, as before, and a control that is the only one inside a `property-row`, `nav-item`, `menu-row` or `list-row` is measured by that row's box; a disabled target is neither measured nor in anyone's way; nodes inside a component instance are judged as rendered and reported on the instance. What is still below 24px passes only by WCAG's **spacing exception**: a 24px circle centred on it must reach no other target's box and no other undersized target's circle (circles that only touch pass; a target nested inside another is not its neighbour). Spacing needs rendered positions, so: - **Detailed mode** (`canvas_evaluate({ canvasId, mode: "detailed" })`) runs the circle test and is the authority: a failure is an **error** that names the neighbour it reaches. - **Fast mode** cannot see spacing, so a target below 24px is a **warning** that names the exception and detailed mode. It blocks presenting until you grow the target or a detailed run clears it. Mobile keeps its own 44px rule (`mobile-touch-target`), which has no spacing exception. +### Desktop-app vocabulary + +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? }` is a standalone text action, at least 24 tall, and a measured target. 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. +- **`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. +- **`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. A control alone inside it is measured by the row's 32px box. +- **`divider`** `{ orientation?: "horizontal" | "vertical", inset? }` is a 1px `$border` hairline; vertical dividers separate panes. Not a target. + +Repeated desktop-app primitives count as component reuse. On an unthemed canvas, stamping a structure that holds them seeds `$accent-tint` and `$border-strong` along with the usual neutrals. + ### 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 8ba945c..477f631 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -207,6 +207,19 @@ One profile ships, keyed by id so a second size is one table row later. Values i - `src/stress.ts:44`: the new entries in `PRIMITIVE_TEXT_PROPS`. - The `breadcrumb` component rebuilt from `link`. +**Slice B — as built (recorded 2026-11-13; read this before slice C).** No spec change. Slice B shipped FR-B1 to FR-B10 plus the three items slice A deferred: FR-A6, the new primitives in the 24px census (D3), and the desktop-app-primitive clauses of FR-C9 (D2). Decisions the spec did not settle: +- **E1: FR-A6 needed no census code.** The accent census reads `fill`, `color`, `stroke` and `iconColor`; `dotColor` is a new prop it never reads, so identity dots are excluded by construction, a dot colour used as a literal elsewhere still counts, and hand-built dots still count. A comment in `tellAccentConsistency` says so; the tests pin all three. +- **E2: the census.** `CLICKABLE_PRIMITIVES` (`src/primitives.ts`) adds `link`, `text-input`, `nav-item`, `tabs` (one target per item, sharing the node id, so an undersized tab stays a detailed-mode warning, slice A D12), `tree-row` and `menu-row` to the phone tappables; `desktopTargets` gives each its own box. `property-row` and `divider` are not targets; inline text links are exempt. A control that is the only one inside a `property-row`, `nav-item`, `menu-row` or `list-row` (`CONTROL_OWNERS`) is measured by the row's box; only `property-row` renders children, so in practice that is an inspector value. Disabled tabs (`items[].disabled`) and disabled rows are not measured. +- **E3: the new primitives are not phone tappables.** The mobile touch census is unchanged; FR-C9's mobile clause warns instead. +- **E4: FR-C9's primitive clauses live in `checkDesktopArtboard`** (`src/desktop-app-rules.ts`), on the instance-expanded tree, reported on the instance. The finding names the first desktop-app primitive found. The overlay clause waits for slice E. +- **E5: colours without new props.** `tabs.fill` is the contained variant's active background (default `$accent-tint`). A `text-input`'s `error` colours its border and message through `stroke` (default `$danger` with an error, else `$border-strong`, else `$border`). Active `nav-item` / `tree-row` default `fill` to `$accent-tint`. Unthemed fallback tint `#EFF4FF`. +- **E6: seeding.** Stamping a structure that holds a desktop-app primitive on an unthemed canvas seeds `accent-tint` and `border-strong` (dark scaffold default `#666666`, at least 3:1 on the three dark surfaces); mobile stamps never seed them. The primitives' copy (`label`, `placeholder`, `value`, `shortcut`, `error`, `items[].label`) is a placeholder. +- **E7: a tree-row leaf keeps the chevron's 14px slot**, so labels align across leaves and branches. +- **E8: a long menu-row shortcut truncates** (at most half the row) like the label; found by the long-text render test. +- **E9: `link.external`** (named in FR-B2, missing from the Plan's prop list) draws a trailing external-link glyph. The hover underline waits for element states (FR-G1). +- **E10: the breadcrumb's parent is a `link`; the current page stays text.** The component keeps its web-only surface (slice D decides what stamps on desktop-app). +- **Open for slice C/D: form coverage ignores `text-input`.** The drift inventory's control list (toggle, checkbox, radio, select) is unchanged, so "3+ input controls demand an error state" does not count text-inputs. The spec is silent; decide with the form rules. + **Slice C: the app rules (FR-C1 to FR-C9)** - `src/evaluate.ts`: one check per rule id, wired in the rule-dispatch block (`:2355-2388`, where the typography, structure and usability checks pick up their type rules) the way the mobile checks are. - Row rhythm and truncation reuse the inventory's table detection; column alignment and the 4-character floor use detailed-mode layout (`computeLayout`, as `mobile-safe-area` does at `:2353`). diff --git a/src/desktop-app-rules.ts b/src/desktop-app-rules.ts index db1b8f7..f72d84f 100644 --- a/src/desktop-app-rules.ts +++ b/src/desktop-app-rules.ts @@ -3,14 +3,17 @@ import type { EvaluationIssue } from './evaluate.js'; import type { SceneNode } from './types.js'; +import { DESKTOP_APP_PRIMITIVES } from './primitives.js'; import { windowProfile, DEFAULT_WINDOW, WINDOW_PROFILES, type SurfaceDeclaration } from './surfaces.js'; -/** `desktop-app-artboard` (base ruleset, every type). Slice A: a desktop-app - * canvas narrower than its window's minimum warns. The clauses about - * desktop-app and overlay primitives on other types land with those - * primitives. */ +/** `desktop-app-artboard` (base ruleset, every type). A desktop-app canvas + * narrower than its window's minimum warns (slice A). A canvas that holds a + * desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) + * must say it is one (slice B): undeclared warns, an explicit `web` gets an + * info, an explicit `mobile` warns. The overlay clause lands with the + * overlay primitives (slice E). Reads the tree with instances expanded. */ export function checkDesktopArtboard(root: SceneNode, surface: SurfaceDeclaration): EvaluationIssue[] { - if (surface.type !== 'desktop-app') return []; + if (surface.type !== 'desktop-app') return checkAppPrimitivesDeclared(root, surface); const profile = windowProfile(surface.device ?? DEFAULT_WINDOW) ?? WINDOW_PROFILES[DEFAULT_WINDOW]; const width = typeof root.width === 'number' ? root.width : profile.width; if (width >= profile.minWidth) return []; @@ -24,3 +27,38 @@ export function checkDesktopArtboard(root: SceneNode, surface: SurfaceDeclaratio suggestion: `Resize it: U("document", { width: ${profile.width}, height: ${profile.height} }) — or canvas_set_type({ type: "mobile" }) / ({ type: "web" }) if it is a phone screen or a narrow web page.`, }]; } + +function firstAppPrimitive(root: SceneNode): SceneNode | undefined { + if (DESKTOP_APP_PRIMITIVES.has(root.type)) return root; + for (const c of root.children ?? []) { + const hit = firstAppPrimitive(c); + if (hit) return hit; + } + return undefined; +} + +function checkAppPrimitivesDeclared(root: SceneNode, surface: SurfaceDeclaration): EvaluationIssue[] { + const hit = firstAppPrimitive(root); + if (!hit) return []; + const what = `a ${hit.type}${hit.name ? ` ("${hit.name}")` : ''}`; + const base = { category: 'structure', rule: 'desktop-app-artboard', nodeId: hit.id, nodeName: hit.name } as const; + if (surface.source === 'default') { + return [{ + ...base, severity: 'warning', + message: `This canvas holds ${what}, a desktop-app primitive, but never declared its type, so it is judged as a web page.`, + suggestion: 'Declare it: canvas_set_type({ type: "desktop-app" }) for an application screen (a tool you work in), or canvas_set_type({ type: "web" }) if it really is a page you read.', + }]; + } + if (surface.type === 'mobile') { + return [{ + ...base, severity: 'warning', + message: `This canvas is declared mobile but holds ${what}, a desktop-app primitive built for pointer input and dense windows.`, + suggestion: 'Use the mobile vocabulary on a phone (list-row, tab-bar, nav-bar, button), or canvas_set_type({ type: "desktop-app" }) if this is an application window.', + }]; + } + return [{ + ...base, severity: 'info', + message: `This canvas is declared web but holds ${what}: an application screen should declare desktop-app so the desktop-app ruleset judges it.`, + suggestion: 'canvas_set_type({ type: "desktop-app" }) if this is a tool you work in.', + }]; +} diff --git a/src/evaluate.ts b/src/evaluate.ts index 3da4728..4488b9d 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -1,4 +1,4 @@ -import type { Canvas, SceneNode, DesignVariables } from './types.js'; +import type { Canvas, SceneNode, DesignVariables, TabItem } from './types.js'; import { resolveVariables } from './variables.js'; import { getCanvasTokens } from './workspaces.js'; import { renderToHtml, resolveInstance } from './renderer.js'; @@ -9,7 +9,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, 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, buttonBox, 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, effectivePosition, listRowMinHeight, navActions, pinsBottom, tabItemBox, tabItems } from './primitives.js'; // --- Types --- @@ -803,10 +803,11 @@ function checkStructure(entries: NodeEntry[], canvas: Canvas): CheckResult { issues.push(...iconFindings); // Component reuse. Phase 30 slice D — a repeated primitive (list rows, - // buttons, tab bars) is reuse too: the primitive is the component. + // buttons, tab bars) is reuse too: the primitive is the component. Phase 31 + // slice B adds the desktop-app vocabulary. const primitiveCounts = new Map(); for (const e of entries) { - if (e.node.type === 'button' || e.node.type === 'list-row' || e.node.type === 'tab-bar') { + if (REUSE_PRIMITIVES.has(e.node.type)) { primitiveCounts.set(e.node.type, (primitiveCounts.get(e.node.type) ?? 0) + 1); } } @@ -838,7 +839,7 @@ function iconSlots(root: SceneNode): Array<{ node: SceneNode; path: string; ref: add(n, 'leading.icon', n.leading?.icon, false, false); if (n.type === 'nav-bar' && Array.isArray(n.trailing)) n.trailing.slice(0, 2).forEach((a, i) => add(n, `trailing[${i}].icon`, a?.icon, false, false)); } else if (n.type === 'tab-bar') { - (Array.isArray(n.items) ? n.items : []).forEach((it, i) => add(n, `items[${i}].icon`, it?.icon, false, true)); + (Array.isArray(n.items) ? n.items as Array : []).forEach((it, i) => add(n, `items[${i}].icon`, it?.icon, false, true)); if (n.variant === 'fab') add(n, 'fab.icon', n.fab?.icon, false, false); } n.children?.forEach(walk); @@ -1798,6 +1799,9 @@ function tellAccentConsistency(ctx: ClicheCtx): EvaluationIssue[] { n.type === 'ellipse' || n.type === 'rectangle' || !!n.icon || (typeof n.width === 'number' && n.width < 600); + // Phase 31 FR-A6 — a nav-item's `dotColor` is an identity dot (a project, + // a label), never an accent: it is deliberately not one of the props read + // below. The same value used as a fill or colour elsewhere still counts. for (const { node } of ctx.entries) { if (node.id === rootId) continue; // page background isn't an accent const raw = ctx.rawById.get(node.id); @@ -1897,6 +1901,8 @@ function generateSummary(overall: number, categories: CategoryScore[], issues: E // tree so padding/dimensions are numbers. const CONTROL_TYPES = new Set(['toggle', 'checkbox', 'radio', 'select']); +/** Primitives whose repetition counts as component reuse (structure advisory). */ +const REUSE_PRIMITIVES = new Set(['button', 'list-row', 'tab-bar', 'link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row']); /** Renderer defaults (controlSize + select's padding-derived height). */ const CONTROL_DEFAULT_SIZE: Record = { toggle: { w: 44, h: 24 }, @@ -2013,6 +2019,16 @@ export function pointerTargets(entries: NodeEntry[], rootWidth: number): Pointer const def = CONTROL_DEFAULT_SIZE[node.type]; let w = typeof node.width === 'number' ? node.width : def.w; let h = typeof node.height === 'number' ? node.height : def.h; + // Phase 31 FR-A4 — a control that is the only one inside a row + // primitive (property-row, nav-item, menu-row, list-row) owns that row's + // box: the row is the target. Its height is the row's; its width the + // row's when known, else the row spans its container. + const owner = parentOf.get(node.id) ?? null; + if (owner && CONTROL_OWNERS.has(owner.type) && countControls(owner) === 1 && Math.min(w, h) < 24) { + const rowH = Math.max(typeof owner.height === 'number' ? owner.height : 0, OWNER_HEIGHT[owner.type] ?? 0); + w = typeof owner.width === 'number' ? owner.width : Infinity; + h = Math.max(h, rowH); + } let cur = parentOf.get(node.id) ?? null; for (let hop = 0; hop < 2 && cur && Math.min(w, h) < 24; hop++) { if (countControls(cur) === 1) { @@ -2027,11 +2043,20 @@ export function pointerTargets(entries: NodeEntry[], rootWidth: number): Pointer for (const t of primitiveTargets(node, parentOf, rootWidth)) { targets.push({ node, what: t.what, w: t.w ?? Infinity, h: t.h, disabled }); } + } else if (CLICKABLE_PRIMITIVES.has(node.type)) { + // Phase 31 slice B — the desktop-app vocabulary, each by its own box + // (a tabs node has one target per item, sharing the node's id). + for (const t of desktopTargets(node)) { + targets.push({ node, what: t.what, w: t.w ?? Infinity, h: t.h, disabled: t.disabled }); + } } } return targets; } +/** The heights the row primitives that own a sole control render at. */ +const OWNER_HEIGHT: Record = { 'property-row': PROPERTY_ROW_HEIGHT, 'nav-item': NAV_ITEM_HEIGHT, 'menu-row': MENU_ROW_HEIGHT, 'list-row': LIST_ROW_HEIGHT }; + /** The live targets still below 24px after the padded-row step — the ones * the circle test must place; [] means no detailed render is needed. */ export function undersizedTargets(targets: PointerTarget[]): PointerTarget[] { @@ -2528,7 +2553,7 @@ export async function evaluateCanvas( if (activeCategories.includes('structure')) { results.set('structure', withRuleIssues(checkStructure(rawEntries, canvas), [ ...(ruleOn.has('mobile-artboard') ? reportOnInstances(checkArtboard(mobile, declared), owners) : []), - ...(ruleOn.has('desktop-app-artboard') ? checkDesktopArtboard(resolvedRoot, declared) : []), + ...(ruleOn.has('desktop-app-artboard') ? reportOnInstances(checkDesktopArtboard(mobileRoot, declared), owners) : []), ])); } if (activeCategories.includes('consistency')) { diff --git a/src/index.ts b/src/index.ts index 5503aee..d4b56fe 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), 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. There are no desktop-app realisations yet: apply_structure refuses every page anatomy and names the types it is realised on (realisation: "web", plus "mobile" for the six mobile anatomies) — realisation: "web" stamps the web split-workbench, dashboard or settings; component scaffolds stamp as usual. On web and desktop-app every pointer target — the four controls and the clickable primitives — 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. +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). 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 — 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. There are no desktop-app realisations yet: apply_structure refuses every page anatomy and names the types it is realised on (realisation: "web", plus "mobile" for the six mobile anatomies) — realisation: "web" stamps the web split-workbench, dashboard or settings; component scaffolds stamp as usual. 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. 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. @@ -560,8 +560,8 @@ Use "document" to reference the root node. Bind results to reuse IDs: header=I(" 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 -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 +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 +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 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,11 +584,22 @@ Mobile primitives (phone screens — they carry their own sizes, hit areas, and - 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?: "sm"|"md"|"lg" (32/44/52), disabled? } — 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. + - 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. - 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? } — a standalone text action, at least 24 tall, measured as a pointer target. 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?, 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. + - 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 sole control inside it is measured by the row's box. + - divider { orientation?: "horizontal"|"vertical", inset? } — a 1px $border hairline; vertical ones separate panes. Not a target. +Labels truncate to one line with an ellipsis and carry their full text as a title; text nodes take title too. On web and desktop-app canvases every one of these except property-row and divider is a pointer target held to the 24px floor. A canvas that holds a nav-item, tabs, tree-row, menu-row or property-row must declare its type (desktop-app-artboard). + 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) @@ -2119,7 +2130,7 @@ server.tool( // --- canvas_evaluate --- server.tool( 'canvas_evaluate', - `Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too; they point at the component definition and carry no fix op. Modes: + `Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action, link, text-input, nav-item, each tab of a tabs node, tree-row, menu-row — inline text links and dividers are not targets, and a sole control inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too; they point at the component definition and carry no fix op. Modes: - "fast": JSON-only, <100ms, deterministic heuristics only. - "detailed": adds Puppeteer-based pixel overlap detection in the consistency category, laid out at the canvas's artboard size (siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt; a bar pinned to the top over in-flow content still counts). - "llm": fast-mode heuristics plus a vision-model critique against a FIXED rubric (provider picked from FRAMESMITH_LLM_PROVIDER env var, or whichever of ANTHROPIC_API_KEY / OPENAI_API_KEY is set). Adds an "llmCritique" field: { rubric: { hierarchy, execution, specificity, restraint, variety } each {score 1-5, rationale}, score (0-100 derived), summary, suggestions, needsRevision, failingAxes }. The verdict is stamped on the canvas (metadata.critique) + the per-project build log for auditability. Cost: one paid API call per invocation. To CLOSE the loop and auto-fix failing axes, use canvas_revise. @@ -2129,7 +2140,7 @@ THE HEURISTIC DIRECTIVE IS THE PRESENTATION GATE. mode: "llm" adds optional dept The result's "genre" field (present whenever cliche ran) makes the genre decision auditable: { active, source ("explicit" param | "provenance" stamp | null), relaxed (tells skipped, by the genre and by the applied preset), notRelaxed ([{ tell, relaxedBy }] — tells still flagging that a DIFFERENT genre would relax), byPreset ({ preset, relaxed } — present when the applied preset relaxed tells on its own, e.g. the material preset) }. active is the canonical genre: an alias reports as its canonical name ("dashboard" → "data", "checkout" → "commerce"). If the score is pinned by tells listed in notRelaxed, the genre is probably wrong — genre follows what the screen is FOR (read screens with the user's own figures → "data"; a screen you complete a purchase on → "commerce"; the Material style → "material" (an editor or admin console is a type, not a genre: declare it with canvas_create / canvas_set_type type "desktop-app")), not what it contains. -The result's "surface" field (always present) reports the canvas TYPE and the rules it selected: { type ("web" | "mobile" | "desktop-app"), device (the profile: a phone such as "iphone-390" on mobile, a window such as "window-1440" on desktop-app, null on web), source ("declared" by canvas_create type / canvas_set_type, or "default" — never declared, judged as web), rulesOn (rule ids the composed type + genre + preset rulesets turned on), rulesOff (rule ids they turned off), conflicts (ids both enabled and disabled — those stay ON) }. On a web canvas rulesOn is ["desktop-app-artboard", "mobile-artboard"] (the base rules, on for every type). On a desktop-app canvas rulesOff lists "type-scale-ratio" (the adjacent font-size ratio check, which tags its warnings with that rule id on web and mobile; dense apps step 12/13/14 on purpose), and desktop-app-artboard (structure, every type) WARNS when a desktop-app canvas is narrower than its window's 1024px minimum. On a mobile canvas it lists the mobile ruleset, and each finding from a rule carries a "rule" field with its id: mobile-touch-target (usability ERROR, −25 per target: a control — toggle/checkbox/radio/select — whose touch target is below 44px in either dimension; the target extends to its row only when the row is a horizontal frame holding that one tappable (no other control or tappable primitive), sized by the row's numeric height/minHeight, else the control plus the row's rendered padding; a row with no width inside a vertical parent that sets no alignItems stretches to that parent's width when the parent's own width is known. The tappable primitives are measured by their own box, never an ancestor's: a button (height by size, 32/44/52, or a larger height/minHeight; never narrower than tall), a list-row (44, 56 with a subtitle; its width when known), each tab-bar tab (bar width / slots × 49) and the FAB (56), each nav-bar action (44×44). Nodes inside an instance are judged as rendered and reported on the instance), mobile-handbuilt-target (usability info: a frame whose only content is one icon, or one icon plus a label of ≤3 words, with a box below 44px — rebuild it as a button if tappable), mobile-tab-bar (usability WARNING, −10 per condition: fewer than 2 or more than 5 tabs (the FAB is not a tab); a tab with no label; not pinned to the bottom — a position override or any y), mobile-safe-area (usability WARNING, −10: content in the status-bar or home-indicator inset, or left under a pinned bar. With root safeArea the renderer reserves the insets; pinned chrome (a fixed status-bar, tab-bar or home-indicator) raises the reservation to its height; so only positioned content is checked: absolute, fixed, and sticky at its stuck y. Without safeArea the first content must clear 47px and the last 34px through padding, spacer frames, pinned chrome, or an in-flow status-bar — padding ≥32px renders scaled down on a phone, about 27% at 390, so use a spacer frame inside the frame that holds your content. A pinned bar (fixed, not chrome) must keep its own content out of the inset, and the scroll must clear it: the last content's clearance from the bottom must reach the bar's height + its bottom offset (for a top bar, the first content's offset must reach its y + height) — the suggestion names the spacer height to add at the end (or start) of your content frame. A sheet's content is never judged (it is a padded overlay). Fast mode adds an info when it cannot place positioned content (inside an in-flow frame, or a fixed node under a blurred or animated ancestor) or cannot work out a pinned bar's height; detailed mode checks rendered rects and is authoritative: content in the top inset, positioned content in the screen's bottom inset, in-flow content in the last 34px of the document, sticky content where it sticks, and in-flow content under a bottom bar at the end of the scroll or a top bar at the start), mobile-type-floor (typography WARNING, −10: text below 11px, a $body text below 16px, prose of 5+ words below 13px; 12+ words at 13–15px is an info; figures and units are not words), mobile-one-column (usability info: prose side by side in a horizontal/grid frame), and mobile-artboard (structure; runs on EVERY type: a mobile canvas ≥500px wide WARNS, any other size than the device's is an info; an undeclared canvas narrower than 500px WARNS until canvas_set_type declares it; declared web and narrower than 500px gets an info). None has an autofix. +The result's "surface" field (always present) reports the canvas TYPE and the rules it selected: { type ("web" | "mobile" | "desktop-app"), device (the profile: a phone such as "iphone-390" on mobile, a window such as "window-1440" on desktop-app, null on web), source ("declared" by canvas_create type / canvas_set_type, or "default" — never declared, judged as web), rulesOn (rule ids the composed type + genre + preset rulesets turned on), rulesOff (rule ids they turned off), conflicts (ids both enabled and disabled — those stay ON) }. On a web canvas rulesOn is ["desktop-app-artboard", "mobile-artboard"] (the base rules, on for every type). On a desktop-app canvas rulesOff lists "type-scale-ratio" (the adjacent font-size ratio check, which tags its warnings with that rule id on web and mobile; dense apps step 12/13/14 on purpose), and desktop-app-artboard (structure, every type) WARNS when a desktop-app canvas is narrower than its window's 1024px minimum, and when a canvas holding a desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) never declared its type or is declared mobile — a canvas declared web gets an info instead. On a mobile canvas it lists the mobile ruleset, and each finding from a rule carries a "rule" field with its id: mobile-touch-target (usability ERROR, −25 per target: a control — toggle/checkbox/radio/select — whose touch target is below 44px in either dimension; the target extends to its row only when the row is a horizontal frame holding that one tappable (no other control or tappable primitive), sized by the row's numeric height/minHeight, else the control plus the row's rendered padding; a row with no width inside a vertical parent that sets no alignItems stretches to that parent's width when the parent's own width is known. The tappable primitives are measured by their own box, never an ancestor's: a button (height by size, 32/44/52, or a larger height/minHeight; never narrower than tall), a list-row (44, 56 with a subtitle; its width when known), each tab-bar tab (bar width / slots × 49) and the FAB (56), each nav-bar action (44×44). Nodes inside an instance are judged as rendered and reported on the instance), mobile-handbuilt-target (usability info: a frame whose only content is one icon, or one icon plus a label of ≤3 words, with a box below 44px — rebuild it as a button if tappable), mobile-tab-bar (usability WARNING, −10 per condition: fewer than 2 or more than 5 tabs (the FAB is not a tab); a tab with no label; not pinned to the bottom — a position override or any y), mobile-safe-area (usability WARNING, −10: content in the status-bar or home-indicator inset, or left under a pinned bar. With root safeArea the renderer reserves the insets; pinned chrome (a fixed status-bar, tab-bar or home-indicator) raises the reservation to its height; so only positioned content is checked: absolute, fixed, and sticky at its stuck y. Without safeArea the first content must clear 47px and the last 34px through padding, spacer frames, pinned chrome, or an in-flow status-bar — padding ≥32px renders scaled down on a phone, about 27% at 390, so use a spacer frame inside the frame that holds your content. A pinned bar (fixed, not chrome) must keep its own content out of the inset, and the scroll must clear it: the last content's clearance from the bottom must reach the bar's height + its bottom offset (for a top bar, the first content's offset must reach its y + height) — the suggestion names the spacer height to add at the end (or start) of your content frame. A sheet's content is never judged (it is a padded overlay). Fast mode adds an info when it cannot place positioned content (inside an in-flow frame, or a fixed node under a blurred or animated ancestor) or cannot work out a pinned bar's height; detailed mode checks rendered rects and is authoritative: content in the top inset, positioned content in the screen's bottom inset, in-flow content in the last 34px of the document, sticky content where it sticks, and in-flow content under a bottom bar at the end of the scroll or a top bar at the start), mobile-type-floor (typography WARNING, −10: text below 11px, a $body text below 16px, prose of 5+ words below 13px; 12+ words at 13–15px is an info; figures and units are not words), mobile-one-column (usability info: prose side by side in a horizontal/grid frame), and mobile-artboard (structure; runs on EVERY type: a mobile canvas ≥500px wide WARNS, any other size than the device's is an info; an undeclared canvas narrower than 500px WARNS until canvas_set_type declares it; declared web and narrower than 500px gets an info). None has an autofix. REPEATED FINDINGS FOLD in this result: three or more warnings or infos sharing a severity, category, rule (or tell) and theme come back as ONE entry when they also share their message — members that carry a fix match on its shape (quoted text and numbers aside, since each fix op holds its node's specifics), members without a fix only when they read the same apart from quoted node text, suggestion included. The entry keeps the first one's message and suggestion and adds nodeIds (distinct, nodeId first), count, and fixes ([{ nodeId, op }] for each member that had a fix) — act on every node it lists. Errors never fold. canvas_autofix and the directive work from the unfolded list.`, { diff --git a/src/primitives.ts b/src/primitives.ts index 4232c26..4ad59c2 100644 --- a/src/primitives.ts +++ b/src/primitives.ts @@ -2,12 +2,12 @@ // 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 } from './types.js'; +import type { SceneNode, TabItem, TabsItem } from './types.js'; import { DEFAULT_DEVICE, DEVICE_PROFILES, usableSafeArea } from './surfaces.js'; -export const BUTTON_HEIGHT = { sm: 32, md: 44, lg: 52 } as const; -export const BUTTON_PADDING = { sm: 12, md: 16, lg: 20 } as const; -export const BUTTON_FONT = { sm: 14, md: 16, lg: 17 } as const; +export const BUTTON_HEIGHT = { xs: 24, sm: 32, md: 44, lg: 52 } as const; +export const BUTTON_PADDING = { xs: 8, sm: 12, md: 16, lg: 20 } as const; +export const BUTTON_FONT = { xs: 12, sm: 14, md: 16, lg: 17 } as const; export const LIST_ROW_HEIGHT = 44; export const LIST_ROW_SUBTITLE_HEIGHT = 56; export const NAV_BAR_HEIGHT = 44; @@ -22,6 +22,32 @@ export const FAB_RAISE = 16; export const FLOATING_INSET = 16; export const TAPPABLE_PRIMITIVES = new Set(['button', 'list-row', 'tab-bar', 'nav-bar']); + +// Phase 31 slice B — the desktop-app vocabulary's geometry, on the 24 / 32 / +// 40 / 48 density ladder. +export const LINK_MIN_HEIGHT = 24; +export const NAV_ITEM_HEIGHT = 32; +export const TABS_HEIGHT = { sm: 32, md: 40 } as const; +export const TREE_ROW_HEIGHT = 32; +export const TREE_INDENT = 16; +export const MENU_ROW_HEIGHT = 32; +export const PROPERTY_ROW_HEIGHT = 32; +export const PROPERTY_LABEL_WIDTH = 96; +export const TEXT_INPUT_HEIGHT = { sm: 32, md: 40 } as const; +/** One line of a multi-line text-input (13px type at 20px leading). */ +export const TEXT_INPUT_LINE = 20; + +/** Every pointer target the web and desktop-app 24px census measures: the + * phone tappables plus the desktop-app vocabulary. `property-row` and + * `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']); + +/** Rows that own a sole control inside them: the control's target is the row. */ +export const CONTROL_OWNERS = new Set(['property-row', 'nav-item', 'menu-row', 'list-row']); + +/** The desktop-app primitives — on a canvas that never declared desktop-app, + * their presence asks for a declaration (desktop-app-artboard). */ +export const DESKTOP_APP_PRIMITIVES = new Set(['nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row']); /** Chrome a pinned position reserves room for, and the edge it pins to. */ export const CHROME_EDGE: Record = { 'status-bar': 'top', 'home-indicator': 'bottom', 'tab-bar': 'bottom' }; @@ -74,8 +100,40 @@ export function navBarHeight(n: SceneNode): number { } /** The tab items that render (a null entry is skipped). */ -export function tabItems(n: SceneNode): NonNullable { - return Array.isArray(n.items) ? n.items.filter((it) => !!it && typeof it === 'object') : []; +export function tabItems(n: SceneNode): TabItem[] { + return Array.isArray(n.items) ? (n.items as Array).filter((it): it is TabItem => !!it && typeof it === 'object') : []; +} + +/** Phase 31 — a `tabs` node's items that render. */ +export function tabsItems(n: SceneNode): TabsItem[] { + return Array.isArray(n.items) ? (n.items as Array).filter((it): it is TabsItem => !!it && typeof it === 'object') : []; +} + +export function textInputHeight(n: SceneNode): number { + const base = TEXT_INPUT_HEIGHT[n.size === 'sm' ? 'sm' : 'md']; + const rows = isNum(n.rows) && n.rows > 1 ? Math.floor(n.rows) : 1; + return rows > 1 ? Math.max(base, rows * TEXT_INPUT_LINE + 12) : base; +} + +/** The pointer targets a desktop-app primitive renders, each by its own box + * (width undefined when it is not known from the scene). `tabs` has one per + * item; the rest have one. Not for the phone tappables (see evaluate). */ +export function desktopTargets(n: SceneNode): Array<{ what: string; w?: number; h: number; disabled: boolean }> { + const w = isNum(n.width) ? n.width : undefined; + const h = (min: number) => Math.max(isNum(n.height) ? n.height : min, isNum(n.minHeight) ? n.minHeight : 0); + const disabled = n.disabled === true; + switch (n.type) { + case 'link': return [{ what: 'link', w, h: h(LINK_MIN_HEIGHT), disabled }]; + case 'text-input': return [{ what: 'text-input', w, h: Math.max(textInputHeight(n), isNum(n.height) ? n.height : 0), disabled }]; + case 'nav-item': return [{ what: 'nav-item', w: n.collapsed ? NAV_ITEM_HEIGHT : w, h: h(NAV_ITEM_HEIGHT), disabled }]; + case 'tree-row': return [{ what: 'tree-row', w, h: h(TREE_ROW_HEIGHT), disabled }]; + case 'menu-row': return [{ what: 'menu-row', w, h: h(MENU_ROW_HEIGHT), disabled }]; + case 'tabs': { + const th = h(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 })); + } + default: return []; + } } /** Slots across the band: one per item, plus the FAB's. */ diff --git a/src/renderer.ts b/src/renderer.ts index f540e94..94ecb06 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -5,6 +5,8 @@ import { usableSafeArea } from './surfaces.js'; import { BUTTON_FONT, BUTTON_PADDING, CHROME_EDGE, FAB_RAISE, FAB_SIZE, FLOATING_INSET, NAV_ACTION, NAV_BAR_HEIGHT, NAV_BAR_LARGE_HEIGHT, TAB_BAND, buttonHeight, chromeHeight, chromeReservation, effectivePosition, listRowMinHeight, navBarHeight, rootInsets, + LINK_MIN_HEIGHT, NAV_ITEM_HEIGHT, TABS_HEIGHT, TREE_ROW_HEIGHT, TREE_INDENT, MENU_ROW_HEIGHT, PROPERTY_ROW_HEIGHT, PROPERTY_LABEL_WIDTH, + tabsItems, textInputHeight, } from './primitives.js'; /** Build a `background: …` declaration from a node's `gradient`. @@ -603,7 +605,8 @@ function renderNode(node: SceneNode, rc: RenderCtx): string { const dataAttr = ` data-node-id="${node.id}"`; if (node.type === 'text') { - return `${escapeHtml(node.content ?? '')}

`; + const title = typeof node.title === 'string' && node.title.trim() ? ` title="${escapeAttr(node.title.trim())}"` : ''; + return `${textWithLinks(node)}

`; } if (node.type === 'image') { @@ -1000,6 +1003,15 @@ function renderPrimitive(node: SceneNode, rc: RenderCtx): string | undefined { case 'button': return renderButton(node, rc, `${dataAttr} tabindex="0" data-focusable`); case 'list-row': return renderListRow(node, rc, dataAttr); case 'sheet': return renderSheet(node, rc, dataAttr); + // Phase 31 slice B — desktop-app vocabulary. + case 'link': return renderLink(node, rc, `${dataAttr} tabindex="0" data-focusable role="link"`); + case 'text-input': return renderTextInput(node, rc, dataAttr); + case 'nav-item': return renderNavItem(node, rc, `${dataAttr} tabindex="0" data-focusable`); + case 'tabs': return renderTabs(node, rc, dataAttr); + case 'tree-row': return renderTreeRow(node, rc, `${dataAttr} tabindex="0" data-focusable role="treeitem"`); + case 'menu-row': return renderMenuRow(node, rc, `${dataAttr} tabindex="0" data-focusable role="menuitem"`); + case 'property-row': return renderPropertyRow(node, rc, dataAttr); + case 'divider': return renderDivider(node, rc, `${dataAttr} role="separator"`); default: return undefined; } } @@ -1145,15 +1157,18 @@ function renderTabBar(node: SceneNode, rc: RenderCtx, dataAttr: string): string } function renderButton(node: SceneNode, rc: RenderCtx, attrs: string): string { - const size = node.size === 'sm' || node.size === 'lg' ? node.size : 'md'; + const size = node.size === 'xs' || node.size === 'sm' || node.size === 'lg' ? node.size : 'md'; + // 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)}"`; const h = buttonHeight(node); const words = text(node.label) ? labelHtml(text(node.label), '') : ''; // Unthemed (a button inside a component skips resolveVariables): the // primary look, so it is never an invisible white-on-transparent label. const fill = node.fill ?? (node.variant === 'secondary' || node.variant === 'ghost' ? 'transparent' : node.variant === 'destructive' ? FALLBACK.danger : FALLBACK.accent); const color = node.color ?? (fill === 'transparent' ? FALLBACK.accent : '#FFFFFF'); - const glyph = iconHtml(node.icon, size === 'sm' ? 16 : 20, color); - const radius = typeof node.cornerRadius === 'number' ? node.cornerRadius : 8; + 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 box = css([ `--fs-ring: ${fill !== 'transparent' ? fill : color}`, ...positionStyles(node, rc), 'display: inline-flex', 'flex-shrink: 0', 'align-items: center', 'justify-content: center', 'gap: 8px', @@ -1225,6 +1240,218 @@ function renderListRow(node: SceneNode, rc: RenderCtx, dataAttr: string): string return `${listRowLeading(node)}${words}${listRowTrailing(node)}${divider}`; } +// ── Phase 31 slice B — the desktop-app vocabulary ──────────────────────── +// Same contract as the mobile primitives: fixed anatomy on the 24/32/40/48 +// ladder, colours from applyControlDefaults (FALLBACK only when a primitive +// skipped it), labels in `data-fs-label` so they truncate with a title. + +/** A label that can truncate, carrying its full text as a title. */ +function titledLabel(value: string, style: string): string { + return `${escapeHtml(value)}`; +} + +/** Width of a row primitive: an authored width, else its container's. */ +function rowWidth(node: SceneNode): string { + return node.width !== undefined ? `width: ${cssLength(node.width)}` : 'align-self: stretch'; +} + +/** A text node's content with its inline links (FR-B2) underlined in place. + * Ranges are character offsets [start, end); bad or overlapping ones are + * skipped, so content always renders whole. */ +function textWithLinks(node: SceneNode): string { + const content = node.content ?? ''; + const ranges = entries<{ start?: unknown; end?: unknown }>(node.links) + .map((r) => ({ start: Number(r.start), end: Number(r.end) })) + .filter((r) => Number.isInteger(r.start) && Number.isInteger(r.end) && r.start >= 0 && r.end > r.start && r.end <= content.length) + .sort((a, b) => a.start - b.start); + let out = ''; + let at = 0; + for (const r of ranges) { + if (r.start < at) continue; + out += escapeHtml(content.slice(at, r.start)); + out += `${escapeHtml(content.slice(r.start, r.end))}`; + at = r.end; + } + return out + escapeHtml(content.slice(at)); +} + +function renderLink(node: SceneNode, rc: RenderCtx, attrs: string): string { + const color = node.color ?? FALLBACK.accent; + const glyph = iconHtml(node.icon, 14, node.iconColor ?? color); + const external = node.external ? iconHtml('external-link', 12, node.iconColor ?? color) : ''; + const words = text(node.label) ? titledLabel(text(node.label), '') : ''; + const box = css([ + ...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, + ]); + const body = node.iconPosition === 'trailing' ? `${words}${glyph}` : `${glyph}${words}`; + return `${body}${external}`; +} + +function renderTextInput(node: SceneNode, rc: RenderCtx, dataAttr: string): string { + const h = textInputHeight(node); + const multi = typeof node.rows === 'number' && node.rows > 1; + const border = node.stroke ?? FALLBACK.border; + const secondary = node.secondaryColor ?? FALLBACK.secondary; + const value = text(node.value); + const shown = value || text(node.placeholder); + const radius = typeof node.cornerRadius === 'number' ? node.cornerRadius : 6; + const field = css([ + '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', + ]); + const glyph = iconHtml(node.icon, 16, secondary); + const words = shown + ? (multi + ? `${escapeHtml(shown)}` + : `${titledLabel(shown, `color: ${value ? node.color ?? FALLBACK.text : secondary}`)}`) + : ''; + const error = text(node.error); + const message = error + ? `
${iconHtml('circle-alert', 14, border)}${titledLabel(error, '')}
` + : ''; + 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, + ]); + const ariaInvalid = error ? ' aria-invalid="true"' : ''; + return `
${glyph}${words}
${message}`; +} + +function renderNavItem(node: SceneNode, rc: RenderCtx, attrs: string): string { + const color = node.color ?? FALLBACK.text; + const accent = node.iconColor ?? FALLBACK.accent; + const label = text(node.label); + if (node.active) attrs += ' aria-current="page"'; + if (node.collapsed && label) attrs += ` aria-label="${escapeAttr(label)}" title="${escapeAttr(label)}"`; + const depth = node.depth === 1 ? 1 : 0; + const bar = node.active + ? `
` + : ''; + const dot = node.dotColor ? `` : ''; + const glyph = iconHtml(node.icon, 16, node.active ? accent : node.secondaryColor ?? FALLBACK.secondary); + const count = text(node.count); + const box = css([ + ...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`, + node.collapsed ? `width: ${NAV_ITEM_HEIGHT}px` : rowWidth(node), + node.collapsed ? 'justify-content: center; padding: 0' : `padding: 0 8px 0 ${8 + depth * TREE_INDENT}px`, + `border-radius: ${typeof node.cornerRadius === 'number' ? node.cornerRadius : 6}px`, + 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, + ]); + if (node.collapsed) return `${bar}${glyph || dot}`; + const tail = count ? `${escapeHtml(count)}` : ''; + return `${bar}${dot}${glyph}${label ? `${titledLabel(label, '')}` : ''}${tail}`; +} + +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'; + const tabs = tabsItems(node).map((it) => { + const label = text(it.label); + const count = text(it.count); + const active = it.active === true; + const tab = css([ + 'position: relative', 'display: flex', 'align-items: center', 'gap: 6px', 'flex-shrink: 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, + ]); + const indicator = line && active + ? `
` + : ''; + const badge = count ? `${escapeHtml(count)}` : ''; + return `
${titledLabel(label, '')}${badge}${indicator}
`; + }).join(''); + const box = css([ + ...positionStyles(node, rc), 'display: flex', 'align-items: stretch', 'gap: 2px', 'flex-shrink: 0', 'box-sizing: border-box', + `height: ${h}px`, rowWidth(node), 'overflow: hidden', 'font-size: 13px', + line ? `border-bottom: 1px solid ${node.stroke ?? FALLBACK.border}` : undefined, + ]); + return `${tabs}`; +} + +function renderTreeRow(node: SceneNode, rc: RenderCtx, attrs: string): string { + 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 box = css([ + ...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, + ]); + const slot = `${chevron}`; + const glyph = iconHtml(node.icon, 16, node.active ? node.iconColor ?? FALLBACK.accent : secondary); + return `${slot}${glyph}${titledLabel(text(node.label), '')}`; +} + +function renderMenuRow(node: SceneNode, rc: RenderCtx, attrs: string): string { + const secondary = node.secondaryColor ?? FALLBACK.secondary; + const color = node.color ?? (node.destructive ? FALLBACK.danger : FALLBACK.text); + if (node.disabled) attrs += ' aria-disabled="true"'; + if (typeof node.checked === 'boolean') attrs += ` aria-checked="${node.checked}"`; + const check = node.checked ? iconHtml('check', 14, node.iconColor ?? FALLBACK.accent) : ''; + const glyph = iconHtml(node.icon, 16, node.destructive ? color : secondary); + // The shortcut keeps its width unless it is long, then truncates (at most + // half the row) like the label, so a long shortcut never pushes the row + // past its menu. + const shortcut = text(node.shortcut) + ? `${titledLabel(text(node.shortcut), '')}` + : ''; + const chevron = node.submenu ? `${iconHtml('chevron-right', 14, secondary)}` : ''; + const box = css([ + ...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, + ]); + const checkSlot = typeof node.checked === 'boolean' ? `${check}` : ''; + return `${checkSlot}${glyph}${titledLabel(text(node.label), '')}${shortcut}${chevron}`; +} + +function renderPropertyRow(node: SceneNode, rc: RenderCtx, dataAttr: string): string { + const width = typeof node.labelWidth === 'number' && node.labelWidth > 0 ? node.labelWidth : PROPERTY_LABEL_WIDTH; + const box = css([ + ...positionStyles(node, rc), 'display: flex', 'align-items: center', 'gap: 8px', 'flex-shrink: 0', 'box-sizing: border-box', + `min-height: ${PROPERTY_ROW_HEIGHT}px`, typeof node.height === 'number' ? `height: ${node.height}px` : undefined, rowWidth(node), + `color: ${node.color ?? FALLBACK.text}`, 'font-size: 13px', + ]); + const label = `
${titledLabel(text(node.label), `color: ${node.secondaryColor ?? FALLBACK.secondary}; font-size: 12px`)}
`; + const value = `
${renderChildren(node, rc)}
`; + return `${label}${value}`; +} + +function renderDivider(node: SceneNode, rc: RenderCtx, attrs: string): string { + const vertical = node.orientation === 'vertical'; + const inset = typeof node.inset === 'number' && node.inset > 0 ? node.inset : 0; + if (vertical) attrs += ' aria-orientation="vertical"'; + const box = css([ + ...positionStyles(node, rc), 'flex-shrink: 0', `background-color: ${node.stroke ?? FALLBACK.border}`, + vertical ? 'width: 1px' : 'height: 1px', + vertical ? 'align-self: stretch' : 'align-self: stretch', + vertical ? (inset ? `margin: ${inset}px 0` : undefined) : (inset ? `margin: 0 ${inset}px` : undefined), + vertical && typeof node.height === 'number' ? `height: ${node.height}px` : undefined, + !vertical && node.width !== undefined ? `width: ${cssLength(node.width)}` : undefined, + ]); + return ``; +} + /** The four authored padding sides as CSS (fluid like every padding). */ function paddingCss(padding: SceneNode['padding']): [string, string, string, string] { const px = (v: unknown) => (typeof v === 'number' ? responsivePadding(v) : '0px'); diff --git a/src/stress.ts b/src/stress.ts index 2497766..1caf49d 100644 --- a/src/stress.ts +++ b/src/stress.ts @@ -50,6 +50,15 @@ export const PRIMITIVE_TEXT_PROPS: { type: string; path: string; fixed?: boolean { type: 'nav-bar', path: 'title' }, { type: 'nav-bar', path: 'leading.label', fixed: true }, { type: 'nav-bar', path: 'trailing[].label', fixed: true }, + // Phase 31 slice B — the desktop-app vocabulary. + { type: 'link', path: 'label' }, + { type: 'nav-item', path: 'label' }, + { type: 'tabs', path: 'items[].label' }, + { type: 'tree-row', path: 'label' }, + { type: 'menu-row', path: 'label' }, + { type: 'menu-row', path: 'shortcut' }, + { type: 'property-row', path: 'label' }, + { type: 'text-input', path: 'value' }, ]; /** One perturbable string: a text node's content or a primitive's prop. */ diff --git a/src/structures.ts b/src/structures.ts index 7fca638..e4b1939 100644 --- a/src/structures.ts +++ b/src/structures.ts @@ -1414,11 +1414,11 @@ const segmentedControl: Structure = { const breadcrumb: Structure = { name: 'breadcrumb', kind: 'component', - description: 'A two-level breadcrumb: muted parent, chevron, bold current page. Extend by copying the parent+chevron pair via batch_design.', + description: 'A two-level breadcrumb: a muted parent link, chevron, bold current page (plain text — it is where you are). The parent is a `link` primitive, so it is a measured 24px target. Extend by copying the link+chevron pair via batch_design.', nodes: [{ id: 'crumb', type: 'frame', name: 'Breadcrumb', layout: 'horizontal', alignItems: 'center', gap: SPACE.xs2, children: [ - { id: 'crumb-parent', type: 'text', content: 'Parent', fontSize: TYPE.textSm, color: COLOR.textSecondary, textOverflow: 'ellipsis' }, + { id: 'crumb-parent', type: 'link', label: 'Parent', fontSize: TYPE.textSm, fontWeight: 400, color: COLOR.textSecondary }, { id: 'crumb-sep', type: 'icon', icon: 'chevron-right', iconSize: 14, iconColor: COLOR.textSecondary }, { id: 'crumb-current', type: 'text', content: 'Current page', fontSize: TYPE.textSm, fontWeight: 600, color: COLOR.textPrimary, textOverflow: 'ellipsis' }, ], @@ -1921,6 +1921,8 @@ const DEFAULT_SCAFFOLD_COLORS: Record = { 'warning-tint': '#33260A', 'danger-tint': '#3A1715', 'neutral-tint': '#25282D', + // Phase 31 — a control's only boundary: 3:1 against every dark surface above. + 'border-strong': '#666666', }; /** Phase 27 slice B — default values for the non-color token namespaces the @@ -1971,13 +1973,22 @@ const COLOR_FIELDS = ['fill', 'color', 'stroke', 'iconColor'] as const; * though no prop names them, so they seed like any other reference — without * this, an unthemed settings-mobile drew near-black row titles on the dark * default background. */ -const PRIMITIVE_TYPES = new Set(['status-bar', 'home-indicator', 'nav-bar', 'tab-bar', 'button', 'list-row', 'sheet']); +const PRIMITIVE_TYPES = new Set([ + 'status-bar', 'home-indicator', 'nav-bar', 'tab-bar', 'button', 'list-row', 'sheet', + // Phase 31 slice B — the desktop-app vocabulary. + 'link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row', 'divider', +]); const PRIMITIVE_COLOR_TOKENS: Record = { 'text-primary': [], 'text-secondary': [], border: [], // The token, then the names applyControlDefaults falls back to: a canvas // that resolves the fallback keeps it rather than getting a seeded default. accent: ['primary'], 'bg-surface': ['surface'], danger: ['error'], }; +/** Phase 31 — the extra tokens the desktop-app vocabulary reads: the active + * fill of nav-item / tree-row / contained tabs, and a text-input's boundary + * (which falls back to `border`). Mobile stamps never seed them. */ +const DESKTOP_PRIMITIVE_TYPES = new Set(['link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row', 'divider']); +const DESKTOP_PRIMITIVE_COLOR_TOKENS: Record = { 'accent-tint': [], 'border-strong': ['border'] }; /** A primitive's copy fields as [path, text]: what an agent replaces. */ function primitiveCopy(n: SceneNode): [string, string][] { @@ -1986,12 +1997,17 @@ function primitiveCopy(n: SceneNode): [string, string][] { add('title', n.title); add('subtitle', n.subtitle); add('label', n.label); + // Phase 31 — the desktop-app vocabulary's copy. + add('placeholder', n.placeholder); + add('value', n.value); + add('shortcut', n.shortcut); + add('error', n.error); const leading = n.leading as Record | undefined; add('leading.initials', leading?.initials); add('leading.label', leading?.label); if (Array.isArray(n.trailing)) n.trailing.forEach((a, i) => add(`trailing[${i}].label`, (a as Record | null)?.label)); else add('trailing.text', (n.trailing as Record | undefined)?.text); - (n.items ?? []).forEach((item, i) => add(`items[${i}].label`, item?.label)); + (Array.isArray(n.items) ? n.items as Array<{ label?: unknown } | null> : []).forEach((item, i) => add(`items[${i}].label`, item?.label)); return out; } @@ -2143,7 +2159,8 @@ export function applyStructure( for (const root of inserted) { walkNodes(root, (n) => { if (PRIMITIVE_TYPES.has(n.type)) { - for (const [token, fallbacks] of Object.entries(PRIMITIVE_COLOR_TOKENS)) { + const tokens = { ...PRIMITIVE_COLOR_TOKENS, ...(DESKTOP_PRIMITIVE_TYPES.has(n.type) ? DESKTOP_PRIMITIVE_COLOR_TOKENS : {}) }; + for (const [token, fallbacks] of Object.entries(tokens)) { if (!fallbacks.some((f) => opts.existingColors?.has(f))) referenced.add(token); } } diff --git a/src/types.ts b/src/types.ts index dcf77b6..67429d8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -9,7 +9,10 @@ export type NodeType = 'frame' | 'text' | 'rectangle' | 'ellipse' | 'image' | 'i | 'chart' // Phase 30 slice D — mobile vocabulary: device chrome, navigation, and the // tappable content primitives (each carries its own hit area). - | 'status-bar' | 'home-indicator' | 'nav-bar' | 'tab-bar' | 'button' | 'list-row' | 'sheet'; + | 'status-bar' | 'home-indicator' | 'nav-bar' | 'tab-bar' | 'button' | 'list-row' | 'sheet' + // Phase 31 slice B — desktop-app vocabulary: links, inputs, navigation, + // menus and inspector rows (each carries its own hit area), and a hairline. + | 'link' | 'text-input' | 'nav-item' | 'tabs' | 'tree-row' | 'menu-row' | 'property-row' | 'divider'; /** Phase 30 slice D — one `nav-bar` action: an icon or a text label. */ export interface NavAction { icon?: string; label?: string } @@ -17,6 +20,14 @@ export interface NavAction { icon?: string; label?: string } /** Phase 30 slice D — one `tab-bar` item. */ export interface TabItem { icon: string; label: string; active?: boolean; badge?: string | number } +/** 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 } + +/** Phase 31 slice B — an inline link inside a `text` node's content: + * character offsets [start, end). */ +export interface TextLink { start: number; end: number } + /** Phase 30 slice D — a `list-row`'s trailing accessory (one of). */ export interface ListRowTrailing { text?: string; chevron?: boolean; toggle?: boolean; badge?: string | number } @@ -279,7 +290,7 @@ export interface SceneNode { /** status-bar / home-indicator: "dark" glyphs for a light screen, "light" * for a dark one; absent follows `color` ($text-primary). */ appearance?: 'dark' | 'light'; - /** nav-bar / list-row title. */ + /** nav-bar / list-row title; on a `text` node (Phase 31) the tooltip, rendered as the title attribute. */ title?: string; /** list-row secondary line. */ subtitle?: string; @@ -290,17 +301,17 @@ export interface SceneNode { trailing?: NavAction[] | ListRowTrailing; /** nav-bar: the 96px large-title form. */ largeTitle?: boolean; - /** tab-bar items (2–5 on a phone). */ - items?: TabItem[]; - /** tab-bar: standard | floating | fab; button: primary | secondary | ghost | destructive. */ - variant?: 'standard' | 'floating' | 'fab' | 'primary' | 'secondary' | 'ghost' | 'destructive'; + /** tab-bar items (2–5 on a phone); tabs items (Phase 31). */ + items?: TabItem[] | TabsItem[]; + /** tab-bar: standard | floating | fab; button: primary | secondary | ghost | destructive; tabs: line | contained. */ + variant?: 'standard' | 'floating' | 'fab' | 'primary' | 'secondary' | 'ghost' | 'destructive' | 'line' | 'contained'; /** tab-bar (variant "fab"): the raised centre action. */ fab?: { icon?: string }; /** button label. */ label?: string; iconPosition?: 'leading' | 'trailing'; - /** button: sm 32 / md 44 / lg 52. */ - size?: 'sm' | 'md' | 'lg'; + /** button: xs 24 / sm 32 / md 44 / lg 52; tabs and text-input: sm 32 / md 40. */ + size?: 'xs' | 'sm' | 'md' | 'lg'; /** list-row: a hairline under the row from the 16px inset. */ divider?: boolean; /** sheet: medium (half the screen) | large | auto (its content). */ @@ -312,6 +323,45 @@ export interface SceneNode { /** tab-bar item badge / list-row badge colour (tab-bar default $danger). */ badgeColor?: string; + // Phase 31 slice B — desktop-app primitives. + /** button (icon-only) / nav-item (collapsed): the accessible name, rendered + * as aria-label and title; never rendered as text. */ + ariaLabel?: string; + /** link: it leaves the app (a trailing external-link glyph). */ + external?: boolean; + /** text: inline links inside `content`, as character ranges. */ + links?: TextLink[]; + /** nav-item: a trailing count. */ + count?: string | number; + /** nav-item: an identity dot's colour (a project, a label). Not an accent. */ + dotColor?: string; + /** nav-item / tree-row: the current location. */ + active?: boolean; + /** nav-item 0 | 1; tree-row 0, 1, 2, … — indents 16px per level. */ + depth?: number; + /** nav-item: the rail form — icon only, 32×32, label as the name. */ + collapsed?: boolean; + /** tree-row: true open, false closed, absent for a leaf. */ + expanded?: boolean; + /** menu-row: a keyboard shortcut, right-aligned. */ + shortcut?: string; + /** menu-row: a destructive action ($danger). */ + destructive?: boolean; + /** menu-row: opens a submenu (trailing chevron). */ + submenu?: boolean; + /** property-row: the label column's width (default 96). */ + labelWidth?: number; + /** text-input: the hint shown when empty. */ + placeholder?: string; + /** text-input: a multi-line field of this many lines. */ + rows?: number; + /** text-input: an error message, shown below the field with an icon. */ + error?: string; + /** divider: horizontal (default) or vertical. */ + orientation?: 'horizontal' | 'vertical'; + /** divider: inset from both ends (px). */ + inset?: number; + // Component / Instance componentId?: string; overrides?: Record>; diff --git a/src/variables.ts b/src/variables.ts index ab512eb..51f081a 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -118,24 +118,28 @@ function applyControlDefaults(node: SceneNode, v: DesignVariables): void { if (node.fill === undefined) node.fill = v.colors?.skeleton ?? v.colors?.border ?? 'rgba(127, 127, 127, 0.22)'; return; } - if (MOBILE_PRIMITIVES.has(t)) { applyPrimitiveDefaults(node, v); return; } + if (PRIMITIVES.has(t)) { applyPrimitiveDefaults(node, v); return; } if (t !== 'toggle' && t !== 'checkbox' && t !== 'radio' && t !== 'select') return; const accent = v.colors?.accent ?? v.colors?.primary ?? CONTROL_FALLBACK.accent; const border = v.colors?.border ?? CONTROL_FALLBACK.border; + // Phase 31 FR-B8 — an unchecked box, ring or track is the control's only + // boundary: it takes $border-strong (3:1) when the design system has it. + // Without the token the render is unchanged. + const boundary = v.colors?.['border-strong'] ?? border; if (node.disabled && node.opacity === undefined) node.opacity = 0.5; if (t === 'toggle') { // fill = track color; the knob is always white. - if (node.fill === undefined) node.fill = node.checked ? accent : border; + if (node.fill === undefined) node.fill = node.checked ? accent : boundary; } else if (t === 'checkbox') { // fill = box background (transparent when unchecked so dark surfaces work). if (node.fill === undefined) node.fill = node.checked ? accent : 'transparent'; - if (node.stroke === undefined) node.stroke = node.checked ? accent : border; + if (node.stroke === undefined) node.stroke = node.checked ? accent : boundary; } else if (t === 'radio') { // stroke = ring, fill = dot (drawn only when checked). - if (node.stroke === undefined) node.stroke = node.checked ? accent : border; + if (node.stroke === undefined) node.stroke = node.checked ? accent : boundary; if (node.fill === undefined) node.fill = accent; } else { // select @@ -147,7 +151,11 @@ function applyControlDefaults(node: SceneNode, v: DesignVariables): void { // Phase 30 slice D — the mobile primitives default the same way: tokens when // the canvas has them, neutral fallbacks when it doesn't, explicit props win. -const MOBILE_PRIMITIVES = new Set(['status-bar', 'home-indicator', 'nav-bar', 'tab-bar', 'button', 'list-row', 'sheet']); +// Phase 31 slice B — the desktop-app vocabulary joins them. +const PRIMITIVES = new Set([ + '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', +]); function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { const c = v.colors ?? {}; @@ -157,10 +165,49 @@ function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { const text = c['text-primary'] ?? CONTROL_FALLBACK.text; const secondary = c['text-secondary'] ?? '#6B7280'; const danger = c.danger ?? c.error ?? '#DC2626'; + const tint = c['accent-tint'] ?? '#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; switch (node.type) { + // Phase 31 slice B — the desktop-app vocabulary. + case 'link': + set('color', accent); + break; + case 'text-input': + set('fill', surface); + // An error colours the boundary and the message below it. + set('stroke', text_(node.error) ? danger : c['border-strong'] ?? border); + set('color', text); + set('secondaryColor', secondary); + break; + case 'nav-item': + case 'tree-row': + set('color', text); + set('secondaryColor', secondary); + set('iconColor', accent); + if (node.active) set('fill', tint); + break; + case 'tabs': + set('color', text); + set('secondaryColor', secondary); + set('iconColor', accent); + set('stroke', border); + // The contained variant's active tab sits on the tint. + set('fill', tint); + break; + case 'menu-row': + set('color', node.destructive ? danger : text); + set('secondaryColor', secondary); + set('iconColor', accent); + break; + case 'property-row': + set('color', text); + set('secondaryColor', secondary); + break; + case 'divider': + set('stroke', border); + break; case 'status-bar': case 'home-indicator': set('color', text); @@ -206,6 +253,11 @@ function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { } } +/** A prop as text, for "is it set?" checks. */ +function text_(value: unknown): string { + return typeof value === 'string' ? value.trim() : ''; +} + /** White or near-black (#111827), whichever contrasts more with a hex fill. */ function onFill(fill: string | undefined): string { const m = /^#([0-9a-f]{6})$/i.exec(fill ?? ''); diff --git a/test-desktop-primitives-render.ts b/test-desktop-primitives-render.ts new file mode 100644 index 0000000..4de69a4 --- /dev/null +++ b/test-desktop-primitives-render.ts @@ -0,0 +1,122 @@ +// Phase 31 slice B — the desktop-app vocabulary as rendered (Chrome): sizes on +// the 24/32/40 ladder, indents, aligned shortcut and value columns, a 1px +// full-height pane divider, both themes, and long text that truncates by +// design instead of clipping or overflowing. +// +// Usage: npx tsx test-desktop-primitives-render.ts + +import './test-env.js'; +import { computeLayout, shutdown, type LayoutRect } from './src/screenshot.js'; +import { renderToHtml } from './src/renderer.js'; +import { resolveVariables } from './src/variables.js'; +import { applyPerturbation, compareLayouts } from './src/stress.js'; +import { generateDesignSystem } from './src/design-language.js'; +import type { Canvas, DesignVariables, SceneNode } from './src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +const inspector: SceneNode[] = [ + { id: 'xs', name: 'xs', type: 'button', icon: 'x', size: 'xs', ariaLabel: 'Close' }, + { id: 'lnk', name: 'lnk', type: 'link', label: 'View all' }, + { id: 'nav', name: 'nav', type: 'nav-item', label: 'Projects', icon: 'folder', active: true, count: 12, width: 240 }, + { id: 'rail', name: 'rail', type: 'nav-item', label: 'Projects', icon: 'folder', collapsed: true }, + { id: 'tsm', name: 'tsm', type: 'tabs', size: 'sm', items: [{ label: 'Quality', active: true }, { label: 'Design system' }] }, + { id: 'tmd', name: 'tmd', type: 'tabs', items: [{ label: 'All', active: true }, { label: 'Archived', count: 3 }], variant: 'contained' }, + { id: 'tr0', name: 'tr0', type: 'tree-row', label: 'src', depth: 0, expanded: true, width: 300 }, + { id: 'tr1', name: 'tr1', type: 'tree-row', label: 'components', depth: 1, expanded: false, width: 300 }, + { id: 'tr2', name: 'tr2', type: 'tree-row', label: 'button.ts', depth: 2, width: 300 }, + { id: 'menu', name: 'menu', type: 'frame', layout: 'vertical', width: 260, children: [ + { id: 'm1', name: 'm1', type: 'menu-row', label: 'Rename', shortcut: 'F2' }, + { id: 'm2', name: 'm2', type: 'menu-row', label: 'Duplicate', shortcut: '⌘D' }, + { id: 'm3', name: 'm3', type: 'menu-row', label: 'Delete', shortcut: '⌘⌫', destructive: true }, + ] }, + { id: 'props', name: 'props', type: 'frame', layout: 'vertical', width: 320, children: [ + { id: 'p1', name: 'p1', type: 'property-row', label: 'Width', children: [{ id: 'v1', name: 'v1', type: 'text-input', value: '1440', size: 'sm' }] }, + { id: 'p2', name: 'p2', type: 'property-row', label: 'Visible', children: [{ id: 'v2', name: 'v2', type: 'toggle', checked: true }] }, + { id: 'p3', name: 'p3', type: 'property-row', label: 'Name', children: [{ id: 'v3', name: 'v3', type: 'text', content: 'Dashboard', textOverflow: 'ellipsis' }] }, + ] }, + { id: 'in-sm', name: 'in-sm', type: 'text-input', size: 'sm', placeholder: 'Search', icon: 'search', width: 240 }, + { id: 'in-md', name: 'in-md', type: 'text-input', placeholder: 'Name', width: 240 }, + { id: 'in-3', name: 'in-3', type: 'text-input', rows: 3, placeholder: 'Comment', width: 320 }, + { id: 'in-err', name: 'in-err', type: 'text-input', value: 'taken', error: 'Name is taken', width: 240 }, + { id: 'panes', name: 'panes', type: 'frame', layout: 'horizontal', height: 120, width: 600, children: [ + { id: 'left', name: 'left', type: 'frame', width: 200, height: '100%' }, + { id: 'dv', name: 'dv', type: 'divider', orientation: 'vertical' }, + { id: 'right', name: 'right', type: 'frame', width: 200, height: '100%' }, + ] }, +]; + +function canvasOf(children: SceneNode[], variables: DesignVariables): Canvas { + return { + id: 'c', name: 'c', projectId: 'p', components: {}, variables, createdAt: '', lastModified: '', + root: { id: 'document', type: 'document', name: 'D', width: 1440, height: 900, fill: '$bg-primary', layout: 'vertical', padding: 24, gap: 12, children }, + metadata: { surface: { type: 'desktop-app', device: 'window-1440' } }, + } as Canvas; +} + +function index(rects: LayoutRect[]): Map { + const m = new Map(); + const walk = (r: LayoutRect) => { m.set(r.nodeId, r); r.children?.forEach(walk); }; + rects.forEach(walk); + return m; +} + +const system = generateDesignSystem('#0E7490', 'technical', { surface: 'desktop-app' }).variables; +const themes: Array<[string, DesignVariables]> = [ + ['unthemed', {}], + ['light', system], + ['dark', { ...system, colors: { ...system.colors, ...system.dark?.colors } }], +]; + +for (const [label, vars] of themes) { + const c = canvasOf(inspector, vars); + const html = renderToHtml(resolveVariables(structuredClone(c.root), vars), 1440, 900, c); + const r = index(await computeLayout(html, undefined, 25, { width: 1440, height: 900 })); + const h = (id: string) => r.get(id)?.height; + const w = (id: string) => r.get(id)?.width; + check(`${label}: xs button is 24×24`, h('xs') === 24 && w('xs') === 24, `${w('xs')}×${h('xs')}`); + check(`${label}: a link is at least 24 tall`, (h('lnk') ?? 0) >= 24, String(h('lnk'))); + check(`${label}: nav-item 32 tall; collapsed 32×32`, h('nav') === 32 && h('rail') === 32 && w('rail') === 32, `${h('nav')} ${w('rail')}×${h('rail')}`); + check(`${label}: tabs 32 at sm, 40 at md`, h('tsm') === 32 && h('tmd') === 40, `${h('tsm')} ${h('tmd')}`); + check(`${label}: tree-rows 32 tall`, ['tr0', 'tr1', 'tr2'].every((id) => h(id) === 32)); + check(`${label}: menu-rows 32 tall`, ['m1', 'm2', 'm3'].every((id) => h(id) === 32)); + check(`${label}: property-rows at least 32 tall`, ['p1', 'p2', 'p3'].every((id) => (h(id) ?? 0) >= 32)); + check(`${label}: every property value starts at one left edge`, new Set(['v1', 'v2', 'v3'].map((id) => r.get(id)?.x)).size === 1, ['v1', 'v2', 'v3'].map((id) => r.get(id)?.x).join(' ')); + check(`${label}: text-input 32 at sm, 40 at md, 72 at three rows`, h('in-sm') === 32 && h('in-md') === 40 && h('in-3') === 72, `${h('in-sm')} ${h('in-md')} ${h('in-3')}`); + check(`${label}: an error adds its message below the field`, (h('in-err') ?? 0) > 40, String(h('in-err'))); + check(`${label}: the vertical divider is 1px wide and as tall as its panes`, w('dv') === 1 && h('dv') === 120, `${w('dv')}×${h('dv')}`); +} + +// Shortcuts right-align to one column (checked in the rendered DOM). +{ + const c = canvasOf(inspector, system); + const html = renderToHtml(resolveVariables(structuredClone(c.root), system), 1440, 900, c); + const { withPage } = await import('./src/screenshot.js'); + const rights = await withPage(async (page) => { + await page.setViewport({ width: 1440, height: 900 }); + await page.setContent(html, { waitUntil: 'domcontentloaded' }); + return page.$$eval('[data-node-id^="m"] kbd', (els) => els.map((e) => Math.round(e.getBoundingClientRect().right))); + }); + check('every menu shortcut right-aligns to one column', rights.length === 3 && new Set(rights).size === 1, rights.join(' ')); +} + +// Long text and i18n: designed truncation only, never a clip or an overflow. +for (const name of ['long-text', 'i18n'] as const) { + const c = canvasOf(inspector, system); + const base = resolveVariables(structuredClone(c.root), system); + const baseline = await computeLayout(renderToHtml(base, 1440, 900, c), undefined, 25, { width: 1440, height: 900 }); + const { root, touched } = applyPerturbation(name, structuredClone(c.root)); + const pert = await computeLayout(renderToHtml(resolveVariables(root, system), 1440, 900, c), undefined, 25, { width: 1440, height: 900 }); + const findings = compareLayouts(baseline, pert, touched, 1440); + const warnings = findings.filter((f) => f.severity === 'warning'); + check(`${name}: no clip or overflow warnings on the desktop-app primitives`, warnings.length === 0, JSON.stringify(warnings.slice(0, 4))); + if (name === 'long-text') check(`${name}: labels report designed truncation`, findings.some((f) => f.severity === 'info'), `${findings.length} findings`); +} + +await shutdown(); +console.log(allPass ? '\nALL PASS' : '\nSOME FAILED'); +process.exit(allPass ? 0 : 1); diff --git a/test-desktop-primitives.ts b/test-desktop-primitives.ts new file mode 100644 index 0000000..fffa92e --- /dev/null +++ b/test-desktop-primitives.ts @@ -0,0 +1,208 @@ +// Phase 31 slice B — the desktop-app vocabulary, without Chrome: the types +// render to the expected markup, colours default from tokens (and fall back +// unthemed), the new primitives join the web/desktop-app 24px census, identity +// dots never count as accents (FR-A6), a canvas holding a desktop-app +// primitive must declare its type (desktop-app-artboard), stress reaches the +// new copy, repeats count as reuse, the breadcrumb is built from links, and +// unthemed stamps seed $accent-tint / $border-strong. Rendered geometry lives +// in test-desktop-primitives-render.ts (Chrome). +// +// Usage: npx tsx test-desktop-primitives.ts + +import './test-env.js'; +import { readFileSync } from 'node:fs'; +import { evaluateCanvas } from './src/evaluate.js'; +import { renderToHtml } from './src/renderer.js'; +import { resolveVariables } from './src/variables.js'; +import { applyPerturbation } from './src/stress.js'; +import { getStructure, applyStructure } from './src/structures.js'; +import { createCanvas } from './src/scene-graph.js'; +import { desktopTargets, CLICKABLE_PRIMITIVES, DESKTOP_APP_PRIMITIVES } from './src/primitives.js'; +import type { Canvas, 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}` : ''}`); +} + +type Surface = { type: 'web' | 'mobile' | 'desktop-app'; device?: string }; +function canvasWith(children: SceneNode[], surface?: Surface, colors?: Record): Canvas { + return { + id: 'c', name: 'c', projectId: 'p', components: {}, createdAt: '', lastModified: '', + variables: colors ? { colors } : {}, + root: { id: 'document', type: 'document', name: 'Document', width: 1440, height: 900, fill: '#FFFFFF', layout: 'vertical', padding: 24, gap: 8, children }, + ...(surface ? { metadata: { surface } } : {}), + } as Canvas; +} +const app: Surface = { type: 'desktop-app', device: 'window-1440' }; +const html = (n: SceneNode, colors?: Record) => { + const c = canvasWith([n], app, colors); + return renderToHtml(resolveVariables(c.root, c.variables), 1440, 900, c); +}; + +// ── FR-B1: button xs + ariaLabel ─────────────────────────────────────────── +{ + const h = html({ id: 'b', name: 'b', type: 'button', icon: 'x', size: 'xs', ariaLabel: 'Close panel' }); + check('an icon-only xs button renders 24px with aria-label and title', /height: 24px/.test(h) && /aria-label="Close panel"/.test(h) && /title="Close panel"/.test(h)); + check('ariaLabel is never drawn as text', !/>Close panelguide') + 4)); + check('a text node renders its title attribute', /]*title="Help copy"/.test(t)); +} + +// ── FR-B3..B9: markup and defaults ───────────────────────────────────────── +{ + const nav = html({ id: 'n', name: 'n', type: 'nav-item', label: 'Projects', icon: 'folder', active: true, count: 12 }); + check('an active nav-item draws fill, bar and weight, with aria-current', /aria-current="page"/.test(nav) && /width: 2px/.test(nav) && /font-weight: 600/.test(nav) && /background-color: #EFF4FF/.test(nav)); + const rail = html({ id: 'n2', name: 'n2', type: 'nav-item', label: 'Projects', icon: 'folder', collapsed: true }); + check('a collapsed nav-item is 32×32 with its label as the accessible name', /width: 32px/.test(rail) && /aria-label="Projects"/.test(rail) && !/>Projects html({ id: `r${d}`, name: 'r', type: 'tree-row', label: 'Node', depth: d, ...(d < 2 ? { expanded: d === 0 } : {}) })); + check('tree-rows indent 0 / 16 / 32 (padding 8 / 24 / 40)', /padding: 0 8px 0 8px/.test(tree[0]) && /padding: 0 8px 0 24px/.test(tree[1]) && /padding: 0 8px 0 40px/.test(tree[2])); + check('a branch has aria-expanded and a chevron; a leaf has neither', /aria-expanded="true"/.test(tree[0]) && /aria-expanded="false"/.test(tree[1]) && !/aria-expanded/.test(tree[2])); + const menu = html({ id: 'm', name: 'm', type: 'menu-row', label: 'Delete', shortcut: '⌘⌫', destructive: true, checked: false, submenu: true }); + check('menu-row: right-aligned kbd shortcut, destructive colour, check slot', /]*margin-left: auto/.test(menu) && /aria-checked="false"/.test(menu) && /color: #DC2626/.test(menu)); + const prop = html({ id: 'p', name: 'p', type: 'property-row', label: 'Width', labelWidth: 80, children: [{ id: 'pv', name: 'pv', type: 'text', content: '1440' }] }); + check('property-row: an 80px label column, then its child', /width: 80px/.test(prop) && /data-node-id="pv"/.test(prop)); + const input = html({ id: 'i', name: 'i', type: 'text-input', placeholder: 'Search canvases', icon: 'search', size: 'sm' }); + check('text-input: 32 tall at sm, a textbox, placeholder shown', /height: 32px/.test(input) && /role="textbox"/.test(input) && />Search canvasesName is taken) => html({ id: 'cb', name: 'cb', type: 'checkbox' }, colors); + check('an unchecked checkbox uses $border-strong when the token exists', /#556677/.test(ctl({ 'border-strong': '#556677', border: '#EEEEEE' }))); + check('…and keeps $border without it (render unchanged)', /#EEEEEE/.test(ctl({ border: '#EEEEEE' })) && !/#556677/.test(ctl({ border: '#EEEEEE' }))); +} + +// ── D3: the census ───────────────────────────────────────────────────────── +{ + check('the clickable set holds the eight-minus-two desktop primitives', ['link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row'].every((t) => CLICKABLE_PRIMITIVES.has(t)) && !CLICKABLE_PRIMITIVES.has('divider') && !CLICKABLE_PRIMITIVES.has('property-row')); + const usab = async (n: SceneNode, surface: Surface = app) => (await evaluateCanvas(canvasWith([n], surface), { mode: 'fast', categories: ['usability'] })).issues.filter((i) => /24px floor/.test(i.message)); + check('default desktop primitives all pass the 24px floor', (await usab({ id: 'w', name: 'w', type: 'frame', layout: 'vertical', children: [ + { id: 'a', name: 'a', type: 'link', label: 'Go' }, { id: 'b', name: 'b', type: 'text-input' }, { id: 'c', name: 'c', type: 'nav-item', label: 'N' }, + { id: 'd', name: 'd', type: 'tabs', size: 'sm', items: [{ label: 'A' }, { label: 'B' }] }, { id: 'e', name: 'e', type: 'tree-row', label: 'T', depth: 0 }, + { id: 'f', name: 'f', type: 'menu-row', label: 'M' }, { id: 'g', name: 'g', type: 'button', icon: 'x', size: 'xs', ariaLabel: 'X' }, + ] })).length === 0); + for (const type of ['web', 'desktop-app'] as const) { + const small = await usab({ id: 'l', name: 'l', type: 'link', label: 'Go', height: 16 }, type === 'web' ? { type } : app); + check(`${type}: a link forced to 16px is measured (fast-mode warning)`, small.length === 1 && small[0].severity === 'warning'); + } + const tabs = await usab({ id: 't', name: 't', type: 'tabs', height: 20, items: [{ label: 'A' }, { label: 'B', disabled: true }, { label: 'C' }] }); + check('each enabled tab is its own target; a disabled tab is not measured', tabs.length === 2, JSON.stringify(tabs.map((i) => i.message))); + const menuOff = await usab({ id: 'm', name: 'm', type: 'menu-row', label: 'M', height: 16, disabled: true }); + check('a disabled menu-row is not measured', menuOff.length === 0); + const inline = await usab({ id: 'tx', name: 'tx', type: 'text', content: 'See the docs', links: [{ start: 8, end: 12 }], fontSize: 12 }); + check('inline text links are exempt', inline.length === 0); + const owned = await usab({ id: 'pr', name: 'pr', type: 'property-row', label: 'Visible', children: [{ id: 'tg', name: 'tg', type: 'checkbox' }] }); + check('a sole checkbox inside a property-row is measured by the row (passes)', owned.length === 0, JSON.stringify(owned.map((i) => i.message))); + const two = await usab({ id: 'pr2', name: 'pr2', type: 'property-row', label: 'Flags', children: [{ id: 'f1', name: 'f1', type: 'frame', layout: 'horizontal', children: [{ id: 'c1', name: 'c1', type: 'checkbox' }, { id: 'c2', name: 'c2', type: 'checkbox' }] }] }); + check('two checkboxes in one property-row are measured bare (fast warnings)', two.length === 2); + const phone = (await evaluateCanvas(canvasWith([{ id: 'l', name: 'l', type: 'link', label: 'Go' }], { type: 'mobile', device: 'iphone-390' }), { mode: 'fast', categories: ['usability'] })).issues; + check('mobile: desktop primitives are not phone tappables (no touch-target finding)', !phone.some((i) => i.rule === 'mobile-touch-target')); +} + +// ── FR-A6: identity dots are not accents ──────────────────────────────────── +{ + const dots = ['#3B82F6', '#F59E0B', '#EC4899', '#22C55E']; + const sidebar = (extra: SceneNode[] = []): SceneNode[] => [ + ...dots.map((d, i) => ({ id: `nv${i}`, name: `Project ${i}`, type: 'nav-item', label: `Project ${i}`, dotColor: d, count: i } as SceneNode)), + ...extra, + ]; + const tell = async (children: SceneNode[]) => (await evaluateCanvas(canvasWith(children, app), { mode: 'fast', categories: ['cliche'] })).issues.filter((i) => i.tell === 'accent-consistency'); + check('four nav-item identity dots do not trip accent-consistency', (await tell(sidebar())).length === 0); + check('the same colours as literal text colours still do', (await tell(dots.map((d, i) => ({ id: `b${i}`, name: 'b', type: 'text', content: 'Go', color: d } as SceneNode)))).length === 1); + const handDots = dots.map((d, i) => ({ id: `h${i}`, name: 'dot', type: 'ellipse', width: 8, height: 8, fill: d } as SceneNode)); + check('hand-built dots with the same colours still count', (await tell(handDots)).length === 1); + check('a dot colour reused as a literal elsewhere still counts', (await tell(sidebar([{ id: 'x1', name: 'x', type: 'text', content: 'A', color: dots[1] }, { id: 'x2', name: 'x', type: 'text', content: 'B', color: dots[2] }, { id: 'x3', name: 'x', type: 'text', content: 'C', color: dots[3] }]))).length === 1); +} + +// ── FR-C9 (slice B clauses): desktop-app primitives ask for a declaration ─── +{ + const art = async (children: SceneNode[], surface?: Surface) => (await evaluateCanvas(canvasWith(children, surface), { mode: 'fast', categories: ['structure'] })).issues.filter((i) => i.rule === 'desktop-app-artboard'); + for (const t of DESKTOP_APP_PRIMITIVES) { + const n = { id: 'p', name: 'p', type: t, label: 'L', items: [{ label: 'A' }] } as SceneNode; + const undeclared = await art([n]); + check(`undeclared canvas with a ${t} warns`, undeclared.length === 1 && undeclared[0].severity === 'warning'); + } + const nav: SceneNode = { id: 'nv', name: 'Home', type: 'nav-item', label: 'Home' }; + check('declared web with a nav-item → info', (await art([nav], { type: 'web' }))[0]?.severity === 'info'); + check('declared mobile with a nav-item → warning', (await art([nav], { type: 'mobile', device: 'iphone-390' })).some((i) => i.severity === 'warning' && /declared mobile/.test(i.message))); + check('declared desktop-app with a nav-item → silent', (await art([nav], app)).length === 0); + check('a link, a text-input or a divider alone never asks', (await art([{ id: 'l', name: 'l', type: 'link', label: 'Go' }, { id: 'i', name: 'i', type: 'text-input' }, { id: 'd', name: 'd', type: 'divider' }])).length === 0); + const comp = canvasWith([{ id: 'inst', name: 'inst', type: 'instance', componentId: 'side' } as SceneNode]); + comp.components = { side: { id: 'side', name: 'Side', type: 'component', children: [{ id: 'deep', name: 'Deep', type: 'frame', children: [nav] }] } as SceneNode }; + const inInst = (await evaluateCanvas(comp, { mode: 'fast', categories: ['structure'] })).issues.filter((i) => i.rule === 'desktop-app-artboard'); + check('a nav-item inside an instance counts, reported on the instance', inInst.length === 1 && inInst[0].nodeId === 'inst', JSON.stringify(inInst.map((i) => i.nodeId))); +} + +// ── FR-B10: stress copy, reuse, breadcrumb, seeding ───────────────────────── +{ + const root: SceneNode = { id: 'document', type: 'document', name: 'D', children: [ + { id: 'l', name: 'l', type: 'link', label: 'Open' }, + { id: 'n', name: 'n', type: 'nav-item', label: 'Projects' }, + { id: 't', name: 't', type: 'tabs', items: [{ label: 'Quality' }, { label: 'Feedback' }] }, + { id: 'r', name: 'r', type: 'tree-row', label: 'src', depth: 0 }, + { id: 'm', name: 'm', type: 'menu-row', label: 'Rename', shortcut: 'F2' }, + { id: 'p', name: 'p', type: 'property-row', label: 'Width', children: [] }, + { id: 'i', name: 'i', type: 'text-input', value: 'hello' }, + ] }; + const { touched } = applyPerturbation('long-text', root); + check('long-text reaches every new primitive\'s copy', ['l', 'n', 't', 'r', 'm', 'p', 'i'].every((id) => touched.includes(id)), touched.join(', ')); + + const many = canvasWith(Array.from({ length: 12 }, (_, i) => ({ id: `n${i}`, name: `n${i}`, type: 'nav-item', label: `Item ${i}` } as SceneNode)), app); + const reuse = (await evaluateCanvas(many, { mode: 'fast', categories: ['structure'] })).issues.filter((i) => /No component instances/.test(i.message)); + check('repeated nav-items count as reuse (no "extract components" advisory)', reuse.length === 0); + + const crumb = getStructure('breadcrumb')!; + check('the breadcrumb parent is a link; the current page stays text', crumb.nodes[0].children?.[0].type === 'link' && crumb.nodes[0].children?.[2].type === 'text'); + + const c = createCanvas('seed', undefined, {}, { type: 'desktop-app', device: 'window-1440' }); + const seed = applyStructure(c, 'breadcrumb', { existingColors: new Set(), realisation: 'web' }); + check('stamping a structure with a desktop-app primitive on an unthemed canvas seeds $accent-tint and $border-strong', seed.seededColors.includes('accent-tint') && seed.seededColors.includes('border-strong'), seed.seededColors.join(', ')); + check('a desktop-app primitive\'s copy is a placeholder', seed.placeholders.some((p) => p.prop === 'label' && p.role === 'Parent')); + const m = createCanvas('mob', undefined, {}, { type: 'mobile', device: 'iphone-390' }); + const mob = applyStructure(m, 'settings', { existingColors: new Set() }); + check('a mobile stamp does not seed the desktop-app tokens', !mob.seededColors.includes('border-strong'), mob.seededColors.join(', ')); +} + +// ── Viewer baseline: the gallery rebuilt with nav-item dots (FR-A6) ───────── +{ + const g = JSON.parse(readFileSync('test-fixtures/viewer-baseline/gallery-pattern-library.json', 'utf-8')) as Canvas; + const find = (n: SceneNode, id: string): SceneNode | undefined => n.id === id ? n : n.children?.map((ch) => find(ch, id)).find(Boolean); + const sidebar = find(g.root, 'imp-frame-33')!; + const rows = (sidebar.children ?? []).filter((r) => r.layout === 'horizontal'); + const rebuilt = rows.map((r, i) => ({ id: `nav-${i}`, name: 'Project', type: 'nav-item', label: String(r.children?.[1]?.content ?? `P${i}`), count: String(r.children?.[2]?.content ?? ''), dotColor: ['#3B82F6', '#F59E0B', '#EC4899', '#22C55E', '#14B8A6', '#A855F7', '#EF4444'][i % 7] } as SceneNode)); + const ev = await evaluateCanvas(canvasWith(rebuilt, app), { mode: 'fast', categories: ['cliche'] }); + check('the baseline sidebar rebuilt with nav-item dots does not trip accent-consistency', !ev.issues.some((i) => i.tell === 'accent-consistency'), `${rebuilt.length} rows`); +} + +console.log(allPass ? '\nALL PASS' : '\nSOME FAILED'); +process.exit(allPass ? 0 : 1); diff --git a/test-pointer-targets.ts b/test-pointer-targets.ts index 1045f5d..81543eb 100644 --- a/test-pointer-targets.ts +++ b/test-pointer-targets.ts @@ -66,6 +66,15 @@ for (const type of ['web', 'desktop-app'] as const) { f = await targetFindings(type, [{ id: 'tb', name: 'tb', type: 'tab-bar', width: 60, position: 'relative', items: ['A', 'B', 'C', 'D', 'E'].map((l) => ({ icon: 'home', label: l })) } as SceneNode]); check(`${type}: a too-narrow tab-bar's tabs stay blocking in detailed mode`, f.length === 5 && f.every((i) => i.severity === 'warning' && /could not place/.test(i.message)), JSON.stringify(f.map((i) => [i.severity, i.message.slice(0, 90)]))); + // Phase 31 slice B — the desktop-app vocabulary in the census. Two 16px + // links touching fail as errors; a tabs node's tabs share its id, so an + // undersized tab stays a blocking warning in detailed mode. + const lnk = (id: string): SceneNode => ({ id, name: id, type: 'link', label: id, height: 16 }); + f = await targetFindings(type, [row(0, [lnk('l1'), lnk('l2')])]); + check(`${type}: two touching 16px links fail in detailed mode`, f.length === 2 && f.every((i) => i.severity === 'error'), JSON.stringify(f.map((i) => [i.severity, i.message.slice(0, 80)]))); + f = await targetFindings(type, [{ id: 'tabs', name: 'tabs', type: 'tabs', height: 18, items: [{ label: 'A' }, { label: 'B' }] } as SceneNode]); + check(`${type}: undersized tabs stay blocking warnings`, f.length === 2 && f.every((i) => i.severity === 'warning' && /could not place/.test(i.message)), JSON.stringify(f.map((i) => [i.severity, i.message.slice(0, 80)]))); + // A neighbour nested past the layout walker's depth cannot be placed, so the // spacing exception is unproven and the small target stays blocking. let deep: SceneNode = btn('deep', 32); From 7ae5102bbb85fa13c0d0c933de90eb00d5b7ff59 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Fri, 13 Nov 2026 19:13:34 +0100 Subject: [PATCH 2/4] Judge the desktop-app primitives as they render, and place slot children Verify round 1 on slice B. The census now uses each primitive's rendered height, a control owns its row only when it is the row's only target, and the layout walker steps through the property-row value slot. Tabs truncate in a narrow tablist, unknown icons and copy props are checked like the phone primitives, and disabled rows leave the tab order. Docs follow. --- README.md | 10 ++-- docs/GUIDELINES.md | 10 ++-- docs/specs/PHASE-31-SPEC.md | 3 ++ src/evaluate.ts | 17 ++++++- src/index.ts | 15 +++--- src/primitives.ts | 21 ++++++-- src/renderer.ts | 40 +++++++++++---- src/screenshot.ts | 15 ++++-- src/variables.ts | 13 ++++- test-desktop-primitives-render.ts | 11 +++- test-desktop-primitives.ts | 84 +++++++++++++++++++++++++++++-- test-pointer-targets.ts | 10 ++-- 12 files changed, 200 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index ebc3c88..ee698d7 100644 --- a/README.md +++ b/README.md @@ -387,12 +387,12 @@ Application screens (`type: "desktop-app"`) are built from eight primitives on t | Type | Key props | What it is | |---|---|---| | `link` | `label`, `icon`, `iconPosition`, `external` | A standalone text action, at least 24 tall. 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`, `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` | +| `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` | -| `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 sole control inside it is measured by the row's box | +| `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 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`). @@ -888,14 +888,14 @@ Every result also carries a **`surface`** field: `{ type, device, source, rulesO | Rule | Category | Severity | Fires on | |---|---|---|---| -| `mobile-touch-target` | usability | error | A tap target below 44px: a control (its target extends to its row only when the row is a horizontal frame holding that one tappable), a `button` (`size: "sm"` is 32), a `list-row`, each `tab-bar` tab and FAB, or each `nav-bar` action. Primitives are measured by their own box; nodes inside an instance are judged as rendered and reported on the instance. | +| `mobile-touch-target` | usability | error | A tap target below 44px: a control (its target extends to its row 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, or each `nav-bar` action. Primitives are measured by their own box; nodes inside an instance are judged as rendered and reported on the instance. | | `mobile-tab-bar` | usability | warning | A `tab-bar` with fewer than 2 or more than 5 tabs (the FAB is not a tab), a tab with no label, or a bar not pinned to the bottom (a `position` override or any `y`). | | `mobile-handbuilt-target` | usability | info | A frame shaped like a tap target (one icon, or an icon plus a label of up to three words) whose box is below 44px; rebuild it as a `button` if it is tappable. | | `mobile-safe-area` | usability | warning | Content under the 47px status-bar or 34px home-indicator inset, or left under a pinned bar. With the root's `safeArea` or pinned chrome the renderer reserves the insets, so fast mode checks positioned content (`absolute`, `fixed`, `sticky` at its stuck `y`) and pinned bars: the scroll's end (or start) must clear a bar you pinned, and the finding names the spacer height to add to your content frame. Without `safeArea`, the first and last content must clear the insets. Padding of 32px or more scales down on a phone, so clear an inset with a spacer frame. A `sheet`'s content is never judged. Detailed mode checks rendered positions and is authoritative. | | `mobile-type-floor` | typography | warning | Text below 11px, `$body` below 16px, or prose of five or more words below 13px (copy of twelve or more words at 13–15px is an info). | | `mobile-one-column` | usability | info | Prose set side by side in a horizontal or grid frame: two or more children each holding eight or more words. | | `mobile-artboard` | structure | warning / info | Runs on every type. A mobile canvas 500px or wider warns, and any other size than the device's is an info. An undeclared canvas narrower than 500px warns until `canvas_set_type` declares it; one declared `web` gets an info. | -| `desktop-app-artboard` | structure | warning | Runs on every type. A desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for. | +| `desktop-app-artboard` | structure | warning / info | Runs on every type. Warns on a desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for. Also warns on a canvas that holds a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) and was never declared, or is declared `mobile`; one declared `web` gets an info. Primitives inside an instance count. | | `type-scale-ratio` | typography | warning | On by default: adjacent font sizes stepping by a ratio below 1.1 or above 2.0 (pinned typography tokens skip it). The desktop-app ruleset turns it off, since dense apps step 12 / 13 / 14 on purpose; it then appears in `rulesOff`. | Repeated findings fold in this result: three or more warnings or infos with the same severity, category, rule (or tell) and theme come back as one entry when they also share their message — on its shape for members that carry a fix (each fix op holds its node's specifics), word for word apart from quoted node text for members without one. The entry keeps the first one's message and adds `nodeIds` (distinct), `count` and, when they had fixes, `fixes: [{ nodeId, op }]`. Errors never fold, and `canvas_autofix` works from the unfolded list. @@ -920,7 +920,7 @@ Whenever the `coverage` category runs on a **base** canvas, the result also carr | `consistency` | 20 | Frames missing `layout`, sibling overlap (detailed mode; positioned siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt, while a bar pinned to the top still counts) — plus score-neutral advisories: **token detachment** (a literal `fill`/`stroke`/`color`/`cornerRadius` that exactly equals a token's value flags with a mechanical `$ref` autofix; ambiguous matches list candidates and never guess) and **ad-hoc motion** (3+ distinct duration/easing combos with no motion tokens declared) | | `cliche` | 15 | Machine-made tells: default purple/indigo accent, gradient/glow overuse, fake browser/OS chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated metrics/testimonials/logos, eyebrow rhythm (an eyebrow above nearly every section), slop copy (stock AI phrasing — filler verbs, scroll cues, placeholder names, hype labels), radius consistency (too many distinct corner radii), pure black/white (`#000000` ink / `#ffffff` page vs off-black/off-white), accent consistency (multiple competing accent hues — the `$success`/`$warning`/`$danger` status vocabulary is exempt when referenced as tokens, since those are semantics rather than a second accent; the same hues as literals still count). Each issue carries a `tell` discriminator. Tells are warning or info severity, but **every tell blocks the directive**, whatever its severity (see the `directive` above). Relaxable per `genre`. The tells know dashboard vocabulary: a violet reached only through a `$chart-*` or `$*-tint` token doesn't count as the default-purple tell (a literal violet, or one through any other token, still does), a gradient reached through a `$token` doesn't count toward gradient overuse, thin rounded sparkline bars aren't mistaken for traffic-light dots (fake-chrome now requires a near-square shape), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric, not an eyebrow. It also knows retail copy: a numeral bound to a unit noun by a tight hyphen (`"30-day returns"`, `"2-year warranty"`, `"24/7 support"`) is a compound modifier, not a numbered section eyebrow. | | `coverage` | 10 | State coverage on **base** canvases with data-bearing content: a detected table demands designed `empty` + `loading` variants, a form (3+ input controls) demands `error` — each missing state is a directive-blocking warning whose suggestion names the `canvas_add_variant` + scaffold path. Variant canvases and non-data screens get no findings. Table detection needs three matching horizontal rows to read as data (two stacked rows are treated as a layout, e.g. a topbar over a greeting); an import-named `Table` frame keeps the looser two-row shape. A list whose every row leads with an icon, a dot or a small image (a sidebar of projects) is navigation and never reads as a table, on every type. On a **`loading`** variant itself, a warning fires per data surface (a detected table, or a frame with 2+ large tabular/numeric texts) that still shows live values while a sibling region is skeletoned — "Loading state is half-designed" — naming the region and suggesting the matching skeleton scaffold. The result's `coverage` field reports `{ dataBearing, states, missing }`. | -| `usability` | 20 | The mechanical UX floors beyond contrast. On web and desktop-app canvases every pointer target (the four controls and the clickable primitives) meets the **24px floor** (WCAG 2.5.8) or its **spacing exception**, a smaller target with nothing else inside a 24px circle around it: detailed mode runs that test and makes a failure an **error**, fast mode **warns** on any target below 24 and names detailed mode — the effective target counts a lone control's padded row, so a well-padded settings row passes while two small controls sharing a row are measured bare; phone-width web artboards additionally get a 44px touch-first info, and a canvas declared `mobile` makes 44px an error instead (`mobile-touch-target`, see the mobile ruleset above). A control with **no text label** in its row or group is a warning (selects carry their own value text). **Vague action copy** — "Click here", "Learn more", "Read more", or "Submit" as the exact label — is an info: name the action. Controls also render with accent-derived `:focus-visible` rings in the live viewer; screenshots stay byte-identical (nothing is focused in a static capture). | +| `usability` | 20 | The mechanical UX floors beyond contrast. On web and desktop-app canvases every pointer target (the four controls and the clickable primitives: `button`, `list-row`, `tab-bar` tabs, `nav-bar` actions, `link`, `text-input`, `nav-item`, each tab of a `tabs`, `tree-row`, `menu-row`; see [Desktop-app primitives](#desktop-app-primitives)) meets the **24px floor** (WCAG 2.5.8) or its **spacing exception**, a smaller target with nothing else inside a 24px circle around it: detailed mode runs that test and makes a failure an **error**, fast mode **warns** on any target below 24 and names detailed mode — the effective target counts a lone control's padded row, so a well-padded settings row passes while two small controls sharing a row are measured bare; phone-width web artboards additionally get a 44px touch-first info, and a canvas declared `mobile` makes 44px an error instead (`mobile-touch-target`, see the mobile ruleset above). A control with **no text label** in its row or group is a warning (selects carry their own value text). **Vague action copy** — "Click here", "Learn more", "Read more", or "Submit" as the exact label — is an info: name the action. Controls also render with accent-derived `:focus-visible` rings in the live viewer; screenshots stay byte-identical (nothing is focused in a static capture). | The weights are relative, not points out of 100. Each category scores 0–100, and `overallScore` is their weighted mean: the sum of score × weight over the categories that ran, divided by the sum of their weights. diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index bbb144a..c56dc60 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -55,7 +55,7 @@ On a `mobile` canvas these rules run. Each finding names its rule in a `rule` fi - **`mobile-touch-target`** (usability, **error**, −25 per target). A tap target below 44px in either dimension. - A control (toggle, checkbox, radio, select): the target extends to the control's row only when that row is a horizontal frame holding this one tappable (no other control or tappable primitive). A toggle in a 56px settings row passes; a lone checkbox inside a padded card is measured at its own size. To fix one, grow the control or put it alone in a horizontal row at least 44px tall. - - The tappable primitives, each by its own box (an ancestor's padding never counts): a `button` (32 / 44 / 52 by `size`, or a larger `height` / `minHeight`; never narrower than tall), so `size: "sm"` is an error on a phone by design; a `list-row` (44, or 56 with a subtitle; a trailing toggle or chevron is part of the row, so the row is the target); each `tab-bar` tab (bar width ÷ slots × 49, where the bar width is its `width` or the artboard's, less 32 for `floating`, and the slots are the tabs plus one for a FAB) and the FAB (56); each `nav-bar` action (44×44). The defaults all pass. + - The tappable primitives, each by its own box (an ancestor's padding never counts): a `button` (24 / 32 / 44 / 52 by `size`, or a larger `height` / `minHeight`; never narrower than tall), so `size: "xs"` and `"sm"` are errors on a phone by design; a `list-row` (44, or 56 with a subtitle; a trailing toggle or chevron is part of the row, so the row is the target); each `tab-bar` tab (bar width ÷ slots × 49, where the bar width is its `width` or the artboard's, less 32 for `floating`, and the slots are the tabs plus one for a FAB) and the FAB (56); each `nav-bar` action (44×44). The defaults all pass. - Nodes inside a component instance are judged as they render, and the finding names the instance. - On web and desktop-app canvases the 24px floor applies instead, with WCAG's spacing exception (see [the 24px floor](#the-24px-floor-web-and-desktop-app)). - **`mobile-handbuilt-target`** (usability, info). A frame shaped like a tap target (one icon, or one icon and a label of three words or fewer) whose box is below 44px. It never blocks, because a frame can't say it is decorative. If it is tappable, rebuild it as a `button` (or a `list-row` / `tab-bar` item when that is what it is). @@ -86,7 +86,7 @@ There are no desktop-app realisations yet: `apply_structure` on a desktop-app ca ### The 24px floor (web and desktop-app) -On web and desktop-app canvases every pointer target is measured against WCAG 2.5.8's 24px floor: the four controls (toggle, checkbox, radio, select) and the clickable primitives (`button`, `list-row`, each `tab-bar` tab and the FAB, each `nav-bar` action, and the [desktop-app vocabulary](#desktop-app-vocabulary): `link`, `text-input`, `nav-item`, each tab of a `tabs` node, `tree-row`, `menu-row`). Inline text links and `divider`s are not targets. A lone control first grows to its padded row, two levels up, as before, and a control that is the only one inside a `property-row`, `nav-item`, `menu-row` or `list-row` is measured by that row's box; a disabled target is neither measured nor in anyone's way; nodes inside a component instance are judged as rendered and reported on the instance. What is still below 24px passes only by WCAG's **spacing exception**: a 24px circle centred on it must reach no other target's box and no other undersized target's circle (circles that only touch pass; a target nested inside another is not its neighbour). Spacing needs rendered positions, so: +On web and desktop-app canvases every pointer target is measured against WCAG 2.5.8's 24px floor: the four controls (toggle, checkbox, radio, select) and the clickable primitives (`button`, `list-row`, each `tab-bar` tab and the FAB, each `nav-bar` action, and the [desktop-app vocabulary](#desktop-app-vocabulary): `link`, `text-input`, `nav-item`, each tab of a `tabs` node, `tree-row`, `menu-row`). Inline text links and `divider`s are not targets. A lone control first grows to its padded row, two levels up, as before, and a control that is the only target directly inside a `property-row`, `nav-item`, `menu-row` or `list-row` (no link, input or button beside it) is measured by that row's box; a disabled target is neither measured nor in anyone's way; nodes inside a component instance are judged as rendered and reported on the instance. What is still below 24px passes only by WCAG's **spacing exception**: a 24px circle centred on it must reach no other target's box and no other undersized target's circle (circles that only touch pass; a target nested inside another is not its neighbour). Spacing needs rendered positions, so: - **Detailed mode** (`canvas_evaluate({ canvasId, mode: "detailed" })`) runs the circle test and is the authority: a failure is an **error** that names the neighbour it reaches. - **Fast mode** cannot see spacing, so a target below 24px is a **warning** that names the exception and detailed mode. It blocks presenting until you grow the target or a detailed run clears it. @@ -104,7 +104,7 @@ Build application screens from these primitives, never from hand-built frames: a - **`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. -- **`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. A control alone inside it is measured by the row's 32px box. +- **`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. A control that is its only target (directly inside, nothing clickable beside it) is measured by the row's 32px box. Only `property-row` renders children; the other desktop-app primitives draw their own anatomy and drop any children you give them. - **`divider`** `{ orientation?: "horizontal" | "vertical", inset? }` is a 1px `$border` hairline; vertical dividers separate panes. Not a target. Repeated desktop-app primitives count as component reuse. On an unthemed canvas, stamping a structure that holds them seeds `$accent-tint` and `$border-strong` along with the usual neutrals. @@ -123,7 +123,7 @@ Build phone screens from the mobile primitives, not hand-built frames. Each 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` (`sm` 32 / `md` 44 / `lg` 52), `disabled` | Never narrower than tall; icon-only is square; `width: "100%"` for a full-width CTA. `sm` is for pointer surfaces and is an error on a phone | +| `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 | | `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 | @@ -235,7 +235,7 @@ The `chart` node owns the value→coordinate math — give it data and domains, - **Unicode glyphs as icon stand-ins.** `✓ ● ▾ ○` read as unfinished. Use the `icon` node type — two sets render by name as inline SVG: 1,900+ [Lucide](https://lucide.dev) (`icon: "check"`) and 3,800+ [Material Symbols](https://fonts.google.com/icons) (`icon: "material:check"`, `iconStyle: "outlined" | "rounded" | "sharp"`, `-fill` suffix for filled variants). `I("parent", { type: "icon", icon: "material:check", iconSize: 16, iconColor: "$primary" })`. For Material-style design systems, prefer the Material set. - **Spelling an icon in the other set's style.** Lucide hyphenates multi-word names (`chevron-right`); Material Symbols keeps underscores and needs the prefix (`material:chevron_right`, `material:chevron_right-fill`). A bare `chevron_right` is looked up in Lucide and renders nothing. A name that resolves in neither set renders an empty slot, so `canvas_evaluate` reports it as a `structure` warning naming the spellings that do resolve — and `canvas_autofix` rewrites it when exactly one does. - **Baking uppercase into `content`.** Use `textTransform: "uppercase"` (with `letterSpacing` for tracking) so the underlying copy stays editable and case-styling lives in the design, not the data. -- **Faking form controls from frames + ellipses.** `toggle`, `checkbox`, `radio`, and `select` are real node types: `I("parent", { type: "toggle", checked: true })`. They style themselves from `$accent`/`$border`/`$bg-surface` tokens (neutral fallbacks when unthemed) and stay pixel-consistent; `fill`/`stroke`/`color` override. +- **Faking form controls from frames + ellipses.** `toggle`, `checkbox`, `radio`, and `select` are real node types: `I("parent", { type: "toggle", checked: true })`. They style themselves from `$accent`/`$border`/`$bg-surface` tokens (neutral fallbacks when unthemed) and stay pixel-consistent; `fill`/`stroke`/`color` override. For a text field on an application screen use `text-input`. - **Faking loading states from plain gray rectangles.** Use `{ type: "skeleton" }` — token-derived fill, correct default radius, and it pulses in the live viewer (always static in screenshots/exports so diffs stay deterministic). Stamp `skeleton-table` / `skeleton-card` / `skeleton-stat-card` instead of hand-placing bars — and skeleton EVERY data surface: the coverage check flags a loading variant that leaves live metric values beside skeletoned regions (a half-designed loading screen flashes real-looking data next to placeholders). - **Hand-building app furniture node by node.** A data table, form field, toolbar, stat card, or settings row is one `apply_structure` stamp: component-kind structures insert under any `targetId` with re-keyed IDs and return an `idMap` for populating. Stamp `data-table`, fill the placeholders, copy rows with `C()` — don't place ~90 nodes by hand. On a phone canvas only the components marked for every type stamp (not `data-table`, `toolbar` or `toggle-row`), and a settings row is a `list-row`. diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 477f631..92a9a73 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -218,6 +218,9 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **E8: a long menu-row shortcut truncates** (at most half the row) like the label; found by the long-text render test. - **E9: `link.external`** (named in FR-B2, missing from the Plan's prop list) draws a trailing external-link glyph. The hover underline waits for element states (FR-G1). - **E10: the breadcrumb's parent is a `link`; the current page stays text.** The component keeps its web-only surface (slice D decides what stamps on desktop-app). +- **E11 (verify round 1): the census judges what renders.** A `link` never renders under 24 (min-height), `tabs` take their height from `size` and a `text-input` from `size` and `rows` (all ignore `height`), and `nav-item` / `tree-row` / `menu-row` take `height` but ignore `minHeight` — so the census does exactly the same. A control owns its row (E2) only when it is the row's only target, a direct child, with no link, input or button beside it. The layout walker steps through a primitive's child slot (`data-fs-slot`, the property-row value) so those nodes are placed. Tabs shrink so their labels truncate in a narrow tablist; disabled tabs and disabled link / nav-item / tree-row / menu-row / text-input leave the tab order. Unknown icons on the new primitives warn, and their copy (`placeholder`, `value`, `shortcut`, `error`, `ariaLabel`, `count`) is not counted as un-tokened style. Without an `accent-tint` token the active fill is the accent mixed 12% into the surface, so a dark palette gets a dark tint. An unthemed `text-input` error is `$danger`-coloured. Inline link edges never split a surrogate pair. +- **E12: only `property-row` renders children.** The other desktop-app primitives draw their own anatomy and drop children; the `batch_design` docs say so. +- **Open for a later slice: a `link` or `text-input` on a phone has no 44px check.** They are not phone tappables (E3) and not in the FR-C9 primitive set (pages and phones use them), so a 32px text-input on a mobile canvas passes silently. Adding them to the mobile touch census is a mobile-ruleset change the spec does not make. - **Open for slice C/D: form coverage ignores `text-input`.** The drift inventory's control list (toggle, checkbox, radio, select) is unchanged, so "3+ input controls demand an error state" does not count text-inputs. The spec is silent; decide with the form rules. **Slice C: the app rules (FR-C1 to FR-C9)** diff --git a/src/evaluate.ts b/src/evaluate.ts index 4488b9d..ded187b 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -835,6 +835,8 @@ function iconSlots(root: SceneNode): Array<{ node: SceneNode; path: string; ref: (function walk(n: SceneNode) { if (n.type === 'icon') add(n, 'icon', n.icon, true, true); else if (n.type === 'button') add(n, 'icon', n.icon, true, false); + // Phase 31 slice B — the desktop-app primitives draw their `icon` too. + else if (n.type === 'link' || n.type === 'nav-item' || n.type === 'tree-row' || n.type === 'menu-row' || n.type === 'text-input') add(n, 'icon', n.icon, true, false); else if (n.type === 'list-row' || n.type === 'nav-bar') { add(n, 'leading.icon', n.leading?.icon, false, false); if (n.type === 'nav-bar' && Array.isArray(n.trailing)) n.trailing.slice(0, 2).forEach((a, i) => add(n, `trailing[${i}].icon`, a?.icon, false, false)); @@ -849,7 +851,11 @@ function iconSlots(root: SceneNode): Array<{ node: SceneNode; path: string; ref: /** Phase 30 slice D — the mobile primitives' copy and enum props: words and * variant names, never style values, so the token census skips them. */ -const PRIMITIVE_COPY_PROPS = new Set(['title', 'subtitle', 'label', 'time', 'variant', 'size', 'detent', 'appearance', 'iconPosition']); +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', +]); /** Spellings worth trying for an icon name that didn't resolve: Material * Symbols names multi-word icons with `_` (chevron_right), Lucide with `-` @@ -2012,6 +2018,11 @@ export function pointerTargets(entries: NodeEntry[], rootWidth: number): Pointer for (const ch of n.children ?? []) c += countControls(ch); return c; }; + const countTargets = (n: SceneNode): number => { + let c = CONTROL_TYPES.has(n.type) || CLICKABLE_PRIMITIVES.has(n.type) ? 1 : 0; + for (const ch of n.children ?? []) c += countTargets(ch); + return c; + }; const targets: PointerTarget[] = []; for (const { node } of entries) { const disabled = node.disabled === true; @@ -2023,8 +2034,10 @@ export function pointerTargets(entries: NodeEntry[], rootWidth: number): Pointer // primitive (property-row, nav-item, menu-row, list-row) owns that row's // box: the row is the target. Its height is the row's; its width the // row's when known, else the row spans its container. + // Ownership needs the control to be the row's ONLY target: a link, + // text-input or button beside it shares the row (countTargets). const owner = parentOf.get(node.id) ?? null; - if (owner && CONTROL_OWNERS.has(owner.type) && countControls(owner) === 1 && Math.min(w, h) < 24) { + if (owner && CONTROL_OWNERS.has(owner.type) && countTargets(owner) === 1 && Math.min(w, h) < 24) { const rowH = Math.max(typeof owner.height === 'number' ? owner.height : 0, OWNER_HEIGHT[owner.type] ?? 0); w = typeof owner.width === 'number' ? owner.width : Infinity; h = Math.max(h, rowH); diff --git a/src/index.ts b/src/index.ts index d4b56fe..9f7705b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -83,7 +83,7 @@ Bulk edits & queries: replace_matching_properties applies one property change to Point-and-tell feedback: the user toggles Comment mode in the viewer and clicks any element to leave a note anchored to that node (or to the whole page). Comments are stored on the canvas, git-diffable in bound repos, and reach the running server automatically. Check get_feedback when picking up a canvas — each entry carries the anchor nodeId plus a node snapshot, enough to act on immediately. Open feedback blocks presenting, same as open inspector comments: address every item, then close each via resolve_feedback with a one-line note saying what changed (your note shows up as a reply in the viewer's Feedback tab). -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), 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). +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). 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 — 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. There are no desktop-app realisations yet: apply_structure refuses every page anatomy and names the types it is realised on (realisation: "web", plus "mobile" for the six mobile anatomies) — realisation: "web" stamps the web split-workbench, dashboard or settings; component scaffolds stamp as usual. 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. @@ -114,7 +114,7 @@ const WORKFLOW_CHEATSHEET = [ 'Final polish when an LLM API key is present: canvas_evaluate mode "llm" (the five-axis vision rubric) → canvas_revise on failing axes → re-judge until it passes or canvas_revise stops. The heuristic gate is the floor; the critique loop is the ceiling — make it the standard last step before presenting, not an exception. It never blocks: still-failing axes after canvas_revise stops get named to the user, not looped on. Keyless sessions skip it (a note says so), nothing else changes.', 'One canvas per screen / state; let the per-project build log nudge you to vary structure.', 'Data screens: design every state — canvas_add_variant for "empty" / "loading" ("error" for forms) + the empty-state / skeleton-table / skeleton-stat-card scaffolds (coverage warns until they exist) — and run canvas_stress before presenting (fix clips/overflows with fluid widths, then re-run until CLEAN — a FRAGILE run keeps canvas_evaluate NOT READY until a full CLEAN run).', - 'Usability gates like contrast does: on web and desktop-app a pointer target (a control or a clickable primitive) under the 24px floor fails — WCAG 2.5.8, with its spacing exception (a smaller target passes when nothing else sits within a 24px circle around it): detailed mode runs that test and ERRORS, fast mode WARNS until you grow it or run mode "detailed" (a lone control inherits its padded row\'s box; on a canvas declared mobile the floor is 44px for controls AND the tappable primitives — button (sm is 32: an error there), list-row, tab-bar tabs, nav-bar actions — mobile-touch-target), an unlabeled control is a warning, "Click here"-style copy is an info. The stock scaffolds already pass — hand-built controls are where these bite.', + 'Usability gates like contrast does: on web and desktop-app a pointer target (a control or a clickable primitive) under the 24px floor fails — WCAG 2.5.8, with its spacing exception (a smaller target passes when nothing else sits within a 24px circle around it): detailed mode runs that test and ERRORS, fast mode WARNS until you grow it or run mode "detailed" (a lone control inherits its padded row\'s box; on a canvas declared mobile the floor is 44px for controls AND the tappable primitives — button (xs is 24 and sm is 32: errors there), list-row, tab-bar tabs, nav-bar actions — mobile-touch-target), an unlabeled control is a warning, "Click here"-style copy is an info. The stock scaffolds already pass — hand-built controls are where these bite.', 'Derive the system before drawing: generate_design_system (seed + personality → the full design language: colors, font pairing, type roles, radii, $elevation depth, $motion) is the headline call; generate_scale / generate_color_system regenerate just the scale or just the palette — then reference $tokens everywhere and let the lint re-attach any literal that drifts.', 'Multi-screen module? Finish as a SET: project_evaluate rolls up per-screen scores + cross-screen drift (radius / accent / token adoption / copied chrome / states) — advisory, the per-canvas directives still gate; mode "llm" adds the flow critique. Compose bento/editorial layouts with real grid (layout "grid" + spans), never nested flex.', 'Picking up an existing canvas? get_feedback first — point-and-tell comments may be waiting (node-anchored or canvas-level). Address every open item, then resolve_feedback with a note saying what changed.', @@ -124,7 +124,7 @@ const WORKFLOW_CHEATSHEET = [ const GOTCHAS = [ 'The bar: craft beautiful UI/UX a designer would sign off on, and polish to it YOURSELF — start from a pattern, use the whole toolkit (icons/fonts/controls/components), and run canvas_evaluate → resolve EVERY comment → re-evaluate until CLEAN (zero blocking issues) BEFORE presenting. Readiness turns on blocking findings, not the score — the score is always reported and worth climbing toward (aim for > 95), but a clean, sub-bar design is still READY. The evaluate result\'s "directive" field says when it\'s safe to present. Never show the user an unpolished design.', '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.', + '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.', '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.', @@ -591,13 +591,14 @@ The renderer reserves room for pinned chrome: the root's top/bottom padding is r 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? } — a standalone text action, at least 24 tall, measured as a pointer target. 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?, 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. + - 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. - - 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 sole control inside it is measured by the row's box. + - 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. - divider { orientation?: "horizontal"|"vertical", inset? } — a 1px $border hairline; vertical ones separate panes. Not a target. +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. Labels truncate to one line with an ellipsis and carry their full text as a title; text nodes take title too. On web and desktop-app canvases every one of these except property-row and divider is a pointer target held to the 24px floor. A canvas that holds a nav-item, tabs, tree-row, menu-row or property-row must declare its type (desktop-app-artboard). Responsive layout (author desktop-first, adapt down): @@ -2130,7 +2131,7 @@ server.tool( // --- canvas_evaluate --- server.tool( 'canvas_evaluate', - `Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action, link, text-input, nav-item, each tab of a tabs node, tree-row, menu-row — inline text links and dividers are not targets, and a sole control inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too; they point at the component definition and carry no fix op. Modes: + `Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action, link, text-input, nav-item, each tab of a tabs node, tree-row, menu-row — inline text links and dividers are not targets, and a control that is the only target directly inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too; they point at the component definition and carry no fix op. Modes: - "fast": JSON-only, <100ms, deterministic heuristics only. - "detailed": adds Puppeteer-based pixel overlap detection in the consistency category, laid out at the canvas's artboard size (siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt; a bar pinned to the top over in-flow content still counts). - "llm": fast-mode heuristics plus a vision-model critique against a FIXED rubric (provider picked from FRAMESMITH_LLM_PROVIDER env var, or whichever of ANTHROPIC_API_KEY / OPENAI_API_KEY is set). Adds an "llmCritique" field: { rubric: { hierarchy, execution, specificity, restraint, variety } each {score 1-5, rationale}, score (0-100 derived), summary, suggestions, needsRevision, failingAxes }. The verdict is stamped on the canvas (metadata.critique) + the per-project build log for auditability. Cost: one paid API call per invocation. To CLOSE the loop and auto-fix failing axes, use canvas_revise. @@ -2140,7 +2141,7 @@ THE HEURISTIC DIRECTIVE IS THE PRESENTATION GATE. mode: "llm" adds optional dept The result's "genre" field (present whenever cliche ran) makes the genre decision auditable: { active, source ("explicit" param | "provenance" stamp | null), relaxed (tells skipped, by the genre and by the applied preset), notRelaxed ([{ tell, relaxedBy }] — tells still flagging that a DIFFERENT genre would relax), byPreset ({ preset, relaxed } — present when the applied preset relaxed tells on its own, e.g. the material preset) }. active is the canonical genre: an alias reports as its canonical name ("dashboard" → "data", "checkout" → "commerce"). If the score is pinned by tells listed in notRelaxed, the genre is probably wrong — genre follows what the screen is FOR (read screens with the user's own figures → "data"; a screen you complete a purchase on → "commerce"; the Material style → "material" (an editor or admin console is a type, not a genre: declare it with canvas_create / canvas_set_type type "desktop-app")), not what it contains. -The result's "surface" field (always present) reports the canvas TYPE and the rules it selected: { type ("web" | "mobile" | "desktop-app"), device (the profile: a phone such as "iphone-390" on mobile, a window such as "window-1440" on desktop-app, null on web), source ("declared" by canvas_create type / canvas_set_type, or "default" — never declared, judged as web), rulesOn (rule ids the composed type + genre + preset rulesets turned on), rulesOff (rule ids they turned off), conflicts (ids both enabled and disabled — those stay ON) }. On a web canvas rulesOn is ["desktop-app-artboard", "mobile-artboard"] (the base rules, on for every type). On a desktop-app canvas rulesOff lists "type-scale-ratio" (the adjacent font-size ratio check, which tags its warnings with that rule id on web and mobile; dense apps step 12/13/14 on purpose), and desktop-app-artboard (structure, every type) WARNS when a desktop-app canvas is narrower than its window's 1024px minimum, and when a canvas holding a desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) never declared its type or is declared mobile — a canvas declared web gets an info instead. On a mobile canvas it lists the mobile ruleset, and each finding from a rule carries a "rule" field with its id: mobile-touch-target (usability ERROR, −25 per target: a control — toggle/checkbox/radio/select — whose touch target is below 44px in either dimension; the target extends to its row only when the row is a horizontal frame holding that one tappable (no other control or tappable primitive), sized by the row's numeric height/minHeight, else the control plus the row's rendered padding; a row with no width inside a vertical parent that sets no alignItems stretches to that parent's width when the parent's own width is known. The tappable primitives are measured by their own box, never an ancestor's: a button (height by size, 32/44/52, or a larger height/minHeight; never narrower than tall), a list-row (44, 56 with a subtitle; its width when known), each tab-bar tab (bar width / slots × 49) and the FAB (56), each nav-bar action (44×44). Nodes inside an instance are judged as rendered and reported on the instance), mobile-handbuilt-target (usability info: a frame whose only content is one icon, or one icon plus a label of ≤3 words, with a box below 44px — rebuild it as a button if tappable), mobile-tab-bar (usability WARNING, −10 per condition: fewer than 2 or more than 5 tabs (the FAB is not a tab); a tab with no label; not pinned to the bottom — a position override or any y), mobile-safe-area (usability WARNING, −10: content in the status-bar or home-indicator inset, or left under a pinned bar. With root safeArea the renderer reserves the insets; pinned chrome (a fixed status-bar, tab-bar or home-indicator) raises the reservation to its height; so only positioned content is checked: absolute, fixed, and sticky at its stuck y. Without safeArea the first content must clear 47px and the last 34px through padding, spacer frames, pinned chrome, or an in-flow status-bar — padding ≥32px renders scaled down on a phone, about 27% at 390, so use a spacer frame inside the frame that holds your content. A pinned bar (fixed, not chrome) must keep its own content out of the inset, and the scroll must clear it: the last content's clearance from the bottom must reach the bar's height + its bottom offset (for a top bar, the first content's offset must reach its y + height) — the suggestion names the spacer height to add at the end (or start) of your content frame. A sheet's content is never judged (it is a padded overlay). Fast mode adds an info when it cannot place positioned content (inside an in-flow frame, or a fixed node under a blurred or animated ancestor) or cannot work out a pinned bar's height; detailed mode checks rendered rects and is authoritative: content in the top inset, positioned content in the screen's bottom inset, in-flow content in the last 34px of the document, sticky content where it sticks, and in-flow content under a bottom bar at the end of the scroll or a top bar at the start), mobile-type-floor (typography WARNING, −10: text below 11px, a $body text below 16px, prose of 5+ words below 13px; 12+ words at 13–15px is an info; figures and units are not words), mobile-one-column (usability info: prose side by side in a horizontal/grid frame), and mobile-artboard (structure; runs on EVERY type: a mobile canvas ≥500px wide WARNS, any other size than the device's is an info; an undeclared canvas narrower than 500px WARNS until canvas_set_type declares it; declared web and narrower than 500px gets an info). None has an autofix. +The result's "surface" field (always present) reports the canvas TYPE and the rules it selected: { type ("web" | "mobile" | "desktop-app"), device (the profile: a phone such as "iphone-390" on mobile, a window such as "window-1440" on desktop-app, null on web), source ("declared" by canvas_create type / canvas_set_type, or "default" — never declared, judged as web), rulesOn (rule ids the composed type + genre + preset rulesets turned on), rulesOff (rule ids they turned off), conflicts (ids both enabled and disabled — those stay ON) }. On a web canvas rulesOn is ["desktop-app-artboard", "mobile-artboard"] (the base rules, on for every type). On a desktop-app canvas rulesOff lists "type-scale-ratio" (the adjacent font-size ratio check, which tags its warnings with that rule id on web and mobile; dense apps step 12/13/14 on purpose), and desktop-app-artboard (structure, every type) WARNS when a desktop-app canvas is narrower than its window's 1024px minimum, and when a canvas holding a desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) never declared its type or is declared mobile — a canvas declared web gets an info instead. On a mobile canvas it lists the mobile ruleset, and each finding from a rule carries a "rule" field with its id: mobile-touch-target (usability ERROR, −25 per target: a control — toggle/checkbox/radio/select — whose touch target is below 44px in either dimension; the target extends to its row only when the row is a horizontal frame holding that one tappable (no other control or tappable primitive), sized by the row's numeric height/minHeight, else the control plus the row's rendered padding; a row with no width inside a vertical parent that sets no alignItems stretches to that parent's width when the parent's own width is known. The tappable primitives are measured by their own box, never an ancestor's: a button (height by size, 24/32/44/52, or a larger height/minHeight; never narrower than tall), a list-row (44, 56 with a subtitle; its width when known), each tab-bar tab (bar width / slots × 49) and the FAB (56), each nav-bar action (44×44). Nodes inside an instance are judged as rendered and reported on the instance), mobile-handbuilt-target (usability info: a frame whose only content is one icon, or one icon plus a label of ≤3 words, with a box below 44px — rebuild it as a button if tappable), mobile-tab-bar (usability WARNING, −10 per condition: fewer than 2 or more than 5 tabs (the FAB is not a tab); a tab with no label; not pinned to the bottom — a position override or any y), mobile-safe-area (usability WARNING, −10: content in the status-bar or home-indicator inset, or left under a pinned bar. With root safeArea the renderer reserves the insets; pinned chrome (a fixed status-bar, tab-bar or home-indicator) raises the reservation to its height; so only positioned content is checked: absolute, fixed, and sticky at its stuck y. Without safeArea the first content must clear 47px and the last 34px through padding, spacer frames, pinned chrome, or an in-flow status-bar — padding ≥32px renders scaled down on a phone, about 27% at 390, so use a spacer frame inside the frame that holds your content. A pinned bar (fixed, not chrome) must keep its own content out of the inset, and the scroll must clear it: the last content's clearance from the bottom must reach the bar's height + its bottom offset (for a top bar, the first content's offset must reach its y + height) — the suggestion names the spacer height to add at the end (or start) of your content frame. A sheet's content is never judged (it is a padded overlay). Fast mode adds an info when it cannot place positioned content (inside an in-flow frame, or a fixed node under a blurred or animated ancestor) or cannot work out a pinned bar's height; detailed mode checks rendered rects and is authoritative: content in the top inset, positioned content in the screen's bottom inset, in-flow content in the last 34px of the document, sticky content where it sticks, and in-flow content under a bottom bar at the end of the scroll or a top bar at the start), mobile-type-floor (typography WARNING, −10: text below 11px, a $body text below 16px, prose of 5+ words below 13px; 12+ words at 13–15px is an info; figures and units are not words), mobile-one-column (usability info: prose side by side in a horizontal/grid frame), and mobile-artboard (structure; runs on EVERY type: a mobile canvas ≥500px wide WARNS, any other size than the device's is an info; an undeclared canvas narrower than 500px WARNS until canvas_set_type declares it; declared web and narrower than 500px gets an info). None has an autofix. REPEATED FINDINGS FOLD in this result: three or more warnings or infos sharing a severity, category, rule (or tell) and theme come back as ONE entry when they also share their message — members that carry a fix match on its shape (quoted text and numbers aside, since each fix op holds its node's specifics), members without a fix only when they read the same apart from quoted node text, suggestion included. The entry keeps the first one's message and suggestion and adds nodeIds (distinct, nodeId first), count, and fixes ([{ nodeId, op }] for each member that had a fix) — act on every node it lists. Errors never fold. canvas_autofix and the directive work from the unfolded list.`, { diff --git a/src/primitives.ts b/src/primitives.ts index 4ad59c2..7b4202f 100644 --- a/src/primitives.ts +++ b/src/primitives.ts @@ -109,9 +109,14 @@ export function tabsItems(n: SceneNode): TabsItem[] { return Array.isArray(n.items) ? (n.items as Array).filter((it): it is TabsItem => !!it && typeof it === 'object') : []; } +/** A text-input's line count: whole lines, at least 1. */ +export function textInputRows(n: SceneNode): number { + return isNum(n.rows) && n.rows >= 2 ? Math.floor(n.rows) : 1; +} + export function textInputHeight(n: SceneNode): number { const base = TEXT_INPUT_HEIGHT[n.size === 'sm' ? 'sm' : 'md']; - const rows = isNum(n.rows) && n.rows > 1 ? Math.floor(n.rows) : 1; + const rows = textInputRows(n); return rows > 1 ? Math.max(base, rows * TEXT_INPUT_LINE + 12) : base; } @@ -120,17 +125,23 @@ export function textInputHeight(n: SceneNode): number { * item; the rest have one. Not for the phone tappables (see evaluate). */ export function desktopTargets(n: SceneNode): Array<{ what: string; w?: number; h: number; disabled: boolean }> { const w = isNum(n.width) ? n.width : undefined; - const h = (min: number) => Math.max(isNum(n.height) ? n.height : min, isNum(n.minHeight) ? n.minHeight : 0); + // 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; switch (n.type) { - case 'link': return [{ what: 'link', w, h: h(LINK_MIN_HEIGHT), disabled }]; - case 'text-input': return [{ what: 'text-input', w, h: Math.max(textInputHeight(n), isNum(n.height) ? n.height : 0), disabled }]; + // A link never renders shorter than 24 (min-height), whatever its height. + case 'link': return [{ what: 'link', w, h: Math.max(LINK_MIN_HEIGHT, h(LINK_MIN_HEIGHT)), disabled }]; + // A text-input's height comes from its size and rows (the renderer ignores `height`). + case 'text-input': return [{ what: 'text-input', w, h: textInputHeight(n), disabled }]; case 'nav-item': return [{ what: 'nav-item', w: n.collapsed ? NAV_ITEM_HEIGHT : w, h: h(NAV_ITEM_HEIGHT), disabled }]; case 'tree-row': return [{ what: 'tree-row', w, h: h(TREE_ROW_HEIGHT), disabled }]; case 'menu-row': return [{ what: 'menu-row', w, h: h(MENU_ROW_HEIGHT), disabled }]; case 'tabs': { - const th = h(TABS_HEIGHT[n.size === 'sm' ? 'sm' : 'md']); + // The tablist's height comes from its size alone (the renderer ignores `height`). + 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 })); + // (A disabled tabs node disables every tab.) } default: return []; } diff --git a/src/renderer.ts b/src/renderer.ts index 94ecb06..45a332e 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -6,7 +6,7 @@ import { BUTTON_FONT, BUTTON_PADDING, CHROME_EDGE, FAB_RAISE, FAB_SIZE, FLOATING_INSET, NAV_ACTION, NAV_BAR_HEIGHT, NAV_BAR_LARGE_HEIGHT, TAB_BAND, buttonHeight, chromeHeight, chromeReservation, effectivePosition, listRowMinHeight, navBarHeight, rootInsets, LINK_MIN_HEIGHT, NAV_ITEM_HEIGHT, TABS_HEIGHT, TREE_ROW_HEIGHT, TREE_INDENT, MENU_ROW_HEIGHT, PROPERTY_ROW_HEIGHT, PROPERTY_LABEL_WIDTH, - tabsItems, textInputHeight, + tabsItems, textInputHeight, textInputRows, } from './primitives.js'; /** Build a `background: …` declaration from a node's `gradient`. @@ -1260,9 +1260,13 @@ function rowWidth(node: SceneNode): string { * skipped, so content always renders whole. */ function textWithLinks(node: SceneNode): string { const content = node.content ?? ''; + // A range edge inside a surrogate pair (an emoji) moves outward so the pair + // is never split; only integer offsets count (no coercion of null / ""). + const low = (i: number) => i > 0 && i < content.length && /[\uDC00-\uDFFF]/.test(content[i]) && /[\uD800-\uDBFF]/.test(content[i - 1]); const ranges = entries<{ start?: unknown; end?: unknown }>(node.links) - .map((r) => ({ start: Number(r.start), end: Number(r.end) })) - .filter((r) => Number.isInteger(r.start) && Number.isInteger(r.end) && r.start >= 0 && r.end > r.start && r.end <= content.length) + .filter((r): r is { start: number; end: number } => Number.isInteger(r.start) && Number.isInteger(r.end)) + .map((r) => ({ start: low(r.start) ? r.start - 1 : r.start, end: low(r.end) ? r.end + 1 : r.end })) + .filter((r) => r.start >= 0 && r.end > r.start && r.end <= content.length) .sort((a, b) => a.start - b.start); let out = ''; let at = 0; @@ -1275,7 +1279,13 @@ function textWithLinks(node: SceneNode): string { return out + escapeHtml(content.slice(at)); } +/** 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; +} + function renderLink(node: SceneNode, rc: RenderCtx, attrs: string): string { + attrs = disabledAttrs(node, attrs); const color = node.color ?? FALLBACK.accent; const glyph = iconHtml(node.icon, 14, node.iconColor ?? color); const external = node.external ? iconHtml('external-link', 12, node.iconColor ?? color) : ''; @@ -1294,8 +1304,10 @@ function renderLink(node: SceneNode, rc: RenderCtx, attrs: string): string { function renderTextInput(node: SceneNode, rc: RenderCtx, dataAttr: string): string { const h = textInputHeight(node); - const multi = typeof node.rows === 'number' && node.rows > 1; - const border = node.stroke ?? FALLBACK.border; + const multi = textInputRows(node) > 1; + // An error colours the boundary and its message: $danger by default + // (unthemed too); an explicit stroke wins. + const border = node.stroke ?? (text(node.error) ? FALLBACK.danger : FALLBACK.border); const secondary = node.secondaryColor ?? FALLBACK.secondary; const value = text(node.value); const shown = value || text(node.placeholder); @@ -1321,10 +1333,12 @@ function renderTextInput(node: SceneNode, rc: RenderCtx, dataAttr: string): stri node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, ]); const ariaInvalid = error ? ' aria-invalid="true"' : ''; - return `
${glyph}${words}
${message}`; + const focus = node.disabled ? ' tabindex="-1" aria-disabled="true"' : ' tabindex="0" data-focusable'; + return `${glyph}${words}${message}`; } function renderNavItem(node: SceneNode, rc: RenderCtx, attrs: string): string { + attrs = disabledAttrs(node, attrs); const color = node.color ?? FALLBACK.text; const accent = node.iconColor ?? FALLBACK.accent; const label = text(node.label); @@ -1361,8 +1375,10 @@ function renderTabs(node: SceneNode, rc: RenderCtx, dataAttr: string): string { const label = text(it.label); const count = text(it.count); const active = it.active === true; + // A tab keeps its width until the tablist runs out, then shrinks so its + // label truncates (never past its padding). const tab = css([ - 'position: relative', 'display: flex', 'align-items: center', 'gap: 6px', 'flex-shrink: 0', 'height: 100%', + '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}`, @@ -1372,7 +1388,8 @@ function renderTabs(node: SceneNode, rc: RenderCtx, dataAttr: string): string { ? `
` : ''; const badge = count ? `${escapeHtml(count)}` : ''; - return `
${titledLabel(label, '')}${badge}${indicator}
`; + const focus = it.disabled ? ' tabindex="-1" aria-disabled="true"' : ' tabindex="0" data-focusable'; + return `
${titledLabel(label, '')}${badge}${indicator}
`; }).join(''); const box = css([ ...positionStyles(node, rc), 'display: flex', 'align-items: stretch', 'gap: 2px', 'flex-shrink: 0', 'box-sizing: border-box', @@ -1383,6 +1400,7 @@ function renderTabs(node: SceneNode, rc: RenderCtx, dataAttr: string): string { } function renderTreeRow(node: SceneNode, rc: RenderCtx, attrs: string): string { + 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}"`; @@ -1404,7 +1422,7 @@ function renderTreeRow(node: SceneNode, rc: RenderCtx, attrs: string): string { function renderMenuRow(node: SceneNode, rc: RenderCtx, attrs: string): string { const secondary = node.secondaryColor ?? FALLBACK.secondary; const color = node.color ?? (node.destructive ? FALLBACK.danger : FALLBACK.text); - if (node.disabled) attrs += ' aria-disabled="true"'; + attrs = disabledAttrs(node, attrs); if (typeof node.checked === 'boolean') attrs += ` aria-checked="${node.checked}"`; const check = node.checked ? iconHtml('check', 14, node.iconColor ?? FALLBACK.accent) : ''; const glyph = iconHtml(node.icon, 16, node.destructive ? color : secondary); @@ -1433,7 +1451,9 @@ function renderPropertyRow(node: SceneNode, rc: RenderCtx, dataAttr: string): st `color: ${node.color ?? FALLBACK.text}`, 'font-size: 13px', ]); const label = `
${titledLabel(text(node.label), `color: ${node.secondaryColor ?? FALLBACK.secondary}; font-size: 12px`)}
`; - const value = `
${renderChildren(node, rc)}
`; + // data-fs-slot: the layout walker steps through this wrapper, so the value + // node is placed (snapshot_layout, the 24px circle test, stress). + const value = `
${renderChildren(node, rc)}
`; return `${label}${value}`; } diff --git a/src/screenshot.ts b/src/screenshot.ts index cf779d1..e9ad1cc 100644 --- a/src/screenshot.ts +++ b/src/screenshot.ts @@ -204,14 +204,21 @@ const LAYOUT_WALKER_SOURCE = `(function (rootId, depth) { if (el.hasAttribute('data-fs-scroll')) result.scrolls = true; if (currentDepth < depth) { var childRects = []; - for (var i = 0; i < el.children.length; i++) { - var childRect = getRect(el.children[i], currentDepth + 1); - if (childRect) childRects.push(childRect); - } + collect(el, currentDepth + 1, childRects); if (childRects.length > 0) result.children = childRects; } return result; } + // A primitive's child slot (data-fs-slot, e.g. a property-row's value) has + // no node id of its own: walk through it so the nodes inside are placed. + function collect(el, childDepth, out) { + for (var i = 0; i < el.children.length; i++) { + var child = el.children[i]; + if (!child.hasAttribute('data-node-id') && child.hasAttribute('data-fs-slot')) { collect(child, childDepth, out); continue; } + var childRect = getRect(child, childDepth); + if (childRect) out.push(childRect); + } + } var rootSelector = rootId ? '[data-node-id="' + rootId + '"]' : '[data-node-id]'; var root = document.querySelector(rootSelector); if (!root) return []; diff --git a/src/variables.ts b/src/variables.ts index 51f081a..6e72383 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -165,7 +165,9 @@ function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { const text = c['text-primary'] ?? CONTROL_FALLBACK.text; const secondary = c['text-secondary'] ?? '#6B7280'; const danger = c.danger ?? c.error ?? '#DC2626'; - const tint = c['accent-tint'] ?? '#EFF4FF'; + // Without an accent-tint token the active fill is the accent washed into the + // surface (12%), so it reads on a dark palette as well as a light one. + const tint = c['accent-tint'] ?? mixHex(accent, surface, 0.12) ?? '#EFF4FF'; const set = (key: K, value: SceneNode[K]) => { if (node[key] === undefined) node[key] = value; }; if (node.disabled && node.opacity === undefined) node.opacity = 0.5; @@ -253,6 +255,15 @@ function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { } } +/** `top` laid over `base` at `alpha`, as #RRGGBB; undefined unless both are #RRGGBB. */ +function mixHex(top: string, base: string, alpha: number): string | undefined { + const t = /^#([0-9a-f]{6})$/i.exec(top); + const b = /^#([0-9a-f]{6})$/i.exec(base); + if (!t || !b) return undefined; + const ch = (hex: string, i: number) => parseInt(hex.slice(i, i + 2), 16); + return '#' + [0, 2, 4].map((i) => Math.round(alpha * ch(t[1], i) + (1 - alpha) * ch(b[1], i)).toString(16).padStart(2, '0')).join('').toUpperCase(); +} + /** A prop as text, for "is it set?" checks. */ function text_(value: unknown): string { return typeof value === 'string' ? value.trim() : ''; diff --git a/test-desktop-primitives-render.ts b/test-desktop-primitives-render.ts index 4de69a4..208eb33 100644 --- a/test-desktop-primitives-render.ts +++ b/test-desktop-primitives-render.ts @@ -26,6 +26,7 @@ const inspector: SceneNode[] = [ { id: 'rail', name: 'rail', type: 'nav-item', label: 'Projects', icon: 'folder', collapsed: true }, { id: 'tsm', name: 'tsm', type: 'tabs', size: 'sm', items: [{ label: 'Quality', active: true }, { label: 'Design system' }] }, { id: 'tmd', name: 'tmd', type: 'tabs', items: [{ label: 'All', active: true }, { label: 'Archived', count: 3 }], variant: 'contained' }, + { id: 'tnarrow', name: 'tnarrow', type: 'tabs', size: 'sm', width: 220, items: [{ label: 'Quality', active: true }, { label: 'Design system' }, { label: 'Feedback', disabled: true }] }, { id: 'tr0', name: 'tr0', type: 'tree-row', label: 'src', depth: 0, expanded: true, width: 300 }, { id: 'tr1', name: 'tr1', type: 'tree-row', label: 'components', depth: 1, expanded: false, width: 300 }, { id: 'tr2', name: 'tr2', type: 'tree-row', label: 'button.ts', depth: 2, width: 300 }, @@ -85,7 +86,8 @@ for (const [label, vars] of themes) { check(`${label}: tree-rows 32 tall`, ['tr0', 'tr1', 'tr2'].every((id) => h(id) === 32)); check(`${label}: menu-rows 32 tall`, ['m1', 'm2', 'm3'].every((id) => h(id) === 32)); check(`${label}: property-rows at least 32 tall`, ['p1', 'p2', 'p3'].every((id) => (h(id) ?? 0) >= 32)); - check(`${label}: every property value starts at one left edge`, new Set(['v1', 'v2', 'v3'].map((id) => r.get(id)?.x)).size === 1, ['v1', 'v2', 'v3'].map((id) => r.get(id)?.x).join(' ')); + const xs = ['v1', 'v2', 'v3'].map((id) => r.get(id)?.x); + check(`${label}: every property value is placed and starts at one left edge`, xs.every((x) => typeof x === 'number') && new Set(xs).size === 1, xs.join(' ')); check(`${label}: text-input 32 at sm, 40 at md, 72 at three rows`, h('in-sm') === 32 && h('in-md') === 40 && h('in-3') === 72, `${h('in-sm')} ${h('in-md')} ${h('in-3')}`); check(`${label}: an error adds its message below the field`, (h('in-err') ?? 0) > 40, String(h('in-err'))); check(`${label}: the vertical divider is 1px wide and as tall as its panes`, w('dv') === 1 && h('dv') === 120, `${w('dv')}×${h('dv')}`); @@ -104,6 +106,13 @@ for (const [label, vars] of themes) { check('every menu shortcut right-aligns to one column', rights.length === 3 && new Set(rights).size === 1, rights.join(' ')); } +// A disabled tab leaves the tab order. +{ + const c = canvasOf(inspector, system); + const html = renderToHtml(resolveVariables(structuredClone(c.root), system), 1440, 900, c); + check('a disabled tab is not focusable', /role="tab" tabindex="-1" aria-disabled="true"/.test(html) && (html.match(/role="tab" tabindex="0"/g) ?? []).length >= 2); +} + // Long text and i18n: designed truncation only, never a clip or an overflow. for (const name of ['long-text', 'i18n'] as const) { const c = canvasOf(inspector, system); diff --git a/test-desktop-primitives.ts b/test-desktop-primitives.ts index fffa92e..c24b8a8 100644 --- a/test-desktop-primitives.ts +++ b/test-desktop-primitives.ts @@ -61,7 +61,9 @@ const html = (n: SceneNode, colors?: Record) => { // ── FR-B3..B9: markup and defaults ───────────────────────────────────────── { const nav = html({ id: 'n', name: 'n', type: 'nav-item', label: 'Projects', icon: 'folder', active: true, count: 12 }); - check('an active nav-item draws fill, bar and weight, with aria-current', /aria-current="page"/.test(nav) && /width: 2px/.test(nav) && /font-weight: 600/.test(nav) && /background-color: #EFF4FF/.test(nav)); + check('an active nav-item draws fill, bar and weight, with aria-current', /aria-current="page"/.test(nav) && /width: 2px/.test(nav) && /font-weight: 600/.test(nav) && /background-color: #E5ECFD/.test(nav), (nav.match(/background-color: #[0-9A-F]{6}/gi) ?? []).join(' ')); + const darkNav = html({ id: 'nd', name: 'nd', type: 'nav-item', label: 'A', active: true }, { accent: '#60A5FA', 'bg-surface': '#111827' }); + check('without an accent-tint token the active fill is the accent washed into the surface (dark stays dark)', /background-color: #1A2940/.test(darkNav), (darkNav.match(/background-color: #[0-9A-F]{6}/gi) ?? []).join(' ')); const rail = html({ id: 'n2', name: 'n2', type: 'nav-item', label: 'Projects', icon: 'folder', collapsed: true }); check('a collapsed nav-item is 32×32 with its label as the accessible name', /width: 32px/.test(rail) && /aria-label="Projects"/.test(rail) && !/>Projects) => { { id: 'f', name: 'f', type: 'menu-row', label: 'M' }, { id: 'g', name: 'g', type: 'button', icon: 'x', size: 'xs', ariaLabel: 'X' }, ] })).length === 0); for (const type of ['web', 'desktop-app'] as const) { - const small = await usab({ id: 'l', name: 'l', type: 'link', label: 'Go', height: 16 }, type === 'web' ? { type } : app); - check(`${type}: a link forced to 16px is measured (fast-mode warning)`, small.length === 1 && small[0].severity === 'warning'); + const small = await usab({ id: 'l', name: 'l', type: 'link', label: 'Go', width: 16 }, type === 'web' ? { type } : app); + check(`${type}: a link narrowed to 16px is measured (fast-mode warning)`, small.length === 1 && small[0].severity === 'warning'); + const short = await usab({ id: 'l2', name: 'l2', type: 'link', label: 'Go', height: 10 }, type === 'web' ? { type } : app); + check(`${type}: a link given height 10 still renders 24 tall, so it is not flagged`, short.length === 0); } - const tabs = await usab({ id: 't', name: 't', type: 'tabs', height: 20, items: [{ label: 'A' }, { label: 'B', disabled: true }, { label: 'C' }] }); - check('each enabled tab is its own target; a disabled tab is not measured', tabs.length === 2, JSON.stringify(tabs.map((i) => i.message))); + const tabsTargets = desktopTargets({ id: 't', name: 't', type: 'tabs', height: 20, items: [{ label: 'A' }, { label: 'B', disabled: true }, { label: 'C' }] } as SceneNode); + check('each tab is its own target, disabled ones marked; height comes from size, not height', tabsTargets.length === 3 && tabsTargets.filter((t) => t.disabled).length === 1 && tabsTargets.every((t) => t.h === 40)); const menuOff = await usab({ id: 'm', name: 'm', type: 'menu-row', label: 'M', height: 16, disabled: true }); check('a disabled menu-row is not measured', menuOff.length === 0); const inline = await usab({ id: 'tx', name: 'tx', type: 'text', content: 'See the docs', links: [{ start: 8, end: 12 }], fontSize: 12 }); @@ -129,6 +133,76 @@ const html = (n: SceneNode, colors?: Record) => { check('mobile: desktop primitives are not phone tappables (no touch-target finding)', !phone.some((i) => i.rule === 'mobile-touch-target')); } +// ── Verify round 1 fixes ─────────────────────────────────────────────────── +{ + for (const t of ['link', 'nav-item', 'tree-row', 'menu-row', 'text-input']) { + const r = await evaluateCanvas(canvasWith([{ id: 'x', name: 'x', type: t as SceneNode['type'], label: 'L', icon: 'no-such-icon-zzz' } as SceneNode], app), { mode: 'fast', categories: ['structure'] }); + check(`an unknown icon on a ${t} warns`, r.issues.some((i) => /no-such-icon-zzz/.test(i.message) && i.severity === 'warning')); + } + const menus = (shortcut: boolean) => canvasWith([ + { id: 't1', name: 't1', type: 'text', content: 'A', color: '$text-primary' }, { id: 't2', name: 't2', type: 'text', content: 'B', color: '$text-primary' }, + ...Array.from({ length: 6 }, (_, i) => ({ id: `m${i}`, name: `m${i}`, type: 'menu-row', label: `Item ${i}`, ...(shortcut ? { shortcut: '⌘I', placeholder: 'p' } : {}) } as SceneNode)), + ], app, { 'text-primary': '#111111' }); + const tok = async (c: Canvas) => (await evaluateCanvas(c, { mode: 'fast', categories: ['structure'] })).issues.filter((i) => /use design tokens/.test(i.message)); + check('menu-row shortcuts are copy, not un-tokened values', (await tok(menus(true))).length === (await tok(menus(false))).length); + const unthemedErr = (() => { const c = canvasWith([{ id: 'e', name: 'e', type: 'text-input', value: 'x', error: 'bad' }], app); return renderToHtml(c.root, 1440, 900, c); })(); + check('an unthemed text-input error is $danger-coloured', /border: 1px solid #DC2626/.test(unthemedErr) && /color: #DC2626/.test(unthemedErr)); + const emoji = html({ id: 'em', name: 'em', type: 'text', content: 'a😀b', links: [{ start: 2, end: 3 }, { start: null as unknown as number, end: 1 }] }); + check('an inline link edge inside an emoji moves outward; a null offset is dropped', /]*>😀<\/span>b/.test(emoji) && (emoji.match(/data-fs-inline-link/g) ?? []).length === 1, emoji.slice(emoji.indexOf('') + 4)); + const half = html({ id: 'h', name: 'h', type: 'text-input', rows: 1.5 }); + check('rows 1.5 is a single-line field', !/aria-multiline/.test(half) && /height: 40px/.test(half)); + for (const t of ['link', 'nav-item', 'tree-row', 'menu-row', 'text-input']) { + const d = html({ id: 'dz', name: 'dz', type: t as SceneNode['type'], label: 'L', disabled: true } as SceneNode); + check(`a disabled ${t} leaves the tab order`, /tabindex="-1"/.test(d) && /aria-disabled="true"/.test(d) && !/tabindex="0"/.test(d)); + } +} + +// ── Verify round 1 (test adequacy): pin the paths mutations survived ────── +{ + const usab = async (n: SceneNode) => (await evaluateCanvas(canvasWith([n], app), { mode: 'fast', categories: ['usability'] })).issues.filter((i) => /24px floor/.test(i.message)); + const pr = (children: SceneNode[]): SceneNode => ({ id: 'pr', name: 'pr', type: 'property-row', label: 'Row', children }); + check('owner rule: a checkbox directly in a property-row passes (the row is the target)', (await usab(pr([{ id: 'c', name: 'c', type: 'checkbox' }]))).length === 0); + check('owner rule: a radio beside a link in a property-row is measured bare', (await usab(pr([{ id: 'w', name: 'w', type: 'frame', layout: 'horizontal', children: [{ id: 'r', name: 'r', type: 'radio' }, { id: 'l', name: 'l', type: 'link', label: 'Edit' }] }]))).some((i) => i.nodeId === 'r')); + check('owner rule: a checkbox beside a text-input is measured bare', (await usab(pr([{ id: 'w', name: 'w', type: 'frame', layout: 'horizontal', children: [{ id: 'c', name: 'c', type: 'checkbox' }, { id: 'i', name: 'i', type: 'text-input' }] }]))).some((i) => i.nodeId === 'c')); + check('owner rule: only a direct child owns the row (wrapped in a frame it is measured)', (await usab(pr([{ id: 'w', name: 'w', type: 'frame', children: [{ id: 'c', name: 'c', type: 'checkbox' }] }]))).some((i) => i.nodeId === 'c')); + check('owner rule: a control directly in a nav-item / menu-row / list-row owns that row too', (await usab({ id: 'ni', name: 'ni', type: 'nav-item', label: 'N', children: [{ id: 'c1', name: 'c1', type: 'checkbox' }] })).length === 0 && (await usab({ id: 'mi', name: 'mi', type: 'menu-row', label: 'M', children: [{ id: 'c2', name: 'c2', type: 'checkbox' }] })).length === 0 && (await usab({ id: 'li', name: 'li', type: 'list-row', title: 'L', children: [{ id: 'c3', name: 'c3', type: 'checkbox' }] })).length === 0); + check('census judges the rendered height: a nav-item at height 16 with minHeight 40 is flagged', (await usab({ id: 'n', name: 'n', type: 'nav-item', label: 'N', height: 16, minHeight: 40 })).length === 1); + check('census judges the rendered height: a text-input ignores height', desktopTargets({ id: 'i', name: 'i', type: 'text-input', height: 10 } as SceneNode)[0].h === 40); + check('a disabled tabs node disables every tab', desktopTargets({ id: 't', name: 't', type: 'tabs', disabled: true, items: [{ label: 'A' }, { label: 'B' }] } as SceneNode).every((t) => t.disabled)); + check('the desktop-app primitive set is exactly the five', JSON.stringify([...DESKTOP_APP_PRIMITIVES].sort()) === JSON.stringify(['menu-row', 'nav-item', 'property-row', 'tabs', 'tree-row'])); + check('the clickable set is exactly the phone tappables plus six', JSON.stringify([...CLICKABLE_PRIMITIVES].sort()) === JSON.stringify(['button', 'link', 'list-row', 'menu-row', 'nav-bar', 'nav-item', 'tab-bar', 'tabs', 'text-input', 'tree-row'])); + for (const t of ['link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row']) { + const c = canvasWith(Array.from({ length: 12 }, (_, i) => ({ id: `${t}${i}`, name: `${t}${i}`, type: t as SceneNode['type'], label: 'L', items: [{ label: 'A' }] } as SceneNode)), app); + const adv = (await evaluateCanvas(c, { mode: 'fast', categories: ['structure'] })).issues.filter((i) => /No component instances/.test(i.message)); + if (adv.length) check(`repeated ${t}s count as reuse`, false); + } + check('every repeated desktop-app primitive counts as reuse', true); + for (const [t, colors] of [['toggle', { 'border-strong': '#556677', border: '#EEEEEE' }], ['radio', { 'border-strong': '#556677', border: '#EEEEEE' }]] as const) { + const withTok = html({ id: 'x', name: 'x', type: t }, colors); + const without = html({ id: 'x', name: 'x', type: t }, { border: '#EEEEEE' }); + check(`an unchecked ${t} uses $border-strong only when the token exists`, /#556677/.test(withTok) && !/#556677/.test(without) && /#EEEEEE/.test(without)); + } + const { registerStructure } = await import('./src/structures.js'); + for (const t of ['link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row', 'divider']) { + registerStructure({ name: `probe-${t}`, kind: 'component', surface: 'any', description: 'probe', nodes: [{ id: 'n', type: t as SceneNode['type'], name: 'n', label: 'L', placeholder: 'Find', value: 'v', shortcut: '⌘K', error: 'Bad', items: [{ label: 'A' }] } as SceneNode] }); + const cv = createCanvas(`seed-${t}`, undefined, {}, { type: 'desktop-app', device: 'window-1440' }); + const res = applyStructure(cv, `probe-${t}`, { existingColors: new Set() }); + if (!res.seededColors.includes('accent-tint') || !res.seededColors.includes('border-strong')) check(`stamping a ${t} seeds the desktop-app tokens`, false, res.seededColors.join(',')); + if (t === 'text-input' && !['placeholder', 'value', 'error'].every((prop) => res.placeholders.some((pl) => pl.prop === prop))) check('text-input copy is a placeholder', false, JSON.stringify(res.placeholders)); + if (t === 'menu-row' && !res.placeholders.some((pl) => pl.prop === 'shortcut')) check('menu-row shortcut is a placeholder', false); + } + check('every desktop-app primitive seeds the tokens; their copy is a placeholder', true); + const withBorder = createCanvas('seed-b', undefined, {}, { type: 'desktop-app', device: 'window-1440' }); + check('an existing $border suppresses border-strong seeding (it falls back to border)', !applyStructure(withBorder, 'probe-text-input', { existingColors: new Set(['border']) }).seededColors.includes('border-strong')); + const sc = { id: 'm', name: 'm', type: 'menu-row', shortcut: '⌘K' } as SceneNode; + const { root: pert } = applyPerturbation('long-text', { id: 'document', type: 'document', name: 'D', children: [sc] }); + check('long-text reaches a menu-row shortcut', (pert.children?.[0].shortcut ?? '').length > 4); + check('a depth-1 nav-item indents 16px', /padding: 0 8px 0 24px/.test(html({ id: 'nd', name: 'nd', type: 'nav-item', label: 'Sub', depth: 1 }))); + check('a long shortcut truncates (at most half the row)', /max-width: 50%/.test(html({ id: 'ms', name: 'ms', type: 'menu-row', label: 'L', shortcut: 'Ctrl+Shift+Alt+K' }))); + const r = html({ id: 'tx', name: 'tx', type: 'text', content: 'abcdefghij', links: [{ start: 6, end: 8 }, { start: 1, end: 3 }, { start: 4, end: 4 }, { start: -1, end: 2 }] }); + check('inline links: unsorted ranges render in order; empty and negative ones are dropped', (r.match(/data-fs-inline-link/g) ?? []).length === 2 && r.indexOf('>bc<') < r.indexOf('>gh<')); +} + // ── FR-A6: identity dots are not accents ──────────────────────────────────── { const dots = ['#3B82F6', '#F59E0B', '#EC4899', '#22C55E']; diff --git a/test-pointer-targets.ts b/test-pointer-targets.ts index 81543eb..e57ebb7 100644 --- a/test-pointer-targets.ts +++ b/test-pointer-targets.ts @@ -69,11 +69,13 @@ for (const type of ['web', 'desktop-app'] as const) { // Phase 31 slice B — the desktop-app vocabulary in the census. Two 16px // links touching fail as errors; a tabs node's tabs share its id, so an // undersized tab stays a blocking warning in detailed mode. - const lnk = (id: string): SceneNode => ({ id, name: id, type: 'link', label: id, height: 16 }); + const lnk = (id: string): SceneNode => ({ id, name: id, type: 'link', label: id, width: 16 }); f = await targetFindings(type, [row(0, [lnk('l1'), lnk('l2')])]); - check(`${type}: two touching 16px links fail in detailed mode`, f.length === 2 && f.every((i) => i.severity === 'error'), JSON.stringify(f.map((i) => [i.severity, i.message.slice(0, 80)]))); - f = await targetFindings(type, [{ id: 'tabs', name: 'tabs', type: 'tabs', height: 18, items: [{ label: 'A' }, { label: 'B' }] } as SceneNode]); - check(`${type}: undersized tabs stay blocking warnings`, f.length === 2 && f.every((i) => i.severity === 'warning' && /could not place/.test(i.message)), JSON.stringify(f.map((i) => [i.severity, i.message.slice(0, 80)]))); + check(`${type}: two touching 16px-wide links fail in detailed mode`, f.length === 2 && f.every((i) => i.severity === 'error'), JSON.stringify(f.map((i) => [i.severity, i.message.slice(0, 80)]))); + // A control inside a property-row's value is placed (the walker steps + // through the value slot), so it is not an unplaced neighbour. + f = await targetFindings(type, [row(4, [btn('a', 20), { id: 'pr', name: 'pr', type: 'property-row', label: 'Name', width: 300, children: [{ id: 'pin', name: 'pin', type: 'text-input', value: 'x' }] } as SceneNode])]); + check(`${type}: a property-row value is placed, so a spaced small target nearby passes`, f.length === 0, JSON.stringify(f.map((i) => [i.severity, i.message.slice(0, 90)]))); // A neighbour nested past the layout walker's depth cannot be placed, so the // spacing exception is unproven and the small target stays blocking. From 48e7240e3d37db8ef1216a1321aba4e175f2af57 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Fri, 13 Nov 2026 19:25:29 +0100 Subject: [PATCH 3/4] Let a clickable row own the control inside it, as FR-A4 says --- docs/specs/PHASE-31-SPEC.md | 3 +++ src/evaluate.ts | 15 ++++++++------- src/primitives.ts | 7 ++++--- test-desktop-primitives.ts | 6 +++++- 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 92a9a73..227d4a3 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -219,6 +219,9 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **E9: `link.external`** (named in FR-B2, missing from the Plan's prop list) draws a trailing external-link glyph. The hover underline waits for element states (FR-G1). - **E10: the breadcrumb's parent is a `link`; the current page stays text.** The component keeps its web-only surface (slice D decides what stamps on desktop-app). - **E11 (verify round 1): the census judges what renders.** A `link` never renders under 24 (min-height), `tabs` take their height from `size` and a `text-input` from `size` and `rows` (all ignore `height`), and `nav-item` / `tree-row` / `menu-row` take `height` but ignore `minHeight` — so the census does exactly the same. A control owns its row (E2) only when it is the row's only target, a direct child, with no link, input or button beside it. The layout walker steps through a primitive's child slot (`data-fs-slot`, the property-row value) so those nodes are placed. Tabs shrink so their labels truncate in a narrow tablist; disabled tabs and disabled link / nav-item / tree-row / menu-row / text-input leave the tab order. Unknown icons on the new primitives warn, and their copy (`placeholder`, `value`, `shortcut`, `error`, `ariaLabel`, `count`) is not counted as un-tokened style. Without an `accent-tint` token the active fill is the accent mixed 12% into the surface, so a dark palette gets a dark tint. An unthemed `text-input` error is `$danger`-coloured. Inline link edges never split a surrogate pair. +- **E13 (after verify round 2): a clickable owner is not its own sibling.** Ownership counts the targets among the row's children only, so a sole control directly inside a `nav-item`, `menu-row` or `list-row` owns the row as FR-A4 says (the row itself is clickable and used to count as a second target). Fixed after the second verifier round, proved red on the previous snapshot and green on the fix, not re-verified by an agent. +- **Open (minor): a crowded tablist can truncate every label.** Tabs shrink to fit (E11), and the census measures their height, not their width, so eight tabs in 220px render as unreadable 26px stubs with no finding. A minimum-width rule for tabs belongs with the app rules (slice C). +- **Open (minor): a non-hex accent keeps the light fallback tint.** The 12% mix (E11) needs `#RRGGBB`; an `hsl()` or named accent without an `accent-tint` token still gets `#EFF4FF`. - **E12: only `property-row` renders children.** The other desktop-app primitives draw their own anatomy and drop children; the `batch_design` docs say so. - **Open for a later slice: a `link` or `text-input` on a phone has no 44px check.** They are not phone tappables (E3) and not in the FR-C9 primitive set (pages and phones use them), so a 32px text-input on a mobile canvas passes silently. Adding them to the mobile touch census is a mobile-ruleset change the spec does not make. - **Open for slice C/D: form coverage ignores `text-input`.** The drift inventory's control list (toggle, checkbox, radio, select) is unchanged, so "3+ input controls demand an error state" does not count text-inputs. The spec is silent; decide with the form rules. diff --git a/src/evaluate.ts b/src/evaluate.ts index ded187b..6fe01ab 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -2030,14 +2030,15 @@ export function pointerTargets(entries: NodeEntry[], rootWidth: number): Pointer const def = CONTROL_DEFAULT_SIZE[node.type]; let w = typeof node.width === 'number' ? node.width : def.w; let h = typeof node.height === 'number' ? node.height : def.h; - // Phase 31 FR-A4 — a control that is the only one inside a row - // primitive (property-row, nav-item, menu-row, list-row) owns that row's - // box: the row is the target. Its height is the row's; its width the - // row's when known, else the row spans its container. - // Ownership needs the control to be the row's ONLY target: a link, - // text-input or button beside it shares the row (countTargets). + // Phase 31 FR-A4 — a control that is the only target directly inside a + // row primitive (property-row, nav-item, menu-row, list-row) owns that + // row's box: the row is the target. Its height is the row's; its width + // the row's when known, else the row spans its container. A link, + // text-input or button beside it shares the row; the row itself never + // counts (a nav-item is clickable, but it is the owner, not a sibling). const owner = parentOf.get(node.id) ?? null; - if (owner && CONTROL_OWNERS.has(owner.type) && countTargets(owner) === 1 && Math.min(w, h) < 24) { + const siblingsAndSelf = owner ? (owner.children ?? []).reduce((c, ch) => c + countTargets(ch), 0) : 0; + if (owner && CONTROL_OWNERS.has(owner.type) && siblingsAndSelf === 1 && Math.min(w, h) < 24) { const rowH = Math.max(typeof owner.height === 'number' ? owner.height : 0, OWNER_HEIGHT[owner.type] ?? 0); w = typeof owner.width === 'number' ? owner.width : Infinity; h = Math.max(h, rowH); diff --git a/src/primitives.ts b/src/primitives.ts index 7b4202f..7d7faf3 100644 --- a/src/primitives.ts +++ b/src/primitives.ts @@ -42,7 +42,8 @@ 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']); -/** Rows that own a sole control inside them: the control's target is the row. */ +/** 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']); /** The desktop-app primitives — on a canvas that never declared desktop-app, @@ -138,10 +139,10 @@ export function desktopTargets(n: SceneNode): Array<{ what: string; w?: number; case 'tree-row': return [{ what: 'tree-row', w, h: h(TREE_ROW_HEIGHT), disabled }]; case 'menu-row': return [{ what: 'menu-row', w, h: h(MENU_ROW_HEIGHT), disabled }]; case 'tabs': { - // The tablist's height comes from its size alone (the renderer ignores `height`). + // 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 })); - // (A disabled tabs node disables every tab.) } default: return []; } diff --git a/test-desktop-primitives.ts b/test-desktop-primitives.ts index c24b8a8..9374938 100644 --- a/test-desktop-primitives.ts +++ b/test-desktop-primitives.ts @@ -165,7 +165,11 @@ const html = (n: SceneNode, colors?: Record) => { check('owner rule: a radio beside a link in a property-row is measured bare', (await usab(pr([{ id: 'w', name: 'w', type: 'frame', layout: 'horizontal', children: [{ id: 'r', name: 'r', type: 'radio' }, { id: 'l', name: 'l', type: 'link', label: 'Edit' }] }]))).some((i) => i.nodeId === 'r')); check('owner rule: a checkbox beside a text-input is measured bare', (await usab(pr([{ id: 'w', name: 'w', type: 'frame', layout: 'horizontal', children: [{ id: 'c', name: 'c', type: 'checkbox' }, { id: 'i', name: 'i', type: 'text-input' }] }]))).some((i) => i.nodeId === 'c')); check('owner rule: only a direct child owns the row (wrapped in a frame it is measured)', (await usab(pr([{ id: 'w', name: 'w', type: 'frame', children: [{ id: 'c', name: 'c', type: 'checkbox' }] }]))).some((i) => i.nodeId === 'c')); - check('owner rule: a control directly in a nav-item / menu-row / list-row owns that row too', (await usab({ id: 'ni', name: 'ni', type: 'nav-item', label: 'N', children: [{ id: 'c1', name: 'c1', type: 'checkbox' }] })).length === 0 && (await usab({ id: 'mi', name: 'mi', type: 'menu-row', label: 'M', children: [{ id: 'c2', name: 'c2', type: 'checkbox' }] })).length === 0 && (await usab({ id: 'li', name: 'li', type: 'list-row', title: 'L', children: [{ id: 'c3', name: 'c3', type: 'checkbox' }] })).length === 0); + // A second control elsewhere stops the document's own padding from crediting + // the checkbox (the padded-row step), so only the owner rule can pass it. + const ownedBy = async (owner: SceneNode) => (await evaluateCanvas(canvasWith([owner, { id: 'other', name: 'other', type: 'checkbox', width: 40, height: 40 }], app), { mode: 'fast', categories: ['usability'] })).issues.filter((i) => /24px floor/.test(i.message) && i.nodeId !== 'other'); + check('owner rule: a control directly in a nav-item / menu-row / list-row / property-row owns that row', (await ownedBy({ id: 'ni', name: 'ni', type: 'nav-item', label: 'N', children: [{ id: 'c1', name: 'c1', type: 'checkbox', width: 16, height: 16 }] })).length === 0 && (await ownedBy({ id: 'mi', name: 'mi', type: 'menu-row', label: 'M', children: [{ id: 'c2', name: 'c2', type: 'checkbox', width: 16, height: 16 }] })).length === 0 && (await ownedBy({ id: 'li', name: 'li', type: 'list-row', title: 'L', children: [{ id: 'c3', name: 'c3', type: 'checkbox', width: 16, height: 16 }] })).length === 0 && (await ownedBy({ id: 'pr2', name: 'pr2', type: 'property-row', label: 'P', children: [{ id: 'c4', name: 'c4', type: 'checkbox', width: 16, height: 16 }] })).length === 0); + check('…and a bare 16px checkbox with no owner is flagged (the probe can fail)', (await ownedBy({ id: 'fr', name: 'fr', type: 'frame', children: [{ id: 'c5', name: 'c5', type: 'checkbox', width: 16, height: 16 }] })).length === 1); check('census judges the rendered height: a nav-item at height 16 with minHeight 40 is flagged', (await usab({ id: 'n', name: 'n', type: 'nav-item', label: 'N', height: 16, minHeight: 40 })).length === 1); check('census judges the rendered height: a text-input ignores height', desktopTargets({ id: 'i', name: 'i', type: 'text-input', height: 10 } as SceneNode)[0].h === 40); check('a disabled tabs node disables every tab', desktopTargets({ id: 't', name: 't', type: 'tabs', disabled: true, items: [{ label: 'A' }, { label: 'B' }] } as SceneNode).every((t) => t.disabled)); From 6d97d11727aff44b88cae2c29d10c88cbd71f072 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Fri, 13 Nov 2026 20:13:46 +0100 Subject: [PATCH 4/4] Mix any parseable accent into the fallback tint; fold open items The 12% tint mix needed #RRGGBB, so an rgb() or hsl() accent on a dark palette got the light fallback. Slice B's open items move into the spec: the tablist and text-input coverage gaps become FR-C7's tabs clause and FR-C10, and the mobile 44px gap goes to the VISION backlog. --- VISION.md | 4 +++- docs/specs/PHASE-31-SPEC.md | 18 +++++++++-------- src/variables.ts | 39 ++++++++++++++++++++++++++++++++----- test-desktop-primitives.ts | 9 +++++++++ 4 files changed, 56 insertions(+), 14 deletions(-) diff --git a/VISION.md b/VISION.md index 5fb1ded..e3daeb8 100644 --- a/VISION.md +++ b/VISION.md @@ -555,6 +555,8 @@ The mobile attempt (2026-09-07) built one iOS screen end to end on v2.2.0 and go All seven slices are merged and the acceptance re-run passed. The phase is closed. +- [ ] Follow-up — `link` and `text-input` join the mobile 44px touch census. Phase 31 slice B added both primitives for app screens; on a phone canvas they are not measured today, so a 32px text-input passes silently. + _Full spec-driven breakdown in [`docs/specs/PHASE-30-SPEC.md`](docs/specs/PHASE-30-SPEC.md). Deliberately out of scope: an Android profile, tablet and other types, a tappable flag on frames, a thumb-reach rule, interaction and flows, mobile import, and mobile commerce archetypes (those come next, on the anatomy/realisation split this phase creates)._ ### Phase 31 — The desktop-app surface (v2.5) @@ -563,7 +565,7 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 - [x] Slice A — the type: `desktop-app` with a 1440×900 window profile, a ruleset that switches off the type-scale ratio, the WCAG 2.5.8 spacing exception on the 24px floor (web and desktop-app; mobile keeps its 44px rule) and navigation lists that never read as tables (every type), evaluate and import results an agent can read (repeated findings fold, keeping every fix), type-aware generation with state and control-color tokens, and the baseline canvases committed as fixtures - [x] Slice B — vocabulary: a 24px `button` with an accessible name, `link`, `text-input`, `nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row` and `divider`, plus identity dots that never count as accents (moved here from slice A: it keys on `nav-item`) -- [ ] Slice C — app rules: every click target measured, hand-built targets named, icon-only actions named, one current item per navigation group, a dense type ladder, row rhythm, honest truncation, one primary per region, and the declaration matching the window +- [ ] Slice C — app rules: every click target measured, hand-built targets named, icon-only actions named, one current item per navigation group, a dense type ladder, row rhythm, honest truncation (a tablist whose every label is truncated included), one primary per region, the declaration matching the window, and form coverage counting text-inputs - [ ] Slice D — panes: resolution for any number of types and six desktop-app realisations (workbench, list-detail, editor-inspector, browser, dashboard, settings) under the pattern gate - [ ] 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 - [ ] Slice F — overlay rules: one modal, text-only tooltips, no large tables in modals, overlays inside the viewport, and advisories on stacked toasts and error toasts diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 227d4a3..06bc5ea 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -118,9 +118,10 @@ One profile ships, keyed by id so a second size is one table row later. Values i | **FR-C4** | **Wayfinding.** Rule `desktop-app-current`, warning: a navigation group (see Terms) with more than one `active` `nav-item`, or with none; a `tabs` node with no active item or more than one; more than one `active` row in one list or tree. A sidebar split into sections is one group per pane, so one active item in one section passes. Navigation deeper than depth 1 (two levels) is out of reach by construction (`depth: 0 \| 1`); a `tree-row` group used for navigation deeper than 2 is an info. | A sidebar with two active items warns, one with none warns, a sectioned sidebar with one active item passes. | | **FR-C5** | **A dense type ladder.** Rule `desktop-app-type-ladder`, replacing `type-scale-ratio` on desktop-app. For each adjacent pair of distinct sizes a < b: it passes when a ≤ 16 and b − a ≤ 4; otherwise it passes when 1.1 ≤ b / a ≤ 2.5; otherwise it warns. Pinned typography tokens skip the pair check, as today. Separately: any text below 11 warns; text of five or more words below 12 warns; a node resolving the `body` role below 13 warns. The 2.5 cap is a house value chosen to admit a dense app's 14→32 heading (2.29) while flagging a 13→36 jump (2.77). | 12/13/14 passes; 14→32 passes; 13→36 warns; a 10px label warns. | | **FR-C6** | **Table rows.** Rule `desktop-app-row-rhythm`, applied to detected tables: a header row whose height differs from the body rows by more than 1px warns (Carbon). Body rows that differ from each other by more than 1px are an info, compared within their class (rows holding two stacked text lines, a title and a subtitle, are compared only with each other), because the ±1px threshold is a proposal no source validated. Detailed mode adds column-edge alignment across rows as an info, for the same reason. Fast mode compares authored heights only. | A table whose header is 40 over 32px rows warns; one 40px body row among 32px rows is an info; one cell 3px off is an info in detailed mode only. | -| **FR-C7** | **Honest truncation.** Rule `desktop-app-truncation`: a table header text with `textOverflow: "ellipsis"` warns (column headers are never truncated; PatternFly and EUI, secondary sources); a hand-built text with an ellipsis and no `title` is an info (the full text must be reachable; primitives add `title` themselves); in detailed mode, an ellipsis that leaves fewer than 4 visible characters is an info (Maersk, a secondary source). | A truncating header warns; a truncating `nav-item` label is silent; a 3-character truncation is an info in detailed mode. | +| **FR-C7** | **Honest truncation.** Rule `desktop-app-truncation`: a table header text with `textOverflow: "ellipsis"` warns (column headers are never truncated; PatternFly and EUI, secondary sources); a hand-built text with an ellipsis and no `title` is an info (the full text must be reachable; primitives add `title` themselves); in detailed mode, an ellipsis that leaves fewer than 4 visible characters is an info (Maersk, a secondary source). **Tabs** (added 2026-11-13, slice B as-built): tabs shrink to fit their tablist, so in detailed mode a `tabs` node where every label is truncated warns (nobody can read the navigation), and a tab whose label shows fewer than 4 characters is an info, like any other short truncation. | A truncating header warns; a truncating `nav-item` label is silent; a 3-character truncation is an info in detailed mode. Eight tabs in a 220px tablist warn in detailed mode; three tabs that fit are silent. | | **FR-C8** | **One primary per region.** Rule `desktop-app-primary-count`, info: more than one `button` with `variant: "primary"` in one region, counting a modal's primary `actions` in the modal's region. Info, because "one primary per region" is a convention no source validated as a threshold. | Two primary buttons in one toolbar produce the info; one primary in a toolbar and one in a modal's actions do not; a grid of six cards each with a primary button does not. | | **FR-C9** | **The declaration matches the window.** Rule `desktop-app-artboard`, in the base ruleset like `mobile-artboard`, so it runs on every type: a desktop-app canvas narrower than 1024 warns; an undeclared canvas containing a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) or an overlay primitive warns until a type is declared; an explicit `web` canvas containing a desktop-app primitive gets an info; an explicit `mobile` canvas containing one warns. Overlays alone never trip the web or mobile cases, since pages and phones use them too. | A 900px desktop-app canvas warns; an undeclared canvas with a `nav-item` is NOT READY until `canvas_set_type`; a mobile canvas with a `nav-item` warns, and one with only a `modal` does not. | +| **FR-C10** | **Form coverage counts text-inputs** (added 2026-11-13, slice B as-built). The coverage category's form demand (3+ input controls on a base canvas demand an `error` variant) counts `text-input` as an input control, on every type, alongside the toggle, checkbox, radio and select. Drift's control list (`CONTROL_TYPES`, `src/drift.ts`) is unchanged: the importer never produces a `text-input`, so adding it there would make every drift comparison report a control the page doesn't have. | Three `text-input`s on a base canvas demand an `error` variant; two `text-input`s and a checkbox do too; the same form with an `error` variant is silent; `canvas_check_drift` output is unchanged. | | **FR-D1** | **Resolution for any number of types.** `resolveStructure` and `listStructures` (`src/structures.ts:1834`, `:1863`) stop assuming two types: an anatomy resolves to the realisation for the canvas type; with none, the error names every type that has one and the `realisation` value that forces it. `Structure.surface` accepts `'desktop-app'`; `'any'` keeps meaning every type. | `apply_structure("pricing")` on a desktop-app canvas refuses and names `web`; `apply_structure("feed")` refuses and names `mobile`. | | **FR-D2** | **Desktop-app realisations.** Six, built only from primitives and $tokens, named `-app`: `split-workbench-app` (the `split-workbench` anatomy: header, sidebar of `nav-item`s, content, optional right panel, a pane toggle as an icon-only `button`), `list-detail-app` (new anatomy `list-detail`: navigation, list and detail panes, with a designed "nothing selected" placeholder in the detail pane), `editor-inspector-app` (new anatomy `editor-inspector`: a work area and a 70/30 inspector of `tabs` and `property-row`s), `browser-app` (new anatomy `browser`: a filter bar of `text-input` and `tabs` over an adaptive grid of item cards with a minimum column width), `dashboard-app` and `settings-app`. Panes fill the window and scroll on their own (`overflow: "auto"` on each pane, the root at window height); stress already treats a scrolling pane's overflow as scrolling (`src/stress.ts:259`). A component `data-table-app` (`surface: 'desktop-app'`) is the ladder version of `data-table`: header row height equals body row height and the toolbar height equals the row height. The web `data-table` is unchanged. | See FR-D3. | | **FR-D3** | **The pattern gate covers desktop-app.** `test-patterns.ts` evaluates every desktop-app realisation on a canvas created with `type: "desktop-app"`, fast mode across its five themes, at the web set's `> 95` bar with zero `desktop-app-*` warnings or errors. Once per realisation in the full tier: detailed mode with zero `desktop-app-*` warnings or errors, and a CLEAN full `canvas_stress` run. `data-table-app` and every component scaffold marked `any` are stamped onto a desktop-app canvas and held to the same rule. | The gate fails if any desktop-app realisation scores 95 or below in any theme, raises a desktop-app warning or error in either mode, or stresses FRAGILE. | @@ -220,15 +221,16 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **E10: the breadcrumb's parent is a `link`; the current page stays text.** The component keeps its web-only surface (slice D decides what stamps on desktop-app). - **E11 (verify round 1): the census judges what renders.** A `link` never renders under 24 (min-height), `tabs` take their height from `size` and a `text-input` from `size` and `rows` (all ignore `height`), and `nav-item` / `tree-row` / `menu-row` take `height` but ignore `minHeight` — so the census does exactly the same. A control owns its row (E2) only when it is the row's only target, a direct child, with no link, input or button beside it. The layout walker steps through a primitive's child slot (`data-fs-slot`, the property-row value) so those nodes are placed. Tabs shrink so their labels truncate in a narrow tablist; disabled tabs and disabled link / nav-item / tree-row / menu-row / text-input leave the tab order. Unknown icons on the new primitives warn, and their copy (`placeholder`, `value`, `shortcut`, `error`, `ariaLabel`, `count`) is not counted as un-tokened style. Without an `accent-tint` token the active fill is the accent mixed 12% into the surface, so a dark palette gets a dark tint. An unthemed `text-input` error is `$danger`-coloured. Inline link edges never split a surrogate pair. - **E13 (after verify round 2): a clickable owner is not its own sibling.** Ownership counts the targets among the row's children only, so a sole control directly inside a `nav-item`, `menu-row` or `list-row` owns the row as FR-A4 says (the row itself is clickable and used to count as a second target). Fixed after the second verifier round, proved red on the previous snapshot and green on the fix, not re-verified by an agent. -- **Open (minor): a crowded tablist can truncate every label.** Tabs shrink to fit (E11), and the census measures their height, not their width, so eight tabs in 220px render as unreadable 26px stubs with no finding. A minimum-width rule for tabs belongs with the app rules (slice C). -- **Open (minor): a non-hex accent keeps the light fallback tint.** The 12% mix (E11) needs `#RRGGBB`; an `hsl()` or named accent without an `accent-tint` token still gets `#EFF4FF`. +- **Folded into slice C (2026-11-13): a crowded tablist can truncate every label.** Tabs shrink to fit (E11), and the census measures their height, not their width, so eight tabs in 220px render as unreadable 26px stubs with no finding. Now FR-C7's tabs clause. +- **Fixed after verification (2026-11-13): a non-hex accent kept the light fallback tint.** The 12% mix (E11) needed `#RRGGBB`; it now mixes `#RGB`, `#RRGGBB(AA)`, `rgb()` and `hsl()` accents and surfaces (alpha ignored). A named accent (`royalblue`) without an `accent-tint` token still gets `#EFF4FF`. - **E12: only `property-row` renders children.** The other desktop-app primitives draw their own anatomy and drop children; the `batch_design` docs say so. -- **Open for a later slice: a `link` or `text-input` on a phone has no 44px check.** They are not phone tappables (E3) and not in the FR-C9 primitive set (pages and phones use them), so a 32px text-input on a mobile canvas passes silently. Adding them to the mobile touch census is a mobile-ruleset change the spec does not make. -- **Open for slice C/D: form coverage ignores `text-input`.** The drift inventory's control list (toggle, checkbox, radio, select) is unchanged, so "3+ input controls demand an error state" does not count text-inputs. The spec is silent; decide with the form rules. +- **Out of Phase 31 (2026-11-13): a `link` or `text-input` on a phone has no 44px check.** They are not phone tappables (E3) and not in the FR-C9 primitive set (pages and phones use them), so a 32px text-input on a mobile canvas passes silently. Adding them to the mobile touch census changes Phase 30's mobile ruleset, so it is a follow-up in the VISION backlog under Phase 30. +- **Folded into slice C (2026-11-13): form coverage ignored `text-input`.** The drift inventory's control list (toggle, checkbox, radio, select) is unchanged, so "3+ input controls demand an error state" did not count text-inputs. Now FR-C10, which counts them in the coverage check and leaves drift alone. -**Slice C: the app rules (FR-C1 to FR-C9)** +**Slice C: the app rules (FR-C1 to FR-C10)** - `src/evaluate.ts`: one check per rule id, wired in the rule-dispatch block (`:2355-2388`, where the typography, structure and usability checks pick up their type rules) the way the mobile checks are. -- Row rhythm and truncation reuse the inventory's table detection; column alignment and the 4-character floor use detailed-mode layout (`computeLayout`, as `mobile-safe-area` does at `:2353`). +- Row rhythm and truncation reuse the inventory's table detection; column alignment and the 4-character floor use detailed-mode layout (`computeLayout`, as `mobile-safe-area` does at `:2353`). The tabs clause of FR-C7 reads the layout walker's `truncated` flag per tab label, which needs the tabs' label elements placed (today the walker records only whether any label inside a primitive overflows). +- FR-C10: the `form` entry of `COVERAGE_DEMANDS` (`src/evaluate.ts`) counts `text-input` nodes on top of `inv.counts.controls`; drift's `CONTROL_TYPES` stays as is. **Slice D: panes (FR-D1 to FR-D3)** - `src/structures.ts:1834`, `:1863`: N-type listing and resolution; `covers()` for `desktop-app`. @@ -263,7 +265,7 @@ One profile ships, keyed by id so a second size is one table row later. Values i 3. Slice A: the target census, the padded-row step kept, the spacing exception (detailed) and the fast-mode warning; navigation lists not tables; identity dots not accents. 4. Slice A: output folding and the import report summary; type-aware generation, the `state` token section and `focus-ring`; the baseline fixtures; viewer window buttons. 5. Slice B: `button` `xs` and `ariaLabel`, `link` and inline links, `nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`, `text-input`, `divider`, `title` on `text`, with defaults, stress props, render tests, and the `breadcrumb` rebuild. -6. Slice C: the nine app rules and their fixtures, including the baseline fixtures. +6. Slice C: the nine app rules (FR-C7 including its tabs clause) and FR-C10's form coverage, with their fixtures, including the baseline fixtures. 7. Slice D: N-type resolution, six realisations, `data-table-app`, the pattern gate. 8. Slice E: the overlay layer, the ladder and the six overlay primitives; the overlay states in the docs. 9. Slice F: the overlay rules. diff --git a/src/variables.ts b/src/variables.ts index 6e72383..3b15d2e 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -255,13 +255,42 @@ function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { } } -/** `top` laid over `base` at `alpha`, as #RRGGBB; undefined unless both are #RRGGBB. */ +/** + * An opaque colour as [r, g, b]: #RGB, #RRGGBB(AA), rgb()/rgba() and hsl()/hsla(), + * alpha ignored. Named colours return undefined. (evaluate.ts has its own + * parseColor; it imports this module, so this one can't import it.) + */ +function rgbOf(color: string): [number, number, number] | undefined { + const c = color.trim(); + let m = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(c); + if (m) return [m[1], m[2], m[3]].map((d) => parseInt(d + d, 16)) as [number, number, number]; + m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})(?:[0-9a-f]{2})?$/i.exec(c); + if (m) return [m[1], m[2], m[3]].map((d) => parseInt(d, 16)) as [number, number, number]; + m = /^rgba?\(\s*(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)\s*(?:[,/][^)]*)?\)$/i.exec(c); + if (m) return [m[1], m[2], m[3]].map((v) => Math.min(255, Math.round(+v))) as [number, number, number]; + m = /^hsla?\(\s*(-?\d+(?:\.\d+)?)(?:deg)?[\s,]+(\d+(?:\.\d+)?)%[\s,]+(\d+(?:\.\d+)?)%\s*(?:[,/][^)]*)?\)$/i.exec(c); + if (!m) return undefined; + const h = (((+m[1] % 360) + 360) % 360) / 360; + const sat = Math.min(1, +m[2] / 100); + const l = Math.min(1, +m[3] / 100); + const q = l < 0.5 ? l * (1 + sat) : l + sat - l * sat; + const p = 2 * l - q; + const hue = (t: number) => { + const x = t < 0 ? t + 1 : t > 1 ? t - 1 : t; + if (x < 1 / 6) return p + (q - p) * 6 * x; + if (x < 1 / 2) return q; + if (x < 2 / 3) return p + (q - p) * (2 / 3 - x) * 6; + return p; + }; + return [hue(h + 1 / 3), hue(h), hue(h - 1 / 3)].map((v) => Math.round(v * 255)) as [number, number, number]; +} + +/** `top` laid over `base` at `alpha`, as #RRGGBB; undefined unless both parse (see `rgbOf`). */ function mixHex(top: string, base: string, alpha: number): string | undefined { - const t = /^#([0-9a-f]{6})$/i.exec(top); - const b = /^#([0-9a-f]{6})$/i.exec(base); + const t = rgbOf(top); + const b = rgbOf(base); if (!t || !b) return undefined; - const ch = (hex: string, i: number) => parseInt(hex.slice(i, i + 2), 16); - return '#' + [0, 2, 4].map((i) => Math.round(alpha * ch(t[1], i) + (1 - alpha) * ch(b[1], i)).toString(16).padStart(2, '0')).join('').toUpperCase(); + return '#' + [0, 1, 2].map((i) => Math.round(alpha * t[i] + (1 - alpha) * b[i]).toString(16).padStart(2, '0')).join('').toUpperCase(); } /** A prop as text, for "is it set?" checks. */ diff --git a/test-desktop-primitives.ts b/test-desktop-primitives.ts index 9374938..f7b9fe2 100644 --- a/test-desktop-primitives.ts +++ b/test-desktop-primitives.ts @@ -64,6 +64,15 @@ const html = (n: SceneNode, colors?: Record) => { check('an active nav-item draws fill, bar and weight, with aria-current', /aria-current="page"/.test(nav) && /width: 2px/.test(nav) && /font-weight: 600/.test(nav) && /background-color: #E5ECFD/.test(nav), (nav.match(/background-color: #[0-9A-F]{6}/gi) ?? []).join(' ')); const darkNav = html({ id: 'nd', name: 'nd', type: 'nav-item', label: 'A', active: true }, { accent: '#60A5FA', 'bg-surface': '#111827' }); check('without an accent-tint token the active fill is the accent washed into the surface (dark stays dark)', /background-color: #1A2940/.test(darkNav), (darkNav.match(/background-color: #[0-9A-F]{6}/gi) ?? []).join(' ')); + const fills = (h: string) => (h.match(/background-color: #[0-9A-F]{6}/gi) ?? []).join(' '); + const rgbNav = html({ id: 'nr', name: 'nr', type: 'nav-item', label: 'A', active: true }, { accent: 'rgb(96, 165, 250)', 'bg-surface': '#111827' }); + check('an rgb() accent washes into the surface like its hex twin', /background-color: #1A2940/.test(rgbNav), fills(rgbNav)); + const hslNav = html({ id: 'nh', name: 'nh', type: 'nav-item', label: 'A', active: true }, { accent: 'hsl(213 94% 68%)', 'bg-surface': 'rgb(17 24 39)' }); + check('an hsl() accent on an rgb() surface washes in too (dark stays dark)', /background-color: #1B2940/.test(hslNav), fills(hslNav)); + const shortNav = html({ id: 'ns', name: 'ns', type: 'nav-item', label: 'A', active: true }, { accent: '#06F', 'bg-surface': '#FFF' }); + check('a #RGB accent and surface mix', /background-color: #E0EDFF/.test(shortNav), fills(shortNav)); + const namedNav = html({ id: 'nn', name: 'nn', type: 'nav-item', label: 'A', active: true }, { accent: 'royalblue', 'bg-surface': '#111827' }); + check('a named accent still falls back to the light tint', /background-color: #EFF4FF/.test(namedNav), fills(namedNav)); const rail = html({ id: 'n2', name: 'n2', type: 'nav-item', label: 'Projects', icon: 'folder', collapsed: true }); check('a collapsed nav-item is 32×32 with its label as the accessible name', /width: 32px/.test(rail) && /aria-label="Projects"/.test(rail) && !/>Projects