From 01982daf0c486173cf1066a4730189324c3c1958 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Fri, 13 Nov 2026 20:47:32 +0100 Subject: [PATCH 1/4] Add the desktop-app rules and count text-inputs in form coverage Phase 31 slice C (FR-C1..C10): eight desktop-app-* rule ids for targets, hand-built targets, icon names, wayfinding, the dense type ladder, row rhythm, truncation and primary count, plus text-inputs in the form coverage demand. Spec change S2 widens FR-C2 to bordered text buttons. --- README.md | 12 +- VISION.md | 2 +- docs/GUIDELINES.md | 17 +- docs/specs/PHASE-31-SPEC.md | 13 + src/desktop-app-rules.ts | 500 ++++++++++++++++++++++++++++- src/evaluate.ts | 77 ++++- src/index.ts | 8 +- src/primitives.ts | 12 +- src/project-evaluate.ts | 11 +- src/renderer.ts | 6 +- src/screenshot.ts | 10 +- src/shape-hash.ts | 16 + src/surfaces.ts | 13 +- test-desktop-app-rules-detailed.ts | 99 ++++++ test-desktop-app-rules.ts | 279 ++++++++++++++++ test-desktop-app.ts | 10 +- 16 files changed, 1038 insertions(+), 47 deletions(-) create mode 100644 src/shape-hash.ts create mode 100644 test-desktop-app-rules-detailed.ts create mode 100644 test-desktop-app-rules.ts diff --git a/README.md b/README.md index ee698d7..18bd9a8 100644 --- a/README.md +++ b/README.md @@ -884,7 +884,7 @@ A `FRAGILE` stress run blocks too. Once `canvas_stress` has recorded a verdict f Whenever the `cliche` category runs, the result also carries a **`genre`** field auditing the genre decision: `{ active, source, relaxed, notRelaxed, byPreset? }` — the genre in effect (canonical: a `"dashboard"` stamp reports `"data"`, a `"checkout"` one `"commerce"`), whether it came from the `genre` param or the canvas's provenance stamp, the tells relaxed, `notRelaxed` (`[{ tell, relaxedBy }]`) — tells still flagging that a *different* genre would relax — and `byPreset` (`{ preset, relaxed }`), present when the applied preset relaxed tells on its own (the material preset relaxes accent-hue and pure-black-white whatever the genre). A score pinned by tells listed in `notRelaxed` usually means the wrong genre was declared. -Every result also carries a **`surface`** field: `{ type, device, source, rulesOn, rulesOff, conflicts }` — the canvas type (`"web"`, `"mobile"` or `"desktop-app"`), its profile (a phone or a window; `null` on web), whether the type was `"declared"` (by `canvas_create` or `canvas_set_type`) or is the `"default"` web of an undeclared canvas, and the rule ids the composed type, genre and preset rulesets turned on (`rulesOn`) and off (`rulesOff`). A rule both enabled and disabled stays on: it is listed in `rulesOn` and in `conflicts`. `canvas_autofix` returns the same field. Every finding from a rule carries its id in a **`rule`** field. On a web canvas `rulesOn` is `["desktop-app-artboard", "mobile-artboard"]`, the two base rules; a desktop-app canvas turns `type-scale-ratio` off (see the last rows); a mobile canvas runs the whole mobile ruleset: +Every result also carries a **`surface`** field: `{ type, device, source, rulesOn, rulesOff, conflicts }` — the canvas type (`"web"`, `"mobile"` or `"desktop-app"`), its profile (a phone or a window; `null` on web), whether the type was `"declared"` (by `canvas_create` or `canvas_set_type`) or is the `"default"` web of an undeclared canvas, and the rule ids the composed type, genre and preset rulesets turned on (`rulesOn`) and off (`rulesOff`). A rule both enabled and disabled stays on: it is listed in `rulesOn` and in `conflicts`. `canvas_autofix` returns the same field. Every finding from a rule carries its id in a **`rule`** field. On a web canvas `rulesOn` is `["desktop-app-artboard", "mobile-artboard"]`, the two base rules; a desktop-app canvas runs the desktop-app rules and turns `type-scale-ratio` off (see the `desktop-app-*` rows); a mobile canvas runs the whole mobile ruleset: | Rule | Category | Severity | Fires on | |---|---|---|---| @@ -897,6 +897,14 @@ Every result also carries a **`surface`** field: `{ type, device, source, rulesO | `mobile-artboard` | structure | warning / info | Runs on every type. A mobile canvas 500px or wider warns, and any other size than the device's is an info. An undeclared canvas narrower than 500px warns until `canvas_set_type` declares it; one declared `web` gets an info. | | `desktop-app-artboard` | structure | warning / info | Runs on every type. Warns on a desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for. Also warns on a canvas that holds a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) and was never declared, or is declared `mobile`; one declared `web` gets an info. 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`. | +| `desktop-app-target` | usability | warning / error | Desktop-app only: the 24px floor (the `usability` row under Categories below), under its rule id. Fast mode warns on a target under 24px; detailed mode errors when its 24px circle reaches a neighbour. An unlabelled `link` measures its glyphs (14px wide). | +| `desktop-app-handbuilt-target` | usability | info | Desktop-app only: a frame below 32px holding one icon, an icon plus a label of up to three words, or (bordered and padded) one such label alone, the shape an imported text button takes. Rebuild it as a `button` or `link` if it is clickable. | +| `desktop-app-icon-label` | usability | warning | Desktop-app only: an icon-only `button` with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`. | +| `desktop-app-current` | usability | warning / info | Desktop-app only: in one pane (a frame with `overflow: "auto"`, or the root), two active `nav-item`s at one depth, or two or more with none active; a `tabs` node with no active tab or more than one; two active `tree-row`s under one parent. A tree with a current row that nests past two levels is an info. | +| `desktop-app-type-ladder` | typography | warning | Desktop-app only, replacing `type-scale-ratio`: adjacent sizes a < b step by at most 4px while a ≤ 16, else by a ratio of 1.1 to 2.5 (pinned token pairs skip). Also text below 11px, prose of five or more words below 12px, and a `$body` text below 13px. | +| `desktop-app-row-rhythm` | consistency | warning / info | Desktop-app only, on detected tables: a header row more than 1px off the one-line body rows warns; a body row off its siblings is an info (title-over-subtitle rows compared only with each other); detailed mode adds a cell off its column's left edge as an info. Fast mode reads authored heights only. | +| `desktop-app-truncation` | usability | warning / info | Desktop-app only: a truncating column header warns; a hand-built ellipsis with no `title` is an info. Detailed mode: a `tabs` node whose every label is cut warns, and an ellipsis leaving fewer than four characters is an info. | +| `desktop-app-primary-count` | structure | info | Desktop-app only: two or more primary `button`s (`variant: "primary"` or no variant) in one pane. Primaries inside three or more same-shaped sibling frames, such as a card grid, don't count. | 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. @@ -919,7 +927,7 @@ Whenever the `coverage` category runs on a **base** canvas, the result also carr | `structure` | 15 | Tree depth, naming coverage, design-token usage %, component reuse, unknown icon names (an icon node, or a mobile primitive's icon prop — `button.icon`, `leading.icon`, nav-bar `trailing[].icon`, `tab-bar` `items[].icon` (required) and `fab.icon` — that resolves in neither set renders an empty slot: a directive-blocking warning, −10 structure score each; autofixable for icon nodes and `button.icon` when one spelling resolves) `mobile-artboard` adds −10 per warning, on every type. | | `consistency` | 20 | Frames missing `layout`, sibling overlap (detailed mode; positioned siblings that content scrolls under — absolute, sticky, pinned chrome, a sheet, a bar pinned to the bottom — are exempt, while a bar pinned to the top still counts) — plus score-neutral advisories: **token detachment** (a literal `fill`/`stroke`/`color`/`cornerRadius` that exactly equals a token's value flags with a mechanical `$ref` autofix; ambiguous matches list candidates and never guess) and **ad-hoc motion** (3+ distinct duration/easing combos with no motion tokens declared) | | `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 }`. | +| `coverage` | 10 | State coverage on **base** canvases with data-bearing content: a detected table demands designed `empty` + `loading` variants, a form (3+ input controls, `text-input` included) demands `error` — each missing state is a directive-blocking warning whose suggestion names the `canvas_add_variant` + scaffold path. Variant canvases and non-data screens get no findings. Table detection needs three matching horizontal rows to read as data (two stacked rows are treated as a layout, e.g. a topbar over a greeting); an import-named `Table` frame keeps the looser two-row shape. A list whose every row leads with an icon, a dot or a small image (a sidebar of projects) is navigation and never reads as a table, on every type. On a **`loading`** variant itself, a warning fires per data surface (a detected table, or a frame with 2+ large tabular/numeric texts) that still shows live values while a sibling region is skeletoned — "Loading state is half-designed" — naming the region and suggesting the matching skeleton scaffold. The result's `coverage` field reports `{ dataBearing, states, missing }`. | | `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/VISION.md b/VISION.md index e3daeb8..e78cf80 100644 --- a/VISION.md +++ b/VISION.md @@ -565,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 (a tablist whose every label is truncated included), one primary per region, the declaration matching the window, and form coverage counting text-inputs +- [x] Slice 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/GUIDELINES.md b/docs/GUIDELINES.md index c56dc60..151d90a 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -46,7 +46,7 @@ A canvas declares what medium it is on, separately from its genre (what it is fo - **`type: "web"` is the default.** An undeclared canvas is judged as web and its evaluate result says `source: "default"`. - **`canvas_set_type` re-declares an existing canvas** (`"web"`, `"mobile"`, `"desktop-app"`, or `null` to clear). A desktop-app canvas narrower than its window's 1024px minimum gets a `hint` naming `U("document", { width: 1440, height: 900 })`. It writes the declaration only, so it never moves the `versionHash`. It never resizes the artboard and never writes or removes `safeArea`, because either would reflow what you placed; clearing the type leaves the root as it is. When a mobile result has a `hint`, follow it: it names `U("document", { safeArea: { top: 47, bottom: 34 } })` when the root doesn't reserve both insets, and `U("document", { width: 390, height: 844 })` when the root is another size. Both ops change the render, so re-check the layout after them. State variants keep the type they were created with, so re-declaring a base does not reach them: the result's `variantsOutOfSync` lists each variant whose type now differs (`{ state, canvasId, type }`); declare those too. - **`generate_design_system` on a mobile canvas** pivots the type scale on the device body size: 17px for every personality except `data-dense`, which uses 16px. **On a desktop-app canvas** it pivots on 14px (13px for `data-dense`), the size dense apps read at. An explicit `baseSize` wins. The result reports the generated pivot as `baseSize` and `baseSizeSource` (`"mobile"`, `"desktop-app"`, `"explicit"`, or `"personality"` on web). A `$body` inherited from a workspace or project design system is preserved by default and listed in `designSystemConflicts`; pass `preserveInherited: false` to take the mobile body. -- **Every evaluate result carries a `surface` report**: `{ type, device, source, rulesOn, rulesOff, conflicts }`. Each axis value (type, genre, preset) contributes a ruleset, and the active rules are their union. `rulesOn` and `rulesOff` name the rule ids the rulesets turned on and off. A rule both enabled and disabled stays on: it is listed in `rulesOn` and in `conflicts`, so composing declarations can never switch a guardrail off. On a web canvas `rulesOn` is `["desktop-app-artboard", "mobile-artboard"]` (the two base rules, on for every type); on a mobile canvas it adds every rule in [the mobile ruleset](#the-mobile-ruleset); on a desktop-app canvas `rulesOff` lists `type-scale-ratio`, the one rule a type turns off today (see [the desktop-app ruleset](#the-desktop-app-ruleset)). +- **Every evaluate result carries a `surface` report**: `{ type, device, source, rulesOn, rulesOff, conflicts }`. Each axis value (type, genre, preset) contributes a ruleset, and the active rules are their union. `rulesOn` and `rulesOff` name the rule ids the rulesets turned on and off. A rule both enabled and disabled stays on: it is listed in `rulesOn` and in `conflicts`, so composing declarations can never switch a guardrail off. On a web canvas `rulesOn` is `["desktop-app-artboard", "mobile-artboard"]` (the two base rules, on for every type); on a mobile canvas it adds every rule in [the mobile ruleset](#the-mobile-ruleset); on a desktop-app canvas it adds every rule in [the desktop-app ruleset](#the-desktop-app-ruleset), and `rulesOff` lists `type-scale-ratio`, the one rule a type turns off today. - **The viewer shows the declaration to the human.** Gallery cards take the artboard's proportions, between a phone held upright (390:844) and 2:1 (a longer page shows its top), so a phone screen is a portrait card. A canvas declared `mobile` opens at 1:1 in a device frame, without the breakpoint, Compare and Fit buttons, and with a **Safe area** toggle that shades the top and bottom insets: each side is the root's `safeArea` when it sets one, else the device's (47 and 34 on `iphone-390`), so a canvas made mobile with `canvas_set_type` shows the bands its content must clear. The overlay is presentation only and never reaches a screenshot or the `versionHash`. A canvas declared `desktop-app` opens at its window size with breakpoint buttons for the narrower window widths of its profile (1024 and 1280 under a 1440 artboard, plus the artboard's own width), and Compare shows them side by side. An undeclared 390px canvas opens as a web page with breakpoint buttons, so a phone screen that was never declared looks wrong to the reviewer as well as to `mobile-artboard`; `canvas_set_type({ canvasId, type: "mobile" })` fixes both, and the open page switches to the device frame on its own. ## The mobile ruleset @@ -75,12 +75,23 @@ 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, 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. +A `desktop-app` canvas is judged as an application, not a page. Its vocabulary is in [Desktop-app vocabulary](#desktop-app-vocabulary); layouts, overlays and element states come in later slices of Phase 31. Each finding from these rules names its rule in a `rule` field, and the `surface` report lists them in `rulesOn`. Errors and warnings block the directive; infos never do. Fast mode is the loop; before presenting, also run `canvas_evaluate({ canvasId, mode: "detailed" })`, which measures rendered rows, column edges and truncation. None of these rules has a mechanical fix, so `canvas_autofix` proposes none. - **`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; 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. +- **`desktop-app-target`** (usability). [The 24px floor](#the-24px-floor-web-and-desktop-app) under its rule id: a target below 24px **warns** in fast mode, and is an **error** in detailed mode when its 24px circle reaches a neighbour. Web runs the same check without the id. A `link` with no label hugs its glyphs, so it is measured at 14px wide (30 with `external`): give it a label, or keep its neighbours out of its circle. +- **`desktop-app-handbuilt-target`** (usability, info). A frame below 32px in either dimension that holds one icon, an icon plus a label of three words or fewer, or, when it has a border (`stroke`) and padding, one such label alone (the shape an imported text button takes). It never blocks, because a frame can't say it is decorative. If it is clickable, rebuild it as a `button` (`xs` or `sm`; icon-only with `ariaLabel`) or a `link`. Fast mode estimates a missing height from the icon or the label's line box plus padding; detailed mode measures the render. A frame inside a `property-row` is never hand-built. +- **`desktop-app-icon-label`** (usability, **warning**). An icon-only `button` (no `label`, an `icon`) with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`: an action with no name for a screen reader or a tooltip. +- **`desktop-app-current`** (usability). The current location must be unambiguous. + - Navigation: all `nav-item`s in one pane (a frame with `overflow: "auto"`, or the root) are one group, whatever section frames they sit in. Two active items at the same depth **warn**; a group of two or more with none active **warns**. An active parent (depth 0) over its active child (depth 1) passes, and a lone item in another pane is not a group. + - A `tabs` node with no active tab, or more than one, **warns**. + - `tree-row`s under one parent are one tree: two active rows **warn**. A tree with a current row that nests past two levels (depth 2 or more) is an **info**: as navigation, more than two levels is hard to keep a place in; a file tree may ignore it. +- **`desktop-app-type-ladder`** (typography, **warning**), replacing `type-scale-ratio`. For each pair of adjacent distinct sizes a < b: it passes when a ≤ 16 and b − a ≤ 4, else when b / a is between 1.1 and 2.5. So 12 / 13 / 14 and 14 → 32 pass and 13 → 36 warns. A pair of pinned typography token sizes skips the check. Separately: any text below 11px, prose of five or more words below 12px, and a text whose `fontSize` is `$body` resolving below 13px each warn. +- **`desktop-app-row-rhythm`** (consistency), on detected tables. A header row (its content is text) more than 1px taller or shorter than the one-line body rows **warns**, as Carbon sets them equal. A body row more than 1px off its siblings is an **info**; rows with a title over a subtitle are compared only with each other. Detailed mode adds a cell whose left edge is more than 1px off its column as an **info**. Fast mode reads authored `height`s only, so rows sized by padding are judged in detailed mode. +- **`desktop-app-truncation`** (usability). A column header text with `textOverflow: "ellipsis"` **warns**: a header is never cut. A hand-built text with an ellipsis and no `title` is an **info**, since the full text must be reachable (primitives add their own `title`). Detailed mode adds: a `tabs` node whose every label is cut **warns** (tabs shrink to fit their tablist, so too many tabs in too little width leaves nothing readable), and an ellipsis that leaves fewer than four visible characters, on a text or a primitive's label, is an **info**. +- **`desktop-app-primary-count`** (structure, info). Two or more primary `button`s in one pane. A button with no `variant` renders as primary and counts; a disabled one doesn't. Primaries inside three or more same-shaped sibling frames (a grid of cards) are each card's own and don't count. 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. @@ -386,7 +397,7 @@ The happy path of one static frame with ideal data is half a design. Real UX liv | `loading` | `skeleton-table` / `skeleton-card` / `skeleton-stat-card` | Real header + `skeleton` blocks matching the loaded geometry, so content lands without layout shift. Skeletons pulse only in the live viewer — screenshots stay static | | `error` | — | The form's validation-failure treatment: field messages + a summary. Design it; there's no generic scaffold because error copy is the design | -**The evaluator demands them.** The `coverage` category warns — directive-blocking — when a base canvas carries data-bearing content with no designed states: a detected table demands `empty` + `loading`; a form (3+ input controls) demands `error`. (Table detection requires three matching horizontal rows — two stacked rows are a layout, not data — so the rare header-plus-one-row table goes undetected; name the frame `Table` to claim the shape explicitly. A list whose every row leads with an icon, a dot or a small image is navigation and never detects.) Variant canvases and non-data screens are silent. The result's `coverage: { dataBearing, states, missing }` tells you where you stand, and `canvas_list` shows the designed states per screen. +**The evaluator demands them.** The `coverage` category warns — directive-blocking — when a base canvas carries data-bearing content with no designed states: a detected table demands `empty` + `loading`; a form (3+ input controls: toggles, checkboxes, radios, selects and `text-input`s outside tables) demands `error`. (Table detection requires three matching horizontal rows — two stacked rows are a layout, not data — so the rare header-plus-one-row table goes undetected; name the frame `Table` to claim the shape explicitly. A list whose every row leads with an icon, a dot or a small image is navigation and never detects.) Variant canvases and non-data screens are silent. The result's `coverage: { dataBearing, states, missing }` tells you where you stand, and `canvas_list` shows the designed states per screen. **Then stress it.** `canvas_stress` re-renders the canvas under hostile-but-realistic content — `long-text` (×2.2 + an unbroken German compound), `i18n` (×1.4), `big-numbers` (`9` → `999+`, `$1.5M` → `$1,520,847.33`), `empty`, `many` (rows ×3) — and reports what broke, by node id: `clip` (info when a designed ellipsis is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; a sheet's own vertical overflow scrolls and is never a clip; warning otherwise), `overflow-x`, `layout-shift` (an untouched node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent, like a full-height sidebar next to a growing table, are all exempt). Only *new* breakage counts. Fix findings with the [width strategies](#width-strategies) above — fluid widths, `minWidth` or `minHeight` floors, wrapping — or give a must-stay-single-line label `textOverflow: "ellipsis"` (the designed-truncation property: the clip downgrades to info because truncating is the design) — and re-run until `CLEAN`. A data screen goes to the user with its states designed and a `CLEAN` stress verdict, the same way it goes with a >95 score. `canvas_evaluate` holds you to it: once stress has recorded a verdict, the evaluate result carries a `stress` field (`{ verdict, warnings, type, current }` — `current` is false after an edit or a type change since the run), and a `FRAGILE` verdict keeps the directive `NOT READY` until a full `CLEAN` run (all five perturbations) replaces it — a subset run can record `FRAGILE` but never clear it. The verdict lives in server memory, so a restart forgets it. diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 06bc5ea..fe86895 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -232,6 +232,19 @@ One profile ships, keyed by id so a second size is one table row later. Values i - 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 C — as built (recorded 2026-11-13; read this before slice D).** +- **Spec change S2 (FR-C2, approved by Victor).** The baseline detail fixture holds no `icon` nodes: its toolbar (Mobile, Tablet, Desktop, Compare, Fit, JSON, Comment, Archive, Delete) imported as bordered frames holding one text label each, so FR-C2 as written could not meet its own acceptance. FR-C2 now also matches a frame with a drawn `stroke` (not `none` or `transparent`, width not 0) and padding that holds exactly one label of three words or fewer and nothing else. Fast mode estimates a missing height from the icon or the label's line box (its font size, default 16, times its numeric line-height, default 1.2) plus vertical padding; an icon-only frame's width the same way; a labelled frame's width stays unknown. Detailed mode measures the render. Measured: the detail fixture reports all nine toolbar buttons, plus one bordered "Excellent" badge, an accepted info. +- **F1: FR-C1 is FR-A4's check under a rule id.** On desktop-app every finding of the 24px floor carries `rule: "desktop-app-target"`; web runs the same check without one. The acceptance's packed case needs an undersized link, and a labelled `link` renders at least 24 both ways, so the test packs two icon-only links. The census used to treat an unlabelled link's width as unknown; it now measures its glyphs (14, plus 16 with `external`), on web too, so an icon-only link is measured on every type (`linkGlyphWidth`, `src/primitives.ts`). +- **F2: FR-C4's groups.** A pane is a frame with `overflow: "auto"` or the root (`modal` and `drawer` join in slice E). A navigation group is every `nav-item` in one pane, depth 0 and 1 together: two active items at the same depth warn, so an active parent over its active child passes; "none active" warns only for a group of two or more, so a lone item in another pane (a footer Settings link) is not a group. A tree is the `tree-row`s under one parent. "Used for navigation" in the deep-tree info is read as "marks a current row": a tree with an active row nesting to depth 2 or more is the info; a file tree with no current row is silent. +- **F3: FR-C5's floors** give each text at most one finding, the first that applies (below 11, then `$body` below 13, then prose below 12), as `mobile-type-floor` does. The ladder reads the numeric `fontSize` of every text in the instance-expanded tree; `$body` means the raw `fontSize` is the string `"$body"`. +- **F4: FR-C6's rows.** The rows are the ones `detectTable` counted. The first row is the header when its content is text (icons allowed, at least two texts); it is compared with the most frequent height of the one-line body rows. A row is two-line when a non-horizontal frame in it stacks two or more texts. One info per class per table names the odd rows. Column alignment compares the left edges of cells across the rows with the most common cell count and reports the first column off, one info per table. Detailed mode reads rendered heights for header and body rows alike. +- **F5: FR-C7's short truncation** estimates the visible characters as `floor(chars × clientWidth / scrollWidth) − 1` (the ellipsis takes about one). It covers text nodes and every primitive's labels: the layout walker now records `labels` (`chars`, `scrollWidth`, `clientWidth` per own label) on every tablist and on any primitive with a cut label, a new `LayoutRect` field that `snapshot_layout` documents. +- **F6: FR-C8's primaries.** A `button` with no `variant` renders as primary, so it counts; a disabled one does not. The repeat exemption uses the shape hash without node names (`shapeHash(node, 3, { names: false })`, moved to `src/shape-hash.ts`), because a card grid's copies are usually renamed per item; with names, six distinct pricing cards did not read as a repeat. The modal's primary waits for slice E. +- **F7: FR-C10** counts `text-input`s outside detected tables, as the inventory counts controls. +- **F8: the expanded render.** On desktop-app, detailed mode now renders the instance-expanded tree at depth 25 (as mobile does), so the rects every detailed check reads on a desktop-app canvas, the consistency overlap check included, carry the expanded ids. +- **F9: categories.** `desktop-app-target`, `-handbuilt-target`, `-icon-label`, `-current` and `-truncation` report under usability, `-type-ladder` under typography, `-row-rhythm` under consistency, `-primary-count` under structure; each warning costs 10 in its category, infos nothing. +- FR-C9 had nothing left for this slice: its overlay clause lands with the overlay primitives (slice E). + **Slice D: panes (FR-D1 to FR-D3)** - `src/structures.ts:1834`, `:1863`: N-type listing and resolution; `covers()` for `desktop-app`. - Six realisations, `data-table-app`, and `test-patterns.ts`'s desktop-app set. diff --git a/src/desktop-app-rules.ts b/src/desktop-app-rules.ts index f72d84f..612647b 100644 --- a/src/desktop-app-rules.ts +++ b/src/desktop-app-rules.ts @@ -2,9 +2,12 @@ // the rule id it honours (see DESKTOP_APP_RULES in surfaces.ts). import type { EvaluationIssue } from './evaluate.js'; +import type { LayoutRect } from './screenshot.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'; +import { CLICKABLE_PRIMITIVES, DESKTOP_APP_PRIMITIVES, tabsItems } from './primitives.js'; +import { fontPx, paddingSides, proseWords } from './mobile-rules.js'; +import { shapeHash } from './shape-hash.js'; +import { windowProfile, DEFAULT_WINDOW, WINDOW_PROFILES, type SurfaceDeclaration, type WindowProfile } from './surfaces.js'; /** `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 @@ -62,3 +65,496 @@ function checkAppPrimitivesDeclared(root: SceneNode, surface: SurfaceDeclaration suggestion: 'canvas_set_type({ type: "desktop-app" }) if this is a tool you work in.', }]; } + +// ── Phase 31 slice C — the app rules ─────────────────────────────────────── +// Each reads the resolved tree with instances expanded (the caller maps +// findings back to instances). Fast mode reads the tree; detailed mode adds +// the rendered rects of that same tree. + +export interface DesktopContext { + /** The resolved tree, instances expanded. */ + root: SceneNode; + profile: WindowProfile; + /** Rendered rects of `root` (detailed mode), by node id. */ + rects?: Map; +} + +const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const hasText = (v: unknown): boolean => (typeof v === 'string' && v.trim() !== '') || isNum(v); +const textOf = (n: SceneNode): string | undefined => + n.type === 'text' && typeof n.content === 'string' && n.content.trim() ? n.content : undefined; +const quote = (s: string) => `"${s.length > 40 ? `${s.slice(0, 37)}…` : s}"`; +const nameOf = (n: SceneNode) => n.name ?? n.id; + +function issue(category: string, rule: string, severity: EvaluationIssue['severity'], node: SceneNode, message: string, suggestion?: string): EvaluationIssue { + return { category, rule, severity, nodeId: node.id, nodeName: node.name, message, ...(suggestion ? { suggestion } : {}) }; +} + +function parents(root: SceneNode): Map { + const out = new Map([[root, null]]); + (function walk(n: SceneNode) { for (const c of n.children ?? []) { out.set(c, n); walk(c); } })(root); + return out; +} + +/** A pane: a frame that scrolls on its own (overflow "auto"), or the root. + * (`modal` and `drawer` join with the overlay primitives, slice E.) */ +function paneOf(n: SceneNode, parentOf: Map): SceneNode { + let cur = parentOf.get(n) ?? null; + let last = n; + while (cur) { + if (cur.type === 'frame' && cur.overflow === 'auto') return cur; + last = cur; + cur = parentOf.get(cur) ?? null; + } + return last; +} + +// ── desktop-app-handbuilt-target (FR-C2) ─────────────────────────────────── + +/** Below this, a frame shaped like a click target is named (the dense + * desktop default control height). */ +const HANDBUILT_BELOW = 32; +const LABEL_WORDS = 3; +/** What the browser draws for text with no font-size / line-height. */ +const DEFAULT_FONT_PX = 16; +const DEFAULT_LINE = 1.2; + +/** A stroke that draws: a colour other than none / transparent, width not 0. */ +const drawsStroke = (n: SceneNode): boolean => + typeof n.stroke === 'string' && n.stroke.trim() !== '' && !/^(none|transparent)$/i.test(n.stroke.trim()) && n.strokeWidth !== 0; + +/** A text's line box in px: its size times its line-height (a number is a + * multiplier, as the renderer emits it). */ +function lineBox(t: SceneNode): number { + const size = fontPx(t.fontSize) ?? DEFAULT_FONT_PX; + return size * (isNum(t.lineHeight) && t.lineHeight > 0 && t.lineHeight < 4 ? t.lineHeight : DEFAULT_LINE); +} + +/** Frames shaped like a click target below 32px in either dimension: one + * icon, one icon plus a label of three words or fewer, or (spec change S2) a + * bordered, padded frame holding one such label and nothing else, the shape + * an imported text button takes. Info only, as on mobile: a frame cannot say + * it is decorative. A frame inside a clickable primitive (a property-row's + * value) is never hand-built. Detailed mode measures the rendered box; fast + * mode reads an authored size, else estimates the height from the icon or + * the label's line box plus vertical padding (an icon-only frame's width the + * same way; a labelled frame's width is unknown). */ +export function checkHandbuiltTargetsApp(ctx: DesktopContext): EvaluationIssue[] { + const issues: EvaluationIssue[] = []; + const shape = (n: SceneNode): { icon?: SceneNode; label?: SceneNode } | null => { + const icons: SceneNode[] = []; + const texts: SceneNode[] = []; + let other = false; + // Stops as soon as the frame can no longer be click-shaped. + (function walk(x: SceneNode) { + for (const c of x.children ?? []) { + if (other || icons.length > 1 || texts.length > 1) return; + if (c.type === 'icon') icons.push(c); + else if (textOf(c) !== undefined) texts.push(c); + else if (c.type !== 'frame' || c.layout === 'grid') other = true; + walk(c); + } + })(n); + if (other || icons.length > 1 || texts.length > 1) return null; + if (texts.length === 1 && proseWords(texts[0].content as string) > LABEL_WORDS) return null; + if (icons.length === 0) { + const pad = paddingSides(n, ctx.profile.width); + const padded = pad.top + pad.right + pad.bottom + pad.left > 0; + if (texts.length !== 1 || !drawsStroke(n) || !padded) return null; + } + return { icon: icons[0], label: texts[0] }; + }; + const dim = (n: SceneNode, axis: 'width' | 'height', s: { icon?: SceneNode; label?: SceneNode }): number | undefined => { + const rect = ctx.rects?.get(n.id); + if (rect) return axis === 'width' ? rect.width : rect.height; + const v = n[axis]; + if (isNum(v)) return v; + if (v !== undefined || (axis === 'width' && s.label)) return undefined; + const pad = paddingSides(n, ctx.profile.width); + const icon = s.icon ? (isNum(s.icon.iconSize) ? s.icon.iconSize : 24) : 0; + const content = Math.max(icon, s.label ? lineBox(s.label) : 0); + return Math.round(content + (axis === 'width' ? pad.left + pad.right : pad.top + pad.bottom)); + }; + (function walk(n: SceneNode) { + if (CLICKABLE_PRIMITIVES.has(n.type) || n.type === 'property-row') return; + if (n.type === 'frame' && n !== ctx.root) { + const s = shape(n); + if (s) { + const w = dim(n, 'width', s); + const h = dim(n, 'height', s); + if ((w !== undefined && w < HANDBUILT_BELOW) || (h !== undefined && h < HANDBUILT_BELOW)) { + const label = s.label ? String(s.label.content).trim() : undefined; + const use = !s.icon + ? `a \`button\` (label "${label}", size "xs" or "sm") or a \`link\`` + : label + ? `a \`link\` (label "${label}", icon "${s.icon.icon}") or a \`button\` with size "xs" or "sm"` + : `an icon-only \`button\` (icon "${s.icon.icon}", size "xs" or "sm", with an ariaLabel)`; + issues.push(issue('usability', 'desktop-app-handbuilt-target', 'info', n, + `"${nameOf(n)}" looks like a hand-built click target (${w ?? '?'}×${h ?? '?'}px). If it is clickable, the target rules cannot measure a frame, and it is not keyboard reachable.`, + `If it is clickable, rebuild it as ${use}. If it is decorative, ignore this.`)); + } + return; // the outermost click-shaped frame is the target + } + } + n.children?.forEach(walk); + })(ctx.root); + return issues; +} + +// ── desktop-app-icon-label (FR-C3) ───────────────────────────────────────── + +/** An icon-only button (blank label, an icon) with no ariaLabel, or a + * collapsed nav-item with a blank label: an action with no name. */ +export function checkIconLabels(ctx: DesktopContext): EvaluationIssue[] { + const issues: EvaluationIssue[] = []; + (function walk(n: SceneNode) { + if (n.type === 'button' && !hasText(n.label) && hasText(n.icon) && !hasText(n.ariaLabel)) { + issues.push(issue('usability', 'desktop-app-icon-label', 'warning', n, + `Icon-only button "${nameOf(n)}" (icon "${n.icon}") has no name — a screen reader announces nothing, and a hover shows no tooltip.`, + `Give it an ariaLabel naming the action: U("${n.id}", { ariaLabel: "…" }). It renders as aria-label and title, never as visible text.`)); + } + if (n.type === 'nav-item' && n.collapsed === true && !hasText(n.label)) { + issues.push(issue('usability', 'desktop-app-icon-label', 'warning', n, + `Collapsed nav-item "${nameOf(n)}" has no label — in the rail form the label is its only name (aria-label and title).`, + `Give it the destination's name: U("${n.id}", { label: "…" }). The rail hides it visually.`)); + } + n.children?.forEach(walk); + })(ctx.root); + return issues; +} + +// ── desktop-app-current (FR-C4) ──────────────────────────────────────────── + +/** Wayfinding: within one pane, the nav-items are one navigation group + * (depth 0 and 1 together, wherever their section frames sit): two active + * items at one depth warn, and a group of two or more items with none active + * warns. A tabs node with no active tab or more than one warns. Tree-rows + * under one parent are one tree: more than one active row warns, and a tree + * with a current row that nests past two levels (depth 2+) is an info. */ +export function checkCurrent(ctx: DesktopContext): EvaluationIssue[] { + const issues: EvaluationIssue[] = []; + const rule = 'desktop-app-current'; + const parentOf = parents(ctx.root); + const groups = new Map(); + const trees = new Map(); + for (const n of parentOf.keys()) { + if (n.type === 'nav-item') { + const pane = paneOf(n, parentOf); + groups.set(pane, [...(groups.get(pane) ?? []), n]); + } else if (n.type === 'tree-row') { + const parent = parentOf.get(n) ?? ctx.root; + trees.set(parent, [...(trees.get(parent) ?? []), n]); + } else if (n.type === 'tabs') { + const items = tabsItems(n); + const active = items.filter((it) => it.active === true).length; + if (items.length > 0 && active !== 1) { + issues.push(issue('usability', rule, 'warning', n, + active === 0 + ? `Tabs "${nameOf(n)}" mark no tab active — the user cannot tell which view they are on.` + : `Tabs "${nameOf(n)}" mark ${active} tabs active — exactly one tab is the current view.`, + 'Set active: true on exactly one item.')); + } + } + } + for (const [pane, items] of groups) { + const depthOf = (n: SceneNode) => (n.depth === 1 ? 1 : 0); + const active = items.filter((n) => n.active === true); + const doubled = [0, 1].map((d) => active.filter((n) => depthOf(n) === d)).find((a) => a.length > 1); + if (doubled) { + issues.push(issue('usability', rule, 'warning', doubled[1], + `${doubled.length} nav-items in ${pane === ctx.root ? 'the screen' : `pane "${nameOf(pane)}"`} are active at depth ${depthOf(doubled[0])} (${doubled.map((n) => `"${n.label ?? nameOf(n)}"`).join(', ')}) — the current location is ambiguous.`, + 'Keep active: true on the one item for the current page (a parent at depth 0 may stay active over its active child).')); + } else if (items.length >= 2 && active.length === 0) { + issues.push(issue('usability', rule, 'warning', items[0], + `None of the ${items.length} nav-items in ${pane === ctx.root ? 'the screen' : `pane "${nameOf(pane)}"`} is active — the user cannot see where they are.`, + 'Set active: true on the nav-item for the current page.')); + } + } + for (const rows of trees.values()) { + const active = rows.filter((n) => n.active === true); + if (active.length > 1) { + issues.push(issue('usability', rule, 'warning', active[1], + `${active.length} rows of one tree are active (${active.map((n) => `"${n.label ?? nameOf(n)}"`).join(', ')}) — one row is the current selection.`, + 'Keep active: true on one row.')); + } + const deepest = Math.max(...rows.map((n) => (isNum(n.depth) ? Math.floor(n.depth) : 0))); + if (active.length > 0 && deepest >= 2) { + issues.push(issue('usability', rule, 'info', active[0], + `This tree marks a current row and nests ${deepest + 1} levels deep — as navigation, more than two levels is hard to keep a place in (Microsoft NavigationView, NN/g).`, + 'If it is navigation, flatten it to two levels; a file or outline tree can nest deeper and may ignore this.')); + } + } + return issues; +} + +// ── desktop-app-type-ladder (FR-C5) ──────────────────────────────────────── + +/** Adjacent sizes a < b step by at most 4px while a ≤ 16, else by a ratio of + * 1.1 to 2.5 (a house cap: 14→32 passes, 13→36 does not). */ +const LADDER_SMALL = 16; +const LADDER_STEP = 4; +const LADDER_RATIO = { min: 1.1, max: 2.5 }; +const PROSE_WORDS = 5; + +/** The dense type ladder that replaces type-scale-ratio on desktop-app, plus + * three floors: any text below the smallest size, prose (five words or + * more) below the prose floor, and the body role below the dense body. + * `rawById` holds the unresolved nodes, so a `$body` reference is visible; + * `pinned` holds the typography token sizes (a pinned pair is not judged). */ +export function checkTypeLadder(ctx: DesktopContext, rawById: Map, pinned: Set): EvaluationIssue[] { + const issues: EvaluationIssue[] = []; + const rule = 'desktop-app-type-ladder'; + const { smallestText, proseFloor, bodyDense } = ctx.profile; + const texts: SceneNode[] = []; + (function walk(n: SceneNode) { if (textOf(n) !== undefined) texts.push(n); n.children?.forEach(walk); })(ctx.root); + const sizes = [...new Set(texts.map((n) => n.fontSize).filter(isNum))].sort((a, b) => a - b); + for (let i = 0; i < sizes.length - 1; i++) { + const [a, b] = [sizes[i], sizes[i + 1]]; + if (pinned.has(a) && pinned.has(b)) continue; + if (a <= LADDER_SMALL && b - a <= LADDER_STEP) continue; + const ratio = b / a; + if (ratio >= LADDER_RATIO.min && ratio <= LADDER_RATIO.max) continue; + const at = texts.find((n) => n.fontSize === b)!; + issues.push(issue('typography', rule, 'warning', at, + `Font sizes ${a}px → ${b}px step by ${ratio.toFixed(2)} — a dense app ladder steps by at most ${LADDER_STEP}px up to ${LADDER_SMALL}px, else by ${LADDER_RATIO.min}–${LADDER_RATIO.max}.`, + ratio > LADDER_RATIO.max + ? `Add an intermediate size between ${a}px and ${b}px, or bring ${b}px down — or declare the sizes as typography tokens to pin them.` + : `Merge ${a}px and ${b}px into one size, or separate them further — or declare the sizes as typography tokens to pin them.`)); + } + for (const n of texts) { + const size = fontPx(n.fontSize); + if (size === undefined) continue; + const content = textOf(n)!; + if (size < smallestText) { + issues.push(issue('typography', rule, 'warning', n, + `${quote(content)} is ${size}px — below the ${smallestText}px smallest text in a desktop app.`, `Raise it to at least ${smallestText}px.`)); + } else if (rawById.get(n.id)?.fontSize === '$body' && size < bodyDense) { + issues.push(issue('typography', rule, 'warning', n, + `${quote(content)} uses the body role at ${size}px — below the ${bodyDense}px body floor in a desktop app.`, + `Raise $body to at least ${bodyDense}px (generate_design_system on a desktop-app canvas gives 14, or 13 for data-dense).`)); + } else if (size < proseFloor && proseWords(content) >= PROSE_WORDS) { + issues.push(issue('typography', rule, 'warning', n, + `${quote(content)} sets ${proseWords(content)} words at ${size}px — prose below ${proseFloor}px is hard to read.`, + `Set prose at ${proseFloor}px or more; keep ${smallestText}px sizes for short labels.`)); + } + } + return issues; +} + +// ── tables: rows, header, classes ────────────────────────────────────────── + +/** The rows the table detector counted (an import-named Table keeps its + * loose shape; otherwise horizontal frames with two or more children). */ +function rowsOf(table: SceneNode): SceneNode[] { + return (table.children ?? []).filter((c) => c.type === 'frame' && (c.children?.length ?? 0) >= 2 + && (table.name === 'Table' || c.layout === 'horizontal')); +} + +/** A header row: its content is text (icons allowed, such as a sort glyph), + * at least two texts. */ +function isHeaderRow(row: SceneNode): boolean { + let texts = 0; + let other = false; + (function walk(n: SceneNode) { + for (const c of n.children ?? []) { + if (textOf(c) !== undefined) texts++; + else if (c.type === 'frame') walk(c); + else if (c.type !== 'icon' && c.type !== 'text') other = true; + } + })(row); + return !other && texts >= 2; +} + +/** A row holding a title over a subtitle: some non-horizontal frame in it + * stacks two or more texts. */ +function isTwoLine(row: SceneNode): boolean { + let found = false; + (function walk(n: SceneNode) { + for (const c of n.children ?? []) { + if (c.type !== 'frame') continue; + if (c.layout !== 'horizontal' && (c.children ?? []).filter((x) => textOf(x) !== undefined).length >= 2) found = true; + walk(c); + } + })(row); + return found; +} + +/** The most frequent value (first seen wins a tie). */ +function mode(values: number[]): number | undefined { + const freq = new Map(); + for (const v of values) freq.set(v, (freq.get(v) ?? 0) + 1); + let best: number | undefined; + for (const [v, f] of freq) if (best === undefined || f > freq.get(best)!) best = v; + return best; +} + +// ── desktop-app-row-rhythm (FR-C6) ───────────────────────────────────────── + +const ROW_TOLERANCE = 1; + +/** Detected tables: a header row whose height differs from the one-line body + * rows by more than 1px warns (Carbon); body rows that differ from their + * class (one-line, or title over subtitle) by more than 1px are one info per + * class; in detailed mode, a cell whose left edge is off its column by more + * than 1px is one info per table. Fast mode reads authored heights only; + * detailed mode reads rendered rects. */ +export function checkRowRhythm(ctx: DesktopContext, tableIds: Set): EvaluationIssue[] { + const issues: EvaluationIssue[] = []; + const rule = 'desktop-app-row-rhythm'; + const heightOf = (n: SceneNode): number | undefined => { + if (ctx.rects) return ctx.rects.get(n.id)?.height; + return isNum(n.height) ? n.height : undefined; + }; + (function walk(n: SceneNode) { + if (!tableIds.has(n.id)) { n.children?.forEach(walk); return; } + const rows = rowsOf(n); + const header = rows.length > 0 && isHeaderRow(rows[0]) ? rows[0] : undefined; + const body = header ? rows.slice(1) : rows; + const classes = [body.filter((r) => !isTwoLine(r)), body.filter(isTwoLine)]; + const oneLine = classes[0].map(heightOf).filter(isNum); + const bodyH = mode(oneLine); + const headerH = header ? heightOf(header) : undefined; + if (header && headerH !== undefined && bodyH !== undefined && Math.abs(headerH - bodyH) > ROW_TOLERANCE) { + issues.push(issue('consistency', rule, 'warning', header, + `Table "${nameOf(n)}": the header row is ${headerH}px tall over ${bodyH}px body rows — a table's header row matches its row height (Carbon).`, + `Make the header row ${bodyH}px tall (the data-table-app scaffold carries the rule).`)); + } + for (const cls of classes) { + const known = cls.filter((r) => heightOf(r) !== undefined); + const ref = mode(known.map((r) => heightOf(r)!)); + const odd = known.filter((r) => Math.abs(heightOf(r)! - ref!) > ROW_TOLERANCE); + if (ref === undefined || odd.length === 0) continue; + issues.push(issue('consistency', rule, 'info', odd[0], + `Table "${nameOf(n)}": ${odd.length} body row${odd.length === 1 ? ' is' : 's are'} not ${ref}px like ${odd.length === 1 ? 'its' : 'their'} siblings (${odd.map((r) => `"${nameOf(r)}" ${heightOf(r)}px`).slice(0, 5).join(', ')}).`, + 'Give every body row the same height; a row with a title over a subtitle is compared only with rows like it.')); + } + if (ctx.rects) { + const width = mode(rows.map((r) => r.children!.length))!; + const aligned = rows.filter((r) => r.children!.length === width); + for (let col = 0; col < width; col++) { + const cells = aligned.map((r) => r.children![col]).filter((c) => ctx.rects!.has(c.id)); + const ref = mode(cells.map((c) => ctx.rects!.get(c.id)!.x)); + const off = cells.find((c) => Math.abs(ctx.rects!.get(c.id)!.x - ref!) > ROW_TOLERANCE); + if (ref === undefined || !off) continue; + issues.push(issue('consistency', rule, 'info', off, + `Table "${nameOf(n)}": column ${col + 1} does not share one left edge — "${nameOf(off)}" starts ${Math.abs(ctx.rects!.get(off.id)!.x - ref)}px off the column.`, + 'Give every row the same column widths (percentages or fixed widths) so cells line up.')); + break; // one per table + } + } + // A detected table consumes its subtree. + })(ctx.root); + return issues; +} + +// ── desktop-app-truncation (FR-C7) ───────────────────────────────────────── + +/** Fewer visible characters than this before the ellipsis reads as no text. */ +const MIN_VISIBLE_CHARS = 4; + +/** The characters left visible by an ellipsis (the ellipsis itself takes + * about one character's width). */ +function visibleChars(chars: number, scrollWidth: number, clientWidth: number): number { + if (scrollWidth <= 0) return chars; + return Math.max(0, Math.floor((chars * clientWidth) / scrollWidth) - 1); +} + +const overflows = (sw: number | undefined, cw: number | undefined) => isNum(sw) && isNum(cw) && sw > cw + 1; + +/** A table header text that truncates warns (a column header is never cut); + * a hand-built text with an ellipsis and no title is an info (the full text + * must be reachable; primitives add their own title). Detailed mode adds: + * a tablist whose every label is cut warns; an ellipsis (text or primitive + * label) leaving fewer than 4 characters is an info. */ +export function checkTruncation(ctx: DesktopContext, tableIds: Set): EvaluationIssue[] { + const issues: EvaluationIssue[] = []; + const rule = 'desktop-app-truncation'; + const headerTexts = new Set(); + (function findHeaders(n: SceneNode) { + if (tableIds.has(n.id)) { + const first = rowsOf(n)[0]; + if (first && isHeaderRow(first)) (function walk(x: SceneNode) { if (x.type === 'text') headerTexts.add(x); x.children?.forEach(walk); })(first); + return; + } + n.children?.forEach(findHeaders); + })(ctx.root); + (function walk(n: SceneNode) { + const content = textOf(n); + if (content !== undefined && n.textOverflow === 'ellipsis') { + if (headerTexts.has(n)) { + issues.push(issue('usability', rule, 'warning', n, + `Column header ${quote(content)} is set to truncate — a header names its column and is never cut (PatternFly, EUI).`, + 'Remove textOverflow from the header; widen the column, shorten the header, or let it wrap.')); + } else if (!hasText(n.title)) { + issues.push(issue('usability', rule, 'info', n, + `${quote(content)} truncates with an ellipsis but has no title — the full text cannot be read anywhere.`, + `Give it the full text as a title: U("${n.id}", { title: ${JSON.stringify(content.trim())} }).`)); + } + } + const rect = ctx.rects?.get(n.id); + if (rect && content !== undefined && rect.ellipsis && overflows(rect.scrollWidth, rect.clientWidth)) { + const visible = visibleChars(content.length, rect.scrollWidth!, rect.clientWidth!); + if (visible < MIN_VISIBLE_CHARS) { + issues.push(issue('usability', rule, 'info', n, + `${quote(content)} truncates to about ${visible} visible character${visible === 1 ? '' : 's'} — too few to recognise.`, + 'Give it more room, or a shorter label.')); + } + } + if (rect?.labels?.length) { + const cut = rect.labels.filter((l) => overflows(l.scrollWidth, l.clientWidth)); + if (n.type === 'tabs' && cut.length === rect.labels.length) { + issues.push(issue('usability', rule, 'warning', n, + `Every tab label in "${nameOf(n)}" is truncated (${rect.labels.length} tabs in ${rect.width}px) — nobody can read the navigation.`, + 'Widen the tablist, shorten the labels, or move some tabs into a menu.')); + } else { + const short = cut.filter((l) => visibleChars(l.chars, l.scrollWidth, l.clientWidth) < MIN_VISIBLE_CHARS); + if (short.length > 0) { + issues.push(issue('usability', rule, 'info', n, + `${n.type} "${nameOf(n)}": ${short.length} label${short.length === 1 ? '' : 's'} truncate${short.length === 1 ? 's' : ''} to fewer than ${MIN_VISIBLE_CHARS} visible characters — too few to recognise.`, + 'Give it more room, or a shorter label.')); + } + } + } + n.children?.forEach(walk); + })(ctx.root); + return issues; +} + +// ── desktop-app-primary-count (FR-C8) ────────────────────────────────────── + +/** A button renders as primary with variant "primary" or no variant. */ +const isPrimary = (n: SceneNode) => n.type === 'button' && (n.variant === undefined || n.variant === 'primary'); +/** Repeated siblings of one shape (a grid of cards) hold their own primaries. */ +const REPEAT_MIN = 3; + +/** More than one primary button in one region (the nearest pane) is an info. + * A primary inside one of three or more same-shaped sibling frames (shape + * hash without names) is not counted. (A modal's primary action joins with the overlays, slice E.) */ +export function checkPrimaryCount(ctx: DesktopContext): EvaluationIssue[] { + const issues: EvaluationIssue[] = []; + const parentOf = parents(ctx.root); + const hashes = new Map(); + // Names are left out: a card grid's copies are often renamed per item. + const hash = (n: SceneNode) => { if (!hashes.has(n)) hashes.set(n, shapeHash(n, 3, { names: false })); return hashes.get(n)!; }; + const repeated = (n: SceneNode): boolean => { + for (let cur: SceneNode | null = n, up = parentOf.get(n) ?? null; cur && up; cur = up, up = parentOf.get(up) ?? null) { + if (cur.type !== 'frame') continue; + const same = (up.children ?? []).filter((s) => s.type === 'frame' && hash(s) === hash(cur!)).length; + if (same >= REPEAT_MIN) return true; + } + return false; + }; + const byPane = new Map(); + for (const n of parentOf.keys()) { + if (!isPrimary(n) || n.disabled === true || repeated(n)) continue; + const pane = paneOf(n, parentOf); + byPane.set(pane, [...(byPane.get(pane) ?? []), n]); + } + for (const [pane, buttons] of byPane) { + if (buttons.length < 2) continue; + issues.push(issue('structure', 'desktop-app-primary-count', 'info', buttons[1], + `${buttons.length} primary buttons share ${pane === ctx.root ? 'the screen' : `pane "${nameOf(pane)}"`} (${buttons.map((b) => `"${b.label ?? b.ariaLabel ?? nameOf(b)}"`).slice(0, 5).join(', ')}) — one primary per region tells the user what to do next.`, + 'Keep one primary; make the others variant "secondary" or "ghost". A button with no variant renders as primary.')); + } + return issues; +} diff --git a/src/evaluate.ts b/src/evaluate.ts index 6fe01ab..47573ee 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -3,11 +3,14 @@ import { resolveVariables } from './variables.js'; import { getCanvasTokens } from './workspaces.js'; import { renderToHtml, resolveInstance } from './renderer.js'; import { computeLayout, type LayoutRect } from './screenshot.js'; -import { checkDesktopArtboard } from './desktop-app-rules.js'; +import { + checkCurrent, checkDesktopArtboard, checkHandbuiltTargetsApp, checkIconLabels, checkPrimaryCount, checkRowRhythm, checkTruncation, + checkTypeLadder, type DesktopContext, +} from './desktop-app-rules.js'; import { extractInventory, expandInstances, isDataLike } from './drift.js'; 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 { relaxedByPreset, relaxedByGenre, canonicalGenre, genreRulesets, activeRulesets, composeRulesets, resolveSurface, deviceProfile, DEVICE_PROFILES, DEFAULT_DEVICE, MOBILE_RULES, DESKTOP_APP_RULES, DEFAULT_WINDOW, WINDOW_PROFILES, windowProfile, type SurfaceType } from './surfaces.js'; import { checkArtboard, checkHandbuiltTargets, checkOneColumn, checkSafeAreaDetailed, checkSafeAreaFast, checkTabBars, checkTypeFloor, paddingSides, type MobileContext } from './mobile-rules.js'; import { CHROME_EDGE, FAB_SIZE, NAV_ACTION, TAPPABLE_PRIMITIVES, CLICKABLE_PRIMITIVES, CONTROL_OWNERS, LIST_ROW_HEIGHT, MENU_ROW_HEIGHT, NAV_ITEM_HEIGHT, PROPERTY_ROW_HEIGHT, buttonBox, desktopTargets, effectivePosition, listRowMinHeight, navActions, pinsBottom, tabItemBox, tabItems } from './primitives.js'; @@ -2344,9 +2347,18 @@ const CATEGORY_WEIGHTS = new Map([ // a false negative is today's status quo, a false positive is friction. /** What each kind of data-bearing content demands (spec C4). */ -const COVERAGE_DEMANDS: { kind: string; demands: string[]; detect: (inv: ReturnType) => boolean; noun: string }[] = [ +/** Text-inputs outside detected tables (a table's cells are its data plane, + * as the inventory treats its controls). */ +function countTextInputs(root: SceneNode, tableIds: Set): number { + if (tableIds.has(root.id)) return 0; + return (root.type === 'text-input' ? 1 : 0) + (root.children ?? []).reduce((a, c) => a + countTextInputs(c, tableIds), 0); +} + +const COVERAGE_DEMANDS: { kind: string; demands: string[]; detect: (inv: ReturnType & { textInputs?: number }) => boolean; noun: string }[] = [ { kind: 'table', demands: ['empty', 'loading'], detect: (inv) => inv.tables.length > 0, noun: 'a data table' }, - { kind: 'form', demands: ['error'], detect: (inv) => inv.counts.controls >= 3, noun: 'a form (3+ input controls)' }, + // Phase 31 FR-C10 — a text-input is an input control too (outside tables, + // as the inventory counts controls); drift's control list stays as is. + { kind: 'form', demands: ['error'], detect: (inv) => inv.counts.controls + (inv.textInputs ?? 0) >= 3, noun: 'a form (3+ input controls)' }, ]; /** Scaffold hint per demanded state — the cheap way to comply (slice B). */ @@ -2409,7 +2421,9 @@ function checkCoverage(canvas: Canvas, designedStates: string[]): { result: Chec return { result: { score: 100, issues: [] } }; } - const inv = extractInventory(expandInstances(canvas.root, canvas)); + const expanded = expandInstances(canvas.root, canvas); + const inv: ReturnType & { textInputs?: number } = extractInventory(expanded); + inv.textInputs = countTextInputs(expanded, new Set(inv.tables.map((t) => t.nodeId))); const demanded = new Map(); // state → noun that demanded it for (const d of COVERAGE_DEMANDS) { if (!d.detect(inv)) continue; @@ -2486,6 +2500,10 @@ export async function evaluateCanvas( const { root: mobileRoot, owners } = expandForRules(resolvedRoot, canvas); const expandedRaw = expandForRules(canvas.root, canvas).root; const mobileTypeRules = MOBILE_RULES.some((id) => ruleOn.has(id)); + // Phase 31 slice C — the desktop-app rules read the expanded tree too, and + // in detailed mode the rects of that tree. + const desktopTypeRules = DESKTOP_APP_RULES.some((id) => ruleOn.has(id)); + const expandedRules = mobileTypeRules || desktopTypeRules; const mobile: MobileContext = { root: mobileRoot, profile: deviceProfile(declared.device ?? DEFAULT_DEVICE) ?? DEVICE_PROFILES[DEFAULT_DEVICE], @@ -2545,14 +2563,29 @@ export async function evaluateCanvas( // Phase 30 slice C — mobile-safe-area reads rendered rects too, deeper. let detailedLayout: LayoutRect[] | undefined; const safeAreaDetailed = activeCategories.includes('usability') && ruleOn.has('mobile-safe-area'); - if (options.mode === 'detailed' && (activeCategories.includes('consistency') || activeCategories.includes('typography') || safeAreaDetailed)) { + const desktopDetailed = desktopTypeRules && activeCategories.includes('usability'); + if (options.mode === 'detailed' && (activeCategories.includes('consistency') || activeCategories.includes('typography') || safeAreaDetailed || desktopDetailed)) { const w = typeof canvas.root.width === 'number' ? canvas.root.width : 1440; const h = typeof canvas.root.height === 'number' ? canvas.root.height : 900; // On a mobile canvas render the tree the mobile rules read: the same // pixels as the canvas render, with every node inside an instance under // its own id, so the rects are unambiguous. Web keeps the canvas render. - const html = mobileTypeRules ? renderToHtml(mobileRoot, w, h, canvas) : renderToHtml(resolvedRoot, w, h, canvas); - detailedLayout = await computeLayout(html, undefined, ruleOn.has('mobile-safe-area') ? 25 : 10, { width: w, height: h }); + const html = expandedRules ? renderToHtml(mobileRoot, w, h, canvas) : renderToHtml(resolvedRoot, w, h, canvas); + detailedLayout = await computeLayout(html, undefined, expandedRules ? 25 : 10, { width: w, height: h }); + } + // Phase 31 slice C — the desktop-app rules' view of the canvas. + let desktop: DesktopContext | undefined; + let desktopTables = new Set(); + if (desktopTypeRules) { + const rects = new Map(); + const index = (r: LayoutRect) => { rects.set(r.nodeId, r); r.children?.forEach(index); }; + detailedLayout?.forEach(index); + desktop = { + root: mobileRoot, + profile: windowProfile(declared.device ?? DEFAULT_WINDOW) ?? WINDOW_PROFILES[DEFAULT_WINDOW], + ...(detailedLayout ? { rects } : {}), + }; + desktopTables = new Set(extractInventory(mobileRoot).tables.map((t) => t.nodeId)); } if (activeCategories.includes('typography')) { const typography = checkTypography(entries, mergedTokens, { @@ -2562,21 +2595,26 @@ export async function evaluateCanvas( tables: extractInventory(resolvedRoot).tables, }); const rawById = new Map(buildTreeContext(expandedRaw).map((en) => [en.node.id, en.node])); - results.set('typography', withRuleIssues(typography, ruleOn.has('mobile-type-floor') ? reportOnInstances(checkTypeFloor(mobile, rawById), owners) : [])); + const pinned = new Set(Object.values(mergedTokens.typography ?? {}).map((t) => t.fontSize).filter((v): v is number => typeof v === 'number')); + results.set('typography', withRuleIssues(typography, reportOnInstances([ + ...(ruleOn.has('mobile-type-floor') ? checkTypeFloor(mobile, rawById) : []), + ...(desktop && ruleOn.has('desktop-app-type-ladder') ? checkTypeLadder(desktop, rawById, pinned) : []), + ], owners))); } if (activeCategories.includes('structure')) { results.set('structure', withRuleIssues(checkStructure(rawEntries, canvas), [ ...(ruleOn.has('mobile-artboard') ? reportOnInstances(checkArtboard(mobile, declared), owners) : []), ...(ruleOn.has('desktop-app-artboard') ? reportOnInstances(checkDesktopArtboard(mobileRoot, declared), owners) : []), + ...(desktop && ruleOn.has('desktop-app-primary-count') ? reportOnInstances(checkPrimaryCount(desktop), owners) : []), ])); } if (activeCategories.includes('consistency')) { const consistencyCtx = { rawEntries, tokens: mergedTokens }; - if (options.mode === 'detailed' && detailedLayout) { - results.set('consistency', checkConsistencyDetailed(entries, detailedLayout, consistencyCtx)); - } else { - results.set('consistency', checkConsistency(entries, consistencyCtx)); - } + const consistency = options.mode === 'detailed' && detailedLayout + ? checkConsistencyDetailed(entries, detailedLayout, consistencyCtx) + : checkConsistency(entries, consistencyCtx); + results.set('consistency', withRuleIssues(consistency, + desktop && ruleOn.has('desktop-app-row-rhythm') ? reportOnInstances(checkRowRhythm(desktop, desktopTables), owners) : [])); } if (activeCategories.includes('usability')) { const touch = ruleOn.has('mobile-touch-target') ? { floor: mobile.profile.touchTarget } : undefined; @@ -2601,9 +2639,14 @@ export async function evaluateCanvas( } const parentOf = new Map(targetEntries.map((en) => [en.node.id, en.parent] as const)); const pointer = checkPointerTargets(targets, parentOf, mobile.width, rects); + // Phase 31 FR-C1 — on desktop-app the floor is the rule + // desktop-app-target (the same check; web runs it unnamed). + const named = ruleOn.has('desktop-app-target') + ? pointer.issues.map((i) => (/24px floor/.test(i.message) ? { ...i, rule: 'desktop-app-target' } : i)) + : pointer.issues; usability = { score: Math.max(0, usability.score - (100 - pointer.score)), - issues: [...usability.issues, ...reportOnInstances(pointer.issues, owners)], + issues: [...usability.issues, ...reportOnInstances(named, owners)], }; } const extra = reportOnInstances([ @@ -2611,6 +2654,10 @@ export async function evaluateCanvas( ...(ruleOn.has('mobile-safe-area') ? (detailedLayout ? checkSafeAreaDetailed(mobile, detailedLayout) : checkSafeAreaFast(mobile)) : []), ...(ruleOn.has('mobile-one-column') ? checkOneColumn(mobile) : []), ...(ruleOn.has('mobile-tab-bar') ? checkTabBars(mobile) : []), + ...(desktop && ruleOn.has('desktop-app-handbuilt-target') ? checkHandbuiltTargetsApp(desktop) : []), + ...(desktop && ruleOn.has('desktop-app-icon-label') ? checkIconLabels(desktop) : []), + ...(desktop && ruleOn.has('desktop-app-current') ? checkCurrent(desktop) : []), + ...(desktop && ruleOn.has('desktop-app-truncation') ? checkTruncation(desktop, desktopTables) : []), ], owners); results.set('usability', withRuleIssues(usability, extra)); } diff --git a/src/index.ts b/src/index.ts index 9f7705b..cacd07e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -85,7 +85,7 @@ Point-and-tell feedback: the user toggles Comment mode in the viewer and clicks Phone app screens: declare the medium. canvas_create({ type: "mobile" }) makes a phone screen — the device artboard (390×844 for the default device "iphone-390") with the root reserving the safe-area insets as safeArea: { top: 47, bottom: 34 } (the renderer adds them to the root's own top/bottom padding, and the root grows with long content keeping that padding past it, so in-flow content never sits under the status bar or home indicator). type: "web" (the default) is a web page; canvas_set_type changes or clears the declaration on an existing canvas (it never resizes or writes safeArea — its result's hint names the op that does). The type selects a ruleset and defaults, never the render: generate_design_system on a mobile canvas pivots the type scale on the device body size (17px; 16px for data-dense), and every evaluate result carries a "surface" report ({ type, device, source "declared" | "default", rulesOn, rulesOff, conflicts }) naming the rule ids the type + genre + preset rulesets turned on and off — a rule both enabled and disabled stays on (in rulesOn) and is listed in conflicts. Start a phone screen from a mobile realisation: apply_structure on a mobile canvas resolves the anatomy name to it — dashboard → dashboard-mobile, settings → settings-mobile, auth → auth-mobile, onboarding → onboarding-mobile, and the mobile-first feed → feed-mobile (a list of rows, pinned tab bar) and detail → detail-mobile (an item with a primary action pinned over the home indicator) — each built from the primitives and gated to pass the mobile ruleset in fast and detailed mode and canvas_stress CLEAN (unthemed and under every personality); stamp it after generate_design_system (the dark, light and material presets carry a 14–15px body that mobile-type-floor flags on a phone). Resolution reads the DECLARED type: an undeclared 390px canvas stamps the web structure, so declare type "mobile" first. Its placeholders include every copy field of its primitives, with prop the field's path (title, subtitle, label, trailing.text, leading.initials, leading.label, items[0].label — a path, not an op key: set a nested one by writing its whole object or array, siblings included). An anatomy with no mobile realisation (the other web pages such as pricing, catalogue or bento-grid; web-only components such as data-table) is refused with the list of those that have one; realisation: "web" stamps the web one anyway. Of the components, form-field, stat-card, empty-state, skeleton-card, skeleton-stat-card, kpi-card, status-chip and initials-avatar stamp on every type. Build phone screens from the mobile primitives (batch_design lists them): status-bar and home-indicator (device chrome), nav-bar, tab-bar, button, list-row, sheet — never hand-built frames — and pin bars with position "fixed" (the renderer reserves room for pinned chrome, so content never starts or ends under it). A mobile canvas runs the mobile ruleset; every finding names its rule in a "rule" field: mobile-touch-target (ERROR: a tap target below 44px — a control (its row counts only when the row is a horizontal frame holding that one tappable), a button (size "sm" is 32, "xs" 24), a list-row, each tab-bar tab and FAB, each nav-bar action; primitives are measured by their own box, inside instances too), mobile-safe-area (WARNING: content under the 47px status-bar or 34px home-indicator inset, or left under a pinned bar at the start or end of the scroll; with root safeArea or pinned chrome the renderer reserves the insets and only positioned content (absolute / fixed / sticky) and pinned bars are checked — padding ≥32px scales down on a phone, so clear a pinned bar with a spacer frame inside your content frame; detailed mode is authoritative), mobile-tab-bar (WARNING: a tab bar with fewer than 2 or more than 5 tabs, an unlabeled tab, or one not pinned to the bottom), mobile-type-floor (WARNING: text below 11px, $body below 16px, prose of 5+ words below 13px), mobile-handbuilt-target (info: an icon-shaped frame below 44px — rebuild it as a button), mobile-one-column (info: two or more side-by-side children each holding 8+ words), and on every type mobile-artboard (a mobile canvas 500px+ wide WARNS; an undeclared canvas narrower than 500px WARNS until canvas_set_type declares it either way). -Application screens: canvas_create({ type: "desktop-app" }) for a tool you work in — an editor, an admin console, a file browser, a viewer: persistent chrome, panes, dense controls, a current selection, in a browser tab or a native window. The test is what the user does: a page you read and scroll is "web", a tool you work in is "desktop-app". It gets the window artboard (1440×900 for the default device "window-1440", no insets); generate_design_system pivots its type on 14px (13 for data-dense); its ruleset turns OFF type-scale-ratio (the adjacent font-size ratio check — dense apps step 12/13/14 on purpose), and desktop-app-artboard (on every type) WARNS when a desktop-app canvas is narrower than 1024px, and when a canvas holding a desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) never declared its type or is declared mobile (declared web gets an info). 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. +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. The desktop-app ruleset (each finding carries its "rule"; canvas_evaluate lists them) adds: name every icon-only button (ariaLabel); mark exactly one current place — one active nav-item per pane (a parent may stay active over its active child), one active tab per tabs, one active row per tree; a dense type ladder (desktop-app-type-ladder, replacing type-scale-ratio: 12/13/14 steps are fine, nothing below 11px, prose ≥12px, $body ≥13px); table header rows as tall as their body rows; column headers never truncated; one primary button per pane (info); and frames shaped like small buttons are named as hand-built targets (info) — rebuild them as button or link. Before presenting a desktop-app screen run mode "detailed" too: it measures rendered rows, column edges and truncation (a tablist whose every label is cut warns). 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. @@ -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 (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.', + '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; on desktop-app an icon-only button without ariaLabel warns, and a nav group, tabs or tree with no single active item warns (desktop-app-current). 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.', @@ -891,7 +891,7 @@ server.tool( // --- snapshot_layout --- server.tool( 'snapshot_layout', - 'Get computed bounding boxes for all nodes by rendering the canvas in a browser. Returns { nodeId, x, y, width, height } for each node — plus, on any node whose content exceeds its box, overflow data: scrollWidth/clientWidth/scrollHeight/clientHeight and an ellipsis flag when a designed text-overflow truncation is active (the same capture canvas_stress uses to detect clipping).', + 'Get computed bounding boxes for all nodes by rendering the canvas in a browser. Returns { nodeId, x, y, width, height } for each node — plus, on any node whose content exceeds its box, overflow data: scrollWidth/clientWidth/scrollHeight/clientHeight and an ellipsis flag when a designed text-overflow truncation is active (the same capture canvas_stress uses to detect clipping). On a primitive: truncated: true when one of its own labels is cut by its ellipsis, and labels ([{ chars, scrollWidth, clientWidth }], one per own label, in order) on every tabs node and on any primitive with a cut label.', { canvasId: z.string().describe('Canvas ID'), nodeId: z.string().optional().describe('Root node ID to start from'), @@ -2141,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, 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. +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 desktop-app canvas rulesOn also lists the desktop-app ruleset, each finding tagged with its "rule": desktop-app-target (usability: the 24px floor above, named — fast WARNING, detailed ERROR when the 24px circle reaches a neighbour; an unlabelled link measures its glyphs, 14px wide), desktop-app-handbuilt-target (usability info, never blocks: a frame below 32px holding one icon, an icon plus a label of ≤3 words, or a bordered padded frame holding one such label — the shape an imported text button takes; rebuild it as a button or link if clickable), desktop-app-icon-label (usability WARNING: an icon-only button with no ariaLabel, a collapsed nav-item with a blank label), desktop-app-current (usability WARNING: in one pane — a frame with overflow "auto", or the root — two active nav-items at one depth, or two or more nav-items with none active; a tabs node with no active tab or more than one; two active tree-rows under one parent; info: a tree with a current row nesting past two levels), desktop-app-type-ladder (typography WARNING, replaces type-scale-ratio: adjacent sizes a 1 ? Math.max(base, rows * TEXT_INPUT_LINE + 12) : base; } +/** The width an unlabelled link renders at: its 14px icon and 12px + * external-link glyph, 4px apart (renderLink). */ +export function linkGlyphWidth(n: SceneNode): number { + const glyphs = [n.icon ? LINK_ICON : 0, n.external ? LINK_EXTERNAL : 0].filter((g) => g > 0); + return glyphs.reduce((a, g) => a + g, 0) + Math.max(0, glyphs.length - 1) * 4; +} + /** 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). */ @@ -132,7 +141,8 @@ export function desktopTargets(n: SceneNode): Array<{ what: string; w?: number; const disabled = n.disabled === true; switch (n.type) { // 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 }]; + // Without a label it hugs its glyphs, so its width is known (slice C). + case 'link': return [{ what: 'link', w: w ?? (hasText(n.label) ? undefined : linkGlyphWidth(n)), 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 }]; diff --git a/src/project-evaluate.ts b/src/project-evaluate.ts index 7409422..842b190 100644 --- a/src/project-evaluate.ts +++ b/src/project-evaluate.ts @@ -13,6 +13,7 @@ import type { Canvas } from './types.js'; import type { SceneNode } from './types.js'; import { evaluateCanvas, rgbToHsl, parseColor } from './evaluate.js'; import { getCanvasTokens } from './workspaces.js'; +import { shapeHash } from './shape-hash.js'; export type ProjectFindingKind = 'radius-drift' | 'accent-drift' | 'token-adoption' | 'copied-chrome' | 'state-coverage'; @@ -73,16 +74,6 @@ const hueDistance = (a: number, b: number): number => { return d > 180 ? 360 - d : d; }; -/** Depth-3 shape hash: type + name + child-count tree. Styles deliberately - * excluded — a copied shell whose active nav item is restyled per screen - * still matches; a structurally edited copy doesn't (miss it rather than - * accuse legitimate variation). */ -function shapeHash(node: SceneNode, depth = 3): string { - const part = `${node.type}:${node.name ?? ''}:${node.children?.length ?? 0}`; - if (depth <= 1 || !node.children?.length) return part; - return `${part}[${node.children.map((c) => shapeHash(c, depth - 1)).join(',')}]`; -} - function subtreeSize(node: SceneNode): number { return 1 + (node.children?.reduce((a, c) => a + subtreeSize(c), 0) ?? 0); } diff --git a/src/renderer.ts b/src/renderer.ts index 45a332e..447f719 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -5,7 +5,7 @@ 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, + LINK_MIN_HEIGHT, LINK_ICON, LINK_EXTERNAL, NAV_ITEM_HEIGHT, TABS_HEIGHT, TREE_ROW_HEIGHT, TREE_INDENT, MENU_ROW_HEIGHT, PROPERTY_ROW_HEIGHT, PROPERTY_LABEL_WIDTH, tabsItems, textInputHeight, textInputRows, } from './primitives.js'; @@ -1287,8 +1287,8 @@ function disabledAttrs(node: SceneNode, attrs: string): string { 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) : ''; + const glyph = iconHtml(node.icon, LINK_ICON, node.iconColor ?? color); + const external = node.external ? iconHtml('external-link', LINK_EXTERNAL, node.iconColor ?? color) : ''; const words = text(node.label) ? titledLabel(text(node.label), '') : ''; const box = css([ ...positionStyles(node, rc), 'display: inline-flex', 'flex-shrink: 0', 'align-items: center', 'gap: 4px', diff --git a/src/screenshot.ts b/src/screenshot.ts index e9ad1cc..d61ebd5 100644 --- a/src/screenshot.ts +++ b/src/screenshot.ts @@ -166,6 +166,11 @@ export interface LayoutRect { /** Phase 30 slice D — a primitive whose label (a `data-fs-label` element) * is cut off by its designed one-line ellipsis. */ truncated?: boolean; + /** Phase 31 slice C — a primitive's own labels, in order: each label's + * character count and its scroll/client widths. Recorded on every tablist + * (so a crowded tablist is judged per tab) and on any other primitive with + * a truncated label (so a short truncation can be measured). */ + labels?: Array<{ chars: number; scrollWidth: number; clientWidth: number }>; /** Phase 30 slice D — a `data-fs-scroll` element (a sheet panel): its * vertical overflow scrolls, it is not a clip. */ scrolls?: boolean; @@ -196,10 +201,13 @@ const LAYOUT_WALKER_SOURCE = `(function (rootId, depth) { } if (el.hasAttribute('data-fs-primitive')) { var labels = el.querySelectorAll('[data-fs-label]'); + var own = []; for (var j = 0; j < labels.length; j++) { if (labels[j].closest('[data-node-id]') !== el) continue; - if (labels[j].scrollWidth > labels[j].clientWidth + 1) { result.truncated = true; break; } + own.push({ chars: (labels[j].textContent || '').length, scrollWidth: labels[j].scrollWidth, clientWidth: labels[j].clientWidth }); + if (labels[j].scrollWidth > labels[j].clientWidth + 1) result.truncated = true; } + if (own.length > 0 && (result.truncated || el.getAttribute('role') === 'tablist')) result.labels = own; } if (el.hasAttribute('data-fs-scroll')) result.scrolls = true; if (currentDepth < depth) { diff --git a/src/shape-hash.ts b/src/shape-hash.ts new file mode 100644 index 0000000..3d0bd4e --- /dev/null +++ b/src/shape-hash.ts @@ -0,0 +1,16 @@ +// The depth-3 shape hash: one definition for the project roll-up (a shell +// copied across screens) and the desktop-app primary-count rule (a grid of +// same-shaped cards). + +import type { SceneNode } from './types.js'; + +/** Depth-3 shape hash: type + name + child-count tree. Styles deliberately + * excluded — a copied shell whose active nav item is restyled per screen + * still matches; a structurally edited copy doesn't (miss it rather than + * accuse legitimate variation). `names: false` drops names too, for repeats + * whose copies are renamed per item (a grid of pricing cards). */ +export function shapeHash(node: SceneNode, depth = 3, opts: { names?: boolean } = {}): string { + const part = `${node.type}:${opts.names === false ? '' : node.name ?? ''}:${node.children?.length ?? 0}`; + if (depth <= 1 || !node.children?.length) return part; + return `${part}[${node.children.map((c) => shapeHash(c, depth - 1, opts)).join(',')}]`; +} diff --git a/src/surfaces.ts b/src/surfaces.ts index e0a8a31..c028836 100644 --- a/src/surfaces.ts +++ b/src/surfaces.ts @@ -190,7 +190,16 @@ export const MOBILE_RULES = [ /** Phase 31: the desktop-app ruleset's rule ids, each registered in the same * change as the check that honours it. `desktop-app-artboard` lives in the * base row (it must run on every type), so it is not listed here. */ -export const DESKTOP_APP_RULES: readonly string[] = []; +export const DESKTOP_APP_RULES: readonly string[] = [ + 'desktop-app-target', + 'desktop-app-handbuilt-target', + 'desktop-app-icon-label', + 'desktop-app-current', + 'desktop-app-type-ladder', + 'desktop-app-row-rhythm', + 'desktop-app-truncation', + 'desktop-app-primary-count', +]; /** Phase 31: default rules — they run unless an active ruleset disables them. * A rule id appears here when some type replaces the check. */ @@ -206,7 +215,7 @@ export const RULESETS: Record> = { // The mobile disable list stays empty until a web-shaped rule is shown to // misfire on a correct mobile idiom (FR-C7). // desktop-app replaces the adjacent-ratio check (dense apps step 12/13/14 - // on purpose); its own type ladder lands with the app rules. + // on purpose) with desktop-app-type-ladder. type: { web: {}, mobile: { enable: [...MOBILE_RULES] }, 'desktop-app': { enable: [...DESKTOP_APP_RULES], disable: ['type-scale-ratio'] } }, genre: { // Material Design legitimately uses a purple accent AND white elevated diff --git a/test-desktop-app-rules-detailed.ts b/test-desktop-app-rules-detailed.ts new file mode 100644 index 0000000..275df68 --- /dev/null +++ b/test-desktop-app-rules-detailed.ts @@ -0,0 +1,99 @@ +// Phase 31 slice C — the desktop-app rules' detailed-mode clauses, on rendered +// rects: the 24px circle test on icon-only links (FR-C1), rendered row heights +// and column edges (FR-C6), short truncations and crowded tablists (FR-C7). +// Each detailed finding has a fast-mode twin that must stay silent, and each +// pass a failing twin. Needs Chrome. +// +// Usage: npx tsx test-desktop-app-rules-detailed.ts + +import './test-env.js'; +import { evaluateCanvas, type EvaluationIssue } from './src/evaluate.js'; +import { shutdown } from './src/screenshot.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}` : ''}`); +} + +function canvasOf(children: SceneNode[]): Canvas { + return { + id: 'c', name: 'c', projectId: 'p', components: {}, variables: {}, createdAt: '', lastModified: '', + root: { id: 'document', type: 'document', name: 'Document', width: 1440, height: 900, fill: '#FFFFFF', layout: 'vertical', padding: 40, gap: 16, alignItems: 'flex-start', children }, + metadata: { surface: { type: 'desktop-app', device: 'window-1440' } }, + } as Canvas; +} +async function findings(rule: string, children: SceneNode[], mode: 'fast' | 'detailed' = 'detailed'): Promise { + const r = await evaluateCanvas(canvasOf(children), { mode }); + return r.issues.filter((i) => i.rule === rule); +} +const show = (f: EvaluationIssue[]) => JSON.stringify(f.map((i) => `${i.severity}: ${i.message}`)); +const text = (id: string, content: string, extra: Partial = {}): SceneNode => + ({ id, name: id, type: 'text', content, fontSize: 13, color: '#111111', ...extra }); +const frame = (id: string, children: SceneNode[], extra: Partial = {}): SceneNode => + ({ id, name: id, type: 'frame', layout: 'vertical', children, ...extra }); + +// ── FR-C1: icon-only links and the 24px circle ───────────────────────────── +{ + const link = (id: string, extra: Partial = {}): SceneNode => ({ id, name: id, type: 'link', icon: 'arrow-left', ...extra }); + const row = (gap: number, children: SceneNode[]) => frame('bar', children, { layout: 'horizontal', alignItems: 'center', gap }); + let f = await findings('desktop-app-target', [row(16, [link('back'), link('fwd', { icon: 'arrow-right' })])]); + check('FR-C1: a 14px "← Back" link with no other target inside its circle passes', f.length === 0, show(f)); + f = await findings('desktop-app-target', [row(0, [link('back'), link('fwd', { icon: 'arrow-right' })])]); + check('FR-C1: packed against a neighbouring link it fails, as errors naming the circle', f.length === 2 && f.every((i) => i.severity === 'error' && /24px circle/.test(i.message)), show(f)); + f = await findings('desktop-app-target', [row(0, [link('back', { label: 'Back' }), link('fwd', { label: 'Forward' })])]); + check('FR-C1: labelled links are no undersized targets, packed or not', f.length === 0, show(f)); +} + +// ── FR-C6: rendered row heights and column edges ─────────────────────────── +{ + const cell = (id: string, content: string, w: number) => text(id, content, { width: w }); + const row = (id: string, pad: number, widths: number[], cells: string[]) => + frame(id, cells.map((c, i) => cell(`${id}-${i}`, c, widths[i])), { layout: 'horizontal', padding: [pad, 12] }); + const table = (headerPad: number, firstWidth: (i: number) => number) => frame('users', [ + row('head', headerPad, [120, 120, 120], ['Name', 'Role', 'Status']), + ...[0, 1, 2, 3].map((i) => row(`r${i}`, 8, [firstWidth(i), 120, 120], [`Ada ${i}`, 'Admin', 'Active'])), + ]); + let f = await findings('desktop-app-row-rhythm', [table(14, () => 120)]); + check('FR-C6: a taller rendered header (no authored heights) warns in detailed mode', f.length === 1 && f[0].severity === 'warning', show(f)); + f = await findings('desktop-app-row-rhythm', [table(14, () => 120)], 'fast'); + check('FR-C6: fast mode, which reads authored heights only, is silent on it', f.length === 0, show(f)); + f = await findings('desktop-app-row-rhythm', [table(8, (i) => (i === 2 ? 123 : 120))]); + check('FR-C6: one cell 3px off its column is an info in detailed mode', f.length === 1 && f[0].severity === 'info' && /3px off/.test(f[0].message), show(f)); + f = await findings('desktop-app-row-rhythm', [table(8, (i) => (i === 2 ? 123 : 120))], 'fast'); + check('FR-C6: the same table is silent in fast mode', f.length === 0, show(f)); + f = await findings('desktop-app-row-rhythm', [table(8, () => 120)]); + check('FR-C6: an aligned table with a matching header is silent', f.length === 0, show(f)); +} + +// ── FR-C7: short truncations and crowded tablists ────────────────────────── +{ + const shortish = (r: EvaluationIssue[]) => r.filter((i) => /visible character|fewer than 4/.test(i.message)); + const cut = (w: number) => text('file', 'Quarterly report final.pdf', { textOverflow: 'ellipsis', title: 'Quarterly report final.pdf', width: w }); + let f = await findings('desktop-app-truncation', [cut(28)]); + check('FR-C7: an ellipsis leaving under 4 characters is an info in detailed mode', shortish(f).length === 1 && shortish(f)[0].severity === 'info', show(f)); + f = await findings('desktop-app-truncation', [cut(28)], 'fast'); + check('FR-C7: fast mode cannot see it', shortish(f).length === 0, show(f)); + f = await findings('desktop-app-truncation', [cut(120)]); + check('FR-C7: an ellipsis leaving a readable label is silent', shortish(f).length === 0, show(f)); + + const navItem = (w: number): SceneNode => ({ id: 'nav', name: 'nav', type: 'nav-item', label: 'Quarterly planning', icon: 'folder', active: true, width: w }); + f = await findings('desktop-app-truncation', [navItem(60)]); + check('FR-C7: a primitive label cut to under 4 characters is an info', shortish(f).length === 1, show(f)); + f = await findings('desktop-app-truncation', [navItem(240)]); + check('FR-C7: the same nav-item with room is silent', f.length === 0, show(f)); + + const tabs = (labels: string[], width: number): SceneNode => ({ id: 'tabs', name: 'Inspector tabs', type: 'tabs', width, items: labels.map((label, i) => ({ label, active: i === 0 })) }); + const eight = ['Overview', 'Spacing', 'Typography', 'Color', 'Structure', 'Consistency', 'Coverage', 'Usability']; + f = await findings('desktop-app-truncation', [tabs(eight, 220)]); + check('FR-C7: eight tabs in a 220px tablist warn in detailed mode', f.some((i) => i.severity === 'warning' && /Every tab label/.test(i.message)), show(f)); + f = await findings('desktop-app-truncation', [tabs(eight, 220)], 'fast'); + check('FR-C7: fast mode cannot see the crowded tablist', f.length === 0, show(f)); + f = await findings('desktop-app-truncation', [tabs(['Issues', 'Tokens', 'History'], 400)]); + check('FR-C7: three tabs that fit are silent', f.length === 0, show(f)); +} + +await shutdown(); +console.log(allPass ? '\nALL PASS' : '\nSOME FAILED'); +process.exit(allPass ? 0 : 1); diff --git a/test-desktop-app-rules.ts b/test-desktop-app-rules.ts new file mode 100644 index 0000000..0f4d57f --- /dev/null +++ b/test-desktop-app-rules.ts @@ -0,0 +1,279 @@ +// Phase 31 slice C — the desktop-app rules in fast mode (FR-C1 to FR-C8) and +// form coverage counting text-inputs (FR-C10). Every asserted pass has a twin +// that must fail, and every rule is shown silent on web. The detailed-mode +// clauses (the circle test on links, rendered row heights, column edges, +// short truncations, crowded tablists) live in test-desktop-app-rules-detailed.ts. +// +// Usage: npx tsx test-desktop-app-rules.ts + +import './test-env.js'; +import { readFileSync } from 'node:fs'; +import { evaluateCanvas, type EvaluationIssue } from './src/evaluate.js'; +import { extractInventory } from './src/drift.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 Kind = 'web' | 'desktop-app'; +function canvasOf(children: SceneNode[], type: Kind = 'desktop-app', variables: Canvas['variables'] = {}): Canvas { + return { + id: 'c', name: 'c', projectId: 'p', components: {}, variables, createdAt: '', lastModified: '', + root: { id: 'document', type: 'document', name: 'Document', width: 1440, height: 900, fill: '#FFFFFF', layout: 'vertical', padding: 24, children }, + metadata: { surface: type === 'web' ? { type } : { type, device: 'window-1440' } }, + } as Canvas; +} +async function findings(rule: string, children: SceneNode[], type: Kind = 'desktop-app', variables: Canvas['variables'] = {}): Promise { + const r = await evaluateCanvas(canvasOf(children, type, variables), { mode: 'fast' }); + return r.issues.filter((i) => i.rule === rule); +} +const show = (f: EvaluationIssue[]) => JSON.stringify(f.map((i) => `${i.severity}: ${i.message}`)); +const text = (id: string, content: string, fontSize = 14, extra: Partial = {}): SceneNode => + ({ id, name: id, type: 'text', content, fontSize, color: '#111111', ...extra }); +const frame = (id: string, children: SceneNode[], extra: Partial = {}): SceneNode => + ({ id, name: id, type: 'frame', layout: 'vertical', children, ...extra }); +const nav = (id: string, extra: Partial = {}): SceneNode => ({ id, name: id, type: 'nav-item', label: id, ...extra }); + +// ── FR-C1: desktop-app-target ────────────────────────────────────────────── +{ + const small = [{ id: 'x', name: 'x', type: 'button', icon: 'x', ariaLabel: 'Close', size: 'sm', width: 20, height: 20 } as SceneNode]; + const app = await evaluateCanvas(canvasOf(small), { mode: 'fast', categories: ['usability'] }); + const web = await evaluateCanvas(canvasOf(small, 'web'), { mode: 'fast', categories: ['usability'] }); + const floor = (r: typeof app) => r.issues.filter((i) => /24px floor/.test(i.message)); + check('FR-C1: an undersized target on desktop-app is rule desktop-app-target, a fast-mode warning', floor(app).length === 1 && floor(app)[0].rule === 'desktop-app-target' && floor(app)[0].severity === 'warning', show(floor(app))); + check('FR-C1: the same target on web keeps the unnamed floor', floor(web).length === 1 && floor(web)[0].rule === undefined, show(floor(web))); + + // The census now knows an unlabelled link's width (it hugs its glyph). + const back = (extra: Partial): SceneNode => ({ id: 'back', name: 'Back', type: 'link', icon: 'arrow-left', ...extra }); + let f = await findings('desktop-app-target', [back({ label: '← Back' })]); + check('FR-C1: a labelled "← Back" link is no undersized target', f.length === 0, show(f)); + f = await findings('desktop-app-target', [back({})]); + check('FR-C1: an icon-only link (14px wide) is an undersized target in fast mode', f.length === 1 && /14×24px/.test(f[0].message), show(f)); + f = await findings('desktop-app-target', [back({ external: true })]); + check('FR-C1: an icon-only external link measures both glyphs (30px) and passes', f.length === 0, show(f)); +} + +// ── FR-C2: desktop-app-handbuilt-target ──────────────────────────────────── +{ + const iconFrame = (id: string, size: number, extra: Partial = {}): SceneNode => + frame(id, [{ id: `${id}-i`, name: 'i', type: 'icon', icon: 'settings', iconSize: 16 }], { width: size, height: size, ...extra }); + let f = await findings('desktop-app-handbuilt-target', [iconFrame('gear', 24)]); + check('FR-C2: a 24px icon frame is named as a possible click target (info)', f.length === 1 && f[0].severity === 'info' && /button/.test(f[0].suggestion ?? ''), show(f)); + f = await findings('desktop-app-handbuilt-target', [iconFrame('gear', 32)]); + check('FR-C2: the same frame at 32px is silent', f.length === 0, show(f)); + f = await findings('desktop-app-handbuilt-target', [frame('row', [iconFrame('gear', 24)], { type: 'property-row', label: 'Gear' } as Partial)]); + check('FR-C2: a frame inside a property-row (a clickable primitive\'s slot) is never hand-built', f.length === 0, show(f)); + f = await findings('desktop-app-handbuilt-target', [frame('back', [{ id: 'bi', name: 'bi', type: 'icon', icon: 'arrow-left', iconSize: 14 }, text('bt', 'Back', 13)], { layout: 'horizontal', padding: [4, 6] })]); + check('FR-C2: an icon plus a short label, height estimated from its line box (~24px), is named as a link', f.length === 1 && /link/.test(f[0].suggestion ?? ''), show(f)); + f = await findings('desktop-app-handbuilt-target', [frame('back', [{ id: 'bi', name: 'bi', type: 'icon', icon: 'arrow-left', iconSize: 14 }, text('bt', 'Go back to the gallery page', 13)], { layout: 'horizontal', padding: [4, 6] })]); + check('FR-C2: an icon with a five-word label is not click-shaped', f.length === 0, show(f)); + + // Spec change S2 — the bordered text button an import produces. + const textButton = (extra: Partial) => frame('archive', [text('at', 'Archive', 13)], { padding: [6, 14], ...extra }); + f = await findings('desktop-app-handbuilt-target', [textButton({ stroke: '#D1D5DB' })]); + check('S2: a bordered, padded frame with one short label (~28px) is named as a button', f.length === 1 && /×28px/.test(f[0].message) && /button/.test(f[0].suggestion ?? ''), show(f)); + f = await findings('desktop-app-handbuilt-target', [textButton({ fill: '#F3F4F6' })]); + check('S2: the same frame with a fill and no border (a chip) is silent', f.length === 0, show(f)); + f = await findings('desktop-app-handbuilt-target', [textButton({ stroke: 'transparent' })]); + check('S2: a transparent stroke is no border', f.length === 0, show(f)); + f = await findings('desktop-app-handbuilt-target', [textButton({ stroke: '#D1D5DB', padding: 0 })]); + check('S2: an unpadded bordered label is not button-shaped', f.length === 0, show(f)); + f = await findings('desktop-app-handbuilt-target', [textButton({ stroke: '#D1D5DB', padding: [10, 14] })]); + check('S2: a bordered text button 36px tall is silent', f.length === 0, show(f)); + + const fixture = JSON.parse(readFileSync('test-fixtures/viewer-baseline/detail-web-dashboard.json', 'utf8')) as Canvas; + fixture.metadata = { ...(fixture.metadata ?? {}), surface: { type: 'desktop-app', device: 'window-1440' } }; + const r = await evaluateCanvas(fixture, { mode: 'fast', categories: ['usability'] }); + const named = r.issues.filter((i) => i.rule === 'desktop-app-handbuilt-target'); + const byId = new Map(); + (function walk(n: SceneNode) { byId.set(n.id, n); n.children?.forEach(walk); })(fixture.root); + const labels = named.map((i) => byId.get(i.nodeId)?.children?.[0]?.content); + const toolbar = ['Mobile', 'Tablet', 'Desktop', 'Compare', 'Fit', 'JSON', 'Comment', 'Archive', 'Delete']; + check('FR-C2: the baseline detail fixture reports its hand-built toolbar as infos', toolbar.every((l) => labels.includes(l)) && named.every((i) => i.severity === 'info'), JSON.stringify(labels)); + const web = await findings('desktop-app-handbuilt-target', [iconFrame('gear', 24)], 'web'); + check('FR-C2: silent on web', web.length === 0, show(web)); +} + +// ── FR-C3: desktop-app-icon-label ────────────────────────────────────────── +{ + const iconBtn = (extra: Partial = {}): SceneNode => ({ id: 'b', name: 'b', type: 'button', icon: 'trash-2', size: 'xs', variant: 'ghost', ...extra }); + let f = await findings('desktop-app-icon-label', [iconBtn()]); + check('FR-C3: an icon-only button without ariaLabel warns', f.length === 1 && f[0].severity === 'warning', show(f)); + f = await findings('desktop-app-icon-label', [iconBtn({ ariaLabel: 'Delete' })]); + check('FR-C3: adding ariaLabel clears it', f.length === 0, show(f)); + f = await findings('desktop-app-icon-label', [iconBtn({ label: 'Delete' })]); + check('FR-C3: a labelled button with an icon is not icon-only', f.length === 0, show(f)); + f = await findings('desktop-app-icon-label', [nav('n', { collapsed: true, label: '', icon: 'home', active: true })]); + check('FR-C3: a collapsed nav-item with a blank label warns', f.length === 1, show(f)); + f = await findings('desktop-app-icon-label', [nav('n', { collapsed: true, label: 'Home', icon: 'home', active: true })]); + check('FR-C3: a collapsed nav-item with a label passes', f.length === 0, show(f)); + f = await findings('desktop-app-icon-label', [iconBtn()], 'web'); + check('FR-C3: silent on web', f.length === 0, show(f)); +} + +// ── FR-C4: desktop-app-current ───────────────────────────────────────────── +{ + const sidebar = (items: SceneNode[], extra: Partial = {}) => frame('sidebar', items, { width: 240, overflow: 'auto', ...extra }); + let f = await findings('desktop-app-current', [sidebar([nav('a', { active: true }), nav('b', { active: true }), nav('c')])]); + check('FR-C4: a sidebar with two active items warns', f.length === 1 && f[0].severity === 'warning' && /ambiguous/.test(f[0].message), show(f)); + f = await findings('desktop-app-current', [sidebar([nav('a'), nav('b'), nav('c')])]); + check('FR-C4: a sidebar with none warns', f.length === 1 && /None of the 3/.test(f[0].message), show(f)); + f = await findings('desktop-app-current', [sidebar([frame('s1', [nav('a', { active: true }), nav('b')]), frame('s2', [nav('c'), nav('d')])])]); + check('FR-C4: a sectioned sidebar with one active item in one section passes', f.length === 0, show(f)); + f = await findings('desktop-app-current', [sidebar([frame('s1', [nav('a', { active: true })]), frame('s2', [nav('c', { active: true })])])]); + check('FR-C4: one active item in EACH section of one pane warns (one group per pane)', f.length === 1, show(f)); + f = await findings('desktop-app-current', [sidebar([nav('a', { active: true }), nav('a1', { depth: 1, active: true }), nav('b')])]); + check('FR-C4: an active parent over its active child passes', f.length === 0, show(f)); + f = await findings('desktop-app-current', [sidebar([nav('a'), nav('a1', { depth: 1, active: true }), nav('a2', { depth: 1, active: true })])]); + check('FR-C4: two active children warn', f.length === 1, show(f)); + f = await findings('desktop-app-current', [sidebar([nav('a', { active: true })]), frame('other', [nav('x', { active: true }), nav('y')], { overflow: 'auto' })]); + check('FR-C4: two panes, each with one active item, pass', f.length === 0, show(f)); + f = await findings('desktop-app-current', [sidebar([nav('a', { active: true }), nav('b')]), nav('settings')]); + check('FR-C4: a lone item in another pane is not a group', f.length === 0, show(f)); + + const tabs = (active: boolean[]): SceneNode => ({ id: 't', name: 'Inspector tabs', type: 'tabs', items: active.map((a, i) => ({ label: `Tab ${i + 1}`, active: a })) }); + f = await findings('desktop-app-current', [tabs([false, true, false])]); + check('FR-C4: tabs with exactly one active tab pass', f.length === 0, show(f)); + f = await findings('desktop-app-current', [tabs([false, false, false])]); + check('FR-C4: tabs with no active tab warn', f.length === 1, show(f)); + f = await findings('desktop-app-current', [tabs([true, true, false])]); + check('FR-C4: tabs with two active tabs warn', f.length === 1, show(f)); + + const row = (id: string, depth: number, active = false): SceneNode => ({ id, name: id, type: 'tree-row', label: id, depth, active }); + f = await findings('desktop-app-current', [frame('tree', [row('r1', 0, true), row('r2', 1), row('r3', 1, true)])]); + check('FR-C4: two active rows in one tree warn', f.some((i) => i.severity === 'warning'), show(f)); + f = await findings('desktop-app-current', [frame('tree', [row('r1', 0), row('r2', 1, true), row('r3', 1)])]); + check('FR-C4: one active row in a two-level tree passes', f.length === 0, show(f)); + f = await findings('desktop-app-current', [frame('tree', [row('r1', 0), row('r2', 1), row('r3', 2, true)])]); + check('FR-C4: a current row in a tree nesting three levels is an info', f.length === 1 && f[0].severity === 'info', show(f)); + f = await findings('desktop-app-current', [frame('tree', [row('r1', 0), row('r2', 1), row('r3', 2)])]); + check('FR-C4: the same tree with no current row is silent (a file tree, not navigation)', f.length === 0, show(f)); + f = await findings('desktop-app-current', [sidebar([nav('a', { active: true }), nav('b', { active: true })])], 'web'); + check('FR-C4: silent on web', f.length === 0, show(f)); +} + +// ── FR-C5: desktop-app-type-ladder ───────────────────────────────────────── +{ + const sizes = (...px: number[]) => px.map((s, i) => text(`t${i}`, 'Label', s)); + let f = await findings('desktop-app-type-ladder', sizes(12, 13, 14)); + check('FR-C5: 12/13/14 passes', f.length === 0, show(f)); + f = await findings('desktop-app-type-ladder', sizes(14, 32)); + check('FR-C5: 14→32 passes (2.29)', f.length === 0, show(f)); + f = await findings('desktop-app-type-ladder', sizes(13, 36)); + check('FR-C5: 13→36 warns (2.77)', f.length === 1 && /2\.77/.test(f[0].message), show(f)); + f = await findings('desktop-app-type-ladder', sizes(20, 21)); + check('FR-C5: 20→21 warns (above 16px, a step needs 1.1)', f.length === 1, show(f)); + f = await findings('desktop-app-type-ladder', sizes(16, 20)); + check('FR-C5: 16→20 passes (a 4px step from 16)', f.length === 0, show(f)); + f = await findings('desktop-app-type-ladder', sizes(13, 36), 'desktop-app', { typography: { a: { fontSize: 13 }, b: { fontSize: 36 } } } as Canvas['variables']); + check('FR-C5: a pinned pair is not judged', f.length === 0, show(f)); + f = await findings('desktop-app-type-ladder', [text('t', 'Tag', 10), text('u', 'Body', 14)]); + check('FR-C5: a 10px label warns', f.some((i) => /10px — below the 11px/.test(i.message)), show(f)); + f = await findings('desktop-app-type-ladder', [text('t', 'Tag', 11), text('u', 'Body', 14)]); + check('FR-C5: an 11px label passes', f.length === 0, show(f)); + f = await findings('desktop-app-type-ladder', [text('t', 'This hint sets five words', 11), text('u', 'Body', 14)]); + check('FR-C5: five words at 11px warn', f.length === 1 && /prose below 12px/.test(f[0].message), show(f)); + f = await findings('desktop-app-type-ladder', [text('t', 'This hint sets five words', 12), text('u', 'Body', 14)]); + check('FR-C5: five words at 12px pass', f.length === 0, show(f)); + const bodyVars = (size: number) => ({ typography: { body: { fontSize: size } } }) as Canvas['variables']; + f = await findings('desktop-app-type-ladder', [text('t', 'Body', '$body' as unknown as number)], 'desktop-app', bodyVars(12)); + check('FR-C5: the body role at 12px warns', f.length === 1 && /body role at 12px/.test(f[0].message), show(f)); + f = await findings('desktop-app-type-ladder', [text('t', 'Body', '$body' as unknown as number)], 'desktop-app', bodyVars(13)); + check('FR-C5: the body role at 13px passes', f.length === 0, show(f)); + f = await findings('desktop-app-type-ladder', [...sizes(13, 36), text('x', 'Tag', 10)], 'web'); + check('FR-C5: silent on web (web keeps type-scale-ratio)', f.length === 0, show(f)); +} + +// ── FR-C6: desktop-app-row-rhythm (fast: authored heights) ───────────────── +{ + const cell = (id: string, content: string) => text(id, content, 13); + const row = (id: string, h: number | undefined, cells: SceneNode[]) => frame(id, cells, { layout: 'horizontal', ...(h === undefined ? {} : { height: h }) }); + const table = (headerH: number | undefined, bodyHs: (number | undefined)[]) => frame('users', [ + row('head', headerH, [cell('h1', 'Name'), cell('h2', 'Role'), cell('h3', 'Status')]), + ...bodyHs.map((h, i) => row(`r${i}`, h, [cell(`r${i}a`, `Ada ${i}`), cell(`r${i}b`, 'Admin'), cell(`r${i}c`, 'Active')])), + ]); + let f = await findings('desktop-app-row-rhythm', [table(40, [32, 32, 32])]); + check('FR-C6: a 40px header over 32px rows warns', f.length === 1 && f[0].severity === 'warning' && /40px tall over 32px/.test(f[0].message), show(f)); + f = await findings('desktop-app-row-rhythm', [table(32, [32, 32, 32])]); + check('FR-C6: a header matching its rows passes', f.length === 0, show(f)); + f = await findings('desktop-app-row-rhythm', [table(33, [32, 32, 32])]); + check('FR-C6: 1px off is within tolerance', f.length === 0, show(f)); + f = await findings('desktop-app-row-rhythm', [table(32, [32, 40, 32, 32])]); + check('FR-C6: one 40px body row among 32px rows is an info', f.length === 1 && f[0].severity === 'info' && f[0].nodeId === 'r1', show(f)); + f = await findings('desktop-app-row-rhythm', [table(undefined, [undefined, undefined, undefined])]); + check('FR-C6: fast mode is silent on rows without authored heights', f.length === 0, show(f)); + const twoLine = (id: string, h: number) => frame(id, [frame(`${id}-who`, [cell(`${id}-t`, 'Ada Lovelace'), cell(`${id}-s`, 'ada@example.com')]), cell(`${id}-r`, 'Admin'), cell(`${id}-st`, 'Active')], { layout: 'horizontal', height: h }); + f = await findings('desktop-app-row-rhythm', [frame('users', [row('head', 32, [cell('h1', 'Name'), cell('h2', 'Role'), cell('h3', 'Status')]), row('r0', 32, [cell('a', 'Ada'), cell('b', 'Admin'), cell('c', 'Active')]), row('r1', 32, [cell('d', 'Bo'), cell('e', 'Admin'), cell('f', 'Active')]), twoLine('r2', 48), twoLine('r3', 48)])]); + check('FR-C6: two-line rows are compared only with each other', f.length === 0, show(f)); + f = await findings('desktop-app-row-rhythm', [table(40, [32, 32, 32])], 'web'); + check('FR-C6: silent on web', f.length === 0, show(f)); +} + +// ── FR-C7: desktop-app-truncation (fast clauses) ─────────────────────────── +{ + const cell = (id: string, content: string, extra: Partial = {}) => text(id, content, 13, extra); + const row = (id: string, cells: SceneNode[]) => frame(id, cells, { layout: 'horizontal' }); + const table = (headerExtra: Partial) => frame('users', [ + row('head', [cell('h1', 'Name', headerExtra), cell('h2', 'Role'), cell('h3', 'Status')]), + ...[0, 1, 2].map((i) => row(`r${i}`, [cell(`r${i}a`, `Ada ${i}`, { textOverflow: 'ellipsis', title: `Ada ${i}` }), cell(`r${i}b`, 'Admin'), cell(`r${i}c`, 'Active')])), + ]); + let f = await findings('desktop-app-truncation', [table({ textOverflow: 'ellipsis' })]); + check('FR-C7: a truncating column header warns', f.length === 1 && f[0].severity === 'warning' && f[0].nodeId === 'h1', show(f)); + f = await findings('desktop-app-truncation', [table({})]); + check('FR-C7: a header that does not truncate (and titled body cells) is silent', f.length === 0, show(f)); + f = await findings('desktop-app-truncation', [nav('Projects with a very long name indeed', { active: true, width: 120 })]); + check('FR-C7: a truncating nav-item label is silent', f.length === 0, show(f)); + f = await findings('desktop-app-truncation', [cell('t', 'A long file name.png', { textOverflow: 'ellipsis', width: 80 })]); + check('FR-C7: a hand-built ellipsis with no title is an info', f.length === 1 && f[0].severity === 'info', show(f)); + f = await findings('desktop-app-truncation', [cell('t', 'A long file name.png', { textOverflow: 'ellipsis', width: 80, title: 'A long file name.png' })]); + check('FR-C7: the same text with a title is silent', f.length === 0, show(f)); + f = await findings('desktop-app-truncation', [table({ textOverflow: 'ellipsis' })], 'web'); + check('FR-C7: silent on web', f.length === 0, show(f)); +} + +// ── FR-C8: desktop-app-primary-count ─────────────────────────────────────── +{ + const btn = (id: string, variant?: SceneNode['variant']): SceneNode => ({ id, name: id, type: 'button', label: id, size: 'sm', ...(variant ? { variant } : {}) }); + const toolbar = (buttons: SceneNode[]) => frame('toolbar', buttons, { layout: 'horizontal', gap: 8 }); + let f = await findings('desktop-app-primary-count', [toolbar([btn('Save', 'primary'), btn('Publish', 'primary')])]); + check('FR-C8: two primary buttons in one toolbar are an info', f.length === 1 && f[0].severity === 'info', show(f)); + f = await findings('desktop-app-primary-count', [toolbar([btn('Save', 'primary'), btn('Cancel', 'secondary')])]); + check('FR-C8: one primary and a secondary pass', f.length === 0, show(f)); + f = await findings('desktop-app-primary-count', [toolbar([btn('Save', 'primary'), btn('Publish')])]); + check('FR-C8: a button with no variant renders as primary and counts', f.length === 1, show(f)); + f = await findings('desktop-app-primary-count', [frame('main', [btn('Save', 'primary')], { overflow: 'auto' }), frame('side', [btn('Apply', 'primary')], { overflow: 'auto' })]); + check('FR-C8: one primary in each of two panes passes', f.length === 0, show(f)); + const card = (i: number) => frame('Card', [text(`ct${i}`, `Plan ${i}`), btn(`Choose ${i}`, 'primary')], { width: 200 }); + f = await findings('desktop-app-primary-count', [frame('grid', [1, 2, 3, 4, 5, 6].map(card), { layout: 'horizontal' })]); + check('FR-C8: a grid of six same-shaped cards, each with a primary, passes', f.length === 0, show(f)); + f = await findings('desktop-app-primary-count', [frame('grid', [1, 2].map(card), { layout: 'horizontal' })]); + check('FR-C8: two such cards are not a repeat (fewer than three) and count', f.length === 1, show(f)); + f = await findings('desktop-app-primary-count', [toolbar([btn('Save', 'primary'), { ...btn('Publish', 'primary'), disabled: true }])]); + check('FR-C8: a disabled primary does not count', f.length === 0, show(f)); + f = await findings('desktop-app-primary-count', [toolbar([btn('Save', 'primary'), btn('Publish', 'primary')])], 'web'); + check('FR-C8: silent on web', f.length === 0, show(f)); +} + +// ── FR-C10: form coverage counts text-inputs ─────────────────────────────── +{ + const input = (id: string): SceneNode => ({ id, name: id, type: 'text-input', placeholder: id }); + const coverage = async (children: SceneNode[], states: string[] = []) => + (await evaluateCanvas(canvasOf(children), { mode: 'fast', categories: ['coverage'], designedStates: states })).issues.filter((i) => i.category === 'coverage'); + let f = await coverage([input('a'), input('b'), input('c')]); + check('FR-C10: three text-inputs demand an error variant', f.length === 1 && /"error"/.test(f[0].message), show(f)); + f = await coverage([input('a'), input('b'), { id: 'cb', name: 'cb', type: 'checkbox' }]); + check('FR-C10: two text-inputs and a checkbox demand one too', f.length === 1, show(f)); + f = await coverage([input('a'), input('b')]); + check('FR-C10: two text-inputs alone demand nothing', f.length === 0, show(f)); + f = await coverage([input('a'), input('b'), input('c')], ['error']); + check('FR-C10: the same form with an error variant is silent', f.length === 0, show(f)); + const web = (await evaluateCanvas(canvasOf([input('a'), input('b'), input('c')], 'web'), { mode: 'fast', categories: ['coverage'] })).issues; + check('FR-C10: counts on every type (web too)', web.length === 1, show(web)); + check('FR-C10: drift\'s inventory still counts no text-input as a control', extractInventory(canvasOf([input('a'), input('b'), input('c')]).root).counts.controls === 0); +} + +console.log(allPass ? '\nALL PASS' : '\nSOME FAILED'); +process.exit(allPass ? 0 : 1); diff --git a/test-desktop-app.ts b/test-desktop-app.ts index 9231d3b..dea479c 100644 --- a/test-desktop-app.ts +++ b/test-desktop-app.ts @@ -11,7 +11,7 @@ import './test-env.js'; import { readFileSync, readdirSync } from 'node:fs'; import { createHash } from 'node:crypto'; import { createCanvas } from './src/scene-graph.js'; -import { surfaceFor, resolveSurface, RULESETS } from './src/surfaces.js'; +import { surfaceFor, resolveSurface, RULESETS, DESKTOP_APP_RULES } from './src/surfaces.js'; import { evaluateCanvas, foldIssues, contrastRatio, parseColor, type EvaluationIssue } from './src/evaluate.js'; import { extractInventory } from './src/drift.js'; import { summarizeImportReport, type ImportReport } from './src/import.js'; @@ -61,8 +61,12 @@ const text = (id: string, content: string, fontSize: number): SceneNode => ({ id const ratio = (r: typeof web) => r.issues.filter((i) => i.rule === 'type-scale-ratio'); check('web keeps the ratio check, tagged type-scale-ratio', ratio(web).length >= 1, JSON.stringify(ratio(web).map((i) => i.message))); check('desktop-app turns type-scale-ratio off', ratio(app).length === 0 && app.surface.rulesOff.includes('type-scale-ratio'), JSON.stringify(app.surface)); - check('desktop-app rulesOn carries the base artboard rules', JSON.stringify(app.surface.rulesOn) === JSON.stringify(['desktop-app-artboard', 'mobile-artboard']), JSON.stringify(app.surface.rulesOn)); - check('the desktop-app row registers only what has a check today', JSON.stringify(RULESETS.type['desktop-app']) === JSON.stringify({ enable: [], disable: ['type-scale-ratio'] })); + // FR-A3 — rulesOn lists every desktop-app-* id registered so far (slice C + // registered the app rules), plus the base artboard rules. + const appIds = [...DESKTOP_APP_RULES]; + check('desktop-app rulesOn carries every desktop-app rule and the base artboard rules', JSON.stringify(app.surface.rulesOn) === JSON.stringify([...appIds, 'desktop-app-artboard', 'mobile-artboard'].sort()), JSON.stringify(app.surface.rulesOn)); + check('the desktop-app row enables the app rules and replaces type-scale-ratio', JSON.stringify(RULESETS.type['desktop-app']) === JSON.stringify({ enable: appIds, disable: ['type-scale-ratio'] })); + check('web and mobile run no desktop-app rule but the artboard', [web.surface.rulesOn].every((on) => on.every((id) => !id.startsWith('desktop-app-') || id === 'desktop-app-artboard')), JSON.stringify(web.surface.rulesOn)); } // ── desktop-app-artboard ──────────────────────────────────────────────────── From e8c5715dcda5a866add6a4bda112ca6c0bd343fb Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Fri, 13 Nov 2026 21:21:23 +0100 Subject: [PATCH 2/4] Fix the verify round 1 findings and name icon-only links Select-all headers stay headers, fast estimates honour min sizes and stacked captions, fluid link widths stay unknown, primaries are what renders filled, the ladder reads string sizes, and findings fold. Spec change S3: link renders ariaLabel and FR-C3 checks icon-only links. --- README.md | 16 ++-- docs/GUIDELINES.md | 24 ++--- docs/specs/PHASE-31-SPEC.md | 12 +-- src/desktop-app-rules.ts | 48 ++++++---- src/index.ts | 10 +-- src/primitives.ts | 5 +- src/renderer.ts | 3 + src/types.ts | 2 +- test-desktop-app-rules-detailed.ts | 10 +++ test-desktop-app-rules.ts | 140 ++++++++++++++++++++++++++++- 10 files changed, 218 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 18bd9a8..1537973 100644 --- a/README.md +++ b/README.md @@ -386,7 +386,7 @@ 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 | +| `link` | `label`, `icon`, `iconPosition`, `external`, `ariaLabel` | A standalone text action, at least 24 tall. With no `label` it hugs its glyphs (14px wide, 30 with `external`) and needs an `ariaLabel` (rendered as `aria-label` and `title`). A `text` node can hold inline links instead: `links: [{ start, end }]` character ranges of its content, drawn underlined and exempt from the 24px floor | | `text-input` | `value`, `placeholder`, `icon`, `size` (`sm` 32 / `md` 40), `rows`, `error` (a message), `disabled` | A field whose border (`$border-strong` when the design system has it) is its only boundary; `error` draws an icon and the message below and turns the border `$danger` | | `nav-item` | `label`, `icon`, `count`, `dotColor`, `active`, `depth` (0 / 1), `collapsed` | A 32px sidebar row. `active` draws an `$accent-tint` fill, a 2px `$accent` bar and a heavier label; `collapsed` is the 32×32 rail form, with the label as its accessible name; `dotColor` is an identity dot, never counted as an accent | | `tabs` | `items: [{ label, count?, active?, disabled? }]`, `variant` (`line` / `contained`), `size` (`sm` 32 / `md` 40) | One tablist; each tab is its own target. The active tab gets an indicator (`line`) or an `$accent-tint` fill (`contained`) | @@ -487,7 +487,7 @@ Get computed bounding boxes via browser rendering. | `nodeId` | string? | Root node to start from | | `maxDepth` | number? | Max depth (default 10) | -Returns `{ nodeId, x, y, width, height, children? }` per node — plus, on any node whose content exceeds its box, overflow data (`scrollWidth`/`clientWidth`/`scrollHeight`/`clientHeight` and an `ellipsis` flag for designed truncation): the same capture `canvas_stress` uses to detect clipping. +Returns `{ nodeId, x, y, width, height, children? }` per node — plus, on any node whose content exceeds its box, overflow data (`scrollWidth`/`clientWidth`/`scrollHeight`/`clientHeight` and an `ellipsis` flag for designed truncation): the same capture `canvas_stress` uses to detect clipping. On a primitive, `truncated: true` when one of its own labels is cut by its ellipsis, and `labels` (`[{ chars, scrollWidth, clientWidth }]`, one per own label, in order) on every `tabs` node and on any primitive with a cut label. ### `generate_scale` @@ -896,15 +896,15 @@ Every result also carries a **`surface`** field: `{ type, device, source, rulesO | `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 / 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`. | -| `desktop-app-target` | usability | warning / error | Desktop-app only: the 24px floor (the `usability` row under Categories below), under its rule id. Fast mode warns on a target under 24px; detailed mode errors when its 24px circle reaches a neighbour. An unlabelled `link` measures its glyphs (14px wide). | -| `desktop-app-handbuilt-target` | usability | info | Desktop-app only: a frame below 32px holding one icon, an icon plus a label of up to three words, or (bordered and padded) one such label alone, the shape an imported text button takes. Rebuild it as a `button` or `link` if it is clickable. | -| `desktop-app-icon-label` | usability | warning | Desktop-app only: an icon-only `button` with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`. | -| `desktop-app-current` | usability | warning / info | Desktop-app only: in one pane (a frame with `overflow: "auto"`, or the root), two active `nav-item`s at one depth, or two or more with none active; a `tabs` node with no active tab or more than one; two active `tree-row`s under one parent. A tree with a current row that nests past two levels is an info. | +| `type-scale-ratio` | typography | warning | On by default: adjacent font sizes stepping by a ratio below 1.1 or above 2.0 (pinned typography tokens skip it). The desktop-app ruleset turns it off, since dense apps step 12 / 13 / 14 on purpose; it then appears in `rulesOff`, and `desktop-app-type-ladder` judges the sizes instead. | +| `desktop-app-target` | usability | warning / error | Desktop-app only: the 24px floor (the `usability` row under Categories below), under its rule id. Fast mode warns on a target under 24px in either dimension; detailed mode errors when its 24px circle reaches a neighbour. An unlabelled `link` with no authored width is measured at its glyphs (14px wide, 30 with `external`), on web too. | +| `desktop-app-handbuilt-target` | usability | info | Desktop-app only: a frame below 32px holding one icon, an icon plus a label of up to three words, or (bordered and padded) one such label alone, the shape an imported text button takes. Frames inside a clickable primitive or a `property-row` are never counted. Rebuild it as a `button` or `link` if it is clickable. | +| `desktop-app-icon-label` | usability | warning | Desktop-app only: an icon-only `button` or `link` with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`. | +| `desktop-app-current` | usability | warning / info | Desktop-app only: in one pane (a frame with `overflow: "auto"`, or the root; each node belongs to its nearest), two active `nav-item`s at one depth, or two or more with none active (give each navigation region its own scrolling pane); a `tabs` node with no active tab or more than one; two active `tree-row`s under one parent. A tree with a current row that nests past two levels is an info. | | `desktop-app-type-ladder` | typography | warning | Desktop-app only, replacing `type-scale-ratio`: adjacent sizes a < b step by at most 4px while a ≤ 16, else by a ratio of 1.1 to 2.5 (pinned token pairs skip). Also text below 11px, prose of five or more words below 12px, and a `$body` text below 13px. | | `desktop-app-row-rhythm` | consistency | warning / info | Desktop-app only, on detected tables: a header row more than 1px off the one-line body rows warns; a body row off its siblings is an info (title-over-subtitle rows compared only with each other); detailed mode adds a cell off its column's left edge as an info. Fast mode reads authored heights only. | | `desktop-app-truncation` | usability | warning / info | Desktop-app only: a truncating column header warns; a hand-built ellipsis with no `title` is an info. Detailed mode: a `tabs` node whose every label is cut warns, and an ellipsis leaving fewer than four characters is an info. | -| `desktop-app-primary-count` | structure | info | Desktop-app only: two or more primary `button`s (`variant: "primary"` or no variant) in one pane. Primaries inside three or more same-shaped sibling frames, such as a card grid, don't count. | +| `desktop-app-primary-count` | structure | info | Desktop-app only: two or more primary `button`s in one pane (any variant but `secondary`, `ghost` or `destructive` renders filled, so it counts; no variant included). Primaries inside three or more same-shaped sibling frames, such as a card grid, don't count. | 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. diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 151d90a..a43290f 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -75,23 +75,25 @@ None of these rules has a mechanical fix, so `canvas_autofix` never proposes one ## The desktop-app ruleset -A `desktop-app` canvas is judged as an application, not a page. Its vocabulary is in [Desktop-app vocabulary](#desktop-app-vocabulary); layouts, overlays and element states come in later slices of Phase 31. Each finding from these rules names its rule in a `rule` field, and the `surface` report lists them in `rulesOn`. Errors and warnings block the directive; infos never do. Fast mode is the loop; before presenting, also run `canvas_evaluate({ canvasId, mode: "detailed" })`, which measures rendered rows, column edges and truncation. None of these rules has a mechanical fix, so `canvas_autofix` proposes none. +A `desktop-app` canvas is judged as an application, not a page. Its vocabulary is in [Desktop-app vocabulary](#desktop-app-vocabulary); layouts, overlays and element states come in later slices of Phase 31. Each finding from these rules names its rule in a `rule` field, and the `surface` report lists them in `rulesOn`. Only `desktop-app-artboard` runs on web and mobile; the other `desktop-app-*` rules run on desktop-app canvases only. Errors and warnings block the directive (the gate on presenting); infos never do. Fast mode is the loop; before presenting, also run `canvas_evaluate({ canvasId, mode: "detailed" })`, which measures rendered rows, column edges and truncation. Nodes inside a component instance are judged as rendered and reported on the instance. None of these rules has a mechanical fix, so `canvas_autofix` proposes none. -- **`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. +Two terms the rules share. A **pane** is a frame that scrolls on its own (`overflow: "auto"`), or the root; every node belongs to its nearest pane. App panes scroll independently, so give each navigation region (a rail, a sidebar, a list) its own pane. **Prose** is text of five or more words, where a word holds letters and no digits (figures and their units are not words). + +- **`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 and replaces it with `desktop-app-type-ladder` below; it is listed in the `surface` report's `rulesOff`. Pinned typography tokens still skip the check on every type. - **`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. -- **`desktop-app-target`** (usability). [The 24px floor](#the-24px-floor-web-and-desktop-app) under its rule id: a target below 24px **warns** in fast mode, and is an **error** in detailed mode when its 24px circle reaches a neighbour. Web runs the same check without the id. A `link` with no label hugs its glyphs, so it is measured at 14px wide (30 with `external`): give it a label, or keep its neighbours out of its circle. -- **`desktop-app-handbuilt-target`** (usability, info). A frame below 32px in either dimension that holds one icon, an icon plus a label of three words or fewer, or, when it has a border (`stroke`) and padding, one such label alone (the shape an imported text button takes). It never blocks, because a frame can't say it is decorative. If it is clickable, rebuild it as a `button` (`xs` or `sm`; icon-only with `ariaLabel`) or a `link`. Fast mode estimates a missing height from the icon or the label's line box plus padding; detailed mode measures the render. A frame inside a `property-row` is never hand-built. -- **`desktop-app-icon-label`** (usability, **warning**). An icon-only `button` (no `label`, an `icon`) with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`: an action with no name for a screen reader or a tooltip. +- **`desktop-app-target`** (usability). [The 24px floor](#the-24px-floor-web-and-desktop-app) under its rule id: a target below 24px in either dimension **warns** in fast mode, and is an **error** in detailed mode when its 24px circle reaches a neighbour. Web runs the same check without the id, including this: a `link` with no label and no authored width hugs its glyphs, so it is measured at 14px wide (30 with `external`) and 24 tall. Give it a label, or keep its neighbours out of its circle. +- **`desktop-app-handbuilt-target`** (usability, info). A frame below 32px in either dimension that holds one icon, an icon plus a label of three words or fewer, or, when it has a border (`stroke`) and padding, one such label alone (the shape an imported text button takes). It never blocks, because a frame can't say it is decorative. If it is clickable, rebuild it as a `button` (`xs` or `sm`; icon-only with `ariaLabel`) or a `link`. Fast mode estimates a missing height from the icon or the label's line box plus padding; detailed mode measures the render. Fast mode honours `minWidth` / `minHeight` and adds up an icon stacked over a caption. A frame inside a clickable primitive or a `property-row` is never hand-built. +- **`desktop-app-icon-label`** (usability, **warning**). An icon-only `button` or `link` (no `label`, an `icon`) with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`: an action with no name for a screen reader or a tooltip. - **`desktop-app-current`** (usability). The current location must be unambiguous. - - Navigation: all `nav-item`s in one pane (a frame with `overflow: "auto"`, or the root) are one group, whatever section frames they sit in. Two active items at the same depth **warn**; a group of two or more with none active **warns**. An active parent (depth 0) over its active child (depth 1) passes, and a lone item in another pane is not a group. + - Navigation: all `nav-item`s in one pane are one group, whatever section frames they sit in. Two active items at the same depth **warn**; a group of two or more with none active **warns**. An active parent (depth 0) over its active child (depth 1) passes, and a lone item in another pane is not a group. So a rail beside a sidebar needs each in its own pane, and a list of actions is `menu-row`s, not `nav-item`s. - A `tabs` node with no active tab, or more than one, **warns**. - `tree-row`s under one parent are one tree: two active rows **warn**. A tree with a current row that nests past two levels (depth 2 or more) is an **info**: as navigation, more than two levels is hard to keep a place in; a file tree may ignore it. -- **`desktop-app-type-ladder`** (typography, **warning**), replacing `type-scale-ratio`. For each pair of adjacent distinct sizes a < b: it passes when a ≤ 16 and b − a ≤ 4, else when b / a is between 1.1 and 2.5. So 12 / 13 / 14 and 14 → 32 pass and 13 → 36 warns. A pair of pinned typography token sizes skips the check. Separately: any text below 11px, prose of five or more words below 12px, and a text whose `fontSize` is `$body` resolving below 13px each warn. -- **`desktop-app-row-rhythm`** (consistency), on detected tables. A header row (its content is text) more than 1px taller or shorter than the one-line body rows **warns**, as Carbon sets them equal. A body row more than 1px off its siblings is an **info**; rows with a title over a subtitle are compared only with each other. Detailed mode adds a cell whose left edge is more than 1px off its column as an **info**. Fast mode reads authored `height`s only, so rows sized by padding are judged in detailed mode. +- **`desktop-app-type-ladder`** (typography, **warning**), replacing `type-scale-ratio`. For each pair of adjacent distinct sizes a < b: it passes when a ≤ 16 and b − a ≤ 4, else when b / a is between 1.1 and 2.5. So 12 / 13 / 14 and 14 → 32 pass and 13 → 36 warns. A pair of pinned typography token sizes skips the check. Sizes are read as rendered (`"14px"` counts; a `clamp()` reads as its minimum). Separately: any text below 11px, prose below 12px, and a text whose `fontSize` is `$body` resolving below 13px each warn, one finding per text. +- **`desktop-app-row-rhythm`** (consistency), on detected tables. A header row (its content is text, plus icons and controls such as a select-all checkbox) more than 1px taller or shorter than the one-line body rows **warns**, as Carbon sets them equal. A body row more than 1px off its siblings is an **info**; rows with a title over a subtitle are compared only with each other. Detailed mode adds a cell whose left edge is more than 1px off its column as an **info**. Fast mode reads authored `height`s only, so rows sized by padding are judged in detailed mode. - **`desktop-app-truncation`** (usability). A column header text with `textOverflow: "ellipsis"` **warns**: a header is never cut. A hand-built text with an ellipsis and no `title` is an **info**, since the full text must be reachable (primitives add their own `title`). Detailed mode adds: a `tabs` node whose every label is cut **warns** (tabs shrink to fit their tablist, so too many tabs in too little width leaves nothing readable), and an ellipsis that leaves fewer than four visible characters, on a text or a primitive's label, is an **info**. -- **`desktop-app-primary-count`** (structure, info). Two or more primary `button`s in one pane. A button with no `variant` renders as primary and counts; a disabled one doesn't. Primaries inside three or more same-shaped sibling frames (a grid of cards) are each card's own and don't count. +- **`desktop-app-primary-count`** (structure, info). Two or more primary `button`s in one pane. Any variant but `secondary`, `ghost` or `destructive` renders filled with the accent, so it counts (no variant included); a disabled one doesn't. Primaries inside three or more same-shaped sibling frames (a grid of cards) are each card's own and don't count. 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. @@ -109,7 +111,7 @@ Mobile keeps its own 44px rule (`mobile-touch-target`), which has no spacing exc Build application screens from these primitives, never from hand-built frames: a frame is not a measured target, and none of the app rules can see it. They sit on the 24 / 32 / 40 / 48 density ladder and take their colours from `$accent`, `$accent-tint`, `$border`, `$border-strong`, `$text-primary`, `$text-secondary` and `$danger` (neutral fallbacks unthemed; `fill`, `stroke`, `color`, `iconColor`, `secondaryColor` override). Labels truncate to one line with an ellipsis and keep their full text as a `title`, so `canvas_stress` reports a designed truncation, not a clip. - **`button` at `size: "xs"`** is the 24px icon button of a dense toolbar. An icon-only button (no `label`) takes `ariaLabel` as its accessible name: it renders `aria-label` and `title` and is never drawn. `xs`, like `sm`, is an error on a phone. -- **`link`** `{ label, icon?, iconPosition?, external? }` 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. +- **`link`** `{ label, icon?, iconPosition?, external?, ariaLabel? }` is a standalone text action, at least 24 tall, and a measured target. Without a `label` it hugs its glyphs (14px wide, 30 with `external`) and takes `ariaLabel` as its name (rendered as `aria-label` and `title`). For a link inside a sentence, keep it in the `text` node: `links: [{ start, end }]` marks character ranges of its `content`, drawn underlined. Inline links are exempt from the 24px floor, as WCAG exempts them. A `text` node also takes `title`, rendered as a tooltip. - **`text-input`** `{ value?, placeholder?, icon?, size?: "sm" | "md", rows?, error?, disabled? }` is a field (32 or 40 tall; `rows` makes it multi-line). Its border is its only boundary, so it uses `$border-strong` when the design system has one. `error` turns the border `$danger` and draws an icon and the message below the field, so the error is never colour alone. - **`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. @@ -397,7 +399,7 @@ The happy path of one static frame with ideal data is half a design. Real UX liv | `loading` | `skeleton-table` / `skeleton-card` / `skeleton-stat-card` | Real header + `skeleton` blocks matching the loaded geometry, so content lands without layout shift. Skeletons pulse only in the live viewer — screenshots stay static | | `error` | — | The form's validation-failure treatment: field messages + a summary. Design it; there's no generic scaffold because error copy is the design | -**The evaluator demands them.** The `coverage` category warns — directive-blocking — when a base canvas carries data-bearing content with no designed states: a detected table demands `empty` + `loading`; a form (3+ input controls: toggles, checkboxes, radios, selects and `text-input`s outside tables) demands `error`. (Table detection requires three matching horizontal rows — two stacked rows are a layout, not data — so the rare header-plus-one-row table goes undetected; name the frame `Table` to claim the shape explicitly. A list whose every row leads with an icon, a dot or a small image is navigation and never detects.) Variant canvases and non-data screens are silent. The result's `coverage: { dataBearing, states, missing }` tells you where you stand, and `canvas_list` shows the designed states per screen. +**The evaluator demands them.** The `coverage` category warns — directive-blocking — when a base canvas carries data-bearing content with no designed states: a detected table demands `empty` + `loading`; a form (3+ input controls: toggles, checkboxes, radios, selects and `text-input`s outside tables, on every type, so an inspector of three text fields counts too) demands `error`. (Table detection requires three matching horizontal rows — two stacked rows are a layout, not data — so the rare header-plus-one-row table goes undetected; name the frame `Table` to claim the shape explicitly. A list whose every row leads with an icon, a dot or a small image is navigation and never detects.) Variant canvases and non-data screens are silent. The result's `coverage: { dataBearing, states, missing }` tells you where you stand, and `canvas_list` shows the designed states per screen. **Then stress it.** `canvas_stress` re-renders the canvas under hostile-but-realistic content — `long-text` (×2.2 + an unbroken German compound), `i18n` (×1.4), `big-numbers` (`9` → `999+`, `$1.5M` → `$1,520,847.33`), `empty`, `many` (rows ×3) — and reports what broke, by node id: `clip` (info when a designed ellipsis is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; a sheet's own vertical overflow scrolls and is never a clip; warning otherwise), `overflow-x`, `layout-shift` (an untouched node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent, like a full-height sidebar next to a growing table, are all exempt). Only *new* breakage counts. Fix findings with the [width strategies](#width-strategies) above — fluid widths, `minWidth` or `minHeight` floors, wrapping — or give a must-stay-single-line label `textOverflow: "ellipsis"` (the designed-truncation property: the clip downgrades to info because truncating is the design) — and re-run until `CLEAN`. A data screen goes to the user with its states designed and a `CLEAN` stress verdict, the same way it goes with a >95 score. `canvas_evaluate` holds you to it: once stress has recorded a verdict, the evaluate result carries a `stress` field (`{ verdict, warnings, type, current }` — `current` is false after an edit or a type change since the run), and a `FRAGILE` verdict keeps the directive `NOT READY` until a full `CLEAN` run (all five perturbations) replaces it — a subset run can record `FRAGILE` but never clear it. The verdict lives in server memory, so a restart forgets it. diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index fe86895..44c87fd 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -83,9 +83,9 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **Clickable primitive**: `button`, `link`, `text-input`, `nav-item`, each tab of a `tabs` node, `tree-row`, `menu-row`, `list-row`, the four controls, Phase 30's `tab-bar` items and `nav-bar` actions, and the header close button and `actions` of a `modal` and the `action` of a `toast`. A node of any other type is never a target, even with `state` set. - **Target circle**: WCAG 2.5.8's test. An undersized target (below 24 in either dimension) passes when a 24px-diameter circle centred on its box intersects no other target's box and no other undersized target's circle. Circles that only touch do not intersect. A target nested inside another target (ancestor or descendant) is not its neighbour. Disabled targets are neither measured nor neighbours. -- **Pane**: a frame with `overflow: "auto"`, a `modal`, a `drawer`, or the root. -- **Navigation group**: within one pane, all `nav-item`s at depth 0 together, wherever their section frames sit; one `tabs` node is its own group. -- **Region**: the nearest pane. Primary buttons inside three or more sibling frames with the same shape hash (`shapeHash`, `src/project-evaluate.ts:80`), such as a grid of cards, are not counted toward their region. +- **Pane**: a frame with `overflow: "auto"`, a `modal`, a `drawer`, or the root. A node belongs to its nearest pane. (`modal` and `drawer` join with the overlay primitives in slice E.) +- **Navigation group**: within one pane, all `nav-item`s at depth 0 together, wherever their section frames sit; one `tabs` node is its own group. (As built, slice C F2: depth 0 and 1 together, two active at one depth warn.) +- **Region**: the nearest pane. Primary buttons inside three or more sibling frames with the same shape hash (`shapeHash`, moved to `src/shape-hash.ts` in slice C and read there without node names, F6), such as a grid of cards, are not counted toward their region. - **Element state**: a primitive's `state` property (FR-G1). **Screen state**: a variant canvas (`canvas_add_variant`). - **Fast / detailed mode, full tier**: as in Phase 30. Fast mode has no rendered rects; detailed mode adds `computeLayout`. @@ -113,8 +113,8 @@ One profile ships, keyed by id so a second size is one table row later. Values i | **FR-B9** | **`divider`.** `divider` (`orientation: 'horizontal' \| 'vertical'`, `inset?`): a 1px hairline in `$border`; vertical dividers separate panes. Not clickable. | A vertical divider between two panes renders 1px wide and full height. | | **FR-B10** | **Defaults, reuse, stress, titles.** Every new primitive's colors default through `applyControlDefaults` (`src/variables.ts:112`) in a branch of its own (today it branches on `MOBILE_PRIMITIVES`), so an unthemed canvas never crashes. The structure category's reuse advisory (`evaluate.ts:798`) counts the new primitives as reuse. Stress reaches their text through `PRIMITIVE_TEXT_PROPS` (`src/stress.ts:44`): `link.label`, `nav-item.label`, `tabs.items[].label`, `tree-row.label`, `menu-row.label`, `menu-row.shortcut`, `property-row.label`, `text-input.value`. Their labels truncate to one line with an ellipsis and a `title`, so stress reports designed truncation. `text` nodes gain `title?` (today `title` is documented for `nav-bar` and `list-row` only, `src/types.ts:283`), rendered as the `title` attribute. | Every new primitive renders unthemed in both themes with no console errors; long-text on each yields designed-truncation infos only; a `text` with `title` renders the attribute. | | **FR-C1** | **Every click target is measured on desktop-app.** Rule `desktop-app-target`: FR-A4's floor, error in detailed mode and warning in fast mode. | The baseline's "← Back", rebuilt as a `link` with no other target inside its circle, passes; packed against a neighbouring `link` it fails in detailed mode. | -| **FR-C2** | **Hand-built click targets are named, not gated.** Rule `desktop-app-handbuilt-target`, info: a frame whose only content is one icon, or one icon plus a label of three words or fewer, below 32px in either dimension, is a possible click target; the finding names `button` (icon-only, `xs` or `sm`) or `link`. It never blocks, mirroring Phase 30 FR-C2. A frame inside a clickable primitive is never hand-built. | The baseline detail fixture reports its hand-built toolbar icons as infos. | -| **FR-C3** | **Icon-only actions have names.** Rule `desktop-app-icon-label`, warning: an icon-only `button` with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`. (The `modal` close button carries a default name, FR-E2.) | An icon-only button without `ariaLabel` warns; adding one clears it. | +| **FR-C2** | **Hand-built click targets are named, not gated.** Rule `desktop-app-handbuilt-target`, info: a frame whose only content is one icon, or one icon plus a label of three words or fewer, or (spec change S2) a bordered, padded frame holding one such label alone, below 32px in either dimension, is a possible click target; the finding names `button` (icon-only, `xs` or `sm`) or `link`. It never blocks, mirroring Phase 30 FR-C2. A frame inside a clickable primitive is never hand-built. | The baseline detail fixture reports its hand-built toolbar icons as infos. | +| **FR-C3** | **Icon-only actions have names.** Rule `desktop-app-icon-label`, warning: an icon-only `button` or (spec change S3) `link` with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`. (The `modal` close button carries a default name, FR-E2.) | An icon-only button without `ariaLabel` warns; adding one clears it. | | **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. | @@ -244,6 +244,8 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **F8: the expanded render.** On desktop-app, detailed mode now renders the instance-expanded tree at depth 25 (as mobile does), so the rects every detailed check reads on a desktop-app canvas, the consistency overlap check included, carry the expanded ids. - **F9: categories.** `desktop-app-target`, `-handbuilt-target`, `-icon-label`, `-current` and `-truncation` report under usability, `-type-ladder` under typography, `-row-rhythm` under consistency, `-primary-count` under structure; each warning costs 10 in its category, infos nothing. - FR-C9 had nothing left for this slice: its overlay clause lands with the overlay primitives (slice E). +- **Spec change S3 (FR-C3, approved by Victor after verify round 1).** An icon-only `link` (an `icon`, no `label`) had no way to carry a name and passed FR-C3 silently, while F1 made it a measured target. `link` now renders `ariaLabel` as `aria-label` and `title` (as `button` does, never as text), and `desktop-app-icon-label` warns on an icon-only link without one. +- **Verify round 1 fixes.** (a) F4's header row also admits controls (a select-all checkbox, a toggle, a radio, a select) beside text and icons, so a select-all header keeps the header warnings of FR-C6 and FR-C7. (b) FR-C2's fast estimate honours `minWidth` / `minHeight`, and in a frame that is not horizontal adds an icon stacked over a caption (plus the gap) instead of taking the larger. (c) F1's glyph width applies only when no `width` is authored; a non-numeric width (`fill_container`, a percentage) stays unknown. (d) F6's primary is what renders filled: any `variant` but `secondary`, `ghost` or `destructive` (an unknown one included). (e) F3's ladder reads sizes as rendered (`fontPx`: `"14px"`, a `clamp()`'s minimum). (f) The `desktop-app-icon-label` and no-title truncation suggestions no longer embed the node id, so repeated findings fold. Accepted as specced: icon-only links on web now warn in fast mode (F1's census correction); three `text-input`s in an inspector demand an `error` variant (FR-C10 on every type, like three toggles); two navigation regions sharing one pane are one group (F2; the docs tell agents to give each its own pane); a tree split across wrapper frames is several trees; the deep-tree info fires on a file tree with a current row (info only). The FR-C7 short-tab info is subsumed when every label is cut (the warning fires instead); kept for tablists where only some labels are cut. **Slice D: panes (FR-D1 to FR-D3)** - `src/structures.ts:1834`, `:1863`: N-type listing and resolution; `covers()` for `desktop-app`. diff --git a/src/desktop-app-rules.ts b/src/desktop-app-rules.ts index 612647b..caf07c5 100644 --- a/src/desktop-app-rules.ts +++ b/src/desktop-app-rules.ts @@ -168,12 +168,18 @@ export function checkHandbuiltTargetsApp(ctx: DesktopContext): EvaluationIssue[] const rect = ctx.rects?.get(n.id); if (rect) return axis === 'width' ? rect.width : rect.height; const v = n[axis]; - if (isNum(v)) return v; + const min = axis === 'width' ? n.minWidth : n.minHeight; + const floor = isNum(min) ? min : 0; + if (isNum(v)) return Math.max(v, floor); if (v !== undefined || (axis === 'width' && s.label)) return undefined; const pad = paddingSides(n, ctx.profile.width); const icon = s.icon ? (isNum(s.icon.iconSize) ? s.icon.iconSize : 24) : 0; - const content = Math.max(icon, s.label ? lineBox(s.label) : 0); - return Math.round(content + (axis === 'width' ? pad.left + pad.right : pad.top + pad.bottom)); + const label = s.label ? lineBox(s.label) : 0; + // A frame stacks its children vertically unless it is horizontal, so a + // stacked icon and caption add up (with the gap between them). + const stacked = axis === 'height' && n.layout !== 'horizontal' && icon > 0 && label > 0; + const content = stacked ? icon + label + (isNum(n.gap) ? n.gap : 0) : Math.max(icon, label); + return Math.max(floor, Math.round(content + (axis === 'width' ? pad.left + pad.right : pad.top + pad.bottom))); }; (function walk(n: SceneNode) { if (CLICKABLE_PRIMITIVES.has(n.type) || n.type === 'property-row') return; @@ -203,20 +209,21 @@ export function checkHandbuiltTargetsApp(ctx: DesktopContext): EvaluationIssue[] // ── desktop-app-icon-label (FR-C3) ───────────────────────────────────────── -/** An icon-only button (blank label, an icon) with no ariaLabel, or a - * collapsed nav-item with a blank label: an action with no name. */ +/** An icon-only button or link (blank label, an icon) with no ariaLabel + * (spec change S3 added the link), or a collapsed nav-item with a blank + * label: an action with no name. */ export function checkIconLabels(ctx: DesktopContext): EvaluationIssue[] { const issues: EvaluationIssue[] = []; (function walk(n: SceneNode) { - if (n.type === 'button' && !hasText(n.label) && hasText(n.icon) && !hasText(n.ariaLabel)) { + if ((n.type === 'button' || n.type === 'link') && !hasText(n.label) && hasText(n.icon) && !hasText(n.ariaLabel)) { issues.push(issue('usability', 'desktop-app-icon-label', 'warning', n, - `Icon-only button "${nameOf(n)}" (icon "${n.icon}") has no name — a screen reader announces nothing, and a hover shows no tooltip.`, - `Give it an ariaLabel naming the action: U("${n.id}", { ariaLabel: "…" }). It renders as aria-label and title, never as visible text.`)); + `Icon-only ${n.type} "${nameOf(n)}" (icon "${n.icon}") has no name — a screen reader announces nothing, and a hover shows no tooltip.`, + 'Give it an ariaLabel naming the action (U(id, { ariaLabel: "…" })). It renders as aria-label and title, never as visible text.')); } if (n.type === 'nav-item' && n.collapsed === true && !hasText(n.label)) { issues.push(issue('usability', 'desktop-app-icon-label', 'warning', n, `Collapsed nav-item "${nameOf(n)}" has no label — in the rail form the label is its only name (aria-label and title).`, - `Give it the destination's name: U("${n.id}", { label: "…" }). The rail hides it visually.`)); + 'Give it the destination\'s name (U(id, { label: "…" })). The rail hides it visually.')); } n.children?.forEach(walk); })(ctx.root); @@ -307,14 +314,16 @@ export function checkTypeLadder(ctx: DesktopContext, rawById: Map n.fontSize).filter(isNum))].sort((a, b) => a - b); + // A size the renderer can read (a number, "14px", a clamp()'s minimum). + const px = (n: SceneNode) => fontPx(n.fontSize); + const sizes = [...new Set(texts.map(px).filter(isNum))].sort((a, b) => a - b); for (let i = 0; i < sizes.length - 1; i++) { const [a, b] = [sizes[i], sizes[i + 1]]; if (pinned.has(a) && pinned.has(b)) continue; if (a <= LADDER_SMALL && b - a <= LADDER_STEP) continue; const ratio = b / a; if (ratio >= LADDER_RATIO.min && ratio <= LADDER_RATIO.max) continue; - const at = texts.find((n) => n.fontSize === b)!; + const at = texts.find((n) => px(n) === b)!; issues.push(issue('typography', rule, 'warning', at, `Font sizes ${a}px → ${b}px step by ${ratio.toFixed(2)} — a dense app ladder steps by at most ${LADDER_STEP}px up to ${LADDER_SMALL}px, else by ${LADDER_RATIO.min}–${LADDER_RATIO.max}.`, ratio > LADDER_RATIO.max @@ -350,8 +359,11 @@ function rowsOf(table: SceneNode): SceneNode[] { && (table.name === 'Table' || c.layout === 'horizontal')); } -/** A header row: its content is text (icons allowed, such as a sort glyph), - * at least two texts. */ +/** Header cells may hold a sort glyph or a select-all control beside text. */ +const HEADER_EXTRAS = new Set(['icon', 'checkbox', 'toggle', 'radio', 'select']); + +/** A header row: its content is text, plus icons and controls (a sort glyph, + * a select-all checkbox), at least two texts. */ function isHeaderRow(row: SceneNode): boolean { let texts = 0; let other = false; @@ -359,7 +371,7 @@ function isHeaderRow(row: SceneNode): boolean { for (const c of n.children ?? []) { if (textOf(c) !== undefined) texts++; else if (c.type === 'frame') walk(c); - else if (c.type !== 'icon' && c.type !== 'text') other = true; + else if (!HEADER_EXTRAS.has(c.type) && c.type !== 'text') other = true; } })(row); return !other && texts >= 2; @@ -488,7 +500,7 @@ export function checkTruncation(ctx: DesktopContext, tableIds: Set): Eva } else if (!hasText(n.title)) { issues.push(issue('usability', rule, 'info', n, `${quote(content)} truncates with an ellipsis but has no title — the full text cannot be read anywhere.`, - `Give it the full text as a title: U("${n.id}", { title: ${JSON.stringify(content.trim())} }).`)); + 'Give it its full text as a title (U(id, { title: "…" })); a title renders as a tooltip.')); } } const rect = ctx.rects?.get(n.id); @@ -522,8 +534,10 @@ export function checkTruncation(ctx: DesktopContext, tableIds: Set): Eva // ── desktop-app-primary-count (FR-C8) ────────────────────────────────────── -/** A button renders as primary with variant "primary" or no variant. */ -const isPrimary = (n: SceneNode) => n.type === 'button' && (n.variant === undefined || n.variant === 'primary'); +/** A button renders filled with the accent (primary) unless its variant is + * secondary, ghost or destructive (renderButton). */ +const NOT_PRIMARY = new Set(['secondary', 'ghost', 'destructive']); +const isPrimary = (n: SceneNode) => n.type === 'button' && !(typeof n.variant === 'string' && NOT_PRIMARY.has(n.variant)); /** Repeated siblings of one shape (a grid of cards) hold their own primaries. */ const REPEAT_MIN = 3; diff --git a/src/index.ts b/src/index.ts index cacd07e..4944b5c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -85,7 +85,7 @@ Point-and-tell feedback: the user toggles Comment mode in the viewer and clicks Phone app screens: declare the medium. canvas_create({ type: "mobile" }) makes a phone screen — the device artboard (390×844 for the default device "iphone-390") with the root reserving the safe-area insets as safeArea: { top: 47, bottom: 34 } (the renderer adds them to the root's own top/bottom padding, and the root grows with long content keeping that padding past it, so in-flow content never sits under the status bar or home indicator). type: "web" (the default) is a web page; canvas_set_type changes or clears the declaration on an existing canvas (it never resizes or writes safeArea — its result's hint names the op that does). The type selects a ruleset and defaults, never the render: generate_design_system on a mobile canvas pivots the type scale on the device body size (17px; 16px for data-dense), and every evaluate result carries a "surface" report ({ type, device, source "declared" | "default", rulesOn, rulesOff, conflicts }) naming the rule ids the type + genre + preset rulesets turned on and off — a rule both enabled and disabled stays on (in rulesOn) and is listed in conflicts. Start a phone screen from a mobile realisation: apply_structure on a mobile canvas resolves the anatomy name to it — dashboard → dashboard-mobile, settings → settings-mobile, auth → auth-mobile, onboarding → onboarding-mobile, and the mobile-first feed → feed-mobile (a list of rows, pinned tab bar) and detail → detail-mobile (an item with a primary action pinned over the home indicator) — each built from the primitives and gated to pass the mobile ruleset in fast and detailed mode and canvas_stress CLEAN (unthemed and under every personality); stamp it after generate_design_system (the dark, light and material presets carry a 14–15px body that mobile-type-floor flags on a phone). Resolution reads the DECLARED type: an undeclared 390px canvas stamps the web structure, so declare type "mobile" first. Its placeholders include every copy field of its primitives, with prop the field's path (title, subtitle, label, trailing.text, leading.initials, leading.label, items[0].label — a path, not an op key: set a nested one by writing its whole object or array, siblings included). An anatomy with no mobile realisation (the other web pages such as pricing, catalogue or bento-grid; web-only components such as data-table) is refused with the list of those that have one; realisation: "web" stamps the web one anyway. Of the components, form-field, stat-card, empty-state, skeleton-card, skeleton-stat-card, kpi-card, status-chip and initials-avatar stamp on every type. Build phone screens from the mobile primitives (batch_design lists them): status-bar and home-indicator (device chrome), nav-bar, tab-bar, button, list-row, sheet — never hand-built frames — and pin bars with position "fixed" (the renderer reserves room for pinned chrome, so content never starts or ends under it). A mobile canvas runs the mobile ruleset; every finding names its rule in a "rule" field: mobile-touch-target (ERROR: a tap target below 44px — a control (its row counts only when the row is a horizontal frame holding that one tappable), a button (size "sm" is 32, "xs" 24), a list-row, each tab-bar tab and FAB, each nav-bar action; primitives are measured by their own box, inside instances too), mobile-safe-area (WARNING: content under the 47px status-bar or 34px home-indicator inset, or left under a pinned bar at the start or end of the scroll; with root safeArea or pinned chrome the renderer reserves the insets and only positioned content (absolute / fixed / sticky) and pinned bars are checked — padding ≥32px scales down on a phone, so clear a pinned bar with a spacer frame inside your content frame; detailed mode is authoritative), mobile-tab-bar (WARNING: a tab bar with fewer than 2 or more than 5 tabs, an unlabeled tab, or one not pinned to the bottom), mobile-type-floor (WARNING: text below 11px, $body below 16px, prose of 5+ words below 13px), mobile-handbuilt-target (info: an icon-shaped frame below 44px — rebuild it as a button), mobile-one-column (info: two or more side-by-side children each holding 8+ words), and on every type mobile-artboard (a mobile canvas 500px+ wide WARNS; an undeclared canvas narrower than 500px WARNS until canvas_set_type declares it either way). -Application screens: canvas_create({ type: "desktop-app" }) for a tool you work in — an editor, an admin console, a file browser, a viewer: persistent chrome, panes, dense controls, a current selection, in a browser tab or a native window. The test is what the user does: a page you read and scroll is "web", a tool you work in is "desktop-app". It gets the window artboard (1440×900 for the default device "window-1440", no insets); generate_design_system pivots its type on 14px (13 for data-dense); its ruleset turns OFF type-scale-ratio (the adjacent font-size ratio check — dense apps step 12/13/14 on purpose), and desktop-app-artboard (on every type) WARNS when a desktop-app canvas is narrower than 1024px, and when a canvas holding a desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) never declared its type or is declared mobile (declared web gets an info). 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. The desktop-app ruleset (each finding carries its "rule"; canvas_evaluate lists them) adds: name every icon-only button (ariaLabel); mark exactly one current place — one active nav-item per pane (a parent may stay active over its active child), one active tab per tabs, one active row per tree; a dense type ladder (desktop-app-type-ladder, replacing type-scale-ratio: 12/13/14 steps are fine, nothing below 11px, prose ≥12px, $body ≥13px); table header rows as tall as their body rows; column headers never truncated; one primary button per pane (info); and frames shaped like small buttons are named as hand-built targets (info) — rebuild them as button or link. Before presenting a desktop-app screen run mode "detailed" too: it measures rendered rows, column edges and truncation (a tablist whose every label is cut warns). +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 and links — never hand-built frames, which no target rule can measure. A nav-item's dotColor is an identity dot and never counts as a competing accent. 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. The desktop-app ruleset (each finding carries its "rule"; canvas_evaluate lists them) adds: name every icon-only button and link (ariaLabel); mark exactly one current place — one active nav-item per pane — a frame with overflow "auto", so give a rail and a sidebar each their own (a parent may stay active over its active child), one active tab per tabs, one active row per tree; a dense type ladder (desktop-app-type-ladder, replacing type-scale-ratio: 12/13/14 steps are fine, nothing below 11px, prose ≥12px, $body ≥13px); table header rows as tall as their body rows; column headers never truncated; one primary button per pane (info); and frames shaped like small buttons are named as hand-built targets (info) — rebuild them as button or link. Before presenting a desktop-app screen run mode "detailed" too: it measures rendered rows, column edges and truncation (a tablist whose every label is cut warns). 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. @@ -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 (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; on desktop-app an icon-only button without ariaLabel warns, and a nav group, tabs or tree with no single active item warns (desktop-app-current). 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; on desktop-app an icon-only button or link without ariaLabel warns, and a nav group, tabs or tree with no single active item warns (desktop-app-current). 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.', @@ -590,7 +590,7 @@ Mobile primitives (phone screens — they carry their own sizes, hit areas, and 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). + - link { label, icon?, iconPosition?, external?, ariaLabel? } — a standalone text action, at least 24 tall, measured as a pointer target. With no label it hugs its glyphs (14px wide, 30 with external) and takes ariaLabel as its name (aria-label + title). A text node can hold INLINE links instead: links: [{ start, end }] character ranges of its content, drawn underlined (inline links are exempt from the 24px floor, as WCAG exempts them). - text-input { value?, placeholder?, icon?, size?: "sm"|"md" (32/40), rows? (a multi-line field), error? (a message), disabled? } — its border ($border-strong when the design system has it) is its only boundary; error draws an icon and the message below and colours the border $danger. - nav-item { label, icon?, count?, dotColor? (an identity dot — never counted as an accent), active?, depth?: 0|1, collapsed? } — 32 tall, spans its sidebar; active draws an $accent-tint fill, a 2px $accent bar and a heavier label (aria-current); collapsed is the 32×32 rail form, its label the accessible name. - tabs { items: [{ label, count?, active?, disabled? }], variant?: "line"|"contained", size?: "sm"|"md" (32/40) } — one tablist; each tab is its own pointer target; the active tab gets an indicator (line) or an $accent-tint fill (contained) and a heavier label. @@ -2131,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 control that is the only target directly inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too; they point at the component definition and carry no fix op. Modes: + `Auto-score a design canvas against quality criteria. Returns an overall score (0-100), category scores, and actionable issues referencing specific node IDs. Categories: spacing, color, typography, structure, consistency (craft), plus "cliche" — the machine-made tells: default purple/indigo accents, gradient/glow overuse, fake browser/phone chrome (traffic-light dots), the hanging eyebrow-beside-heading header, fabricated-looking metrics/testimonials/logos, too many eyebrow labels (template rhythm — an eyebrow above nearly every section), slop copy (stock AI phrasing: filler verbs, scroll cues, placeholder names like "Jane Doe", hype labels), mixed radius systems (radius consistency — too many distinct corner radii), pure black/white (harsh #000000 ink or a stark #ffffff page vs a designed off-black/off-white), and competing accents (accent consistency — more than one accent hue). cliche issues carry a "tell" discriminator and are warning/info severity — but EVERY tell blocks the directive regardless of severity. The tells know dashboard vocabulary: a violet reached only through a $chart-* or $*-tint token doesn't trip the default-purple tell (a literal violet, or one through any OTHER token, still does), a gradient reached through a $token doesn't count toward gradient-overuse, thin rounded sparkline bars no longer match fake-chrome's small-circle census (it now requires a near-square shape: both dimensions ≤20px, aspect ratio ≤1.5:1, and round), and an uppercase label sitting beside a large tabular figure reads as a KPI-card metric — not counted in the eyebrow-rhythm census. The color category is DUAL-THEME aware: when the design system has a dark token layer (dark.colors — see set_variables / generate_color_system), contrast is checked in BOTH themes — dark-run issues carry theme: "dark", the category score takes the worse theme, and dark failures point at the dark token layer instead of carrying a literal fix (a node-level literal would break the light theme). Contrast is measured as rendered: translucent fills (rgba / #RRGGBBAA) composite over the fills behind them (over the white page when no opaque fill is behind), translucent text blends into that, and "transparent" is see-through — so a tinted selected or hover fill is judged by its real color, and the message names the composited one. WCAG 2.2 remains the gate; WCAG-passing pairs that are perceptually weak by APCA (Lc below ~75 body / ~60 large) get an INFO advisory — APCA is a candidate method, not a standard, and never blocks. Plus "coverage" (Phase 24): a BASE canvas whose content carries data — a detected table (empty + loading demanded) or a form of 3+ input controls, text-inputs included (error demanded) — gets a directive-blocking WARNING per missing state variant (table detection needs THREE matching horizontal rows to read as data — two stacked rows are a layout, not a table — unless the frame is import-named "Table", which keeps the looser two-row shape); the result's "coverage" field reports { dataBearing, states, missing }. Designing the state is one canvas_add_variant + one scaffold stamp (empty-state / skeleton-table / skeleton-card / skeleton-stat-card); variant canvases themselves and non-data screens get no coverage findings. On a "loading" variant, coverage also flags a HALF-DESIGNED loading state — a data surface (a detected table, or a frame holding 2+ large tabular/numeric texts) still showing live values while a sibling region is skeletoned, one warning per offending region naming it and pointing at the matching skeleton scaffold. Plus "usability" (Phase 27): the mechanical UX floors beyond contrast — on web and desktop-app canvases every pointer target (the four controls and the clickable primitives: button, list-row, each tab-bar tab and FAB, each nav-bar action, link, text-input, nav-item, each tab of a tabs node, tree-row, menu-row — inline text links and dividers are not targets, and a control that is the only target directly inside a property-row, nav-item, menu-row or list-row is measured by that row's box) is held to the 24px WCAG 2.5.8 floor with its SPACING EXCEPTION: a target still below 24 after the padded-row step passes only when a 24px circle centred on it reaches no other target's box and no other undersized target's circle (touching passes; nested targets and disabled ones never count). Spacing needs rendered rects, so DETAILED mode runs the circle test (ERROR when it fails, naming the neighbour) and FAST mode WARNS on any target below 24, naming detailed mode — grow it or run mode "detailed" before presenting. Instances are expanded for this census and findings report on the instance. (The effective target counts a lone control's padded row, so a well-padded settings row passes; two controls sharing a row are measured bare; phone-width WEB artboards additionally get a 44px touch-first info on the four controls; on a canvas declared mobile, 44px is an ERROR instead — see the surface paragraph), a control with no text label in its row or group is a WARNING (selects carry their own value text and are exempt), and vague action copy ("Click here" / "Learn more" / "Read more" / "Submit" as the exact label) is an INFO — name the action instead. The structure category also WARNS (directive-blocking, -10 structure score each) on every icon node, and every mobile primitive icon prop (button.icon, list-row / nav-bar leading.icon, nav-bar trailing[].icon, tab-bar items[].icon — required, so a tab with no icon warns too — and tab-bar fab.icon), whose name resolves in neither bundled set — it would render as an empty slot, invisible in a screenshot: the suggestion names the spellings that do resolve (hyphen/underscore swap, or the missing material: prefix), and when exactly one does — or several do but only one matches the icon set the rest of the canvas uses — an icon node or button.icon carries a fix canvas_autofix applies (the nested props name the spelling to write). Icons inside component instances are checked too; they point at the component definition and carry no fix op. Modes: - "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. @@ -2141,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 desktop-app canvas rulesOn also lists the desktop-app ruleset, each finding tagged with its "rule": desktop-app-target (usability: the 24px floor above, named — fast WARNING, detailed ERROR when the 24px circle reaches a neighbour; an unlabelled link measures its glyphs, 14px wide), desktop-app-handbuilt-target (usability info, never blocks: a frame below 32px holding one icon, an icon plus a label of ≤3 words, or a bordered padded frame holding one such label — the shape an imported text button takes; rebuild it as a button or link if clickable), desktop-app-icon-label (usability WARNING: an icon-only button with no ariaLabel, a collapsed nav-item with a blank label), desktop-app-current (usability WARNING: in one pane — a frame with overflow "auto", or the root — two active nav-items at one depth, or two or more nav-items with none active; a tabs node with no active tab or more than one; two active tree-rows under one parent; info: a tree with a current row nesting past two levels), desktop-app-type-ladder (typography WARNING, replaces type-scale-ratio: adjacent sizes a = {} check('FR-C7: three tabs that fit are silent', f.length === 0, show(f)); } +// ── F8: detailed mode renders the instance-expanded tree ─────────────────── +{ + const c = canvasOf([{ id: 'inst', name: 'Sidebar', type: 'instance', componentId: 'side' } as SceneNode]); + c.components = { side: { id: 'side', name: 'Side', type: 'component', layout: 'vertical', children: [ + { id: 'side-nav', name: 'nav', type: 'nav-item', label: 'Quarterly planning', icon: 'folder', active: true, width: 60 }, + ] } } as Canvas['components']; + const f = (await evaluateCanvas(c, { mode: 'detailed' })).issues.filter((i) => i.rule === 'desktop-app-truncation'); + check('F8: a short truncation inside an instance is measured and reported on the instance', f.length === 1 && f[0].nodeId === 'inst' && /inside instance/.test(f[0].message), show(f)); +} + await shutdown(); console.log(allPass ? '\nALL PASS' : '\nSOME FAILED'); process.exit(allPass ? 0 : 1); diff --git a/test-desktop-app-rules.ts b/test-desktop-app-rules.ts index 0f4d57f..22bd8a4 100644 --- a/test-desktop-app-rules.ts +++ b/test-desktop-app-rules.ts @@ -8,7 +8,10 @@ import './test-env.js'; import { readFileSync } from 'node:fs'; -import { evaluateCanvas, type EvaluationIssue } from './src/evaluate.js'; +import { evaluateCanvas, foldIssues, type EvaluationIssue } from './src/evaluate.js'; +import { linkGlyphWidth } from './src/primitives.js'; +import { renderToHtml } from './src/renderer.js'; +import { DESKTOP_APP_RULES } from './src/surfaces.js'; import { extractInventory } from './src/drift.js'; import type { Canvas, SceneNode } from './src/types.js'; @@ -18,12 +21,12 @@ function check(name: string, cond: boolean, extra?: string) { console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); } -type Kind = 'web' | 'desktop-app'; +type Kind = 'web' | 'mobile' | 'desktop-app'; function canvasOf(children: SceneNode[], type: Kind = 'desktop-app', variables: Canvas['variables'] = {}): Canvas { return { id: 'c', name: 'c', projectId: 'p', components: {}, variables, createdAt: '', lastModified: '', root: { id: 'document', type: 'document', name: 'Document', width: 1440, height: 900, fill: '#FFFFFF', layout: 'vertical', padding: 24, children }, - metadata: { surface: type === 'web' ? { type } : { type, device: 'window-1440' } }, + metadata: { surface: type === 'desktop-app' ? { type, device: 'window-1440' } : { type } }, } as Canvas; } async function findings(rule: string, children: SceneNode[], type: Kind = 'desktop-app', variables: Canvas['variables'] = {}): Promise { @@ -275,5 +278,136 @@ const nav = (id: string, extra: Partial = {}): SceneNode => ({ id, na check('FR-C10: drift\'s inventory still counts no text-input as a control', extractInventory(canvasOf([input('a'), input('b'), input('c')]).root).counts.controls === 0); } +// ── Round-1 fixes and the gaps the mutation pass found ───────────────────── +{ + // One tree that trips every desktop-app rule in fast mode, judged on each + // type: every rule fires on desktop-app, in its category; none but the + // artboard rule fires on web or mobile. + const cells = (id: string, extra: Partial = {}) => [text(`${id}a`, 'Name', 13, extra), text(`${id}b`, 'Role', 13), text(`${id}c`, 'Status', 13)]; + const everything: SceneNode[] = [ + { id: 'x', name: 'x', type: 'button', icon: 'x', size: 'sm', width: 20, height: 20 } as SceneNode, + frame('gear', [{ id: 'gi', name: 'gi', type: 'icon', icon: 'settings', iconSize: 16 }], { width: 24, height: 24 }), + frame('side', [nav('a', { active: true }), nav('b', { active: true })], { overflow: 'auto' }), + text('big', 'Title', 36), text('small', 'Label', 13), + frame('users', [frame('head', cells('h', { textOverflow: 'ellipsis' }), { layout: 'horizontal', height: 40 }), ...[0, 1, 2].map((i) => frame(`r${i}`, cells(`r${i}`), { layout: 'horizontal', height: 32 }))]), + frame('bar', [{ id: 'p1', name: 'p1', type: 'button', label: 'Save', variant: 'primary' }, { id: 'p2', name: 'p2', type: 'button', label: 'Publish', variant: 'primary' }], { layout: 'horizontal' }), + ]; + const expected: Record = { + 'desktop-app-target': 'usability', 'desktop-app-handbuilt-target': 'usability', 'desktop-app-icon-label': 'usability', + 'desktop-app-current': 'usability', 'desktop-app-type-ladder': 'typography', 'desktop-app-row-rhythm': 'consistency', + 'desktop-app-truncation': 'usability', 'desktop-app-primary-count': 'structure', + }; + check('the combined tree covers every registered desktop-app rule', JSON.stringify(Object.keys(expected).sort()) === JSON.stringify([...DESKTOP_APP_RULES].sort())); + const app = (await evaluateCanvas(canvasOf(everything), { mode: 'fast' })).issues; + for (const [rule, category] of Object.entries(expected)) { + const f = app.filter((i) => i.rule === rule); + check(`F9: ${rule} fires on desktop-app, under ${category}`, f.length > 0 && f.every((i) => i.category === category), show(f)); + } + for (const type of ['web', 'mobile'] as const) { + const r = (await evaluateCanvas(canvasOf(everything, type), { mode: 'fast' })).issues; + const leaked = r.filter((i) => i.rule?.startsWith('desktop-app-') && i.rule !== 'desktop-app-artboard'); + check(`${type} runs none of the desktop-app rules but the artboard`, leaked.length === 0, show(leaked)); + } +} +{ + // Severities the first round left unasserted. + const sev = async (rule: string, children: SceneNode[]) => (await findings(rule, children)).map((i) => i.severity); + check('FR-C5: a ladder pair is a warning', JSON.stringify(await sev('desktop-app-type-ladder', [text('a', 'A', 13), text('b', 'B', 36)])) === '["warning"]'); + check('FR-C5: the 11px floor is a warning', JSON.stringify(await sev('desktop-app-type-ladder', [text('a', 'Tag', 10), text('b', 'Body', 12)])) === '["warning"]'); + check('FR-C4: none active is a warning', JSON.stringify(await sev('desktop-app-current', [frame('s', [nav('a'), nav('b')], { overflow: 'auto' })])) === '["warning"]'); + check('FR-C4: tabs with none active is a warning', JSON.stringify(await sev('desktop-app-current', [{ id: 't', name: 't', type: 'tabs', items: [{ label: 'A' }, { label: 'B' }] } as SceneNode])) === '["warning"]'); + check('FR-C3: a nameless collapsed nav-item is a warning', JSON.stringify(await sev('desktop-app-icon-label', [nav('n', { collapsed: true, label: '', icon: 'home', active: true })])) === '["warning"]'); +} +{ + // FR-C2 boundaries, and the fast-mode estimate fixes (round 1). + const iconFrame = (size: number, extra: Partial = {}) => frame('f', [{ id: 'fi', name: 'fi', type: 'icon', icon: 'settings', iconSize: 16 }], { width: size, height: size, ...extra }); + const hb = (children: SceneNode[]) => findings('desktop-app-handbuilt-target', children); + check('FR-C2: a 31px icon frame is named', (await hb([iconFrame(31)])).length === 1); + const labelled = (words: string) => frame('f', [{ id: 'fi', name: 'fi', type: 'icon', icon: 'x', iconSize: 14 }, text('ft', words, 13)], { layout: 'horizontal', height: 24 }); + check('FR-C2: an icon with a three-word label is named', (await hb([labelled('Open the file')])).length === 1); + check('FR-C2: an icon with a four-word label is not', (await hb([labelled('Open the file now')])).length === 0); + const bordered = (extra: Partial) => frame('f', [text('ft', 'Archive', 13)], { padding: [6, 14], stroke: '#D1D5DB', ...extra }); + check('S2: strokeWidth 0 is no border', (await hb([bordered({ strokeWidth: 0 })])).length === 0); + check('S2: stroke "none" is no border', (await hb([bordered({ stroke: 'none' })])).length === 0); + check('FR-C2: minWidth/minHeight 32 lift an unsized icon frame out of range', (await hb([frame('f', [{ id: 'fi', name: 'fi', type: 'icon', icon: 'x', iconSize: 16 }], { minWidth: 32, minHeight: 32 })])).length === 0); + check('FR-C2: minHeight alone leaves a 16px-wide icon frame named', (await hb([frame('f', [{ id: 'fi', name: 'fi', type: 'icon', icon: 'x', iconSize: 16 }], { minHeight: 32 })])).length === 1); + const stacked = (iconSize: number, font: number, padding: number) => frame('f', [{ id: 'fi', name: 'fi', type: 'icon', icon: 'house', iconSize }, text('ft', 'Home', font)], { layout: 'vertical', padding }); + check('FR-C2: a stacked icon and caption add up (20 + 13 + 8 = 41px, silent)', (await hb([stacked(20, 11, 4)])).length === 0); + check('FR-C2: a small stacked icon and caption still count (12 + 12 + 4 = 28px, named)', (await hb([stacked(12, 10, 2)])).length === 1); +} +{ + // FR-C3 and S3: an icon-only link needs a name too. + const link = (extra: Partial): SceneNode => ({ id: 'l', name: 'l', type: 'link', icon: 'arrow-left', ...extra }); + let f = await findings('desktop-app-icon-label', [link({})]); + check('S3: an icon-only link without ariaLabel warns', f.length === 1 && f[0].severity === 'warning' && /Icon-only link/.test(f[0].message), show(f)); + f = await findings('desktop-app-icon-label', [link({ ariaLabel: 'Back' })]); + check('S3: an ariaLabel clears it', f.length === 0, show(f)); + f = await findings('desktop-app-icon-label', [link({ label: 'Back' })]); + check('S3: a labelled link is not icon-only', f.length === 0, show(f)); + const c = canvasOf([link({ ariaLabel: 'Back' })]); + const html = renderToHtml(c.root, 1440, 900, c); + check('S3: a link renders its ariaLabel as aria-label and title, never as text', /aria-label="Back" title="Back"/.test(html) && !/>Back ({ id: `b${i}`, name: `b${i}`, type: 'button', icon: 'trash-2', size: 'sm', variant: 'ghost' } as SceneNode))), { mode: 'fast', categories: ['usability'] })).issues; + const folded = foldIssues(ten).filter((i) => i.rule === 'desktop-app-icon-label'); + check('round 1: ten nameless icon buttons fold into one entry', folded.length === 1 && folded[0].count === 10, show(folded)); +} +{ + // F1: the glyph width, and a non-numeric width staying unknown (round 1). + check('F1: linkGlyphWidth is 14 / 12 / 30 / 0', [linkGlyphWidth({ id: 'a', type: 'link', icon: 'x' }), linkGlyphWidth({ id: 'b', type: 'link', external: true }), linkGlyphWidth({ id: 'c', type: 'link', icon: 'x', external: true }), linkGlyphWidth({ id: 'd', type: 'link' })].join() === '14,12,30,0'); + let f = await findings('desktop-app-target', [frame('w', [{ id: 'l', name: 'l', type: 'link', icon: 'arrow-left', width: 'fill_container' } as SceneNode], { width: 300 })]); + check('F1: an icon-only link with a fluid width is not measured at its glyph', f.length === 0, show(f)); + f = await findings('desktop-app-target', [{ id: 'l', name: 'l', type: 'link', icon: 'arrow-left', width: 20 } as SceneNode]); + check('F1: a numeric 20px width still is', f.length === 1, show(f)); + f = await findings('desktop-app-target', [{ id: 'l', name: 'l', type: 'link', icon: 'arrow-left' } as SceneNode], 'web'); + check('F1: on web an icon-only link is measured too (unnamed)', (await evaluateCanvas(canvasOf([{ id: 'l', name: 'l', type: 'link', icon: 'arrow-left' } as SceneNode], 'web'), { mode: 'fast', categories: ['usability'] })).issues.some((i) => /14×24px/.test(i.message) && i.rule === undefined)); +} +{ + // FR-C5 boundaries. + const ladder = (...sizes: Array) => findings('desktop-app-type-ladder', sizes.map((s, i) => text(`t${i}`, 'Label', s as number))); + check('FR-C5: 16→17 passes (a 1px step from 16)', (await ladder(16, 17)).length === 0); + check('FR-C5: 17→18 warns (above 16 a step needs 1.1)', (await ladder(17, 18)).length === 1); + check('FR-C5: 20→22 passes (1.1)', (await ladder(20, 22)).length === 0); + check('FR-C5: "14px" and 40 are read as sizes (2.86 warns)', (await ladder('14px', 40)).length === 1); + const four = await findings('desktop-app-type-ladder', [text('t', 'Hint sets four words', 11), text('u', 'Body', 13)]); + check('FR-C5: four words at 11px pass the prose floor', four.length === 0, show(four)); + const one = await findings('desktop-app-type-ladder', [text('t', 'This hint sets five words', 10), text('u', 'Body', 13)]); + check('F3: a text tripping two floors gets one finding (the first)', one.length === 1 && /below the 11px/.test(one[0].message), show(one)); + const half = await findings('desktop-app-type-ladder', [text('a', 'A', 13), text('b', 'B', 36)], 'desktop-app', { typography: { a: { fontSize: 13 } } } as Canvas['variables']); + check('FR-C5: pinning one size of a pair does not skip it', half.length === 1, show(half)); +} +{ + // FR-C6 / FR-C7 with a select-all header (round 1), and the tolerance edge. + const row = (id: string, h: number, cells: SceneNode[]) => frame(id, cells, { layout: 'horizontal', height: h }); + const table = (headerH: number, headerExtra: Partial = {}) => frame('users', [ + row('head', headerH, [{ id: 'hc', name: 'hc', type: 'checkbox' }, text('h1', 'Name', 13, headerExtra), text('h2', 'Role', 13)]), + ...[0, 1, 2].map((i) => row(`r${i}`, 32, [{ id: `c${i}`, name: `c${i}`, type: 'checkbox' }, text(`r${i}a`, `Ada ${i}`, 13), text(`r${i}b`, 'Admin', 13)])), + ]); + let f = await findings('desktop-app-row-rhythm', [table(40)]); + check('round 1: a header with a select-all checkbox is still a header (40 over 32 warns)', f.length === 1 && f[0].severity === 'warning' && f[0].nodeId === 'head', show(f)); + f = await findings('desktop-app-row-rhythm', [table(34)]); + check('FR-C6: 2px off warns', f.length === 1, show(f)); + f = await findings('desktop-app-truncation', [table(32, { textOverflow: 'ellipsis' })]); + check('round 1: a truncating header beside a select-all checkbox warns', f.length === 1 && f[0].severity === 'warning', show(f)); +} +{ + // FR-C8 edges (round 1: a primary is whatever renders filled). + const btn = (id: string, variant?: unknown): SceneNode => ({ id, name: id, type: 'button', label: id, size: 'sm', ...(variant === undefined ? {} : { variant: variant as SceneNode['variant'] }) }); + let f = await findings('desktop-app-primary-count', [frame('bar', [btn('A', 'outline'), btn('B', 'primary')], { layout: 'horizontal' })]); + check('round 1: an unknown variant renders filled and counts', f.length === 1, show(f)); + f = await findings('desktop-app-primary-count', [frame('bar', [btn('A', 'destructive'), btn('B', 'primary')], { layout: 'horizontal' })]); + check('FR-C8: a destructive button is not a primary', f.length === 0, show(f)); + const card = (i: number) => frame('Card', [text(`ct${i}`, `Plan ${i}`), btn(`Choose ${i}`, 'primary')], { width: 200 }); + f = await findings('desktop-app-primary-count', [frame('grid', [1, 2, 3].map(card), { layout: 'horizontal' })]); + check('FR-C8: exactly three same-shaped cards are a repeat', f.length === 0, show(f)); +} +{ + // FR-C10: text-inputs inside a table are its data plane. + const row = (id: string) => frame(id, [text(`${id}t`, `Item ${id}`, 13), { id: `${id}i`, name: `${id}i`, type: 'text-input', value: 'x' } as SceneNode, text(`${id}s`, 'Open', 13)], { layout: 'horizontal' }); + const tableOnly = (await evaluateCanvas(canvasOf([frame('t', [frame('head', [text('h1', 'Item', 13), text('h2', 'Qty', 13), text('h3', 'State', 13)], { layout: 'horizontal' }), row('a'), row('b'), row('c')])]), { mode: 'fast', categories: ['coverage'] })).issues; + check('FR-C10: text-inputs inside a table do not make a form', !tableOnly.some((i) => /"error"/.test(i.message)) && tableOnly.some((i) => /"empty"/.test(i.message)), show(tableOnly)); +} + console.log(allPass ? '\nALL PASS' : '\nSOME FAILED'); process.exit(allPass ? 0 : 1); From f14510755694c080ec997afaba6f3976e08f67f7 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Fri, 13 Nov 2026 21:36:27 +0100 Subject: [PATCH 3/4] Keep row-select data rows out of the header and narrow two estimates A first row holding a control is a header only when its text is styled apart from the next row. The stacked icon-and-caption estimate needs both as in-flow children; auto, null and px link widths are measured again. --- README.md | 2 +- docs/GUIDELINES.md | 6 +++--- docs/specs/PHASE-31-SPEC.md | 1 + src/desktop-app-rules.ts | 43 +++++++++++++++++++++++++++---------- src/index.ts | 2 +- src/primitives.ts | 16 +++++++++++--- test-desktop-app-rules.ts | 39 ++++++++++++++++++++++++++++++++- 7 files changed, 89 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 1537973..d4522ef 100644 --- a/README.md +++ b/README.md @@ -897,7 +897,7 @@ Every result also carries a **`surface`** field: `{ type, device, source, rulesO | `mobile-artboard` | structure | warning / info | Runs on every type. A mobile canvas 500px or wider warns, and any other size than the device's is an info. An undeclared canvas narrower than 500px warns until `canvas_set_type` declares it; one declared `web` gets an info. | | `desktop-app-artboard` | structure | warning / info | Runs on every type. Warns on a desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for. Also warns on a canvas that holds a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) and was never declared, or is declared `mobile`; one declared `web` gets an info. Primitives inside an instance count. | | `type-scale-ratio` | typography | warning | On by default: adjacent font sizes stepping by a ratio below 1.1 or above 2.0 (pinned typography tokens skip it). The desktop-app ruleset turns it off, since dense apps step 12 / 13 / 14 on purpose; it then appears in `rulesOff`, and `desktop-app-type-ladder` judges the sizes instead. | -| `desktop-app-target` | usability | warning / error | Desktop-app only: the 24px floor (the `usability` row under Categories below), under its rule id. Fast mode warns on a target under 24px in either dimension; detailed mode errors when its 24px circle reaches a neighbour. An unlabelled `link` with no authored width is measured at its glyphs (14px wide, 30 with `external`), on web too. | +| `desktop-app-target` | usability | warning / error | Desktop-app only: the 24px floor (the `usability` row under Categories below), under its rule id. Fast mode warns on a target under 24px in either dimension; detailed mode errors when its 24px circle reaches a neighbour. An unlabelled `link` with no width (or `"auto"`) is measured at its glyphs (14px wide, 30 with `external`), on web too. | | `desktop-app-handbuilt-target` | usability | info | Desktop-app only: a frame below 32px holding one icon, an icon plus a label of up to three words, or (bordered and padded) one such label alone, the shape an imported text button takes. Frames inside a clickable primitive or a `property-row` are never counted. Rebuild it as a `button` or `link` if it is clickable. | | `desktop-app-icon-label` | usability | warning | Desktop-app only: an icon-only `button` or `link` with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`. | | `desktop-app-current` | usability | warning / info | Desktop-app only: in one pane (a frame with `overflow: "auto"`, or the root; each node belongs to its nearest), two active `nav-item`s at one depth, or two or more with none active (give each navigation region its own scrolling pane); a `tabs` node with no active tab or more than one; two active `tree-row`s under one parent. A tree with a current row that nests past two levels is an info. | diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index a43290f..23f94b0 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -83,15 +83,15 @@ Two terms the rules share. A **pane** is a frame that scrolls on its own (`overf - **`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. -- **`desktop-app-target`** (usability). [The 24px floor](#the-24px-floor-web-and-desktop-app) under its rule id: a target below 24px in either dimension **warns** in fast mode, and is an **error** in detailed mode when its 24px circle reaches a neighbour. Web runs the same check without the id, including this: a `link` with no label and no authored width hugs its glyphs, so it is measured at 14px wide (30 with `external`) and 24 tall. Give it a label, or keep its neighbours out of its circle. -- **`desktop-app-handbuilt-target`** (usability, info). A frame below 32px in either dimension that holds one icon, an icon plus a label of three words or fewer, or, when it has a border (`stroke`) and padding, one such label alone (the shape an imported text button takes). It never blocks, because a frame can't say it is decorative. If it is clickable, rebuild it as a `button` (`xs` or `sm`; icon-only with `ariaLabel`) or a `link`. Fast mode estimates a missing height from the icon or the label's line box plus padding; detailed mode measures the render. Fast mode honours `minWidth` / `minHeight` and adds up an icon stacked over a caption. A frame inside a clickable primitive or a `property-row` is never hand-built. +- **`desktop-app-target`** (usability). [The 24px floor](#the-24px-floor-web-and-desktop-app) under its rule id: a target below 24px in either dimension **warns** in fast mode, and is an **error** in detailed mode when its 24px circle reaches a neighbour. Web runs the same check without the id, including this: a `link` with no label and no width (or `"auto"`) hugs its glyphs, so it is measured at 14px wide (30 with `external`) and 24 tall; a px width is measured as written, a fluid or token width is not measured. Give it a label, or keep its neighbours out of its circle. +- **`desktop-app-handbuilt-target`** (usability, info). A frame below 32px in either dimension that holds one icon, an icon plus a label of three words or fewer, or, when it has a border (`stroke`) and padding, one such label alone (the shape an imported text button takes). It never blocks, because a frame can't say it is decorative. If it is clickable, rebuild it as a `button` (`xs` or `sm`; icon-only with `ariaLabel`) or a `link`. Fast mode estimates a missing height from the icon or the label's line box plus padding; detailed mode measures the render. Fast mode honours `minWidth` / `minHeight` and adds up an icon stacked over a caption when both sit directly in the frame. A frame inside a clickable primitive or a `property-row` is never hand-built. - **`desktop-app-icon-label`** (usability, **warning**). An icon-only `button` or `link` (no `label`, an `icon`) with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`: an action with no name for a screen reader or a tooltip. - **`desktop-app-current`** (usability). The current location must be unambiguous. - Navigation: all `nav-item`s in one pane are one group, whatever section frames they sit in. Two active items at the same depth **warn**; a group of two or more with none active **warns**. An active parent (depth 0) over its active child (depth 1) passes, and a lone item in another pane is not a group. So a rail beside a sidebar needs each in its own pane, and a list of actions is `menu-row`s, not `nav-item`s. - A `tabs` node with no active tab, or more than one, **warns**. - `tree-row`s under one parent are one tree: two active rows **warn**. A tree with a current row that nests past two levels (depth 2 or more) is an **info**: as navigation, more than two levels is hard to keep a place in; a file tree may ignore it. - **`desktop-app-type-ladder`** (typography, **warning**), replacing `type-scale-ratio`. For each pair of adjacent distinct sizes a < b: it passes when a ≤ 16 and b − a ≤ 4, else when b / a is between 1.1 and 2.5. So 12 / 13 / 14 and 14 → 32 pass and 13 → 36 warns. A pair of pinned typography token sizes skips the check. Sizes are read as rendered (`"14px"` counts; a `clamp()` reads as its minimum). Separately: any text below 11px, prose below 12px, and a text whose `fontSize` is `$body` resolving below 13px each warn, one finding per text. -- **`desktop-app-row-rhythm`** (consistency), on detected tables. A header row (its content is text, plus icons and controls such as a select-all checkbox) more than 1px taller or shorter than the one-line body rows **warns**, as Carbon sets them equal. A body row more than 1px off its siblings is an **info**; rows with a title over a subtitle are compared only with each other. Detailed mode adds a cell whose left edge is more than 1px off its column as an **info**. Fast mode reads authored `height`s only, so rows sized by padding are judged in detailed mode. +- **`desktop-app-row-rhythm`** (consistency), on detected tables. A header row (its content is text, plus icons and controls such as a select-all checkbox; a first row holding a control counts only when its text is styled apart from the next row's, since a row-select data row looks the same) more than 1px taller or shorter than the one-line body rows **warns**, as Carbon sets them equal. A body row more than 1px off its siblings is an **info**; rows with a title over a subtitle are compared only with each other. Detailed mode adds a cell whose left edge is more than 1px off its column as an **info**. Fast mode reads authored `height`s only, so rows sized by padding are judged in detailed mode. - **`desktop-app-truncation`** (usability). A column header text with `textOverflow: "ellipsis"` **warns**: a header is never cut. A hand-built text with an ellipsis and no `title` is an **info**, since the full text must be reachable (primitives add their own `title`). Detailed mode adds: a `tabs` node whose every label is cut **warns** (tabs shrink to fit their tablist, so too many tabs in too little width leaves nothing readable), and an ellipsis that leaves fewer than four visible characters, on a text or a primitive's label, is an **info**. - **`desktop-app-primary-count`** (structure, info). Two or more primary `button`s in one pane. Any variant but `secondary`, `ghost` or `destructive` renders filled with the accent, so it counts (no variant included); a disabled one doesn't. Primaries inside three or more same-shaped sibling frames (a grid of cards) are each card's own and don't count. diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 44c87fd..6e8a856 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -246,6 +246,7 @@ One profile ships, keyed by id so a second size is one table row later. Values i - FR-C9 had nothing left for this slice: its overlay clause lands with the overlay primitives (slice E). - **Spec change S3 (FR-C3, approved by Victor after verify round 1).** An icon-only `link` (an `icon`, no `label`) had no way to carry a name and passed FR-C3 silently, while F1 made it a measured target. `link` now renders `ariaLabel` as `aria-label` and `title` (as `button` does, never as text), and `desktop-app-icon-label` warns on an icon-only link without one. - **Verify round 1 fixes.** (a) F4's header row also admits controls (a select-all checkbox, a toggle, a radio, a select) beside text and icons, so a select-all header keeps the header warnings of FR-C6 and FR-C7. (b) FR-C2's fast estimate honours `minWidth` / `minHeight`, and in a frame that is not horizontal adds an icon stacked over a caption (plus the gap) instead of taking the larger. (c) F1's glyph width applies only when no `width` is authored; a non-numeric width (`fill_container`, a percentage) stays unknown. (d) F6's primary is what renders filled: any `variant` but `secondary`, `ghost` or `destructive` (an unknown one included). (e) F3's ladder reads sizes as rendered (`fontPx`: `"14px"`, a `clamp()`'s minimum). (f) The `desktop-app-icon-label` and no-title truncation suggestions no longer embed the node id, so repeated findings fold. Accepted as specced: icon-only links on web now warn in fast mode (F1's census correction); three `text-input`s in an inspector demand an `error` variant (FR-C10 on every type, like three toggles); two navigation regions sharing one pane are one group (F2; the docs tell agents to give each its own pane); a tree split across wrapper frames is several trees; the deep-tree info fires on a file tree with a current row (info only). The FR-C7 short-tab info is subsumed when every label is cut (the warning fires instead); kept for tablists where only some labels are cut. +- **Verify round 2 fixes** (proved red on e8c5715 and green on the fix; not re-verified by an agent). (a) Fix (a) above read the first data row of a headerless row-select table as a header, so its height and a truncating first cell raised header warnings: a first row holding a control is now a header only when its first text is styled apart from the next row's (`fontWeight`, `fontSize`, `color`, `textTransform` or `letterSpacing`). (b) Fix (b) summed an icon and label nested in a horizontal wrapper, or positioned: the sum now needs both to be in-flow children of the frame itself. (c) Fix (c) left `width: "auto"`, `null`, `""` and px strings unmeasured: those hug the glyphs (or measure the px value); only fluid and token widths stay unknown. **Slice D: panes (FR-D1 to FR-D3)** - `src/structures.ts:1834`, `:1863`: N-type listing and resolution; `covers()` for `desktop-app`. diff --git a/src/desktop-app-rules.ts b/src/desktop-app-rules.ts index caf07c5..7839972 100644 --- a/src/desktop-app-rules.ts +++ b/src/desktop-app-rules.ts @@ -175,9 +175,11 @@ export function checkHandbuiltTargetsApp(ctx: DesktopContext): EvaluationIssue[] const pad = paddingSides(n, ctx.profile.width); const icon = s.icon ? (isNum(s.icon.iconSize) ? s.icon.iconSize : 24) : 0; const label = s.label ? lineBox(s.label) : 0; - // A frame stacks its children vertically unless it is horizontal, so a - // stacked icon and caption add up (with the gap between them). - const stacked = axis === 'height' && n.layout !== 'horizontal' && icon > 0 && label > 0; + // A frame stacks its children vertically unless it is horizontal, so an + // icon and caption that are both its in-flow children add up (with the + // gap between them); nested or positioned, the larger one stands in. + const direct = (c?: SceneNode) => !!c && (n.children ?? []).includes(c) && c.position !== 'absolute' && c.position !== 'fixed'; + const stacked = axis === 'height' && n.layout !== 'horizontal' && icon > 0 && label > 0 && direct(s.icon) && direct(s.label); const content = stacked ? icon + label + (isNum(n.gap) ? n.gap : 0) : Math.max(icon, label); return Math.max(floor, Math.round(content + (axis === 'width' ? pad.left + pad.right : pad.top + pad.bottom))); }; @@ -360,21 +362,40 @@ function rowsOf(table: SceneNode): SceneNode[] { } /** Header cells may hold a sort glyph or a select-all control beside text. */ -const HEADER_EXTRAS = new Set(['icon', 'checkbox', 'toggle', 'radio', 'select']); +const CONTROLS = new Set(['checkbox', 'toggle', 'radio', 'select']); + +/** The first text in a row, depth first. */ +function firstTextIn(row: SceneNode): SceneNode | undefined { + for (const c of row.children ?? []) { + if (textOf(c) !== undefined) return c; + const t = c.type === 'frame' ? firstTextIn(c) : undefined; + if (t) return t; + } + return undefined; +} /** A header row: its content is text, plus icons and controls (a sort glyph, - * a select-all checkbox), at least two texts. */ -function isHeaderRow(row: SceneNode): boolean { + * a select-all checkbox), at least two texts. A first row holding a control + * reads the same as a row-select data row, so it is a header only when its + * text is styled apart from the next row's (weight, size, colour, case or + * tracking). */ +function isHeaderRow(row: SceneNode, next?: SceneNode): boolean { let texts = 0; + let controls = 0; let other = false; (function walk(n: SceneNode) { for (const c of n.children ?? []) { if (textOf(c) !== undefined) texts++; else if (c.type === 'frame') walk(c); - else if (!HEADER_EXTRAS.has(c.type) && c.type !== 'text') other = true; + else if (CONTROLS.has(c.type)) controls++; + else if (c.type !== 'icon' && c.type !== 'text') other = true; } })(row); - return !other && texts >= 2; + if (other || texts < 2) return false; + if (controls === 0) return true; + const [a, b] = [firstTextIn(row), next ? firstTextIn(next) : undefined]; + if (!a || !b) return false; + return (['fontWeight', 'fontSize', 'color', 'textTransform', 'letterSpacing'] as const).some((k) => a[k] !== b[k]); } /** A row holding a title over a subtitle: some non-horizontal frame in it @@ -420,7 +441,7 @@ export function checkRowRhythm(ctx: DesktopContext, tableIds: Set): Eval (function walk(n: SceneNode) { if (!tableIds.has(n.id)) { n.children?.forEach(walk); return; } const rows = rowsOf(n); - const header = rows.length > 0 && isHeaderRow(rows[0]) ? rows[0] : undefined; + const header = rows.length > 0 && isHeaderRow(rows[0], rows[1]) ? rows[0] : undefined; const body = header ? rows.slice(1) : rows; const classes = [body.filter((r) => !isTwoLine(r)), body.filter(isTwoLine)]; const oneLine = classes[0].map(heightOf).filter(isNum); @@ -484,8 +505,8 @@ export function checkTruncation(ctx: DesktopContext, tableIds: Set): Eva const headerTexts = new Set(); (function findHeaders(n: SceneNode) { if (tableIds.has(n.id)) { - const first = rowsOf(n)[0]; - if (first && isHeaderRow(first)) (function walk(x: SceneNode) { if (x.type === 'text') headerTexts.add(x); x.children?.forEach(walk); })(first); + const [first, second] = rowsOf(n); + if (first && isHeaderRow(first, second)) (function walk(x: SceneNode) { if (x.type === 'text') headerTexts.add(x); x.children?.forEach(walk); })(first); return; } n.children?.forEach(findHeaders); diff --git a/src/index.ts b/src/index.ts index 4944b5c..3643356 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2141,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 desktop-app canvas rulesOn also lists the desktop-app ruleset, each finding tagged with its "rule": desktop-app-target (usability: the 24px floor above, named — fast WARNING, detailed ERROR when the 24px circle reaches a neighbour; an unlabelled link with no authored width measures its glyphs, 14px wide or 30 with external, on web too), desktop-app-handbuilt-target (usability info, never blocks: a frame below 32px holding one icon, an icon plus a label of ≤3 words, or a bordered padded frame holding one such label — the shape an imported text button takes; never inside a clickable primitive; rebuild it as a button or link if clickable), desktop-app-icon-label (usability WARNING: an icon-only button or link with no ariaLabel, a collapsed nav-item with a blank label), desktop-app-current (usability WARNING: in one pane — a frame with overflow "auto", or the root; each node belongs to its nearest, so give each navigation region its own pane — two active nav-items at one depth, or two or more nav-items with none active; a tabs node with no active tab or more than one; two active tree-rows under one parent; info: a tree with a current row nesting past two levels), desktop-app-type-ladder (typography WARNING, replaces type-scale-ratio: adjacent sizes a 1 ? Math.max(base, rows * TEXT_INPUT_LINE + 12) : base; } +/** A width written as a px string ("10px"). */ +function pxWidth(v: unknown): number | undefined { + const m = typeof v === 'string' ? /^\s*(\d+(?:\.\d+)?)px\s*$/.exec(v) : null; + return m ? Number(m[1]) : undefined; +} + +/** No width, or one that sizes to content. */ +const hugsWidth = (v: unknown): boolean => v === undefined || v === null || v === '' || v === 'auto'; + /** The width an unlabelled link renders at: its 14px icon and 12px * external-link glyph, 4px apart (renderLink). */ export function linkGlyphWidth(n: SceneNode): number { @@ -141,9 +150,10 @@ export function desktopTargets(n: SceneNode): Array<{ what: string; w?: number; const disabled = n.disabled === true; switch (n.type) { // A link never renders shorter than 24 (min-height), whatever its height. - // Without a label and without an authored width it hugs its glyphs, so - // its width is known (slice C); a non-numeric width stays unknown. - case 'link': return [{ what: 'link', w: w ?? (n.width === undefined && !hasText(n.label) ? linkGlyphWidth(n) : undefined), h: Math.max(LINK_MIN_HEIGHT, h(LINK_MIN_HEIGHT)), disabled }]; + // A px width is its width; without a label and with no width (or "auto") + // it hugs its glyphs, so its width is known (slice C); a fluid or token + // width stays unknown. + case 'link': return [{ what: 'link', w: w ?? pxWidth(n.width) ?? (hugsWidth(n.width) && !hasText(n.label) ? linkGlyphWidth(n) : undefined), 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 }]; diff --git a/test-desktop-app-rules.ts b/test-desktop-app-rules.ts index 22bd8a4..6aa55bf 100644 --- a/test-desktop-app-rules.ts +++ b/test-desktop-app-rules.ts @@ -381,7 +381,7 @@ const nav = (id: string, extra: Partial = {}): SceneNode => ({ id, na // FR-C6 / FR-C7 with a select-all header (round 1), and the tolerance edge. const row = (id: string, h: number, cells: SceneNode[]) => frame(id, cells, { layout: 'horizontal', height: h }); const table = (headerH: number, headerExtra: Partial = {}) => frame('users', [ - row('head', headerH, [{ id: 'hc', name: 'hc', type: 'checkbox' }, text('h1', 'Name', 13, headerExtra), text('h2', 'Role', 13)]), + row('head', headerH, [{ id: 'hc', name: 'hc', type: 'checkbox' }, text('h1', 'Name', 13, { fontWeight: 600, ...headerExtra }), text('h2', 'Role', 13, { fontWeight: 600 })]), ...[0, 1, 2].map((i) => row(`r${i}`, 32, [{ id: `c${i}`, name: `c${i}`, type: 'checkbox' }, text(`r${i}a`, `Ada ${i}`, 13), text(`r${i}b`, 'Admin', 13)])), ]); let f = await findings('desktop-app-row-rhythm', [table(40)]); @@ -390,6 +390,43 @@ const nav = (id: string, extra: Partial = {}): SceneNode => ({ id, na check('FR-C6: 2px off warns', f.length === 1, show(f)); f = await findings('desktop-app-truncation', [table(32, { textOverflow: 'ellipsis' })]); check('round 1: a truncating header beside a select-all checkbox warns', f.length === 1 && f[0].severity === 'warning', show(f)); + // Round 2: a table with NO header whose rows each lead with a row-select + // checkbox — the first data row is styled like the rest, so it is data. + const headerless = (firstH: number, firstExtra: Partial = {}) => frame('users', [0, 1, 2].map((i) => + row(`r${i}`, i === 0 ? firstH : 32, [{ id: `c${i}`, name: `c${i}`, type: 'checkbox' }, text(`r${i}a`, `Ada ${i}`, 13, i === 0 ? firstExtra : {}), text(`r${i}b`, 'Admin', 13)]))); + f = await findings('desktop-app-row-rhythm', [headerless(40)]); + check('round 2: a headerless row-select table compares its first row as a body row (info, not a header warning)', f.length === 1 && f[0].severity === 'info', show(f)); + f = await findings('desktop-app-truncation', [headerless(32, { textOverflow: 'ellipsis' })]); + check('round 2: a truncating first data cell is no column header (info, not a warning)', f.length === 1 && f[0].severity === 'info', show(f)); +} +{ + // Round 2: the stacked estimate sums only an icon and caption that are both + // in-flow children of the frame. + const icon20 = (): SceneNode => ({ id: 'si', name: 'si', type: 'icon', icon: 'house', iconSize: 20 }); + let f = await findings('desktop-app-handbuilt-target', [frame('f', [frame('w', [icon20(), text('st', 'Home', 11)], { layout: 'horizontal' })], { layout: 'vertical', padding: 4 })]); + check('round 2: an icon and caption side by side in a nested row are not stacked (28px, named)', f.length === 1, show(f)); + f = await findings('desktop-app-handbuilt-target', [frame('f', [icon20(), text('st', 'Home', 11, { position: 'absolute' })], { layout: 'vertical', padding: 4 })]); + check('round 2: an absolutely positioned caption is not stacked (28px, named)', f.length === 1, show(f)); +} +{ + // Round 2: link widths that size to content, or are written in px, are known. + const link = (width: unknown): SceneNode => ({ id: 'l', name: 'l', type: 'link', icon: 'arrow-left', width } as unknown as SceneNode); + for (const [width, expect] of [['auto', /14×24px/], [null, /14×24px/], ['', /14×24px/], ['10px', /10×24px/]] as const) { + const f = await findings('desktop-app-target', [link(width)]); + check(`round 2: an icon-only link with width ${JSON.stringify(width)} is measured`, f.length === 1 && expect.test(f[0].message), show(f)); + } + const f = await findings('desktop-app-target', [link('$link-width')]); + check('round 2: a token width stays unknown (not measured at the glyph)', f.length === 0, show(f)); +} +{ + // Round 2: S3 edges. + const c = canvasOf([{ id: 'l', name: 'l', type: 'link', icon: 'arrow-left', ariaLabel: 'a"b&d', disabled: true } as SceneNode]); + const html = renderToHtml(c.root, 1440, 900, c); + check('round 2: a disabled link keeps its escaped name', /aria-disabled="true"/.test(html) && html.includes('aria-label="a"b<c>&d"'), html.match(/aria-label="[^"]*"/)?.[0]); + const f = await findings('desktop-app-icon-label', [{ id: 'l', name: 'l', type: 'link', icon: 'arrow-left', ariaLabel: ' ' } as SceneNode]); + check('round 2: a blank ariaLabel is no name', f.length === 1, show(f)); + const tok = await findings('desktop-app-type-ladder', [text('a', 'A', '$missing' as unknown as number), text('b', 'B', 36)]); + check('round 2: an unresolved size reads as the 14px fallback (14 → 36 warns, no crash)', tok.length === 1 && /14px → 36px/.test(tok[0].message), show(tok)); } { // FR-C8 edges (round 1: a primary is whatever renders filled). From 6f1616000a05566a9558956f695e38f209afe720 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Fri, 13 Nov 2026 21:43:21 +0100 Subject: [PATCH 4/4] Tidy three desktop-app rule comments --- src/desktop-app-rules.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/desktop-app-rules.ts b/src/desktop-app-rules.ts index 7839972..27148d5 100644 --- a/src/desktop-app-rules.ts +++ b/src/desktop-app-rules.ts @@ -134,8 +134,8 @@ function lineBox(t: SceneNode): number { * icon, one icon plus a label of three words or fewer, or (spec change S2) a * bordered, padded frame holding one such label and nothing else, the shape * an imported text button takes. Info only, as on mobile: a frame cannot say - * it is decorative. A frame inside a clickable primitive (a property-row's - * value) is never hand-built. Detailed mode measures the rendered box; fast + * it is decorative. A frame inside a clickable primitive or a property-row + * (its value slot) is never hand-built. Detailed mode measures the rendered box; fast * mode reads an authored size, else estimates the height from the icon or * the label's line box plus vertical padding (an icon-only frame's width the * same way; a labelled frame's width is unknown). */ @@ -361,7 +361,7 @@ function rowsOf(table: SceneNode): SceneNode[] { && (table.name === 'Table' || c.layout === 'horizontal')); } -/** Header cells may hold a sort glyph or a select-all control beside text. */ +/** The controls a header cell may hold beside its text (a select-all box). */ const CONTROLS = new Set(['checkbox', 'toggle', 'radio', 'select']); /** The first text in a row, depth first. */ @@ -564,7 +564,8 @@ const REPEAT_MIN = 3; /** More than one primary button in one region (the nearest pane) is an info. * A primary inside one of three or more same-shaped sibling frames (shape - * hash without names) is not counted. (A modal's primary action joins with the overlays, slice E.) */ + * hash without names) is not counted. A modal's primary action joins with the + * overlays (slice E). */ export function checkPrimaryCount(ctx: DesktopContext): EvaluationIssue[] { const issues: EvaluationIssue[] = []; const parentOf = parents(ctx.root);