diff --git a/README.md b/README.md index d4522ef..48d1a84 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ MCP Client → stdio → framesmith server Left to itself, an AI agent tends to produce UI that *looks* AI-generated — generic spacing, no icons, a purple gradient by default, placeholder text that reads like placeholder text. framesmith closes that gap by moving design **before** code and holding it to a bar: -1. **Start from taste, not a blank canvas.** The agent stamps one of **11 vetted page patterns** (dashboard, auth, pricing, settings, onboarding, and more), or on a phone canvas one of **6 mobile realisations** built from the mobile primitives — each regression-tested to score **> 95 with zero cliché tells** under the neutral default theme and all four presets (a mobile realisation takes the presets' colours over a phone type scale, is also held to every personality's generated phone system, and raises no mobile-ruleset finding), and every structure (page and component alike) built entirely from type-role tokens so it re-voices under a generated design system instead of injecting stray pixel sizes, and hardened to survive hostile-length content (`canvas_stress` CLEAN) — then adapts it. A blank canvas is where slop comes from; a pattern is a non-slop starting point. *(`list_structures` / `apply_structure`)* +1. **Start from taste, not a blank canvas.** The agent stamps one of **11 vetted page patterns** (dashboard, auth, pricing, settings, onboarding, and more), or on a phone canvas one of **6 mobile realisations** built from the mobile primitives, or on an application canvas one of **6 desktop-app realisations** built from the desktop-app primitives — each regression-tested to score **> 95 with zero cliché tells** under the neutral default theme and all four presets (a mobile realisation takes the presets' colours over a phone type scale, is also held to every personality's generated phone system, and raises no mobile-ruleset finding), and every structure (page and component alike) built entirely from type-role tokens so it re-voices under a generated design system instead of injecting stray pixel sizes, and hardened to survive hostile-length content (`canvas_stress` CLEAN) — then adapts it. A blank canvas is where slop comes from; a pattern is a non-slop starting point. *(`list_structures` / `apply_structure`)* 2. **Use the whole toolkit — like a real UI does.** Real icons (Lucide + Material Symbols), fonts resolved by name, real input controls (`toggle` / `checkbox` / `radio` / `select`), data-driven charts (line/bar/donut/sparkline, multi-series, bar emphasis), reusable components, and layered design tokens — never faked with Unicode glyphs, stray ellipses, or hand-drawn SVG paths standing in for a chart. 3. **Evaluate, then self-correct.** `canvas_evaluate` scores the design across five craft categories plus a **cliché-tell** detector, a **state-coverage** check (a data screen without designed empty/loading states isn't done), and a **usability** layer (hit-target floor, label association, honest action copy), and returns a **`READY` / `NOT READY` directive**. The agent resolves every warning and tell and only presents once it's `READY` — polishing to the bar is the agent's job, not yours. 4. **Review in the browser, own the output.** You browse canvases like design files, with a live **quality inspector** and **design-system panel**. Designs persist as **open JSON checked into your repo** — no proprietary format, no lock-in — and can be re-imported from shipped HTML to keep the design honest. @@ -52,7 +52,7 @@ Left to itself, an AI agent tends to produce UI that *looks* AI-generated — ge | Area | What you get | |------|--------------| | **Rendering** | Scene graph → HTML/CSS → Puppeteer PNG · responsive breakpoints · real CSS grid (`layout: "grid"` + spans) for bento/editorial compositions · gradients, shadows, blur, glassmorphism · SVG paths · animations · data-driven charts (line/bar/donut/sparkline, multi-series, bar emphasis + in-SVG gradients) | -| **Pattern library** | 11 vetted page archetypes + 6 mobile realisations + 14 component scaffolds, all scoring > 95 with zero cliché tells, typography built from type-role tokens (not literal pixel sizes), and stress-hardened to survive hostile-length content; taxonomy axes + a diversification signal so successive screens vary | +| **Pattern library** | 11 vetted page archetypes + 6 mobile realisations + 6 desktop-app realisations + 16 component scaffolds, all scoring > 95 with zero cliché tells, typography built from type-role tokens (not literal pixel sizes), and stress-hardened to survive hostile-length content; taxonomy axes + a diversification signal so successive screens vary | | **Quality & taste** | `canvas_evaluate` (8 categories incl. cliché tells, state coverage + usability floors) with a `READY`/`NOT READY` directive · `canvas_autofix` (mechanical fixes) · optional vision-model rubric critique + `canvas_revise` · `canvas_add_variant` clones a screen into a linked empty/loading/error state · `canvas_stress` content-perturbation testing (long text, i18n, big numbers, empty/many rows) · `project_evaluate` rolls up a project's screens for cross-screen consistency (radius/accent drift, token adoption, hand-copied chrome, state coverage) plus an optional multi-screen flow critique — advisory, never a gate | | **Design systems** | `generate_design_system`: one seed + one personality (`technical` / `editorial` / `soft` / `data-dense`) → the complete design language — colors, curated font pairing, typography roles, radius/density stances, `$elevation` depth tokens (dark-aware), `$motion` defaults · layered `$token`s (workspace ▸ project ▸ canvas) · style presets · `DESIGN.md` import · `generate_scale` derives a modular type + spacing scale from a named ratio (optional fluid `clamp()` sizes) · `generate_color_system` turns one seed color into OKLCH ramps + AA-checked semantic tokens, a categorical chart palette, and a tint layer for chips/tiles/badges, dark theme included · dual-theme rendering + evaluation (`theme: "dark"` on screenshot/export, both-theme contrast in `canvas_evaluate` with APCA advisory) · token-detachment lint re-attaches literals that drift from a token | | **Primitives** | Lucide + Material Symbols icons · Google Fonts by name · real form controls · components with instance overrides — `create_component` promotes existing work, `copy_nodes` carries subtrees (and their component defs) across canvases | @@ -392,7 +392,7 @@ Application screens (`type: "desktop-app"`) are built from eight primitives on t | `tabs` | `items: [{ label, count?, active?, disabled? }]`, `variant` (`line` / `contained`), `size` (`sm` 32 / `md` 40) | One tablist; each tab is its own target. The active tab gets an indicator (`line`) or an `$accent-tint` fill (`contained`) | | `tree-row` | `label`, `depth`, `expanded` (absent for a leaf), `icon`, `active` | A 32px row indented 16px per level, with a chevron when `expanded` is set | | `menu-row` | `label`, `icon`, `shortcut`, `checked`, `destructive`, `disabled`, `submenu` | A 32px menu item; the shortcut right-aligns in a muted `kbd` style, `destructive` uses `$danger` | -| `property-row` | `label`, `labelWidth` (96), one child | An inspector row: a muted label column, then its value (a control, a `text-input`, a `button`, a text). A control that is its only target is measured by the row's box. The other desktop-app primitives drop any children | +| `property-row` | `label`, `labelWidth` (96), one child | An inspector row: a muted label column, then its value (a control, a `text-input`, a `button`, a text). A control that is its only target is measured by the row's box. The row's `label` names a control directly inside it; with a blank label only text inside the row itself does (a sibling row's text does not count). The other desktop-app primitives drop any children | | `divider` | `orientation` (`horizontal` / `vertical`), `inset` | A 1px `$border` hairline; vertical dividers separate panes | `fill`, `stroke`, `color`, `iconColor` and `secondaryColor` override the token defaults (`tabs.fill` is the contained variant's active background). A canvas that holds a `nav-item`, `tabs`, `tree-row`, `menu-row` or `property-row` must declare its type (`desktop-app-artboard`). @@ -662,13 +662,15 @@ Two kinds: **Mobile realisations.** Each structure realises an anatomy for one canvas type. Six page anatomies have a mobile realisation for a `type: "mobile"` canvas, built from the mobile primitives (status bar, nav bar, list rows, buttons, a pinned tab bar or home indicator) and gated like the web set: > 95 with zero cliché tells and zero mobile-ruleset findings in fast mode (the default theme, the four presets' colours over a phone type scale, and every personality's generated phone system), zero mobile-ruleset findings in detailed mode (as stamped and with every list tripled), and a CLEAN full `canvas_stress` run unthemed and under every personality: `dashboard-mobile`, `settings-mobile`, `auth-mobile`, `onboarding-mobile`, and two mobile-first anatomies, `feed-mobile` (a list of rows) and `detail-mobile` (an item with a pinned primary action). 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; the rest are web-only. The other web pages (`marquee-hero`, `bento-grid`, `stat-led`, `editorial-longform`, `split-workbench`, `catalogue`, `pricing`) have no mobile realisation. +**Desktop-app realisations.** Six page anatomies have a realisation for a `type: "desktop-app"` canvas, built from the desktop-app primitives (nav-items, tabs, property rows, text inputs, 24px icon buttons) and filling the window: the stamp sets the root's `overflow` to `"hidden"` so the root keeps the artboard's height, and every pane scrolls on its own. They are `split-workbench-app` (a sidebar, a header with a pane toggle, a work area and a detail panel), `list-detail-app` (navigation, a searchable list and a detail pane with a "nothing selected" placeholder), `editor-inspector-app` (a work area with a tool strip beside a 70/30 inspector of tabs and property rows), `browser-app` (a filter bar over an adaptive grid of item cards), `dashboard-app` and `settings-app`. Two components join them: `data-table-app` (a 32px toolbar, header row, body rows and pager, Carbon's density ladder) and its loading state `skeleton-table-app`. They are gated like the other sets, and harder: > 95 with zero cliché tells, zero desktop-app findings at any severity and zero warnings or errors in fast mode, under the default theme, the four presets merged after the stamp, every personality on three seeds, and a workspace design system inherited from above; in detailed mode, as stamped and with every list tripled; a CLEAN `canvas_stress` run unthemed and under every personality, at 1440×900, 1280×800 and 1024×768; tripled content scrolling inside its pane without squashing a row; and `data-table` stamped into each realisation's wide pane at 1440, 1100 and 1024 wide, wherever that pane is at least 480px wide (its documented minimum). `list-detail`, `editor-inspector` and `browser` exist only on desktop-app. + ### `apply_structure` Stamp a layout structure onto a canvas and return the placeholder node IDs to populate. Scaffolds are token-driven, not hard-coded: every scaffold's spacing, radius, elevation, and typography — all of it, every text node's `fontSize`, not just titles — reference `$space-*` / `$radius-*` / `$elevation.*` / the type-role tokens (`$display`/`$title`/`$heading`/`$text-lg`/`$text-sm`/`$body`/`$label`/`$caption`, plus the usual `$color` tokens), so once a project has a generated design system, stamping a pattern already reads in its density, depth, and voice — no re-theming pass needed, and no scaffold can inject a size the generated scale doesn't have. `apply_structure` seeds neutral defaults (the pre-generator literal values) for any of those tokens the canvas can't already resolve, so an unthemed canvas still renders correctly; the result's `seededColors` / `seededTokens` list exactly which names got seeded. Populate the placeholders with `batch_design` `U` ops, then `screenshot` to verify. - **Page scaffolds** insert at the canvas root (refusing on a non-empty canvas unless `replace`), record provenance (`metadata.provenance`), and append to the **per-project build log** that feeds the `diversification` signal. - **Component scaffolds** insert under `targetId` (default root), repeatably — every stamp re-keys its node IDs (`form-field-1-…`, `form-field-2-…`) and returns an `idMap` (template ID → live ID) for follow-up ops. Component stamps don't touch provenance or the build log: they don't shape the page. -- **The name resolves by the canvas's declared type.** An anatomy name stamps that anatomy's realisation for the type: `dashboard` on a mobile canvas stamps `dashboard-mobile`. A realisation name is used as is. A name with no realisation for the type is refused with the anatomies of the same kind that have one (`pricing` on a phone; a web-only component too, whose anatomy is its own name); `realisation` stamps another type's realisation anyway. Resolution reads the *declared* type (`canvas_create({ type: "mobile" })` or `canvas_set_type`): an undeclared canvas is web, whatever its width. The result names the `anatomy` and `surface` it stamped, and 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 `prop` is a path, not an op key: set a nested one by writing its whole object or array, siblings included (`U(id, { trailing: { text: "2h" } })` replaces `trailing`, so carry a `chevron` along; `items[0].label` means rewriting `items`). A stamp holding a primitive also seeds the colours the primitives read by default (`$text-primary`, `$text-secondary`, `$border`, and `$accent` / `$bg-surface` / `$danger` unless the canvas resolves `$primary` / `$surface` / `$error`), so `seededColors` can list names no node mentions. A scaffold node that names `$accent` or `$bg-surface` itself still seeds it, as every scaffold always has, so a hand-themed canvas should define both before stamping (the presets and `generate_design_system` do). +- **The name resolves by the canvas's declared type.** An anatomy name stamps that anatomy's realisation for the type: `dashboard` on a mobile canvas stamps `dashboard-mobile`, and on a desktop-app canvas `dashboard-app`. A realisation name is used as is. A name with no realisation for the type is refused with the anatomies of the same kind that have one (`pricing` on a phone; a web-only component too, whose anatomy is its own name); `realisation` stamps another type's realisation anyway. Resolution reads the *declared* type (`canvas_create({ type: "mobile" })` or `canvas_set_type`): an undeclared canvas is web, whatever its width. The result names the `anatomy` and `surface` it stamped, and 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 `prop` is a path, not an op key: set a nested one by writing its whole object or array, siblings included (`U(id, { trailing: { text: "2h" } })` replaces `trailing`, so carry a `chevron` along; `items[0].label` means rewriting `items`). A stamp holding a primitive also seeds the colours the primitives read by default (`$text-primary`, `$text-secondary`, `$border`, and `$accent` / `$bg-surface` / `$danger` unless the canvas resolves `$primary` / `$surface` / `$error`), so `seededColors` can list names no node mentions. A scaffold node that names `$accent` or `$bg-surface` itself still seeds it, as every scaffold always has, so a hand-themed canvas should define both before stamping (the presets and `generate_design_system` do). A stamp holding a desktop-app primitive also seeds `$border-strong`, never `$accent-tint`. | Param | Type | Description | |-------|------|-------------| @@ -676,7 +678,7 @@ Stamp a layout structure onto a canvas and return the placeholder node IDs to po | `structure` | string | Structure name (use `list_structures`, e.g. `"marquee-hero"`, `"data-table"`) | | `replace` | boolean? | Page scaffolds: if the root already has children, clear them before stamping. Default `false` (refuses on a non-empty canvas) | | `targetId` | string? | Component scaffolds: node to stamp under (default `"document"`) | -| `realisation` | `"web"` \| `"mobile"` \| `"desktop-app"`? | Stamp the realisation for this type instead of the canvas's own (e.g. `"web"` for the web dashboard on a phone canvas) | +| `realisation` | `"web"` \| `"mobile"` \| `"desktop-app"`? | Stamp the realisation for this type instead of the canvas's own (e.g. `"web"` for the web dashboard on a phone canvas, or a web-only component such as `toolbar` on a desktop-app canvas) | ### `canvas_import_html` @@ -1049,10 +1051,10 @@ Content stress test — does the design survive real data? Re-renders the canvas | `long-text` | Non-data text ×2.2 plus one long unbroken token (the wrap-breaker) | | `i18n` | Text ×1.4 — the German/Finnish expansion rule | | `big-numbers` | Data-like text to its widest realistic form: `9` → `999+`, `$1.5M` → `$1,520,847.33` | -| `empty` | Detected tables lose their data rows (and runs of two or more consecutive `list-row`s are emptied) | -| `many` | Data rows ×3 (and `list-row` runs ×3) | +| `empty` | Detected tables lose their data rows (and runs of two or more consecutive `list-row`s are emptied; on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row`, and card grids) | +| `many` | Data rows ×3 (and `list-row` runs ×3; on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row`, and card grids, a grid of three or more same-shaped children). Copies drop `active`, so a tripled list keeps one current row | -Finding kinds: `clip` (content cut off — *info* when a designed `text-overflow: ellipsis` is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; a sheet's own vertical overflow scrolls and is never a clip; *warning* otherwise), `overflow-x` (a node escapes its parent box or the canvas), `layout-shift` (an **untouched** node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent are exempt). Only **new** breakage counts: anything already clipping at baseline is the design's standing state. Tables are found with the same inventory drift and coverage use; component instances are expanded first. +Finding kinds: `clip` (content cut off — *info* when a designed `text-overflow: ellipsis` is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet or of any frame with `overflow: "auto"` (an app pane) scrolls and is never a clip, while its horizontal overflow still is; *warning* otherwise), `overflow-x` (a node escapes its parent box or the canvas), `layout-shift` (an **untouched** node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent are exempt). Only **new** breakage counts: anything already clipping at baseline is the design's standing state. Tables are found with the same inventory drift and coverage use; component instances are expanded first. | Param | Type | Description | |-------|------|-------------| diff --git a/VISION.md b/VISION.md index e78cf80..3a1077b 100644 --- a/VISION.md +++ b/VISION.md @@ -566,7 +566,8 @@ 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`) - [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 +- [x] Slice D — panes: resolution for any number of types, six desktop-app realisations (workbench, list-detail, editor-inspector, browser, dashboard, settings) and the `data-table-app` / `skeleton-table-app` components under the pattern gate, scrolling panes that stress reads as scrolling, and stress runs that triple app rows and card grids +- [ ] Follow-up — the web scaffolds' tint tokens (`success-tint` and the rest) are seeded dark and survive a later light `apply_preset`, as `accent-tint` did before Phase 31 slice D stopped seeding it; derive them from the applied palette instead - [ ] 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 - [ ] Slice G — element states: hover, focus, pressed and disabled as a primitive property, drawn from state tokens diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 23f94b0..c641f50 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -75,7 +75,7 @@ None of these rules has a mechanical fix, so `canvas_autofix` never proposes one ## The desktop-app ruleset -A `desktop-app` canvas is judged as an application, not a page. Its vocabulary is in [Desktop-app vocabulary](#desktop-app-vocabulary); 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. +A `desktop-app` canvas is judged as an application, not a page. Its vocabulary is in [Desktop-app vocabulary](#desktop-app-vocabulary) and its layouts in [Starting an application screen](#starting-an-application-screen-desktop-app-realisations); 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. 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). @@ -95,7 +95,7 @@ Two terms the rules share. A **pane** is a frame that scrolls on its own (`overf - **`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. -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. +Start an application screen from a desktop-app realisation, not a web page: see [Starting an application screen](#starting-an-application-screen-desktop-app-realisations). ### The 24px floor (web and desktop-app) @@ -117,10 +117,10 @@ Build application screens from these primitives, never from hand-built frames: a - **`tabs`** `{ items: [{ label, count?, active?, disabled? }], variant?: "line" | "contained", size?: "sm" | "md" }` is one tablist (32 or 40 tall). Each tab is its own target. The active tab gets an underline indicator (`line`) or an `$accent-tint` fill (`contained`, from the node's `fill`) and a heavier label. - **`tree-row`** `{ label, depth, expanded?, icon?, active? }` is a 32px row indented 16px per level. `expanded: true` / `false` draws an open / closed chevron; a leaf leaves it out and keeps the slot, so labels align. - **`menu-row`** `{ label, icon?, shortcut?, checked?, destructive?, disabled?, submenu? }` is a 32px menu item. The shortcut right-aligns in a muted `kbd` style, `destructive` uses `$danger`, `submenu` adds a chevron, and `checked` reserves a check slot. -- **`property-row`** `{ label, labelWidth? }` with one child is an inspector row: a muted label column (96px by default) and the value (a control, a `text-input`, a `button`, a text). Every row's value starts at the same edge. A control that is its only target (directly inside, nothing clickable beside it) is measured by the row's 32px box. Only `property-row` renders children; the other desktop-app primitives draw their own anatomy and drop any children you give them. +- **`property-row`** `{ label, labelWidth? }` with one child is an inspector row: a muted label column (96px by default) and the value (a control, a `text-input`, a `button`, a text). Every row's value starts at the same edge. The row's `label` names a control directly inside it; with a blank label only text inside the row itself does, and otherwise the control gets the usability warning "has no text label" (a sibling row's text does not count). A control that is its only target (directly inside, nothing clickable beside it) is measured by the row's 32px box. Only `property-row` renders children; the other desktop-app primitives draw their own anatomy and drop any children you give them. - **`divider`** `{ orientation?: "horizontal" | "vertical", inset? }` is a 1px `$border` hairline; vertical dividers separate panes. Not a target. -Repeated desktop-app primitives count as component reuse. On an unthemed canvas, stamping a structure that holds them seeds `$accent-tint` and `$border-strong` along with the usual neutrals. +Repeated desktop-app primitives count as component reuse. On an unthemed canvas, stamping a structure that holds them seeds `$border-strong` along with the usual neutrals, never `$accent-tint`: without that token an active fill mixes 12% of `$accent` into whatever surface is applied later. ### Lists that lead with a mark are not tables (every type) @@ -171,10 +171,31 @@ A structure realises an **anatomy** (a screen kind) for one canvas type. A canva Every one starts with a `status-bar`, ends with a `home-indicator` or a pinned `tab-bar`, and builds every tap target from a primitive, so it passes the mobile ruleset in fast and detailed mode and survives `canvas_stress`, unthemed and under every personality. Adapt it like any scaffold, taking node ids and fields from the result's `placeholders` rather than guessing them: each entry is `{ id, role, prop? }`, where `role` is the placeholder copy and `prop` is the path of a primitive's copy field (`title`, `subtitle`, `label`, `trailing.text`, `leading.initials`, `leading.label`, `items[0].label`). A `prop` is a path, not an op key: set a top-level one directly, a nested one by writing its whole object or array with its siblings (a `trailing` you write replaces the old one, chevron included; a tab label means rewriting `items`): `U("dm-row-1", { title: "Morning run", subtitle: "5.2 km", trailing: { text: "7:12" } })`, `U("amb-submit", { label: "Sign in" })`. - **Use `generate_design_system` for a phone's type**, then stamp. The `dark`, `light` and `material` presets set a 14–15px `$body` (`minimal` sets 16), which `mobile-type-floor` flags on every phone screen that sets text in `$body` (`auth`, `onboarding` and `detail` do); the stamp's own neutral defaults (a 16px body) pass. -- **`list_structures({ canvasId })`** lists what stamps on that canvas: on a phone, the six realisations and the components marked for every type (`form-field`, `stat-card`, `empty-state`, `skeleton-card`, `skeleton-stat-card`, `kpi-card`, `status-chip`, `initials-avatar`). Each entry names its `anatomy` (for a component, its own name), its `surface` (`web`, `mobile` or `any`) and `surfaces`, the types its anatomy is realised on (`["web", "mobile"]` for `dashboard`, `["mobile"]` for `feed-mobile`). Passing `canvasId` and `type` together is an error. +- **`list_structures({ canvasId })`** lists what stamps on that canvas: on a phone, the six realisations and the components marked for every type (`form-field`, `stat-card`, `empty-state`, `skeleton-card`, `skeleton-stat-card`, `kpi-card`, `status-chip`, `initials-avatar`). Each entry names its `anatomy` (for a component, its own name), its `surface` (`web`, `mobile`, `desktop-app` or `any`) and `surfaces`, the types its anatomy is realised on (`["web", "mobile"]` for `dashboard`, `["mobile"]` for `feed-mobile`). Passing `canvasId` and `type` together is an error. - **A name with no realisation for the canvas's type is refused**, with the anatomies of the same kind that have one: `pricing` on a phone, or a web-only component such as `data-table` (its 28px pager buttons are hand-built), `toolbar` or `toggle-row`. `realisation: "web"` stamps the web one anyway, and `realisation: "mobile"` stamps a mobile one on a web canvas. - **The realisations never write `safeArea`.** Their pinned chrome makes the renderer reserve the insets, so they are also correct on a canvas made mobile with `canvas_set_type`. +## Starting an application screen (desktop-app realisations) + +On a desktop-app canvas, `apply_structure` resolves an anatomy name to its desktop-app realisation, so `apply_structure({ canvasId, structure: "dashboard" })` stamps `dashboard-app`. Six page anatomies have one; three of them exist only on desktop-app: + +| Anatomy | Desktop-app realisation | Shape | Coverage asks for | +|---|---|---|---| +| `split-workbench` | `split-workbench-app` | A sidebar of nav-items, a header (title, a secondary and a primary action, a pane toggle as an icon-only `xs` button), a work area and a 300px detail panel of property rows | nothing | +| `list-detail` | `list-detail-app` | A sidebar, a searchable list of `list-row`s and a detail pane holding a designed "nothing selected" placeholder (no row is active until one is chosen) | nothing | +| `editor-inspector` | `editor-inspector-app` | A header (a breadcrumb `link`, the document title, Share and Publish), a work area with a tool strip of icon-only buttons, and a 70/30 inspector of `tabs` and property rows (two text inputs, a select, a toggle, a button) | `error` (its four controls make it a form) | +| `browser` | `browser-app` | A sidebar, a header with the one primary action, a filter bar (search field, contained tabs) and an adaptive grid of item cards (columns at least 240px wide) whose titles are links | nothing | +| `dashboard` | `dashboard-app` | A sidebar, a header with Export, a four-up stat row, a trend chart and a recent-items table on the 32px ladder | `empty`, `loading` (the table) | +| `settings` | `settings-app` | A sidebar of setting sections beside a column of grouped property rows (text inputs, a select, toggles), a danger zone with a destructive Delete, and Cancel / Save | `error` (a form) | + +Two components join them: `data-table-app` (the `data-table` anatomy on desktop-app: a 32px toolbar with a search field and a filter, a 32px header row over 32px body rows with a right-aligned amount and an icon-only row-actions button under a blank header, and a 32px pager; coverage asks for `empty` and `loading`; stamp it into a pane at least 480px wide, such as a content, work or detail pane, not the 300px side panel, the inspector, or `list-detail-app`'s detail pane in a 1024px window, where its column names wrap and the header outgrows its rows) and `skeleton-table-app` (its loading state, the same header over skeleton rows of the same height and columns). Stamp a component by its anatomy name under a node: `apply_structure({ canvasId, structure: "data-table", targetId })` stamps `data-table-app` on a desktop-app canvas; stamped into each realisation's wide pane, at 1440, 1100 and 1024 wide wherever that pane is at least 480px, it is gated like the realisation itself. For the loading state, `canvas_add_variant({ canvasId, state: "loading" })`, delete the table's rows in the variant and stamp `skeleton-table` there the same way (it resolves to `skeleton-table-app`); the coverage hint for a missing `loading` state names it. An empty state is `empty-state`, which stamps on every type. An anatomy that exists only on desktop-app (`list-detail`, `editor-inspector`, `browser`) is refused on a web or phone canvas with `Pass realisation: "desktop-app"`, which stamps it anyway. + +- **They fill the window and scroll by pane.** A desktop-app page stamp sets the root's `overflow` to `"hidden"`, which keeps the root at the artboard's height (a root with no authored overflow grows with its content). The shell is `height: "100%"`, and the sidebar, list, detail, work area, inspector and content panes are each `overflow: "auto"`, so long content scrolls inside its pane while the window stays put. Stamping a different page with `replace` removes that root `overflow` again, unless it no longer reads `"hidden"` (an `overflow` you set to anything else stays). Keep the pattern when you adapt one: put new content inside a pane, never give a pane's direct child a fixed `height` or an `overflow` (either lets the pane squash it instead of scrolling), and give a fixed-width pane a matching `minWidth` (a scrolling pane may otherwise shrink below its width). Rows go inside the frame that already holds rows (in `settings-app`, a group's `Rows` frame; in `list-detail-app`, the `Rows` frame of the list pane), which is a direct child of the pane only through its group, so it grows and the pane scrolls. +- **They pass the gate the docs promise.** Each scores > 95 with zero cliché tells, zero desktop-app findings at any severity and zero warnings or errors in fast mode, under the default theme, the four presets applied after the stamp, every personality on three seeds and a workspace design system inherited from above; in detailed mode as stamped and with every list tripled; with a CLEAN `canvas_stress` run unthemed and under every personality; and at 1024×768 and 1280×800, where long labels truncate instead of pushing a bar past the window (the shell fills any artboard height, and the narrowest window the desktop-app layouts are built for is 1024 wide; 1440×900 is the default). Infos from other categories may remain; nothing that blocks the directive does, so after a stamp `canvas_evaluate` says READY TO PRESENT unless coverage asks for a state. Coverage is the exception: a stamp with a table or a form asks for the states in the table above, which you design with `canvas_add_variant`. +- **Stamp after `generate_design_system`, or apply a preset after the stamp.** Both work. A stamp on an unthemed canvas seeds `$border-strong` but not `$accent-tint`: without the token an active `nav-item` or `tabs` fill mixes 12% of `$accent` into whatever surface is applied later, so a light preset never inherits a dark tint. +- **Adapt it from the placeholders.** As on mobile, the result's `placeholders` list every copy field with its `prop` path (`label`, `placeholder`, `value`, `items[0].label`). A control inside a `property-row` is labelled by that row's `label`, so keep it filled. +- **Web-only components stay web-only.** `toolbar`, `toggle-row`, `segmented-control` and `breadcrumb` are refused on desktop-app with the list of components that stamp there; `realisation: "web"` forces one anyway. The realisations draw their own breadcrumb from a `link`. + ## Responsive hints Set `responsive` on **container nodes** (frames with `layout: "horizontal"` or `layout: "grid"` and children). The renderer emits the right media-query rules — flex-wrap for horizontal containers, a single-column collapse with spans reset for grid. @@ -396,12 +417,12 @@ The happy path of one static frame with ideal data is half a design. Real UX liv | State | Scaffold | Notes | |---|---|---| | `empty` | `empty-state` | Icon + title + one-line hint + CTA — an empty screen is a first-run experience, never a bare void | -| `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 | +| `loading` | `skeleton-table` / `skeleton-card` / `skeleton-stat-card` (`skeleton-table-app` on a desktop-app canvas) | 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, 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. +**Then stress it.** `canvas_stress` re-renders the canvas under hostile-but-realistic content — `long-text` (×2.2 + an unbroken German compound), `i18n` (×1.4), `big-numbers` (`9` → `999+`, `$1.5M` → `$1,520,847.33`), `empty`, `many` (rows ×3; tables and runs of `list-row`s on every type, and on a desktop-app canvas also runs of `nav-item`, `tree-row`, `menu-row` or `property-row` and card grids, a grid of three or more same-shaped children; a tripled list keeps one active row) — and reports what broke, by node id: `clip` (info when a designed ellipsis is doing its job, or when it's a primitive's label hitting its designed ellipsis, or a root with an authored `overflow` clipping or scrolling inside itself; the vertical overflow of a sheet or of any frame with `overflow: "auto"` scrolls and is never a clip, while its horizontal overflow still is; warning otherwise), `overflow-x`, `layout-shift` (an untouched node ballooning — perturbed nodes, their ancestors, and a stretch sibling that merely follows a legitimately growing parent, like a full-height sidebar next to a growing table, are all exempt). Only *new* breakage counts. Fix findings with the [width strategies](#width-strategies) above — fluid widths, `minWidth` or `minHeight` floors, wrapping — or give a must-stay-single-line label `textOverflow: "ellipsis"` (the designed-truncation property: the clip downgrades to info because truncating is the design) — and re-run until `CLEAN`. A data screen goes to the user with its states designed and a `CLEAN` stress verdict, the same way it goes with a >95 score. `canvas_evaluate` holds you to it: once stress has recorded a verdict, the evaluate result carries a `stress` field (`{ verdict, warnings, type, current }` — `current` is false after an edit or a type change since the run), and a `FRAGILE` verdict keeps the directive `NOT READY` until a full `CLEAN` run (all five perturbations) replaces it — a subset run can record `FRAGILE` but never clear it. The verdict lives in server memory, so a restart forgets it. ## Reviewing the set diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 6e8a856..07008ab 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -123,7 +123,7 @@ One profile ships, keyed by id so a second size is one table row later. Values i | **FR-C9** | **The declaration matches the window.** Rule `desktop-app-artboard`, in the base ruleset like `mobile-artboard`, so it runs on every type: a desktop-app canvas narrower than 1024 warns; an undeclared canvas containing a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) or an overlay primitive warns until a type is declared; an explicit `web` canvas containing a desktop-app primitive gets an info; an explicit `mobile` canvas containing one warns. Overlays alone never trip the web or mobile cases, since pages and phones use them too. | A 900px desktop-app canvas warns; an undeclared canvas with a `nav-item` is NOT READY until `canvas_set_type`; a mobile canvas with a `nav-item` warns, and one with only a `modal` does not. | | **FR-C10** | **Form coverage counts text-inputs** (added 2026-11-13, slice B as-built). The coverage category's form demand (3+ input controls on a base canvas demand an `error` variant) counts `text-input` as an input control, on every type, alongside the toggle, checkbox, radio and select. Drift's control list (`CONTROL_TYPES`, `src/drift.ts`) is unchanged: the importer never produces a `text-input`, so adding it there would make every drift comparison report a control the page doesn't have. | Three `text-input`s on a base canvas demand an `error` variant; two `text-input`s and a checkbox do too; the same form with an `error` variant is silent; `canvas_check_drift` output is unchanged. | | **FR-D1** | **Resolution for any number of types.** `resolveStructure` and `listStructures` (`src/structures.ts:1834`, `:1863`) stop assuming two types: an anatomy resolves to the realisation for the canvas type; with none, the error names every type that has one and the `realisation` value that forces it. `Structure.surface` accepts `'desktop-app'`; `'any'` keeps meaning every type. | `apply_structure("pricing")` on a desktop-app canvas refuses and names `web`; `apply_structure("feed")` refuses and names `mobile`. | -| **FR-D2** | **Desktop-app realisations.** Six, built only from primitives and $tokens, named `-app`: `split-workbench-app` (the `split-workbench` anatomy: header, sidebar of `nav-item`s, content, optional right panel, a pane toggle as an icon-only `button`), `list-detail-app` (new anatomy `list-detail`: navigation, list and detail panes, with a designed "nothing selected" placeholder in the detail pane), `editor-inspector-app` (new anatomy `editor-inspector`: a work area and a 70/30 inspector of `tabs` and `property-row`s), `browser-app` (new anatomy `browser`: a filter bar of `text-input` and `tabs` over an adaptive grid of item cards with a minimum column width), `dashboard-app` and `settings-app`. Panes fill the window and scroll on their own (`overflow: "auto"` on each pane, the root at window height); stress already treats a scrolling pane's overflow as scrolling (`src/stress.ts:259`). A component `data-table-app` (`surface: 'desktop-app'`) is the ladder version of `data-table`: header row height equals body row height and the toolbar height equals the row height. The web `data-table` is unchanged. | See FR-D3. | +| **FR-D2** | **Desktop-app realisations.** Six, built only from primitives and $tokens, named `-app`: `split-workbench-app` (the `split-workbench` anatomy: header, sidebar of `nav-item`s, content, optional right panel, a pane toggle as an icon-only `button`), `list-detail-app` (new anatomy `list-detail`: navigation, list and detail panes, with a designed "nothing selected" placeholder in the detail pane), `editor-inspector-app` (new anatomy `editor-inspector`: a work area and a 70/30 inspector of `tabs` and `property-row`s), `browser-app` (new anatomy `browser`: a filter bar of `text-input` and `tabs` over an adaptive grid of item cards with a minimum column width), `dashboard-app` and `settings-app`. Panes fill the window and scroll on their own (`overflow: "auto"` on each pane, the root at window height); stress treats a scrolling pane's vertical overflow as scrolling (spec change S4). A component `data-table-app` (`surface: 'desktop-app'`) is the ladder version of `data-table`: header row height equals body row height and the toolbar height equals the row height. The web `data-table` is unchanged. | See FR-D3. | | **FR-D3** | **The pattern gate covers desktop-app.** `test-patterns.ts` evaluates every desktop-app realisation on a canvas created with `type: "desktop-app"`, fast mode across its five themes, at the web set's `> 95` bar with zero `desktop-app-*` warnings or errors. Once per realisation in the full tier: detailed mode with zero `desktop-app-*` warnings or errors, and a CLEAN full `canvas_stress` run. `data-table-app` and every component scaffold marked `any` are stamped onto a desktop-app canvas and held to the same rule. | The gate fails if any desktop-app realisation scores 95 or below in any theme, raises a desktop-app warning or error in either mode, or stresses FRAGILE. | | **FR-E1** | **The overlay layer and its ladder.** The renderer lifts every overlay primitive out of the content tree into one overlay layer, a sibling after the content, whatever the overlay's position in the tree. Authored `x`/`y` are root coordinates. Within the layer, `z-index` comes from the kind: popover and menu 400, scrim 500, modal and drawer 510, toast 600, tooltip 800. Content keeps its own stacking (`fixed` 10, `sticky` 5, `src/renderer.ts:1457-1458`), all below the layer. There is no `zIndex` property. | A `menu` authored inside a `sticky` toolbar inside a scrolling pane renders above a `fixed` sibling and is not clipped by the pane. A tooltip and a modal render tooltip above modal above scrim above content, whatever their tree order. | | **FR-E2** | **Overlay primitives.** Each is positioned by authored `x`/`y` in root coordinates and may name its trigger with `anchor: nodeId`, which rules use (FR-F1) and the renderer ignores. `tooltip` (`text`, max width 240; text only). `popover` (a container; width from the overlay width set; the overlay elevation shadow and `$radius`). `menu` (a container of `menu-row`s and `divider`s, min width 192). `modal` (`title`, `size: 'sm' \| 'md' \| 'lg'` for 480 / 640 / 960, `actions: [{ label, variant }]` rendered right-aligned with the primary rightmost, a header close button named "Close" unless `closeLabel` says otherwise, body children; centred in the viewport by default, and it always renders its own full-viewport scrim). `toast` (`text`, `tone: 'neutral' \| 'success' \| 'warning' \| 'danger'`, `action?: { label }`, bottom-centre by default). `drawer` (a container pinned to the right edge, width 320 or 480, optional scrim). All colors default through `applyControlDefaults`. | Each renders in both themes with no console errors; `snapshot_layout` reads a `md` modal 640 wide and centred with a scrim covering the viewport. | @@ -245,6 +245,7 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **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. +- **H9: the inspector holds a `button`** (US2: tabs, property-row, text-input and button), a secondary Choose in a Source row; FR-D2's shorter list did not name it. - **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. @@ -252,6 +253,32 @@ One profile ships, keyed by id so a second size is one table row later. Values i - `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. +**Slice D — contracts pinned before build (2026-11-14; amended after the pre-freeze gate verifier, frozen at the commit that adds this block).** +- **G1: FR-D1 is mostly built.** Slice A shipped N-type resolution and listing (`resolveStructure` names every type a refused anatomy is realised on; `listStructures` and `covers()` iterate `SURFACE_TYPES`). Slice D adds the tests for FR-D1's two refusals, `list_structures({ type: "desktop-app" })` listing the six realisations, the two desktop-app components and the components marked `any`, and rewrites every agent surface that says desktop-app has no realisations yet. Every test that stamps the whole registry derives each canvas's type from the structure's `surface` (`test-patterns.ts`, `test-scaffold-system.ts`, `test-structures.ts`, `test-discoverability.ts`), so a desktop-app structure is never stamped on a web canvas. +- **G2: the fast gate's inputs** (`test-patterns.ts`). Every desktop-app page realisation, stamped on `createCanvas(…, { type: "desktop-app" })`, under (a) the five themes the web gate uses, the four presets applied after the stamp through `applyPresetTokens` as `apply_preset` does (a merge, not a replacement) with `genre` = the theme; (b) `generate_design_system` on the desktop-app surface for each of the four personalities × three seeds (`#166534`, `#2563EB`, `#B45309`), set before stamping as an agent does; (c) one personality's system generated at workspace scope (web pivot) and inherited by the desktop-app canvas. Where a theme has a dark layer, fast evaluate checks both themes, as it does today. **Pass** = score > 95, zero cliché tells, zero `desktop-app-*` findings at any severity, zero warnings or errors in any gated category (spacing, color, typography, structure, consistency, cliche, usability), and, where the canvas resolves `$accent-tint`, `$text-primary` on it at 4.5:1 or more in each theme (an active `nav-item` label must stay legible; evaluate does not measure it yet). Coverage is excluded from the score bar, as on web, but each realisation's `coverage.missing` is pinned in the test and stated in the docs, so an agent knows which state variants a stamp asks for. The zero-blocking clauses are stricter than FR-D3's text on purpose: a scaffold that stamps NOT READY teaches the agent to start broken, and the web `split-workbench`, `dashboard` and `settings` already stamp at 100 with zero warnings (measured on c9c5b1e). +- **G3: the full-tier gate's inputs** (new `test-patterns-desktop.ts`, Chrome). Per realisation: detailed evaluate unthemed and under each personality (seed `#166534`), as stamped and after the `many` perturbation, held to G2's pass rule minus the score and the tint clause (which reads tokens only, so the fast gate's check covers it); a full five-perturbation stress run built as `canvas_stress` builds it (instances expanded, the desktop-app perturbation rules of S5) CLEAN, unthemed and under each personality; `many` and `empty` each touch at least one node; after `many`, the root is still the artboard's height and no node is shorter than at baseline (rows scroll, they never squash), and a page realisation's content tripled twice scrolls inside a pane (as built: H4; a component has no pane of its own); and one stamp on a 1024×768 desktop-app canvas raises no `desktop-app-*` finding in detailed mode and no node's right edge passes the artboard. Renders use fallback fonts, as `test-patterns-mobile.ts` does; the test states that limit (the font cache would need the network). +- **G4: components.** `data-table-app` and `skeleton-table-app` (components, anatomies `data-table` and `skeleton-table`, surface `desktop-app`) are stamped under the root of a desktop-app canvas whose root fill is `$bg-primary`, as it is under a page stamp, and held to G2 and G3. Every component marked `any` is stamped on a bare desktop-app canvas and held to zero `desktop-app-*` findings at any severity (amended by S7 to warnings and errors) in fast and detailed mode and a CLEAN stress run; its score stays the web gate's business, as on mobile. +- **G5: panes and the window.** A page realisation may carry root props (`Structure.root`, new); every desktop-app realisation carries `{ overflow: "hidden" }`, which keeps the root at the artboard's height (the renderer grows a root only when it authors no overflow). Its shell is `height: "100%"`, so it fills any artboard height, and every pane (sidebar, list, detail, inspector, content) has `overflow: "auto"`, so tripled content scrolls inside its pane, never the page. A later page stamp with `replace` removes root props the previous stamp's structure set when the root still holds them unchanged, so stamping a web page over an app page does not leave the root clipped. +- **G6: anatomies.** `list-detail`, `editor-inspector` and `browser` are new and desktop-app only: on web and mobile they are refused naming `realisation: "desktop-app"`. `split-workbench`, `dashboard` and `settings` gain a desktop-app realisation beside their web (and mobile) ones; `data-table` and `skeleton-table` gain desktop-app components. Each page realisation carries `axes`, so diversification works as on web. +- **G7: what stays web-only.** `breadcrumb`, `toolbar`, `toggle-row` and `segmented-control` keep their web surface (`realisation: "web"` forces one onto a desktop-app canvas, as today); a realisation that needs a breadcrumb draws it from `link`s. The coverage hints name the desktop-app components on a desktop-app canvas (`data-table-app`'s loading state is `skeleton-table-app`). +- **Spec change S4 (FR-D2's stress premise was false).** FR-D2 said stress already treats a scrolling pane's overflow as scrolling; it treated only a `sheet`'s panel so (`data-fs-scroll`, `src/renderer.ts:1506`). The renderer now marks every node with `overflow: "auto"` (the only scrolling value `overflow` takes) with `data-fs-scroll`, on every type, so stress reads its vertical overflow as scrolling; horizontal overflow still clips. This loosens stress on existing web canvases with scrolling frames, which is the correct verdict. +- **Spec change S5 (desktop-app stress runs).** `many` and `empty` read only detected tables and runs of `list-row`, so on an app screen they touched nothing and passed by default. On a desktop-app canvas they also act on runs of two or more sibling `nav-item`, `tree-row`, `menu-row` or `property-row` nodes of one type, and on the children of a grid frame holding three or more children with one shape hash (a card grid). Web and mobile are unchanged. +- **Spec change S6 (slice B's E6, partly reversed).** Stamping a desktop-app primitive no longer seeds `$accent-tint`: presets carry no tint, so the dark seed survived `apply_preset light` and drew an active `nav-item` as a navy chip on a light page. Without the token the renderer's 12% accent mix (E11) follows whatever theme is applied. `$border-strong` stays seeded (`#666666` clears 3:1 on the dark and light preset surfaces). The same survival affects the web scaffolds' Phase 28 tints (`success-tint` and the rest) under a light preset; that is a follow-up, not this slice. +- **Spec change S7 (G4, during build).** G4 held the components marked `any` to zero `desktop-app-*` findings at any severity. Five of them (`form-field`, `stat-card`, `kpi-card`, `status-chip`, `initials-avatar`) raise infos on a desktop-app canvas: cut texts without a `title` and display pieces that FR-C2's never-blocking heuristic reads as small buttons (a delta pill, an icon tile beside its label). They were built for web and mobile, and FR-D3 gates warnings and errors, so G4 now holds them to zero `desktop-app-*` warnings and errors in fast and detailed mode, as FR-D3 says. The desktop-app realisations and components keep the any-severity rule. + +**Slice D — as built (recorded 2026-11-14; read this before slice E).** Spec changes S4 to S7 above. Decisions the pinned contracts did not settle: +- **H1: a `property-row`'s label names its control.** The usability check's "control has no text label" warning looked for a text node near the control and ignored the row's `label` prop, so every inspector and settings toggle warned. A control directly inside a `property-row` is now labelled by that row's `label`; with a blank label, only by text inside the row itself, never by a sibling row's text one hop up (`checkUsability`, `src/evaluate.ts`; the text-in-row fallback came in verify round 1). +- **H2: the scaffold token vocabulary moved to `src/structure-tokens.ts`,** so the desktop-app structures live in `src/structures-desktop.ts` without an import cycle; `structures.ts` registers them. +- **H3: `many` copies drop `active`.** A tripled run of nav-items carried three active items and tripped `desktop-app-current`; a longer list still has one current place (`withoutActive`, `src/stress.ts`). Only the copied row itself loses it: a tripled card keeps the active tab of its own `tabs`, which is its own group. +- **H4: G3's scroll check triples twice.** One `many` run leaves four realisations' content inside a 900px pane, so "every pane holding tripled content scrolls" could only fail on correct stamps. The gate asserts the root height and the no-squash rule after one `many` run, and after two (×9) that some pane scrolls with the root and every row at their own heights. +- **H5: table rows.** (FR-D2's header-equals-body holds at rest: a header whose long name wraps grows past its body rows, and `desktop-app-row-rhythm` then warns on that content, as it should.) Body rows are 32 tall with text cells sized straight to their column (no cell frame, which kept the tree within the 8-level depth advisory); the header row has no fixed height (32 at rest) so a long column name wraps instead of clipping, since a header is never cut. The table frame carries no `overflow`: a frame with one, directly in a scrolling pane, shrank below its rows under `many` (the full-tier gate caught it); the header row has no fill of its own to poke past the rounded corners. +- **H6: panes hold their content directly,** with padding and gap on the pane, rather than through an inner frame, keeping the tree within 8 levels; no pane's direct child has a fixed height or an `overflow`. +- **H7: the browser's tabs sit in a shrinkable slot** (a frame with `minWidth: 0`), because a `tabs` node never shrinks and long labels pushed the filter bar past the window. The settings footer wraps, so two long button labels never escape it. +- **H8: ghost icon buttons use `$text-secondary`.** The 24px tools and row actions rendered in the accent colour and competed with the one primary action. +- **Verify round 1 fixes.** (a) G3 gains the narrower windows: a full stress run CLEAN at 1024×768 (unthemed and per personality) and 1280×800, and detailed mode clean at 1280×800 (`test-patterns-desktop-window.ts`); long labels had pushed header actions and the breadcrumb past the window. Labelled buttons in the realisations cap at 200px, a header's action group keeps its content width (`minWidth: "max-content"`) so the title truncates instead, the breadcrumb's parent `link` sits in a shrinkable slot, and table header names break inside their column. (b) `data-table` stamped into each realisation's wide pane is gated the same way; to stay within the 8-level depth advisory there, the row-actions column is the icon button's own 24px under a blank header cell (no cell frame). (c) H1 refined: a blank-labelled `property-row` is still labelled by text inside the row itself, never by a sibling row's text (verify found a toggle beside its own text in the row newly warning). (d) The editor inspector holds a `button` (H9). (e) Twins for the gate's predicates (an info-level desktop-app finding, a cliché tell, a weak tint through the full verdict) and pinned values the mutation round found unasserted (pane `minWidth` floors, 32px table rows, the 240px grid minimum, icon-button ink). Accepted as specced: a scrolling frame hides a vertical clip on web too (S4); a header whose long name wraps raises `desktop-app-row-rhythm` (H5); `data-table-app` in a 300px side panel or the inspector is a misuse the description and docs name; a score at or below 95 with nothing blocking has no twin, since every gated deduction comes with a warning. +- **After verify round 2 (3b)** (proved red on d875156 and green on the fix; not re-verified by an agent). The 3b verifier confirmed every round 1 fix and found no regression, but `data-table` stamped into the split-workbench and list-detail panes clipped under long text at 1100 and 1024 wide, where the gate had stamped tables only at 1440. The table toolbar's search now sits in a shrinkable 240px slot (a `text-input` never shrinks) and the pager's row count truncates; the window gate stamps the table at 1440, 1100 and 1024 wide. Left as found: a labelled `property-row` whose control sits inside a wrapper frame still warns "has no text label" (pre-existing, every type; the row's label applies only to a direct child), and a header with six capped buttons can still push past a narrow window (no realisation has more than three actions). +- **After CI on PR #248 (2026-11-15).** The Linux browser job failed one case the macOS runs passed: `data-table` in `list-detail-app`'s detail pane in a 1024px window, a 422px pane where Linux fonts wrap the column names and the header outgrows its 32px rows (`desktop-app-row-rhythm`). A five-column table in that width is the same misuse as the 300px side panel, so `data-table-app` documents a 480px minimum pane, and the window gate stamps it only into panes that wide, asserting that list-detail's detail pane at 1024 is the only one it skips. Proved green locally; CI is the Linux check. + **Slice E: overlays (FR-E1 to FR-E3)** - `src/types.ts`: `tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer`; `anchor`, `closeLabel`, `actions`, `tone`, `action`. - `src/renderer.ts`: the overlay layer (a pass that collects overlay nodes and renders them after the content), the layer constant table, the modal's own scrim. diff --git a/src/evaluate.ts b/src/evaluate.ts index 47573ee..8a84a4e 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -2233,6 +2233,13 @@ function checkUsability(entries: NodeEntry[], rootWidth: number, touch?: { floor if (node.type !== 'select') { let scope = parentOf.get(node.id) ?? null; let labeled = false; + // Phase 31 slice D — a property-row's label names its value. With a + // blank label only text inside the row itself can, never a sibling + // row's text one hop up. + if (scope?.type === 'property-row') { + labeled = (typeof scope.label === 'string' && scope.label.trim().length > 0) || hasText(scope); + scope = null; + } for (let hop = 0; hop < 2 && scope && !labeled; hop++) { labeled = hasText(scope); scope = parentOf.get(scope.id) ?? null; @@ -2367,6 +2374,12 @@ const COVERAGE_HINTS: Record = { loading: 'canvas_add_variant with state "loading", replace the data rows with the skeleton-table (or skeleton-card) scaffold.', error: 'canvas_add_variant with state "error", show the form\'s validation-failure treatment (field messages + summary).', }; +/** Phase 31 slice D — on a desktop-app canvas the loading hint names the + * desktop-app skeleton (the web skeleton-table is refused there). */ +const COVERAGE_HINTS_APP: Record = { + ...COVERAGE_HINTS, + loading: 'canvas_add_variant with state "loading", replace the data rows with the skeleton-table-app scaffold (data-table-app\'s loading state), or skeleton-card for cards.', +}; function checkCoverage(canvas: Canvas, designedStates: string[]): { result: CheckResult; report?: EvaluationResult['coverage'] } { // A variant IS a designed state — demanding states of it would recurse. @@ -2436,7 +2449,7 @@ function checkCoverage(canvas: Canvas, designedStates: string[]): { result: Chec severity: 'warning', nodeId: canvas.root.id, message: `This screen has ${demanded.get(state)} but no "${state}" state variant is designed — the shipped UI will improvise it.`, - suggestion: COVERAGE_HINTS[state], + suggestion: (resolveSurface(canvas).type === 'desktop-app' ? COVERAGE_HINTS_APP : COVERAGE_HINTS)[state], })); return { result: { score: Math.max(0, 100 - missing.length * 35), issues }, diff --git a/src/index.ts b/src/index.ts index 3643356..95645c4 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 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). +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. Start an app screen from a desktop-app realisation: apply_structure on a desktop-app canvas resolves the anatomy name to it — split-workbench → split-workbench-app, dashboard → dashboard-app, settings → settings-app, and three app-only anatomies: list-detail → list-detail-app (navigation, a searchable list, a detail pane with a "nothing selected" placeholder), editor-inspector → editor-inspector-app (a work area beside a 70/30 inspector of tabs and property-rows), browser → browser-app (a filter bar over an adaptive card grid); data-table → data-table-app (32px toolbar, header, rows and pager; stamp it into a pane at least 480px wide, not a 300px side panel) and skeleton-table → skeleton-table-app (its loading state). Each is built from the primitives and gated: > 95 with no warning, error, tell or desktop-app finding in fast and detailed mode under the presets, every personality and an inherited system, canvas_stress CLEAN at 1440, 1280 and 1024 wide, data-table stamped into a pane at least 480px wide clean too — so a fresh stamp is READY TO PRESENT unless coverage asks for a state. They fill the window: the stamp sets root overflow "hidden" (the root keeps the artboard height) and every pane is overflow "auto", so long content scrolls inside its pane — keep new content inside a pane, and never give a pane's direct child a fixed height or an overflow (the pane squashes it instead of scrolling). Coverage still asks for states: dashboard-app and data-table-app need "empty" + "loading", editor-inspector-app and settings-app (forms) need "error". toolbar, toggle-row, segmented-control and breadcrumb stay web-only (realisation: "web" forces one). On web and desktop-app every pointer target — the four controls and the clickable primitives (button, list-row, tab-bar tabs, nav-bar actions, link, text-input, nav-item, each tab of a tabs, tree-row, menu-row; inline text links are exempt) — meets the 24px WCAG 2.5.8 floor or its spacing exception (nothing else within a 24px circle around it): detailed mode runs that circle test (ERROR on failure), fast mode WARNS on anything under 24 and names detailed mode. The desktop-app ruleset (each finding carries its "rule"; canvas_evaluate lists them) adds: name every icon-only button and link (ariaLabel); mark exactly one current place — one active nav-item per pane — a frame with overflow "auto", so give a rail and a sidebar each their own (a parent may stay active over its active child), one active tab per tabs, one active row per tree; a dense type ladder (desktop-app-type-ladder, replacing type-scale-ratio: 12/13/14 steps are fine, nothing below 11px, prose ≥12px, $body ≥13px); table header rows as tall as their body rows; column headers never truncated; one primary button per pane (info); and frames shaped like small buttons are named as hand-built targets (info) — rebuild them as button or link. 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. @@ -105,7 +105,7 @@ const server = new McpServer({ * it reads the connect-time instructions or calls init. */ const WORKFLOW_CHEATSHEET = [ 'The bar: craft beautiful UI/UX a designer would sign off on. Polishing to it is YOUR job — never show the user an unpolished design.', - 'Start from a taste-vetted pattern: list_structures → apply_structure, then ADAPT it — don\'t start from a blank canvas. On a phone canvas the same names stamp the mobile realisations (dashboard, settings, auth, onboarding, feed, detail).', + 'Start from a taste-vetted pattern: list_structures → apply_structure, then ADAPT it — don\'t start from a blank canvas. On a phone canvas the same names stamp the mobile realisations (dashboard, settings, auth, onboarding, feed, detail); on a desktop-app canvas the desktop-app ones (split-workbench, list-detail, editor-inspector, browser, dashboard, settings).', 'Use the whole toolkit by default — icons, fonts, real controls (toggle/checkbox/radio/select), components, $tokens. Never fake them; never omit them where a real UI has them.', 'Read the framesmith://guidelines resource before drawing (esp. "Designing with taste": one focal point, real hierarchy, one type + spacing scale, restraint).', 'Author at one target width (the canvas artboard — pass width/height to canvas_create for another size; for a phone app screen pass type: "mobile", which sizes the artboard to the device and reserves its safe-area insets on the root); reference tokens with $name (e.g. fill: "$surface").', @@ -143,6 +143,7 @@ const GOTCHAS = [ 'Derive, don\'t hand-pick: generate_design_system (seed + REQUIRED personality: technical/editorial/soft/data-dense) writes the whole design language in one call — including $display/$heading/$title/$body/$label typography roles, $elevation.* shadow tokens (reference as shadow: "$elevation.raised"; the dark layer re-states depth), and $motion defaults. For targeted regeneration only: generate_scale gives a modular type + space scale from a ratio (craft defaults baked in; fluid clamp() optional); generate_color_system gives OKLCH ramps + a matched neutral + status colors + the semantic tokens the structures use, AA by construction, WITH a dark theme (sparse dark.colors layer) AND the color range — chart-1…chart-6 for series/segments/legend dots, plus the accent/success/warning/danger/neutral -tint layer for chips/tiles/badges (pair tint as fill with its base color as ink; AA by construction, dark included). Render dark via theme: "dark" on screenshot/screenshot_responsive/export; canvas_evaluate contrast-checks both themes automatically (dark failures point at the dark layer — never write a literal fix; APCA Lc is info-only, WCAG 2.2 gates). Literals that equal a token get re-attached by autofix; timing belongs in $motion tokens.', 'Beyond one canvas: bento/editorial compositions are REAL grid — layout: "grid" + gridColumns (count / fr-weight array / template string) + gridColumn/gridRow spans (a number means span N); responsive: "stack" collapses to one column on mobile. Never approximate tiles with nested flex. When a multi-screen module feels done, project_evaluate reviews the SET — radius-drift / accent-drift / token-adoption / copied-chrome / state-coverage findings, each naming its canvases — and mode "llm" judges up to 8 screens together for flow consistency (flowSkipped lists anything past the cap; keyless → full roll-up + a note). ADVISORY: only the per-canvas directives gate presenting.', 'Start a phone screen from its mobile realisation: generate_design_system, then apply_structure with the anatomy name on the mobile canvas — dashboard, settings, auth, onboarding, feed or detail stamp dashboard-mobile etc. (status bar, nav bar, list rows, buttons, pinned tab bar or home indicator; every tap target a primitive). Resolution reads the DECLARED type: canvas_create({ width: 390 }) with no type stamps the web dashboard. pricing and the web-only components (data-table, toolbar, …) are refused on a phone with the list of what has a mobile realisation; realisation: "web" forces the web one. list_structures({ canvasId }) lists what stamps on that canvas. Read the result\'s placeholders for node ids and fields (prop) instead of guessing them.', + 'Start an application screen from its desktop-app realisation: canvas_create({ type: "desktop-app" }), generate_design_system, then apply_structure with the anatomy name — split-workbench, list-detail, editor-inspector, browser, dashboard or settings stamp split-workbench-app etc. (nav-items, panes that scroll on their own, every click target a primitive). Adapt inside the panes: a pane\'s direct child with a fixed height or an overflow gets squashed instead of scrolled. data-table stamps data-table-app (its loading state is skeleton-table-app). list_structures({ canvasId }) lists what stamps on the canvas; realisation: "web" forces a web-only one such as toolbar.', 'Declare the medium: a phone app screen is canvas_create({ type: "mobile" }) (device "iphone-390": 390×844, root safeArea: { top: 47, bottom: 34 } added to the root padding by the renderer) — not a 390px-wide web canvas. canvas_set_type re-declares an existing canvas (type: "web" | "mobile" | null) WITHOUT resizing it or writing safeArea; follow its hint. The type changes the ruleset and defaults only (generate_design_system pivots on a 17px body, 16 for data-dense), never pixels; evaluate\'s "surface" report shows the type, its source ("declared" | "default"; canvas_create reports the same as typeSource) and the rulesOn / rulesOff / conflicts the rulesets composed. Build a phone screen from the mobile primitives — status-bar, nav-bar, list-row, button, tab-bar, home-indicator, sheet — not hand-built frames: they carry 44px targets and pin themselves. On mobile a tap target below 44px is an ERROR (mobile-touch-target), content in the status-bar / home-indicator insets or left under a pinned bar is a WARNING (mobile-safe-area), and a tab bar outside 2–5 labeled tabs or not pinned to the bottom WARNS (mobile-tab-bar). Keep root safeArea; the root grows with long content and keeps its end padding. A pinned CTA bar: position "fixed", bottom: 0, padding under 32 (larger padding scales down on a phone) and a 34px spacer frame as its last child, plus a spacer at the end of your content frame tall enough that it and the root\'s 34px bottom inset reach the bar\'s height (the rule names it: 68 for a 102px bar; re-evaluate after changing the bar). An undeclared canvas under 500px wide WARNS (mobile-artboard) until you declare it either way. canvas_set_type does not reach existing state variants — its variantsOutOfSync lists them.', 'Gate integrity: a canvas describing a SHIPPED view is a contract — run canvas_check_drift against the live route BEFORE designing on it (findings: missing-in-page / missing-in-canvas / control-mismatch / table-mismatch), and reconcile deliberately: update the canvas, flag the implementation, or ask — never silently annotate a difference. canvas_sync_from_url answers "how much does it LOOK different" (pixel %); canvas_version makes approvals falsifiable — record { canvasId, versionHash } at approval time and check with expectedHash later (metadata/feedback never moves the hash; ANY inherited workspace/project token edit DOES, even to a token the canvas does not use). A legacy sha256: hash still checks but carries a warning — re-record it as the current sha256r: versionHash. CI can demand both: npx framesmith check-drift / verify exit 1 on failure.', ]; @@ -176,7 +177,7 @@ server.resource( // --- canvas_create --- server.tool( 'canvas_create', - 'Create a new design canvas. Returns the canvas ID, root node ID, project assignment, the artboard `width`/`height`, viewer URL, and a `diversification` signal — the recently-built structures in this project plus a hint to differ on at least one taxonomy axis, so successive canvases don\'t converge on the same layout. Always share the viewer URL with the user so they can see the design live in their browser. If `projectId` is omitted, the canvas lands in the default Untitled project. The artboard defaults to 1440×900; pass `width`/`height` for another size. Building a PHONE APP screen? Pass `type: "mobile"` — it declares the canvas a phone screen (it selects the mobile ruleset, and generate_design_system gives it a 17px body) and gives you the device artboard (390×844 for the default `device: "iphone-390"`) with the root reserving the device\'s safe-area insets as `safeArea: { top: 47, bottom: 34 }` (the renderer adds them to the root\'s top/bottom padding, and the root grows with long content keeping that padding, so in-flow content never sits under the status bar or home indicator). Building an APPLICATION screen (a tool you work in: an editor, an admin console, a file browser — persistent chrome, panes, dense controls, a current selection, in a browser tab or a native window)? Pass `type: "desktop-app"` — it selects the desktop-app ruleset, generate_design_system gives it a 14px body (13 for data-dense) plus state tokens, and the artboard is the window (1440×900 for the default `device: "window-1440"`, no insets). `type: "web"` (the default) declares a web page — a page you read and scroll (marketing, docs, content, pricing). The result reports `type`, `typeSource` ("declared" | "default"), and for mobile and desktop-app the `device` (plus `safeArea` on mobile). Change it later with canvas_set_type. Then start it from a pattern: on a mobile canvas apply_structure stamps the mobile realisations (dashboard, settings, auth, onboarding, feed, detail).', + 'Create a new design canvas. Returns the canvas ID, root node ID, project assignment, the artboard `width`/`height`, viewer URL, and a `diversification` signal — the recently-built structures in this project plus a hint to differ on at least one taxonomy axis, so successive canvases don\'t converge on the same layout. Always share the viewer URL with the user so they can see the design live in their browser. If `projectId` is omitted, the canvas lands in the default Untitled project. The artboard defaults to 1440×900; pass `width`/`height` for another size. Building a PHONE APP screen? Pass `type: "mobile"` — it declares the canvas a phone screen (it selects the mobile ruleset, and generate_design_system gives it a 17px body) and gives you the device artboard (390×844 for the default `device: "iphone-390"`) with the root reserving the device\'s safe-area insets as `safeArea: { top: 47, bottom: 34 }` (the renderer adds them to the root\'s top/bottom padding, and the root grows with long content keeping that padding, so in-flow content never sits under the status bar or home indicator). Building an APPLICATION screen (a tool you work in: an editor, an admin console, a file browser — persistent chrome, panes, dense controls, a current selection, in a browser tab or a native window)? Pass `type: "desktop-app"` — it selects the desktop-app ruleset, generate_design_system gives it a 14px body (13 for data-dense) plus state tokens, and the artboard is the window (1440×900 for the default `device: "window-1440"`, no insets). `type: "web"` (the default) declares a web page — a page you read and scroll (marketing, docs, content, pricing). The result reports `type`, `typeSource` ("declared" | "default"), and for mobile and desktop-app the `device` (plus `safeArea` on mobile). Change it later with canvas_set_type. Then start it from a pattern: on a mobile canvas apply_structure stamps the mobile realisations (dashboard, settings, auth, onboarding, feed, detail), on a desktop-app canvas the desktop-app ones (split-workbench, list-detail, editor-inspector, browser, dashboard, settings).', { name: z.string().optional().describe('Name for the canvas'), projectId: z.string().optional().describe('Project to create the canvas in. Defaults to the built-in Untitled project. Use project_list to see available projects.'), @@ -596,7 +597,7 @@ Desktop-app primitives (application screens — canvas_create type "desktop-app" - tabs { items: [{ label, count?, active?, disabled? }], variant?: "line"|"contained", size?: "sm"|"md" (32/40) } — one tablist; each tab is its own pointer target; the active tab gets an indicator (line) or an $accent-tint fill (contained) and a heavier label. - tree-row { label, depth, expanded? (absent for a leaf), icon?, active? } — 32 tall, indents 16 per level, a chevron when expanded is set. - menu-row { label, icon?, shortcut?, checked?, destructive?, disabled?, submenu? } — 32 tall; the shortcut right-aligns in a muted kbd style, destructive uses $danger, submenu adds a chevron. - - property-row { label, labelWidth? (96), children: [one value] } — an inspector row: muted label column, then its single child (a control, a text-input, a button, a text); a control that is its only target (nothing clickable beside it) is measured by the row's box. + - property-row { label, labelWidth? (96), children: [one value] } — an inspector row: muted label column, then its single child (a control, a text-input, a button, a text); a control that is its only target (nothing clickable beside it) is measured by the row's box. Its label names a control directly inside it; with a blank label only text inside the row itself does (a sibling row's text does not count). - divider { orientation?: "horizontal"|"vertical", inset? } — a 1px $border hairline; vertical ones separate panes. Not a target. Only property-row renders children; link, text-input, nav-item, tabs, tree-row, menu-row and divider draw their own anatomy and drop any children you give them. Labels truncate to one line with an ellipsis and carry their full text as a title; text nodes take title too. On web and desktop-app canvases every one of these except property-row and divider is a pointer target held to the 24px floor. A canvas that holds a nav-item, tabs, tree-row, menu-row or property-row must declare its type (desktop-app-artboard). @@ -1516,7 +1517,7 @@ server.tool( `List available layout structures for one canvas type, two kinds: - kind "page" — whole-page scaffolds (marquee-hero, bento-grid, …) stamped once at the canvas root, tagged on four taxonomy axes (heroTreatment, density, rhythm, alignment) so you deliberately vary page shape. - kind "component" — reusable fragments (data-table, form-field, toolbar, stat-card, toggle-row, the state scaffolds empty-state, skeleton-table, skeleton-card, skeleton-stat-card, and the micro-patterns kpi-card, status-chip, segmented-control, breadcrumb, initials-avatar) stamped under ANY node via apply_structure targetId, repeatably — a high-fidelity table costs one stamp instead of ~90 hand-placed nodes. -Each structure realises an ANATOMY (a screen kind such as dashboard or settings) for one canvas type: pass canvasId (or type) to list what stamps on that canvas — a phone canvas lists the mobile realisations (dashboard-mobile, settings-mobile, auth-mobile, onboarding-mobile, feed-mobile, detail-mobile) and the components marked for every type. With neither, the web listing. Every entry carries its anatomy, its surface ("web" | "mobile" | "any") and surfaces (the canvas types its anatomy is realised on). +Each structure realises an ANATOMY (a screen kind such as dashboard or settings) for one canvas type: pass canvasId (or type) to list what stamps on that canvas — a phone canvas lists the mobile realisations (dashboard-mobile, settings-mobile, auth-mobile, onboarding-mobile, feed-mobile, detail-mobile) and the components marked for every type; a desktop-app canvas lists the desktop-app realisations (split-workbench-app, list-detail-app, editor-inspector-app, browser-app, dashboard-app, settings-app), the components data-table-app and skeleton-table-app, and the components marked for every type. With neither, the web listing. Every entry carries its anatomy, its surface ("web" | "mobile" | "desktop-app" | "any") and surfaces (the canvas types its anatomy is realised on). Distinct from presets: structures define layout skeleton, presets define color/token theme. Pass projectId to also get a diversification signal (recently-built page structures + a hint to differ). Apply one with apply_structure, then screenshot and verify before populating.`, { canvasId: z.string().optional().describe('List what stamps on this canvas (its declared type picks the realisations). Not with type.'), @@ -1551,14 +1552,14 @@ server.tool( `Stamp a layout structure (see list_structures) onto a canvas. Two kinds: - page scaffolds insert at the canvas root and record provenance; refuses if the root already has content unless replace is true. - component scaffolds (data-table, form-field, toolbar, stat-card, toggle-row, …) insert under targetId (default root), repeatably — every stamp re-keys its node IDs and returns an idMap (templateId → live id) for follow-up batch_design ops. -The name resolves by the canvas's declared type: an anatomy name stamps that anatomy's realisation for the type — "dashboard" on a mobile canvas stamps dashboard-mobile (status bar, nav bar, list rows, pinned tab bar, all primitives) — and the result names the anatomy and surface it stamped; its placeholders include every copy field of its primitives, with prop the field's path. A realisation name (dashboard-mobile) is used as is. A name with no realisation for the canvas's type is refused with the anatomies that have one (pricing on a phone canvas; components not marked for every type too); realisation: "web" | "mobile" stamps that type's realisation anyway. -Scaffolds reference $space-*/$radius-*/$elevation.*/type-role tokens ($display/$title/$heading/$text-lg/$text-sm/$body/$label/$caption) for spacing, corner radius, depth, and EVERY text node's size (not just $color, and not just titles) — stamp AFTER generate_design_system on a project and the pattern already reads in that system's density, personality, and voice; no scaffold can inject a size the generated scale doesn't have. Also hardened to survive hostile-length content (canvas_stress CLEAN). Seeds neutral defaults (the pre-generator literal values) for any of those tokens the canvas can't already resolve, so an unthemed canvas still renders correctly; the result's seededColors/seededTokens list exactly what got seeded (a stamp holding a mobile primitive also seeds the colours primitives read by default: $text-primary, $text-secondary, $border, and $accent / $bg-surface / $danger unless the canvas resolves $primary / $surface / $error — a scaffold node that names $accent or $bg-surface itself still seeds it, so define $accent and $bg-surface on a hand-themed canvas before stamping). Returns the placeholder node ids to populate — fill them with batch_design U ops, then call screenshot to verify the layout.`, +The name resolves by the canvas's declared type: an anatomy name stamps that anatomy's realisation for the type — "dashboard" on a mobile canvas stamps dashboard-mobile (status bar, nav bar, list rows, pinned tab bar, all primitives) — and on a desktop-app canvas dashboard-app (a sidebar of nav-items, panes that scroll on their own; the page stamp sets root overflow "hidden" so the root keeps the window height, and a later page stamp with replace removes it again unless you changed it) — and the result names the anatomy and surface it stamped; its placeholders include every copy field of its primitives, with prop the field's path. A realisation name (dashboard-mobile, dashboard-app) is used as is. A name with no realisation for the canvas's type is refused with the anatomies that have one (pricing on a phone or desktop-app canvas; list-detail, editor-inspector and browser on web or a phone; components not marked for every type too); realisation: "web" | "mobile" | "desktop-app" stamps that type's realisation anyway. +Scaffolds reference $space-*/$radius-*/$elevation.*/type-role tokens ($display/$title/$heading/$text-lg/$text-sm/$body/$label/$caption) for spacing, corner radius, depth, and EVERY text node's size (not just $color, and not just titles) — stamp AFTER generate_design_system on a project and the pattern already reads in that system's density, personality, and voice; no scaffold can inject a size the generated scale doesn't have. Also hardened to survive hostile-length content (canvas_stress CLEAN). Seeds neutral defaults (the pre-generator literal values) for any of those tokens the canvas can't already resolve, so an unthemed canvas still renders correctly; the result's seededColors/seededTokens list exactly what got seeded (a stamp holding a desktop-app primitive also seeds $border-strong, never $accent-tint — without it an active fill mixes 12% accent into whatever surface is applied later; a stamp holding a mobile primitive also seeds the colours primitives read by default: $text-primary, $text-secondary, $border, and $accent / $bg-surface / $danger unless the canvas resolves $primary / $surface / $error — a scaffold node that names $accent or $bg-surface itself still seeds it, so define $accent and $bg-surface on a hand-themed canvas before stamping). Returns the placeholder node ids to populate — fill them with batch_design U ops, then call screenshot to verify the layout.`, { canvasId: z.string().describe('Canvas ID'), structure: z.string().describe('Structure name (use list_structures, e.g. marquee-hero, data-table)'), replace: z.boolean().optional().describe('Page scaffolds only: if the root already has children, clear them before stamping. Default false (refuses on a non-empty canvas).'), targetId: z.string().optional().describe('Component scaffolds only: node to stamp under (default "document"). Page scaffolds always stamp at the root.'), - realisation: z.enum(['web', 'mobile', 'desktop-app']).optional().describe('Stamp the realisation for this canvas type instead of the canvas\'s own type (e.g. "web" to put the web dashboard on a mobile canvas, or the web split-workbench / dashboard / settings on a desktop-app canvas, which has no realisations of its own yet).'), + realisation: z.enum(['web', 'mobile', 'desktop-app']).optional().describe('Stamp the realisation for this canvas type instead of the canvas\'s own type (e.g. "web" to put the web dashboard on a mobile canvas, or a web-only component such as toolbar on a desktop-app canvas).'), }, async ({ canvasId, structure, replace, targetId, realisation }) => { ensureFresh(canvasId); @@ -2282,9 +2283,9 @@ server.tool( 'canvas_stress', `Content stress test: does the design survive real data? Re-renders the canvas under hostile-but-realistic content perturbations and reports exactly what broke, by node id — the too-long name that clips, the German label that wraps ugly, the "999+" badge that blows its box. Never mutates the canvas. -Perturbations (default: all): long-text (non-data text ×2.2 plus one long unbroken token — the wrap-breaker), i18n (×1.4 — the German/Finnish expansion rule), big-numbers (data-like text to its widest realistic form: "9" → "999+", "$1.5M" → "$1,520,847.33"), empty (detected tables lose their data rows), many (data rows ×3). Tables are found with the same inventory drift and coverage use. +Perturbations (default: all): long-text (non-data text ×2.2 plus one long unbroken token — the wrap-breaker), i18n (×1.4 — the German/Finnish expansion rule), big-numbers (data-like text to its widest realistic form: "9" → "999+", "$1.5M" → "$1,520,847.33"), empty (detected tables lose their data rows), many (data rows ×3). Tables are found with the same inventory drift and coverage use; runs of two or more list-rows are lists too, and on a desktop-app canvas so are runs of nav-item, tree-row, menu-row or property-row and card grids (a grid of three or more same-shaped children). A tripled list keeps one active row. -Finding kinds: clip (content cut off — INFO when a designed text-overflow ellipsis is doing its job (a primitive's label truncating included), or when it is just a root with an authored overflow clipping or scrolling inside itself; WARNING otherwise; a sheet's own vertical overflow scrolls and is never a clip), overflow-x (a node escapes its parent box or the canvas), layout-shift (an UNTOUCHED node ballooning — perturbed nodes, their ancestors, and siblings that merely stretch with a growing parent are exempt). Only NEW breakage counts: anything already clipping at baseline is the design's standing state, not the perturbation's fault. verdict is CLEAN only with zero warnings — fix findings with fluid widths, minWidth or minHeight floors, wrapping, or textOverflow: "ellipsis" on labels that must stay single-line (that is the designed-truncation property the info path rewards), then re-run. The verdict is remembered for canvas_evaluate, with the canvas type it ran under: any run with warnings records FRAGILE (the directive stays NOT READY), and only a run of the full default set records CLEAN — a passing subset never clears an earlier FRAGILE. On a mobile canvas, long-text leaves strings of three characters or fewer alone (monograms, short labels), and the tab and nav-bar action labels (fixed vocabulary; i18n still lengthens them). The mobile primitives' own copy is perturbed (button label, list-row title / subtitle / trailing text, nav-bar title and action labels, tab labels), and two or more consecutive sibling list-rows are a list for empty and many. Chrome required; ~1 render per perturbation.`, +Finding kinds: clip (content cut off — INFO when a designed text-overflow ellipsis is doing its job (a primitive's label truncating included), or when it is just a root with an authored overflow clipping or scrolling inside itself; WARNING otherwise; the vertical overflow of a sheet or of any frame with overflow "auto" (an app pane) scrolls and is never a clip; its horizontal overflow still is), overflow-x (a node escapes its parent box or the canvas), layout-shift (an UNTOUCHED node ballooning — perturbed nodes, their ancestors, and siblings that merely stretch with a growing parent are exempt). Only NEW breakage counts: anything already clipping at baseline is the design's standing state, not the perturbation's fault. verdict is CLEAN only with zero warnings — fix findings with fluid widths, minWidth or minHeight floors, wrapping, or textOverflow: "ellipsis" on labels that must stay single-line (that is the designed-truncation property the info path rewards), then re-run. The verdict is remembered for canvas_evaluate, with the canvas type it ran under: any run with warnings records FRAGILE (the directive stays NOT READY), and only a run of the full default set records CLEAN — a passing subset never clears an earlier FRAGILE. On a mobile canvas, long-text leaves strings of three characters or fewer alone (monograms, short labels), and the tab and nav-bar action labels (fixed vocabulary; i18n still lengthens them). The mobile primitives' own copy is perturbed (button label, list-row title / subtitle / trailing text, nav-bar title and action labels, tab labels), and two or more consecutive sibling list-rows are a list for empty and many. Chrome required; ~1 render per perturbation.`, { canvasId: z.string().describe('Canvas to stress'), perturbations: z.array(z.enum(['long-text', 'i18n', 'big-numbers', 'empty', 'many'])).optional() diff --git a/src/renderer.ts b/src/renderer.ts index e87a2b6..512850e 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -602,7 +602,9 @@ function renderNode(node: SceneNode, rc: RenderCtx): string { const styles = buildStyles(node, rc); const styleAttr = styles ? ` style="${escapeStyleValue(styles)}"` : ''; - const dataAttr = ` data-node-id="${node.id}"`; + // Phase 31 slice D (spec change S4) — a scrolling frame is marked like a + // sheet panel, so stress reads its vertical overflow as scrolling. + const dataAttr = ` data-node-id="${node.id}"${node.overflow === 'auto' ? ' data-fs-scroll' : ''}`; if (node.type === 'text') { const title = typeof node.title === 'string' && node.title.trim() ? ` title="${escapeAttr(node.title.trim())}"` : ''; diff --git a/src/stress.ts b/src/stress.ts index 1caf49d..17871c9 100644 --- a/src/stress.ts +++ b/src/stress.ts @@ -13,6 +13,7 @@ import type { SceneNode } from './types.js'; import type { LayoutRect } from './screenshot.js'; import type { SurfaceType } from './surfaces.js'; import { extractInventory, isDataLike } from './drift.js'; +import { shapeHash } from './shape-hash.js'; export type PerturbationName = 'long-text' | 'i18n' | 'big-numbers' | 'empty' | 'many'; export const PERTURBATION_NAMES: PerturbationName[] = ['long-text', 'i18n', 'big-numbers', 'empty', 'many']; @@ -98,18 +99,32 @@ function walkTexts(root: SceneNode, visit: (slot: TextSlot) => void): void { root.children?.forEach((c) => walkTexts(c, visit)); } -/** Runs of two or more consecutive sibling `list-row`s — a list, for the - * empty and many perturbations. Lives here, not in the drift inventory, which - * coverage, typography and drift share and which must not change. */ -function listRuns(root: SceneNode): Array<{ container: SceneNode; start: number; length: number }> { +/** Phase 31 slice D (spec change S5) — the desktop-app rows `many` and + * `empty` also act on. */ +const DESKTOP_ROW_TYPES = new Set(['nav-item', 'tree-row', 'menu-row', 'property-row']); +const CARD_GRID_MIN = 3; + +/** Runs of two or more sibling rows of one type, for the empty and many + * perturbations: `list-row` on every type, plus the desktop-app rows on a + * desktop-app canvas, where the children of a grid holding three or more + * same-shaped children (a card grid) are a run too. Lives here, not in the + * drift inventory, which coverage, typography and drift share and which must + * not change. */ +function listRuns(root: SceneNode, desktop = false): Array<{ container: SceneNode; start: number; length: number }> { const runs: Array<{ container: SceneNode; start: number; length: number }> = []; + const isRow = (n: SceneNode): boolean => n.type === 'list-row' || (desktop && DESKTOP_ROW_TYPES.has(n.type)); (function walk(n: SceneNode) { const kids = n.children ?? []; - for (let i = 0; i < kids.length;) { - let j = i; - while (j < kids.length && kids[j].type === 'list-row') j++; - if (j - i >= 2) runs.push({ container: n, start: i, length: j - i }); - i = j > i ? j : i + 1; + const cardGrid = desktop && n.layout === 'grid' && kids.length >= CARD_GRID_MIN + && kids.every((k) => shapeHash(k, 3, { names: false }) === shapeHash(kids[0], 3, { names: false })); + if (cardGrid) runs.push({ container: n, start: 0, length: kids.length }); + else { + for (let i = 0; i < kids.length;) { + let j = i; + while (j < kids.length && isRow(kids[j]) && kids[j].type === kids[i].type) j++; + if (j - i >= 2) runs.push({ container: n, start: i, length: j - i }); + i = j > i ? j : i + 1; + } } kids.forEach(walk); })(root); @@ -139,6 +154,14 @@ function tableRows(container: SceneNode): SceneNode[] { return (container.children ?? []).filter((c) => c.type === 'frame' && (c.children?.length ?? 0) >= 2); } +/** A copy that is not the current row (Phase 31 slice D: `many` on a run of + * nav-items must not add a second active one). */ +function withoutActive(node: SceneNode): SceneNode { + if (node.active === undefined) return node; + const { active: _active, ...rest } = node; + return rest; +} + function cloneWithSuffix(node: SceneNode, suffix: string): SceneNode { const clone: SceneNode = { ...node, id: `${node.id}${suffix}` }; if (node.children) clone.children = node.children.map((c) => cloneWithSuffix(c, suffix)); @@ -199,12 +222,15 @@ export function applyPerturbation(name: PerturbationName, root: SceneNode, opts: } touched.push(container.id); } - // Runs of list-rows, last run first so earlier indices stay valid. - for (const run of listRuns(clone).reverse()) { + // Runs of rows (list-rows; desktop-app rows and card grids on desktop-app), + // last run first so earlier indices stay valid. Nested runs are fine: a + // container's own indices only move when its own run is edited. + for (const run of listRuns(clone, opts.type === 'desktop-app').reverse()) { const kids = run.container.children!; const rows = kids.slice(run.start, run.start + run.length); if (name === 'empty') kids.splice(run.start, run.length); - else kids.splice(run.start + run.length, 0, ...[1, 2].flatMap((i) => rows.map((r) => cloneWithSuffix(r, `-x${i}`)))); + // A tripled list still has one current place: copies drop `active`. + else kids.splice(run.start + run.length, 0, ...[1, 2].flatMap((i) => rows.map((r) => withoutActive(cloneWithSuffix(r, `-x${i}`))))); touch(run.container.id); } return { root: clone, touched }; diff --git a/src/structure-tokens.ts b/src/structure-tokens.ts new file mode 100644 index 0000000..1ab80d1 --- /dev/null +++ b/src/structure-tokens.ts @@ -0,0 +1,57 @@ +// Phase 31 slice D — the token vocabulary every scaffold references, shared by +// the web/mobile scaffolds (structures.ts) and the desktop-app realisations +// (structures-desktop.ts). + +/** Standard color tokens these scaffolds reference (the preset vocabulary). */ +export const COLOR = { + bgPrimary: '$bg-primary', + bgSurface: '$bg-surface', + bgElevated: '$bg-elevated', + textPrimary: '$text-primary', + textSecondary: '$text-secondary', + accent: '$accent', + border: '$border', +} as const; + +/** Phase 27 slice B — density comes from tokens, not literals. Scaffolds + * reference the space/radius/elevation vocabulary generate_design_system + * writes; applyStructure seeds neutral defaults (the pre-27 literal values) + * for anything not already resolvable, so unthemed canvases render exactly + * as before and a personality re-densifies every stamp. */ +export const SPACE = { + xxs: '$space-3xs', // 2 + xs2: '$space-2xs', // 4 + xs: '$space-xs', // 8 + sm: '$space-sm', // 12 + md: '$space-md', // 16 + lg: '$space-lg', // 24 + xl: '$space-xl', // 32 + xl2: '$space-2xl', // 48 +} as const; +export const RADIUS = { + sm: '$radius-sm', // 8 + md: '$radius-md', // 12 + lg: '$radius-lg', // 16 +} as const; +export const ELEV = { + flat: '$elevation.flat', + raised: '$elevation.raised', +} as const; +export const TYPE = { + display: '$display', // hero headlines — the display face at full size + title: '$title', // page/screen titles, one step below display + heading: '$heading', // section heads + textLg: '$text-lg', // card titles, subheads — the step above body + textSm: '$text-sm', // small body text — untracked (nav items, prose, meta) + body: '$body', // prose and item text + label: '$label', // control, CTA, breadcrumb and table-header text + caption: '$caption', // metadata, timestamps, eyebrows +} as const; +/** Phase 28 — the tint pair: tint as the FILL, base color as the INK. */ +export const TINT = { + accent: { bg: '$accent-tint', ink: COLOR.accent }, + success: { bg: '$success-tint', ink: '$success' }, + warning: { bg: '$warning-tint', ink: '$warning' }, + danger: { bg: '$danger-tint', ink: '$danger' }, + neutral: { bg: '$neutral-tint', ink: COLOR.textSecondary }, +} as const; diff --git a/src/structures-desktop.ts b/src/structures-desktop.ts new file mode 100644 index 0000000..1e33e08 --- /dev/null +++ b/src/structures-desktop.ts @@ -0,0 +1,579 @@ +import type { SceneNode, Structure } from './types.js'; +import { COLOR, SPACE, RADIUS, ELEV, TYPE } from './structure-tokens.js'; + +// Phase 31 slice D — the desktop-app realisations (FR-D2). Built only from +// primitives and $tokens. Each fills the window: the stamp sets the root's +// overflow to hidden (Structure.root) so the root keeps the artboard's height, +// the shell is `height: "100%"`, and every pane scrolls on its own +// (`overflow: "auto"`). A pane's direct children carry no fixed height and no +// overflow, so tripled content scrolls inside its pane instead of squashing +// its rows or growing the page. +// Fixed widths carry a matching minWidth, since a scrolling flex item may +// otherwise shrink below its width. + +const APP_ROOT = { overflow: 'hidden' as const }; +const SIDEBAR_WIDTH = 240; +const HEADER_HEIGHT = 48; +const ROW_HEIGHT = 32; + +/** The window-filling shell: panes side by side. */ +function shell(id: string, children: SceneNode[]): SceneNode { + return { id, type: 'frame', name: 'Shell', width: '100%', height: '100%', layout: 'horizontal', fill: COLOR.bgPrimary, children }; +} + +/** A pane that scrolls on its own. Its direct children never carry a fixed + * height, so they keep their content size and the pane scrolls instead of + * squashing them. */ +function pane(id: string, name: string, children: SceneNode[], opts: { width?: number | string; minWidth?: number; fill?: string; gap?: string; padding?: string } = {}): SceneNode { + return { + id, type: 'frame', name, layout: 'vertical', overflow: 'auto', minHeight: 0, + width: opts.width ?? '100%', minWidth: opts.minWidth ?? 0, + gap: opts.gap ?? SPACE.md, padding: opts.padding ?? SPACE.lg, + ...(opts.fill ? { fill: opts.fill } : {}), + children, + }; +} + +const vDivider = (id: string): SceneNode => ({ id, type: 'divider', orientation: 'vertical' }); + +/** The navigation sidebar: product name over nav-items, the first active. */ +function sidebar(id: string, items: Array<[string, string]>, footer: Array<[string, string]> = []): SceneNode { + const navItem = (key: string, [label, icon]: [string, string], active = false): SceneNode => + ({ id: `${id}-${key}`, type: 'nav-item', label, icon, ...(active ? { active: true } : {}) }); + return pane(id, 'Sidebar', [ + { id: `${id}-brand`, type: 'text', content: 'Product name', fontSize: TYPE.body, fontWeight: 600, color: COLOR.textPrimary, padding: [SPACE.xs2, SPACE.xs] }, + { + id: `${id}-nav`, type: 'frame', name: 'Navigation', width: '100%', layout: 'vertical', gap: SPACE.xxs, + children: items.map((item, i) => navItem(`nav-${i + 1}`, item, i === 0)), + }, + ...(footer.length ? [{ + id: `${id}-more`, type: 'frame' as const, name: 'Secondary navigation', width: '100%', layout: 'vertical' as const, gap: SPACE.xxs, + children: footer.map((item, i) => navItem(`more-${i + 1}`, item)), + }] : []), + ], { width: SIDEBAR_WIDTH, minWidth: SIDEBAR_WIDTH, fill: COLOR.bgSurface, gap: SPACE.lg, padding: SPACE.sm }); +} + +/** A pane header bar: a title and its actions, 48 tall, ruled below. */ +function header(id: string, title: string, actions: SceneNode[]): SceneNode { + return { + id, type: 'frame', name: 'Header', width: '100%', height: HEADER_HEIGHT, minHeight: HEADER_HEIGHT, + layout: 'horizontal', alignItems: 'center', justifyContent: 'space-between', gap: SPACE.md, + padding: [0, SPACE.md], borderBottom: { width: 1, color: COLOR.border }, + children: [ + { id: `${id}-title`, type: 'text', content: title, fontSize: TYPE.textLg, fontWeight: 600, color: COLOR.textPrimary, textOverflow: 'ellipsis', title }, + // The title truncates; the actions (each button capped) never shrink. + { id: `${id}-actions`, type: 'frame', name: 'Actions', layout: 'horizontal', alignItems: 'center', gap: SPACE.xs, minWidth: 'max-content', children: actions }, + ], + }; +} + +/** The column beside the sidebar: fixed bars on top, then a row of panes + * that takes the height left (`height: 100%` + `minHeight: 0` shrinks it by + * exactly the bars, which keep theirs through their own minHeight). */ +function main(id: string, bars: SceneNode[], panes: SceneNode[]): SceneNode { + return { + id, type: 'frame', name: 'Main', width: '100%', minWidth: 0, layout: 'vertical', + children: [ + ...bars, + { id: `${id}-panes`, type: 'frame', name: 'Panes', width: '100%', height: '100%', minHeight: 0, layout: 'horizontal', children: panes }, + ], + }; +} + +/** A labelled button caps its width, so a long label truncates instead of + * pushing its bar past a 1024px window. */ +const BUTTON_MAX = 200; +const secondary = (id: string, label: string, icon?: string): SceneNode => + ({ id, type: 'button', label, variant: 'secondary', size: 'sm', maxWidth: BUTTON_MAX, ...(icon ? { icon } : {}) }); +const primary = (id: string, label: string): SceneNode => ({ id, type: 'button', label, size: 'sm', maxWidth: BUTTON_MAX }); +/** A 24px icon-only tool, named for screen readers, in quiet ink (a toolbar + * of accent-coloured glyphs would compete with the one primary action). */ +const iconButton = (id: string, icon: string, ariaLabel: string): SceneNode => + ({ id, type: 'button', icon, ariaLabel, variant: 'ghost', size: 'xs', color: COLOR.textSecondary }); + +/** A text that may be cut: one line, an ellipsis, its full copy as `title`. */ +function cut(id: string, content: string, extra: Partial = {}): SceneNode { + return { id, type: 'text', content, fontSize: TYPE.label, color: COLOR.textPrimary, textOverflow: 'ellipsis', title: content, minWidth: 0, ...extra }; +} + +/** A section heading inside a pane. */ +const sectionTitle = (id: string, content: string): SceneNode => + ({ id, type: 'text', content, fontSize: TYPE.body, fontWeight: 600, color: COLOR.textPrimary }); + +// ── the app table (data-table-app, skeleton-table-app, dashboard-app) ─────── +// Carbon's ladder: the toolbar, every body row and (at rest) the header row +// are 32 tall. + +// The row-actions column is the button's own 24px under a blank header (the +// usual overflow-menu column), so the button sits straight in the row: one +// level less, which keeps a table stamped into a realisation's pane within +// the 8-level depth advisory. +const ACTIONS_WIDTH = 24; +const COLUMNS: Array<{ key: string; label: string; width: string; end?: boolean }> = [ + { key: 'name', label: 'Name', width: '36%' }, + { key: 'status', label: 'Status', width: '18%' }, + { key: 'updated', label: 'Updated', width: '20%' }, + { key: 'amount', label: 'Amount', width: '18%', end: true }, + { key: 'actions', label: '', width: `${ACTIONS_WIDTH}px`, end: true }, +]; + +/** A 32px row: one cell per column, a text cell sized straight to its + * column width, the actions cell (the icon button, or the header's blank + * frame) at the column's fixed 24px. */ +function tableRow(id: string, cells: (col: (typeof COLUMNS)[number]) => SceneNode, extra: Partial = {}): SceneNode { + return { + id, type: 'frame', name: 'Row', width: '100%', height: ROW_HEIGHT, minHeight: ROW_HEIGHT, layout: 'horizontal', alignItems: 'center', + gap: SPACE.md, padding: [0, SPACE.md], borderBottom: { width: 1, color: COLOR.border }, ...extra, + children: COLUMNS.map((col) => { + const cell = cells(col); + if (cell.type === 'text') return { ...cell, width: col.width, ...(col.end ? { textAlign: 'right' as const } : {}) }; + return { ...cell, width: ACTIONS_WIDTH, minWidth: ACTIONS_WIDTH }; + }), + }; +} + +/** The header row: column names in full (a header is never cut), so it has + * no fixed height: 32 at rest, taller when a long name wraps. */ +function headerRow(id: string): SceneNode { + // minWidth 0 lets a long unbroken name break inside its column. + const row = tableRow(id, (col) => (col.key === 'actions' + ? { id: `${id}-${col.key}`, type: 'frame', name: 'Actions' } + : { id: `${id}-${col.key}-text`, type: 'text', content: col.label, fontSize: TYPE.caption, fontWeight: 600, color: COLOR.textSecondary, minWidth: 0 }), { name: 'Header' }); + delete row.height; + return row; +} + +function bodyRow(id: string, last = false): SceneNode { + return tableRow(id, (col) => { + const cid = `${id}-${col.key}-cell`; + if (col.key === 'actions') return iconButton(`${id}-actions`, 'ellipsis', 'Row actions'); + if (col.key === 'amount') return cut(cid, 'Amount — TBD', { tabularNums: true }); + if (col.key === 'name') return cut(cid, 'Item name', { fontWeight: 500 }); + return cut(cid, col.key === 'status' ? 'Status' : 'Date', { color: COLOR.textSecondary }); + }, last ? { borderBottom: undefined } : {}); +} + +function skeletonRow(id: string, last = false): SceneNode { + const bar: Record = { name: '60%', status: '50%', updated: '55%', amount: '45%', actions: '100%' }; + return { + id, type: 'frame', name: 'Skeleton row', width: '100%', height: ROW_HEIGHT, minHeight: ROW_HEIGHT, layout: 'horizontal', alignItems: 'center', + gap: SPACE.md, padding: [0, SPACE.md], ...(last ? {} : { borderBottom: { width: 1, color: COLOR.border } }), + children: COLUMNS.map((col) => ({ + id: `${id}-${col.key}`, type: 'frame' as const, width: col.width, minWidth: 0, ...(col.end ? { alignItems: 'end' as const } : {}), + children: [{ id: `${id}-${col.key}-bar`, type: 'skeleton' as const, width: bar[col.key], height: 12, cornerRadius: RADIUS.sm }], + })), + }; +} + +/** The table's toolbar: search, a filter, 32 tall like the rows. */ +function tableToolbar(id: string): SceneNode { + return { + id, type: 'frame', name: 'Toolbar', width: '100%', height: ROW_HEIGHT, minHeight: ROW_HEIGHT, layout: 'horizontal', alignItems: 'center', + justifyContent: 'space-between', gap: SPACE.sm, + children: [ + // A text-input never shrinks: its 240px slot does, so a narrow pane + // keeps the filter in view. + { + id: `${id}-search-slot`, type: 'frame', name: 'Search', width: 240, minWidth: 0, + children: [{ id: `${id}-search`, type: 'text-input', placeholder: 'Search', icon: 'search', size: 'sm', width: '100%' }], + }, + secondary(`${id}-filter`, 'Filter', 'list-filter'), + ], + }; +} + +/** A bordered table: header row over body rows. It never clips (a frame with + * `overflow` may shrink below its rows inside a scrolling pane), so the header + * carries no fill of its own to poke past the rounded corners. */ +function appTable(id: string, rows: SceneNode[]): SceneNode { + return { + id, type: 'frame', name: 'Table', width: '100%', layout: 'vertical', + cornerRadius: RADIUS.sm, fill: COLOR.bgSurface, stroke: COLOR.border, strokeWidth: 1, + children: [headerRow(`${id}-header`), ...rows], + }; +} + +function pager(id: string): SceneNode { + return { + id, type: 'frame', name: 'Pagination', width: '100%', height: ROW_HEIGHT, minHeight: ROW_HEIGHT, layout: 'horizontal', + alignItems: 'center', justifyContent: 'space-between', gap: SPACE.sm, + children: [ + cut(`${id}-count`, 'Row count — TBD', { fontSize: TYPE.caption, color: COLOR.textSecondary, tabularNums: true }), + { + id: `${id}-pages`, type: 'frame', name: 'Pager', layout: 'horizontal', alignItems: 'center', gap: SPACE.xs2, + children: [iconButton(`${id}-prev`, 'chevron-left', 'Previous page'), iconButton(`${id}-next`, 'chevron-right', 'Next page')], + }, + ], + }; +} + +export const dataTableApp: Structure = { + name: 'data-table-app', + kind: 'component', + anatomy: 'data-table', + surface: 'desktop-app', + description: 'The desktop-app data table on the density ladder: a 32px toolbar (search field, filter), a 32px header row over 32px body rows (name, status, date, a right-aligned amount, an icon-only row-actions button under a blank header), and a 32px pager. Stamp it into a pane at least 480px wide (a content, work or detail pane), not a 300px side panel: narrower, its column names wrap. Copy rows with batch_design C ops to extend. Its loading state is skeleton-table-app.', + nodes: [{ + id: 'dta', type: 'frame', name: 'Data table', width: '100%', layout: 'vertical', gap: SPACE.sm, + children: [ + tableToolbar('dta-toolbar'), + appTable('dta-table', [bodyRow('dta-r1'), bodyRow('dta-r2'), bodyRow('dta-r3', true)]), + pager('dta-pager'), + ], + }], +}; + +export const skeletonTableApp: Structure = { + name: 'skeleton-table-app', + kind: 'component', + anatomy: 'skeleton-table', + surface: 'desktop-app', + description: 'Loading state for data-table-app: the same 32px header row over skeleton rows of the same height and columns, so the loaded table lands without a layout shift.', + nodes: [{ + id: 'ska', type: 'frame', name: 'Skeleton table', width: '100%', layout: 'vertical', gap: SPACE.sm, + children: [appTable('ska-table', [skeletonRow('ska-r1'), skeletonRow('ska-r2'), skeletonRow('ska-r3', true)])], + }], +}; + +// ── split-workbench-app ───────────────────────────────────────────────────── + +const NAV: Array<[string, string]> = [ + ['Overview', 'layout-dashboard'], ['Projects', 'folder'], ['Members', 'users'], ['Reports', 'chart-column'], +]; +const MORE: Array<[string, string]> = [['Settings', 'settings']]; + +function propertyText(id: string, label: string): SceneNode { + return { id, type: 'property-row', label, children: [cut(`${id}-value`, 'Value — TBD')] }; +} + +export const splitWorkbenchApp: Structure = { + name: 'split-workbench-app', + anatomy: 'split-workbench', + surface: 'desktop-app', + description: 'The desktop-app shell: a sidebar of nav-items beside a header (title, actions, a pane toggle as an icon-only button) over a work area and a right detail panel of property rows. Every pane scrolls on its own; the window never does.', + axes: { heroTreatment: 'split', density: 'dense', rhythm: 'asymmetric', alignment: 'split' }, + root: APP_ROOT, + nodes: [shell('swa-shell', [ + sidebar('swa-sidebar', NAV, MORE), + vDivider('swa-div-1'), + main('swa-main', [ + header('swa-header', 'Workspace', [ + secondary('swa-secondary', 'Secondary'), + primary('swa-primary', 'Primary action'), + iconButton('swa-toggle', 'panel-right', 'Toggle panel'), + ]), + ], [ + pane('swa-work', 'Work area', [{ + id: 'swa-canvas', type: 'frame', name: 'Work surface', width: '100%', height: '100%', layout: 'vertical', + alignItems: 'center', justifyContent: 'center', cornerRadius: RADIUS.md, + fill: COLOR.bgSurface, stroke: COLOR.border, strokeWidth: 1, + children: [{ id: 'swa-canvas-label', type: 'text', content: 'Work area', fontSize: TYPE.body, color: COLOR.textSecondary }], + }]), + vDivider('swa-div-2'), + pane('swa-panel', 'Detail panel', [ + sectionTitle('swa-panel-title', 'Details'), + { + id: 'swa-props', type: 'frame', name: 'Properties', width: '100%', layout: 'vertical', gap: SPACE.xs, + children: [propertyText('swa-prop-1', 'Owner'), propertyText('swa-prop-2', 'Status'), propertyText('swa-prop-3', 'Updated')], + }, + ], { width: 300, minWidth: 300, fill: COLOR.bgSurface }), + ]), + ])], +}; + +// ── list-detail-app ───────────────────────────────────────────────────────── + +function listItem(id: string): SceneNode { + return { + id, type: 'list-row', title: 'Item title', subtitle: 'Supporting detail', + trailing: { text: 'Meta' }, + }; +} + +export const listDetailApp: Structure = { + name: 'list-detail-app', + anatomy: 'list-detail', + surface: 'desktop-app', + description: 'Navigation, list and detail panes side by side: a sidebar of nav-items, a searchable list of rows, and a detail pane holding a designed "nothing selected" placeholder until a row is chosen. Each pane scrolls on its own.', + axes: { heroTreatment: 'split', density: 'dense', rhythm: 'asymmetric', alignment: 'left' }, + root: APP_ROOT, + nodes: [shell('lda-shell', [ + sidebar('lda-sidebar', [['Inbox', 'inbox'], ['Assigned', 'user'], ['Archive', 'archive']], MORE), + vDivider('lda-div-1'), + pane('lda-list', 'List', [ + { + id: 'lda-list-head', type: 'frame', name: 'List header', width: '100%', layout: 'vertical', gap: SPACE.sm, + children: [ + sectionTitle('lda-list-title', 'Inbox'), + { id: 'lda-search', type: 'text-input', placeholder: 'Search', icon: 'search', size: 'sm', width: '100%' }, + ], + }, + { + id: 'lda-rows', type: 'frame', name: 'Rows', width: '100%', layout: 'vertical', + children: [listItem('lda-row-1'), listItem('lda-row-2'), listItem('lda-row-3'), listItem('lda-row-4')], + }, + ], { width: 360, minWidth: 360, gap: SPACE.sm, padding: SPACE.sm }), + vDivider('lda-div-2'), + pane('lda-detail', 'Detail', [{ + id: 'lda-empty', type: 'frame', name: 'Nothing selected', width: '100%', height: '100%', layout: 'vertical', + alignItems: 'center', justifyContent: 'center', gap: SPACE.sm, + children: [ + { id: 'lda-empty-icon', type: 'icon', icon: 'mouse-pointer-click', iconSize: 32, iconColor: COLOR.textSecondary }, + { id: 'lda-empty-title', type: 'text', content: 'Nothing selected', fontSize: TYPE.body, fontWeight: 600, color: COLOR.textPrimary, textAlign: 'center' }, + { id: 'lda-empty-body', type: 'text', content: 'Choose an item from the list to see its details here.', fontSize: TYPE.body, color: COLOR.textSecondary, textAlign: 'center', maxWidth: 360 }, + ], + }]), + ])], +}; + +// ── editor-inspector-app ──────────────────────────────────────────────────── + +export const editorInspectorApp: Structure = { + name: 'editor-inspector-app', + anatomy: 'editor-inspector', + surface: 'desktop-app', + description: 'An editor: a header (a breadcrumb of links, the document title, actions) over a work area with a tool strip of icon-only buttons, beside a 70/30 inspector of tabs and property rows (text inputs, a select, a toggle, a button). Each pane scrolls on its own.', + axes: { heroTreatment: 'split', density: 'dense', rhythm: 'asymmetric', alignment: 'split' }, + root: APP_ROOT, + nodes: [shell('eia-shell', [ + main('eia-main', [{ + id: 'eia-header', type: 'frame', name: 'Header', width: '100%', height: HEADER_HEIGHT, minHeight: HEADER_HEIGHT, + layout: 'horizontal', alignItems: 'center', justifyContent: 'space-between', gap: SPACE.md, + padding: [0, SPACE.md], borderBottom: { width: 1, color: COLOR.border }, + children: [ + { + id: 'eia-crumbs', type: 'frame', name: 'Breadcrumb', layout: 'horizontal', alignItems: 'center', gap: SPACE.xs, minWidth: 0, + children: [ + // The slot shrinks (a link never does), so a long parent name truncates. + { id: 'eia-crumb-slot', type: 'frame', name: 'Parent', minWidth: 0, children: [{ id: 'eia-crumb-parent', type: 'link', label: 'Documents' }] }, + { id: 'eia-crumb-sep', type: 'icon', icon: 'chevron-right', iconSize: 14, iconColor: COLOR.textSecondary }, + { id: 'eia-title', type: 'text', content: 'Document title', fontSize: TYPE.label, fontWeight: 600, color: COLOR.textPrimary, textOverflow: 'ellipsis', title: 'Document title', minWidth: 0 }, + ], + }, + { + id: 'eia-actions', type: 'frame', name: 'Actions', layout: 'horizontal', alignItems: 'center', gap: SPACE.xs, minWidth: 'max-content', + children: [secondary('eia-share', 'Share'), primary('eia-publish', 'Publish')], + }, + ], + }], [ + pane('eia-work', 'Work area', [ + { + id: 'eia-tools', type: 'frame', name: 'Tools', width: 'fit-content', layout: 'horizontal', alignItems: 'center', gap: SPACE.xs2, + padding: SPACE.xs2, cornerRadius: RADIUS.sm, fill: COLOR.bgSurface, stroke: COLOR.border, strokeWidth: 1, + children: [ + iconButton('eia-tool-select', 'mouse-pointer-2', 'Select'), + iconButton('eia-tool-pan', 'hand', 'Pan'), + iconButton('eia-tool-zoom-in', 'zoom-in', 'Zoom in'), + iconButton('eia-tool-zoom-out', 'zoom-out', 'Zoom out'), + ], + }, + { + id: 'eia-canvas', type: 'frame', name: 'Work surface', width: '100%', height: '100%', layout: 'vertical', + alignItems: 'center', justifyContent: 'center', cornerRadius: RADIUS.md, + fill: COLOR.bgSurface, stroke: COLOR.border, strokeWidth: 1, + children: [{ id: 'eia-canvas-label', type: 'text', content: 'Work area', fontSize: TYPE.body, color: COLOR.textSecondary }], + }, + ], { width: '70%', gap: SPACE.sm }), + vDivider('eia-div'), + pane('eia-inspector', 'Inspector', [ + { id: 'eia-tabs', type: 'tabs', items: [{ label: 'Design', active: true }, { label: 'Layout' }, { label: 'Notes' }], size: 'sm' }, + sectionTitle('eia-props-title', 'Properties'), + { + id: 'eia-props', type: 'frame', name: 'Properties', width: '100%', layout: 'vertical', gap: SPACE.xs, + children: [ + { id: 'eia-prop-name', type: 'property-row', label: 'Name', children: [{ id: 'eia-prop-name-input', type: 'text-input', value: 'Value', size: 'sm', width: '100%' }] }, + { id: 'eia-prop-width', type: 'property-row', label: 'Width', children: [{ id: 'eia-prop-width-input', type: 'text-input', value: 'Value', size: 'sm', width: '100%' }] }, + { id: 'eia-prop-mode', type: 'property-row', label: 'Mode', children: [{ id: 'eia-prop-mode-select', type: 'select', value: 'Option', width: '100%' }] }, + { id: 'eia-prop-visible', type: 'property-row', label: 'Visible', children: [{ id: 'eia-prop-visible-toggle', type: 'toggle', checked: true }] }, + { id: 'eia-prop-source', type: 'property-row', label: 'Source', children: [{ ...secondary('eia-prop-source-button', 'Choose'), maxWidth: '100%' }] }, + ], + }, + ], { width: '30%', minWidth: 280, fill: COLOR.bgSurface, gap: SPACE.sm, padding: SPACE.md }), + ]), + ])], +}; + +// ── browser-app ───────────────────────────────────────────────────────────── + +function itemCard(id: string): SceneNode { + return { + id, type: 'frame', name: 'Item card', width: '100%', minWidth: 0, layout: 'vertical', overflow: 'hidden', + cornerRadius: RADIUS.md, fill: COLOR.bgSurface, stroke: COLOR.border, strokeWidth: 1, shadow: ELEV.flat, + children: [ + { id: `${id}-media`, type: 'frame', name: 'Preview', width: '100%', height: 140, fill: COLOR.bgElevated }, + { + id: `${id}-copy`, type: 'frame', name: 'Copy', width: '100%', layout: 'vertical', gap: SPACE.xxs, padding: SPACE.sm, + children: [ + { id: `${id}-title`, type: 'link', label: 'Item title' }, + cut(`${id}-meta`, 'Meta — TBD', { fontSize: TYPE.caption, color: COLOR.textSecondary }), + ], + }, + ], + }; +} + +export const browserApp: Structure = { + name: 'browser-app', + anatomy: 'browser', + surface: 'desktop-app', + description: 'A browser of items: a sidebar of nav-items, a header with the one primary action, a filter bar (search field, tabs) and an adaptive grid of item cards (minimum column width 240) whose titles are links. The grid pane scrolls on its own.', + axes: { heroTreatment: 'none', density: 'balanced', rhythm: 'uniform', alignment: 'left' }, + root: APP_ROOT, + nodes: [shell('bra-shell', [ + sidebar('bra-sidebar', [['All items', 'layout-grid'], ['Recent', 'clock'], ['Shared', 'users']], MORE), + vDivider('bra-div'), + main('bra-main', [ + header('bra-header', 'Items', [primary('bra-new', 'New item')]), + { + id: 'bra-filters', type: 'frame', name: 'Filter bar', width: '100%', height: HEADER_HEIGHT, minHeight: HEADER_HEIGHT, + layout: 'horizontal', alignItems: 'center', gap: SPACE.md, padding: [0, SPACE.md], borderBottom: { width: 1, color: COLOR.border }, + children: [ + { id: 'bra-search', type: 'text-input', placeholder: 'Search', icon: 'search', size: 'sm', width: 280 }, + { + // The slot shrinks (a tablist never does), so long labels truncate inside it. + id: 'bra-tabs-slot', type: 'frame', name: 'Tabs', width: '100%', minWidth: 0, + children: [{ id: 'bra-tabs', type: 'tabs', variant: 'contained', size: 'sm', items: [{ label: 'All', active: true }, { label: 'Starred' }, { label: 'Archived' }] }], + }, + ], + }, + ], [ + pane('bra-grid-pane', 'Items', [{ + id: 'bra-grid', type: 'frame', name: 'Item grid', width: '100%', layout: 'grid', + gridColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: SPACE.md, rowGap: SPACE.md, + children: [1, 2, 3, 4, 5, 6].map((i) => itemCard(`bra-card-${i}`)), + }]), + ]), + ])], +}; + +// ── dashboard-app ─────────────────────────────────────────────────────────── + +function statTile(id: string): SceneNode { + return { + id, type: 'frame', name: 'Stat', width: '100%', minWidth: 0, layout: 'vertical', gap: SPACE.xs, + padding: SPACE.md, cornerRadius: RADIUS.md, fill: COLOR.bgSurface, stroke: COLOR.border, strokeWidth: 1, + children: [ + cut(`${id}-label`, 'Metric label', { fontSize: TYPE.caption, color: COLOR.textSecondary }), + cut(`${id}-value`, 'Value — TBD', { fontSize: TYPE.textLg, fontWeight: 600, tabularNums: true }), + cut(`${id}-delta`, 'Change — TBD', { fontSize: TYPE.caption, color: COLOR.textSecondary }), + ], + }; +} + +export const dashboardApp: Structure = { + name: 'dashboard-app', + anatomy: 'dashboard', + surface: 'desktop-app', + description: 'The desktop-app dashboard: a sidebar of nav-items, a header with actions, and a scrolling content pane of a four-up stat row, a trend chart panel and a recent-items table on the 32px ladder. No fabricated numbers.', + axes: { heroTreatment: 'stat-led', density: 'dense', rhythm: 'uniform', alignment: 'left' }, + root: APP_ROOT, + nodes: [shell('dba-shell', [ + sidebar('dba-sidebar', NAV, MORE), + vDivider('dba-div'), + main('dba-main', [ + header('dba-header', 'Overview', [secondary('dba-export', 'Export', 'download')]), + ], [ + pane('dba-content', 'Content', [ + { + id: 'dba-stats', type: 'frame', name: 'Stat row', width: '100%', layout: 'grid', gridColumns: 4, gap: SPACE.md, + children: [statTile('dba-stat-1'), statTile('dba-stat-2'), statTile('dba-stat-3'), statTile('dba-stat-4')], + }, + { + id: 'dba-chart', type: 'frame', name: 'Chart panel', width: '100%', layout: 'vertical', gap: SPACE.sm, + padding: SPACE.md, cornerRadius: RADIUS.md, fill: COLOR.bgSurface, stroke: COLOR.border, strokeWidth: 1, + children: [ + sectionTitle('dba-chart-title', 'Trend'), + { + id: 'dba-chart-area', type: 'chart', name: 'Chart area', width: '100%', height: 220, + kind: 'line', curve: 'smooth', gridlines: 4, + series: [{ data: [12, 18, 15, 24, 22, 30, 34], stroke: COLOR.accent, strokeWidth: 2, area: true }], + xLabels: ['Label', '', '', '', '', '', 'Label'], + yLabels: ['Label', '', '', '', 'Label'], + }, + ], + }, + sectionTitle('dba-recent-title', 'Recent'), + appTable('dba-table', [bodyRow('dba-r1'), bodyRow('dba-r2'), bodyRow('dba-r3', true)]), + ]), + ]), + ])], +}; + +// ── settings-app ──────────────────────────────────────────────────────────── + +function settingsGroup(id: string, title: string, rows: SceneNode[]): SceneNode { + return { + id, type: 'frame', name: title, width: '100%', layout: 'vertical', gap: SPACE.sm, + children: [ + sectionTitle(`${id}-title`, title), + { + id: `${id}-rows`, type: 'frame', name: 'Rows', width: '100%', layout: 'vertical', gap: SPACE.xs, padding: [SPACE.sm, SPACE.md], + cornerRadius: RADIUS.md, fill: COLOR.bgSurface, stroke: COLOR.border, strokeWidth: 1, + children: rows, + }, + ], + }; +} + +const settingRow = (id: string, label: string, control: SceneNode): SceneNode => + ({ id, type: 'property-row', label, labelWidth: 200, children: [control] }); + +export const settingsApp: Structure = { + name: 'settings-app', + anatomy: 'settings', + surface: 'desktop-app', + description: 'Desktop-app settings: a sidebar of setting sections as nav-items beside a scrolling column of grouped property rows (text inputs, a select, toggles), a danger zone with a destructive action set apart, and Cancel / Save at the foot.', + axes: { heroTreatment: 'none', density: 'balanced', rhythm: 'uniform', alignment: 'left' }, + root: APP_ROOT, + nodes: [shell('sta-shell', [ + sidebar('sta-sidebar', [['General', 'sliders-horizontal'], ['Notifications', 'bell'], ['Members', 'users'], ['Billing', 'credit-card']]), + vDivider('sta-div'), + pane('sta-content', 'Content', [{ + id: 'sta-col', type: 'frame', name: 'Column', width: '100%', maxWidth: 720, layout: 'vertical', gap: SPACE.lg, + children: [ + { id: 'sta-title', type: 'text', content: 'General', fontSize: TYPE.textLg, fontWeight: 600, color: COLOR.textPrimary }, + settingsGroup('sta-profile', 'Workspace', [ + settingRow('sta-name', 'Workspace name', { id: 'sta-name-input', type: 'text-input', value: 'Value', size: 'sm', width: '100%' }), + settingRow('sta-url', 'Address', { id: 'sta-url-input', type: 'text-input', value: 'Value', size: 'sm', width: '100%' }), + settingRow('sta-lang', 'Language', { id: 'sta-lang-select', type: 'select', value: 'Option', width: '100%' }), + ]), + settingsGroup('sta-notify', 'Notifications', [ + settingRow('sta-email', 'Email updates', { id: 'sta-email-toggle', type: 'toggle', checked: true }), + settingRow('sta-digest', 'Weekly digest', { id: 'sta-digest-toggle', type: 'toggle' }), + ]), + { + id: 'sta-danger', type: 'frame', name: 'Danger zone', width: '100%', layout: 'horizontal', alignItems: 'center', + justifyContent: 'space-between', gap: SPACE.md, padding: SPACE.md, cornerRadius: RADIUS.md, + fill: COLOR.bgSurface, stroke: '$danger', strokeWidth: 1, + children: [ + { + id: 'sta-danger-copy', type: 'frame', name: 'Copy', layout: 'vertical', gap: SPACE.xxs, minWidth: 0, + children: [ + { id: 'sta-danger-title', type: 'text', content: 'Delete workspace', fontSize: TYPE.body, fontWeight: 600, color: COLOR.textPrimary }, + { id: 'sta-danger-desc', type: 'text', content: 'Consequence — to confirm', fontSize: TYPE.body, color: COLOR.textSecondary }, + ], + }, + { id: 'sta-delete', type: 'button', label: 'Delete', variant: 'destructive', size: 'sm' }, + ], + }, + { + id: 'sta-footer', type: 'frame', name: 'Footer actions', width: '100%', layout: 'horizontal', justifyContent: 'end', + alignItems: 'center', gap: SPACE.xs, wrap: true, + children: [secondary('sta-cancel', 'Cancel'), primary('sta-save', 'Save changes')], + }, + ], + }]), + ])], +}; + +/** Every desktop-app structure, in registry order. */ +export const DESKTOP_APP_STRUCTURES: Array<[string, Structure]> = [ + ['split-workbench-app', splitWorkbenchApp], + ['list-detail-app', listDetailApp], + ['editor-inspector-app', editorInspectorApp], + ['browser-app', browserApp], + ['dashboard-app', dashboardApp], + ['settings-app', settingsApp], + ['data-table-app', dataTableApp], + ['skeleton-table-app', skeletonTableApp], +]; diff --git a/src/structures.ts b/src/structures.ts index e4b1939..dbd612d 100644 --- a/src/structures.ts +++ b/src/structures.ts @@ -1,5 +1,7 @@ import type { BuildLogEntry, Canvas, SceneNode, Structure, StructureAxes } from './types.js'; import { resolveSurface, SURFACE_TYPES, type SurfaceType } from './surfaces.js'; +import { COLOR, SPACE, RADIUS, ELEV, TYPE, TINT } from './structure-tokens.js'; +import { DESKTOP_APP_STRUCTURES } from './structures-desktop.js'; // Phase 11 — layout scaffold library. A Structure is a named page shape: a // partial scene tree of *labeled placeholder* children (C8 — never fabricated @@ -15,60 +17,6 @@ import { resolveSurface, SURFACE_TYPES, type SurfaceType } from './surfaces.js'; // structures carry the layout skeleton. `registerStructure` keeps the door open // for dynamically contributed structures, mirroring `registerPreset`. -/** Standard color tokens these scaffolds reference (the preset vocabulary). */ -const COLOR = { - bgPrimary: '$bg-primary', - bgSurface: '$bg-surface', - bgElevated: '$bg-elevated', - textPrimary: '$text-primary', - textSecondary: '$text-secondary', - accent: '$accent', - border: '$border', -} as const; - -/** Phase 27 slice B — density comes from tokens, not literals. Scaffolds - * reference the space/radius/elevation vocabulary generate_design_system - * writes; applyStructure seeds neutral defaults (the pre-27 literal values) - * for anything not already resolvable, so unthemed canvases render exactly - * as before and a personality re-densifies every stamp. */ -const SPACE = { - xxs: '$space-3xs', // 2 - xs2: '$space-2xs', // 4 - xs: '$space-xs', // 8 - sm: '$space-sm', // 12 - md: '$space-md', // 16 - lg: '$space-lg', // 24 - xl: '$space-xl', // 32 - xl2: '$space-2xl', // 48 -} as const; -const RADIUS = { - sm: '$radius-sm', // 8 - md: '$radius-md', // 12 - lg: '$radius-lg', // 16 -} as const; -const ELEV = { - flat: '$elevation.flat', - raised: '$elevation.raised', -} as const; -const TYPE = { - display: '$display', // hero headlines — the display face at full size - title: '$title', // page/screen titles, one step below display - heading: '$heading', // section heads - textLg: '$text-lg', // card titles, subheads — the step above body - textSm: '$text-sm', // small body text — untracked (nav items, prose, meta) - body: '$body', // prose and item text - label: '$label', // control, CTA, breadcrumb and table-header text - caption: '$caption', // metadata, timestamps, eyebrows -} as const; -/** Phase 28 — the tint pair: tint as the FILL, base color as the INK. */ -const TINT = { - accent: { bg: '$accent-tint', ink: COLOR.accent }, - success: { bg: '$success-tint', ink: '$success' }, - warning: { bg: '$warning-tint', ink: '$warning' }, - danger: { bg: '$danger-tint', ink: '$danger' }, - neutral: { bg: '$neutral-tint', ink: COLOR.textSecondary }, -} as const; - /** A labeled placeholder card — a surface with a role label + neutral body. */ function card( id: string, @@ -1784,6 +1732,8 @@ const structureMap = new Map([ ['onboarding-mobile', onboardingMobile], ['feed-mobile', feedMobile], ['detail-mobile', detailMobile], + // Phase 31 slice D — desktop-app realisations and components + ...DESKTOP_APP_STRUCTURES, ]); // ── anatomy and realisation (Phase 30 slice E) ────────────────────────────── @@ -1984,11 +1934,14 @@ const PRIMITIVE_COLOR_TOKENS: Record = { // that resolves the fallback keeps it rather than getting a seeded default. accent: ['primary'], 'bg-surface': ['surface'], danger: ['error'], }; -/** Phase 31 — the extra tokens the desktop-app vocabulary reads: the active - * fill of nav-item / tree-row / contained tabs, and a text-input's boundary - * (which falls back to `border`). Mobile stamps never seed them. */ +/** Phase 31 — the extra token the desktop-app vocabulary reads: a + * text-input's and a control's boundary (which falls back to `border`). + * Mobile stamps never seed it. Slice D (spec change S6) stopped seeding + * `accent-tint`, the active fill of nav-item / tree-row / contained tabs: + * presets carry no tint, so a dark seed survived a later light preset; without + * the token the renderer mixes 12% accent into whatever surface is applied. */ const DESKTOP_PRIMITIVE_TYPES = new Set(['link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row', 'divider']); -const DESKTOP_PRIMITIVE_COLOR_TOKENS: Record = { 'accent-tint': [], 'border-strong': ['border'] }; +const DESKTOP_PRIMITIVE_COLOR_TOKENS: Record = { 'border-strong': ['border'] }; /** A primitive's copy fields as [path, text]: what an agent replaces. */ function primitiveCopy(n: SceneNode): [string, string][] { @@ -2124,6 +2077,15 @@ export function applyStructure( inserted = structure.nodes.map((n) => structuredClone(n)); canvas.root.children = inserted; + // Root props (Phase 31 slice D): drop the ones the previous page stamp + // wrote and the root still holds unchanged, then write this structure's. + const previous = getStructure(canvas.metadata?.provenance?.structure ?? ''); + const rootProps = canvas.root as unknown as Record; + for (const [key, value] of Object.entries(previous?.root ?? {})) { + if (rootProps[key] === value) delete rootProps[key]; + } + Object.assign(canvas.root, structuredClone(structure.root ?? {})); + // Give the document root a page background so the scaffold fills the viewport // rather than showing browser-default white. createCanvas seeds a white root // fill, so treat white/unset as the default backdrop and override it — but diff --git a/src/types.ts b/src/types.ts index ea1aa15..bfc86e4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -453,6 +453,11 @@ export interface Structure { /** Phase 30 — the canvas type this realisation is for (default `web`); * `any` stamps on every type. (anatomy, surface) is unique in the registry. */ surface?: 'web' | 'mobile' | 'desktop-app' | 'any'; + /** Phase 31 slice D — props a page stamp writes onto `canvas.root` (the + * desktop-app realisations set `overflow: "hidden"`, so the root keeps the + * window's height and the panes scroll). A later page stamp with `replace` + * removes the ones the root still holds unchanged. */ + root?: Partial>; /** Placeholder children inserted under `canvas.root` by `apply_structure`. */ nodes: SceneNode[]; } diff --git a/test-desktop-primitives.ts b/test-desktop-primitives.ts index f7b9fe2..ce4caff 100644 --- a/test-desktop-primitives.ts +++ b/test-desktop-primitives.ts @@ -4,7 +4,7 @@ // dots never count as accents (FR-A6), a canvas holding a desktop-app // primitive must declare its type (desktop-app-artboard), stress reaches the // new copy, repeats count as reuse, the breadcrumb is built from links, and -// unthemed stamps seed $accent-tint / $border-strong. Rendered geometry lives +// unthemed stamps seed $border-strong (not $accent-tint, spec change S6). Rendered geometry lives // in test-desktop-primitives-render.ts (Chrome). // // Usage: npx tsx test-desktop-primitives.ts @@ -200,11 +200,11 @@ const html = (n: SceneNode, colors?: Record) => { registerStructure({ name: `probe-${t}`, kind: 'component', surface: 'any', description: 'probe', nodes: [{ id: 'n', type: t as SceneNode['type'], name: 'n', label: 'L', placeholder: 'Find', value: 'v', shortcut: '⌘K', error: 'Bad', items: [{ label: 'A' }] } as SceneNode] }); const cv = createCanvas(`seed-${t}`, undefined, {}, { type: 'desktop-app', device: 'window-1440' }); const res = applyStructure(cv, `probe-${t}`, { existingColors: new Set() }); - if (!res.seededColors.includes('accent-tint') || !res.seededColors.includes('border-strong')) check(`stamping a ${t} seeds the desktop-app tokens`, false, res.seededColors.join(',')); + if (res.seededColors.includes('accent-tint') || !res.seededColors.includes('border-strong')) check(`stamping a ${t} seeds $border-strong and not $accent-tint`, false, res.seededColors.join(',')); if (t === 'text-input' && !['placeholder', 'value', 'error'].every((prop) => res.placeholders.some((pl) => pl.prop === prop))) check('text-input copy is a placeholder', false, JSON.stringify(res.placeholders)); if (t === 'menu-row' && !res.placeholders.some((pl) => pl.prop === 'shortcut')) check('menu-row shortcut is a placeholder', false); } - check('every desktop-app primitive seeds the tokens; their copy is a placeholder', true); + check('every desktop-app primitive seeds $border-strong, never $accent-tint; their copy is a placeholder', true); const withBorder = createCanvas('seed-b', undefined, {}, { type: 'desktop-app', device: 'window-1440' }); check('an existing $border suppresses border-strong seeding (it falls back to border)', !applyStructure(withBorder, 'probe-text-input', { existingColors: new Set(['border']) }).seededColors.includes('border-strong')); const sc = { id: 'm', name: 'm', type: 'menu-row', shortcut: '⌘K' } as SceneNode; @@ -273,7 +273,9 @@ const html = (n: SceneNode, colors?: Record) => { const c = createCanvas('seed', undefined, {}, { type: 'desktop-app', device: 'window-1440' }); const seed = applyStructure(c, 'breadcrumb', { existingColors: new Set(), realisation: 'web' }); - check('stamping a structure with a desktop-app primitive on an unthemed canvas seeds $accent-tint and $border-strong', seed.seededColors.includes('accent-tint') && seed.seededColors.includes('border-strong'), seed.seededColors.join(', ')); + // Spec change S6: no $accent-tint seed, so a later light preset is not left + // with a dark tint; the renderer mixes 12% accent into the applied surface. + check('stamping a structure with a desktop-app primitive on an unthemed canvas seeds $border-strong, not $accent-tint', !seed.seededColors.includes('accent-tint') && seed.seededColors.includes('border-strong'), seed.seededColors.join(', ')); check('a desktop-app primitive\'s copy is a placeholder', seed.placeholders.some((p) => p.prop === 'label' && p.role === 'Parent')); const m = createCanvas('mob', undefined, {}, { type: 'mobile', device: 'iphone-390' }); const mob = applyStructure(m, 'settings', { existingColors: new Set() }); diff --git a/test-desktop-structures.ts b/test-desktop-structures.ts new file mode 100644 index 0000000..62b514f --- /dev/null +++ b/test-desktop-structures.ts @@ -0,0 +1,100 @@ +import './test-env.js'; +/** + * Phase 31 slice D — the pieces around the desktop-app realisations, each pass + * with a twin that must fail: + * - spec change S5: `many` / `empty` act on desktop-app rows and card grids + * on a desktop-app canvas only, and a tripled list keeps one active row; + * - a property-row's label names its control (and only its own label does); + * - the coverage loading hint names skeleton-table-app on desktop-app. + * No Chrome. Run with: npx tsx test-desktop-structures.ts + */ +import { applyPerturbation } from './src/stress.js'; +import { createCanvas } from './src/scene-graph.js'; +import { applyStructure } from './src/structures.js'; +import { evaluateCanvas } from './src/evaluate.js'; +import type { SceneNode } from './src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +const doc = (children: SceneNode[]): SceneNode => ({ id: 'document', type: 'document', children }); +const count = (root: SceneNode, pred: (n: SceneNode) => boolean): number => + (pred(root) ? 1 : 0) + (root.children ?? []).reduce((sum, c) => sum + count(c, pred), 0); + +// ── S5: desktop-app stress runs ───────────────────────────────────────────── +{ + const nav: SceneNode = { + id: 'nav', type: 'frame', layout: 'vertical', children: [ + { id: 'a', type: 'nav-item', label: 'A', active: true }, + { id: 'b', type: 'nav-item', label: 'B' }, + { id: 'c', type: 'nav-item', label: 'C' }, + ], + }; + const app = applyPerturbation('many', doc([nav]), { type: 'desktop-app' }); + check('many triples a run of nav-items on desktop-app', count(app.root, (n) => n.type === 'nav-item') === 9 && app.touched.includes('nav')); + check('a tripled nav keeps exactly one active item', count(app.root, (n) => n.active === true) === 1); + const web = applyPerturbation('many', doc([nav]), { type: 'web' }); + check('twin: web leaves nav-items alone', count(web.root, (n) => n.type === 'nav-item') === 3 && web.touched.length === 0); + const empty = applyPerturbation('empty', doc([nav]), { type: 'desktop-app' }); + check('empty removes the run on desktop-app', count(empty.root, (n) => n.type === 'nav-item') === 0); + + for (const t of ['tree-row', 'menu-row', 'property-row'] as const) { + const run = doc([{ id: 'r', type: 'frame', children: [{ id: 'r1', type: t, label: 'x' }, { id: 'r2', type: t, label: 'y' }] }]); + check(`many triples a run of ${t}`, count(applyPerturbation('many', run, { type: 'desktop-app' }).root, (n) => n.type === t) === 6); + } + const mixed = doc([{ id: 'm', type: 'frame', children: [{ id: 'm1', type: 'nav-item', label: 'x' }, { id: 'm2', type: 'tree-row', label: 'y', depth: 0 }] }]); + check('twin: two rows of different types are no run', applyPerturbation('many', mixed, { type: 'desktop-app' }).touched.length === 0); + + const card = (id: string): SceneNode => ({ id, type: 'frame', children: [{ id: `${id}-t`, type: 'text', content: 'Title' }] }); + const grid = doc([{ id: 'g', type: 'frame', layout: 'grid', children: [card('k1'), card('k2'), card('k3')] }]); + const tripled = applyPerturbation('many', grid, { type: 'desktop-app' }); + check('many triples a card grid on desktop-app', tripled.root.children?.[0].children?.length === 9 && tripled.touched.includes('g')); + check('twin: web leaves the card grid alone', applyPerturbation('many', grid, { type: 'web' }).root.children?.[0].children?.length === 3); + const two = doc([{ id: 'g2', type: 'frame', layout: 'grid', children: [card('k1'), card('k2')] }]); + check('twin: a grid of two cards is not a card grid', applyPerturbation('many', two, { type: 'desktop-app' }).touched.length === 0); + const odd = doc([{ id: 'g3', type: 'frame', layout: 'grid', children: [card('k1'), card('k2'), { id: 'k3', type: 'text', content: 'x' }] }]); + check('twin: a grid with a differently shaped child is not a card grid', applyPerturbation('many', odd, { type: 'desktop-app' }).touched.length === 0); + const stack = doc([{ id: 'v', type: 'frame', layout: 'vertical', children: [card('k1'), card('k2'), card('k3')] }]); + check('twin: three identical cards in a vertical frame are not a card grid', applyPerturbation('many', stack, { type: 'desktop-app' }).touched.length === 0); + const deep = (id: string, inner: SceneNode['type']): SceneNode => ({ id, type: 'frame', children: [{ id: `${id}-a`, type: 'frame', children: [{ id: `${id}-b`, type: inner }] }] }); + const unlike = doc([{ id: 'g4', type: 'frame', layout: 'grid', children: [deep('d1', 'text'), deep('d2', 'text'), deep('d3', 'icon')] }]); + check('twin: cards that differ two levels down are not a card grid', applyPerturbation('many', unlike, { type: 'desktop-app' }).touched.length === 0); +} + +// ── a property-row's label names its control ──────────────────────────────── +{ + const unlabeled = async (rows: SceneNode[]) => { + const c = createCanvas('pr', undefined, {}, { type: 'desktop-app' }); + c.root.children = [{ id: 'group', type: 'frame', layout: 'vertical', children: rows }]; + return (await evaluateCanvas(c, { mode: 'fast', categories: ['usability'] })).issues.filter((i) => /has no text label/.test(i.message)).map((i) => i.nodeId); + }; + check('a toggle in a labelled property-row is labelled', (await unlabeled([{ id: 'r', type: 'property-row', label: 'Visible', children: [{ id: 't', type: 'toggle' }] }])).length === 0); + check('a blank-labelled property-row with its own text beside the toggle is labelled', + (await unlabeled([{ id: 'r', type: 'property-row', label: '', children: [{ id: 't', type: 'toggle' }, { id: 'x', type: 'text', content: 'Notify me' }] }])).length === 0); + check('twin: a property-row with no label prop flags its toggle (no throw)', + (await unlabeled([{ id: 'r', type: 'property-row', children: [{ id: 't', type: 'toggle' }] }])).includes('t')); + check('twin: a toggle in a blank-labelled property-row is not', + (await unlabeled([{ id: 'r', type: 'property-row', label: ' ', children: [{ id: 't', type: 'toggle' }] }])).includes('t')); + check('twin: a sibling row\'s label does not rescue a blank one', (await unlabeled([ + { id: 'r1', type: 'property-row', label: 'Name', children: [{ id: 'v', type: 'text', content: 'Value' }] }, + { id: 'r2', type: 'property-row', label: '', children: [{ id: 't', type: 'toggle' }] }, + ])).includes('t')); +} + +// ── the coverage loading hint names the desktop-app skeleton ─────────────── +{ + const hint = async (type: 'web' | 'desktop-app', structure: string) => { + const c = createCanvas('cov', undefined, {}, type === 'web' ? undefined : { type }); + applyStructure(c, structure); + return (await evaluateCanvas(c, { mode: 'fast', categories: ['coverage'] })).issues.find((i) => /"loading"/.test(i.message))?.suggestion ?? ''; + }; + check('on desktop-app the loading hint names skeleton-table-app', /skeleton-table-app/.test(await hint('desktop-app', 'data-table'))); + const web = await hint('web', 'data-table'); + check('twin: on web it names skeleton-table', /skeleton-table \(/.test(web) && !/skeleton-table-app/.test(web), web); +} + +console.log(allPass ? '\nAll desktop-structure tests passed.' : '\nSOME TESTS FAILED'); +process.exit(allPass ? 0 : 1); diff --git a/test-discoverability.ts b/test-discoverability.ts index 581cf53..1931048 100644 --- a/test-discoverability.ts +++ b/test-discoverability.ts @@ -105,6 +105,23 @@ const guidelines = readFileSync('docs/GUIDELINES.md', 'utf-8'); gotchas.includes('list_structures({ canvasId })') && anatomies.every((a) => gotchas.includes(a))); } +// ── 5c. Phase 31 slice D: desktop-app realisations ─────────────────────────── +// An agent on a desktop-app canvas must learn the realisations it can stamp, +// the components that replace data-table there, and the pane rule. +{ + const instructions = /const INSTRUCTIONS = `([\s\S]*?)`;/.exec(indexSrc)?.[1] ?? ''; + const gotchas = /const GOTCHAS = \[([\s\S]*?)\n\];/.exec(indexSrc)?.[1] ?? ''; + const app = listStructures({ type: 'desktop-app' }).filter((s) => s.surface === 'desktop-app'); + const anatomies = [...new Set(app.filter((s) => s.kind === 'page').map((s) => s.anatomy))]; + expect('there are desktop-app page anatomies to document', anatomies.length > 0); + const missingInstr = app.map((s) => s.name).filter((n) => !instructions.includes(n)); + expect('every desktop-app structure named in INSTRUCTIONS', instructions !== '' && missingInstr.length === 0, missingInstr.join(', ')); + const missingGl = [...anatomies, ...app.map((s) => s.name)].filter((a) => !guidelines.includes(`\`${a}\``)); + expect('every desktop-app anatomy and realisation named (backticked) in GUIDELINES', missingGl.length === 0, missingGl.join(', ')); + expect('GOTCHAS tell an app agent to start from a realisation', anatomies.every((a) => gotchas.includes(a)) && gotchas.includes('desktop-app realisation')); + expect('INSTRUCTIONS and GUIDELINES state the pane rule', /overflow "auto"/.test(instructions) && /overflow: "auto"/.test(guidelines)); +} + // ── 6. every cliche tell is surfaced where agents look ─────────────────────── // Tell slugs are kebab ('accent-hue') but the agent surfaces describe them in // prose, so each slug maps to a phrase that MUST appear in both the index.ts diff --git a/test-patterns-desktop-window.ts b/test-patterns-desktop-window.ts new file mode 100644 index 0000000..f39da5e --- /dev/null +++ b/test-patterns-desktop-window.ts @@ -0,0 +1,144 @@ +import './test-env.js'; +/** + * Phase 31 slice D (FR-D3, spec G3) — the desktop-app gate at the narrower + * windows the viewer offers, and the documented move of stamping a table into + * a realisation's pane. test-patterns-desktop.ts covers the 1440×900 window; + * this covers what verify round 1 found it missed: + * + * 1. a full stress run is CLEAN at 1024×768 (unthemed and under each + * personality) and at 1280×800 (unthemed), and detailed mode raises no + * desktop-app finding at 1280×800 — long labels must truncate, never push + * a bar past the window; + * 2. `data-table` stamped into each page realisation's wide pane (it + * resolves to data-table-app), at 1440, 1100 and 1024 wide wherever the + * pane is at least 480px wide (the documented minimum), leaves + * nothing blocking in fast mode, no desktop-app finding in detailed + * mode, and a CLEAN stress run. + * + * Fallback fonts, as in test-patterns-desktop.ts. Needs Chrome. + * Run with: npx tsx test-patterns-desktop-window.ts + */ +import { listStructures, applyStructure } from './src/structures.js'; +import { createCanvas } from './src/scene-graph.js'; +import { evaluateCanvas } from './src/evaluate.js'; +import { getVariables, resolveVariables, setVariables } from './src/variables.js'; +import { renderToHtml } from './src/renderer.js'; +import { expandInstances } from './src/drift.js'; +import { computeLayout, shutdown } from './src/screenshot.js'; +import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from './src/stress.js'; +import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from './src/design-language.js'; +import { getCanvasTokens } from './src/workspaces.js'; +import type { Canvas, SceneNode } from './src/types.js'; + +const CATEGORIES = ['spacing', 'color', 'typography', 'structure', 'consistency', 'cliche', 'usability']; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +function stamped(name: string, component: boolean, size: { width: number; height: number }, personality?: PersonalityName): Canvas { + const canvas = createCanvas(`win-${name}`, undefined, size, { type: 'desktop-app' }); + if (component) canvas.root.fill = '$bg-primary'; + if (personality) setVariables(canvas, generateDesignSystem('#166534', personality, { surface: 'desktop-app' }).variables); + const m = getCanvasTokens(canvas); + applyStructure(canvas, name, { + replace: true, + existingColors: new Set(Object.keys(m.colors ?? {})), + existingTokens: new Set([...Object.keys(m.spacing ?? {}), ...Object.keys(m.radius ?? {}), ...Object.keys(m.typography ?? {}), ...Object.keys(m.elevation ?? {}).map((k) => `elevation.${k}`)]), + }); + return canvas; +} + +async function stressWarnings(canvas: Canvas): Promise { + const w = canvas.root.width as number; + const h = canvas.root.height as number; + const merged = getVariables(canvas); + const layoutOf = (root: SceneNode) => computeLayout(renderToHtml(resolveVariables(structuredClone(root), merged), w, h, canvas), undefined, 25, { width: w, height: h }); + const base = expandInstances(canvas.root, canvas); + const baseline = await layoutOf(base); + const warnings: string[] = []; + for (const p of PERTURBATION_NAMES) { + const run = applyPerturbation(p, base, { type: 'desktop-app' }); + if (run.touched.length === 0) continue; + for (const f of compareLayouts(baseline, await layoutOf(run.root), run.touched, w)) { + if (f.severity === 'warning') warnings.push(`${p}:${f.kind}@${f.nodeId}`); + } + } + return warnings; +} + +/** Every rendered rect of the canvas, flattened. */ +async function layoutRects(canvas: Canvas): Promise<{ nodeId: string; width: number }[]> { + const w = canvas.root.width as number; + const h = canvas.root.height as number; + const rects = await computeLayout(renderToHtml(resolveVariables(structuredClone(expandInstances(canvas.root, canvas)), getVariables(canvas)), w, h, canvas), undefined, 25, { width: w, height: h }); + const out: { nodeId: string; width: number }[] = []; + const walk = (r: { nodeId: string; width: number; children?: unknown[] }) => { out.push(r); (r.children as typeof r[] | undefined)?.forEach(walk); }; + rects.forEach(walk); + return out; +} + +const appFindings = async (canvas: Canvas, mode: 'fast' | 'detailed'): Promise => + (await evaluateCanvas(canvas, { mode, categories: CATEGORIES })).issues.flatMap((i) => + (i.rule?.startsWith('desktop-app-') || i.severity !== 'info' || i.category === 'cliche' ? [`${i.severity}:${i.rule ?? i.tell ?? i.category}@${i.nodeId}`] : [])); + +const SMALL = { width: 1024, height: 768 }; +const MEDIUM = { width: 1280, height: 800 }; +const app = listStructures({ type: 'desktop-app' }).filter((s) => s.surface === 'desktop-app'); + +// ── 1. narrower windows ───────────────────────────────────────────────────── +for (const s of app) { + const component = s.kind === 'component'; + for (const personality of [undefined, ...PERSONALITY_NAMES]) { + const warnings = await stressWarnings(stamped(s.name, component, SMALL, personality)); + check(`${s.name}: full stress run CLEAN at 1024×768 (${personality ?? 'unthemed'})`, warnings.length === 0, warnings.slice(0, 4).join(' | ')); + } + const medium = stamped(s.name, component, MEDIUM); + const warnings = await stressWarnings(medium); + check(`${s.name}: full stress run CLEAN at 1280×800`, warnings.length === 0, warnings.slice(0, 4).join(' | ')); + const findings = await appFindings(medium, 'detailed'); + check(`${s.name}: detailed mode clean at 1280×800`, findings.length === 0, findings.slice(0, 4).join(' | ')); +} + +// ── 2. a table stamped into a realisation's wide pane ────────────────────── +const WIDE_PANE: Record = { + 'split-workbench-app': 'swa-work', + 'list-detail-app': 'lda-detail', + 'editor-inspector-app': 'eia-work', + 'browser-app': 'bra-grid-pane', + 'dashboard-app': 'dba-content', + 'settings-app': 'sta-content', +}; +check('every page realisation names its wide pane', app.filter((s) => s.kind === 'page').every((s) => WIDE_PANE[s.name] !== undefined)); +// data-table-app's five columns need a pane at least this wide: narrower, the +// column names wrap (on Linux fonts already in list-detail's 422px detail pane +// at 1024 wide) and the header outgrows its 32px rows. The docs state it. +const TABLE_MIN_PANE = 480; +const narrowPanes: string[] = []; +for (const [page, paneId] of Object.entries(WIDE_PANE)) for (const size of [{ width: 1440, height: 900 }, { width: 1100, height: 900 }, SMALL]) { + const at = `${size.width}×${size.height}`; + const canvas = stamped(page, false, size); + const paneWidth = (await layoutRects(canvas)).find((r) => r.nodeId === paneId)?.width ?? 0; + if (paneWidth < TABLE_MIN_PANE) { + narrowPanes.push(`${paneId}@${at}`); + continue; + } + const stamp = applyStructure(canvas, 'data-table', { targetId: paneId }); + check(`data-table into ${page}'s ${paneId} stamps data-table-app (${at})`, stamp.applied === 'data-table-app'); + const fast = await appFindings(canvas, 'fast'); + check(`${page} + data-table-app: nothing blocking in fast mode (${at})`, fast.length === 0, fast.slice(0, 4).join(' | ')); + const detailed = await appFindings(canvas, 'detailed'); + check(`${page} + data-table-app: detailed mode clean (${at})`, detailed.length === 0, detailed.slice(0, 4).join(' | ')); + const warnings = await stressWarnings(canvas); + check(`${page} + data-table-app: full stress run CLEAN (${at})`, warnings.length === 0, warnings.slice(0, 4).join(' | ')); +} + +// The only pane the docs' minimum rules out, so the skip can never grow silently. +check(`only list-detail's detail pane in a 1024px window is narrower than ${TABLE_MIN_PANE}px`, + JSON.stringify(narrowPanes) === JSON.stringify(['lda-detail@1024×768']), narrowPanes.join(', ')); + +console.log(allPass ? '\nAll desktop-app window tests passed.' : '\nSOME TESTS FAILED'); +await shutdown(); +process.exit(allPass ? 0 : 1); diff --git a/test-patterns-desktop.ts b/test-patterns-desktop.ts new file mode 100644 index 0000000..9ad9da2 --- /dev/null +++ b/test-patterns-desktop.ts @@ -0,0 +1,216 @@ +import './test-env.js'; +/** + * Phase 31 slice D (FR-D3, spec G3 + G4) — the pattern gate's layout half for + * the desktop-app realisations and components. test-patterns.ts holds them to + * > 95, zero tells and zero blocking findings in fast mode across themes and + * generated systems; this runs what fast mode cannot see: + * + * 1. detailed mode (a Chrome layout pass) raises no desktop-app finding at + * any severity and no warning or error in any gated category, unthemed + * and under each personality's generated system, as stamped and with + * every list tripled (the `many` perturbation); + * 2. a full five-perturbation stress run, built the way canvas_stress builds + * it (instances expanded, the desktop-app perturbation rules), is CLEAN + * unthemed and under each personality; `many` and `empty` each touch + * something, so the run is never vacuous; + * 3. after `many` the root keeps the artboard's height and no node is + * shorter than at baseline (rows scroll, they never squash); tripled + * twice, the content outgrows its pane, which then scrolls; + * 4. a stamp on a 1024×768 window raises no desktop-app finding in detailed + * mode and no node reaches past the artboard's right edge (stress at the + * narrower windows and tables stamped into panes live in + * test-patterns-desktop-window.ts). + * + * Components marked for every type get detailed mode (no desktop-app warning + * or error, spec change S7) and a CLEAN stress run on a bare desktop-app + * canvas. Renders use fallback fonts, as test-patterns-mobile.ts does: the + * personalities' faces would need the network to reach the font cache. + * Needs Chrome. Run with: npx tsx test-patterns-desktop.ts + */ +import { listStructures, applyStructure } from './src/structures.js'; +import { createCanvas } from './src/scene-graph.js'; +import { evaluateCanvas } from './src/evaluate.js'; +import { getVariables, resolveVariables, setVariables } from './src/variables.js'; +import { renderToHtml } from './src/renderer.js'; +import { expandInstances } from './src/drift.js'; +import { computeLayout, shutdown, type LayoutRect } from './src/screenshot.js'; +import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from './src/stress.js'; +import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from './src/design-language.js'; +import { getCanvasTokens } from './src/workspaces.js'; +import type { Canvas, SceneNode } from './src/types.js'; + +const CATEGORIES = ['spacing', 'color', 'typography', 'structure', 'consistency', 'cliche', 'usability']; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +/** Detailed-mode findings that block a realisation: any desktop-app finding, + * any tell, any warning or error. `infos` false keeps only desktop-app + * warnings and errors (the rule for the components marked `any`). */ +async function detailedFindings(canvas: Canvas, infos = true): Promise { + const ev = await evaluateCanvas(canvas, { mode: 'detailed', categories: CATEGORIES }); + return ev.issues.flatMap((i) => { + const app = i.rule?.startsWith('desktop-app-') && (infos || i.severity !== 'info'); + const blocking = infos ? i.severity !== 'info' || i.category === 'cliche' : i.rule?.startsWith('desktop-app-') && i.severity !== 'info'; + return app || blocking ? [`${i.severity}:${i.rule ?? i.tell ?? i.category}@${i.nodeId}`] : []; + }); +} + +/** A desktop-app canvas with the structure stamped as apply_structure stamps + * it, optionally after a generated system; a component goes under a root + * painted as a page stamp paints it. */ +function stamped(name: string, component: boolean, personality?: PersonalityName, size: { width?: number; height?: number } = {}): Canvas { + const canvas = createCanvas(`gate-${name}-${personality ?? 'plain'}`, undefined, size, { type: 'desktop-app' }); + if (component) canvas.root.fill = '$bg-primary'; + if (personality) setVariables(canvas, generateDesignSystem('#166534', personality, { surface: 'desktop-app' }).variables); + const m = getCanvasTokens(canvas); + applyStructure(canvas, name, { + replace: true, + existingColors: new Set(Object.keys(m.colors ?? {})), + existingTokens: new Set([...Object.keys(m.spacing ?? {}), ...Object.keys(m.radius ?? {}), ...Object.keys(m.typography ?? {}), ...Object.keys(m.elevation ?? {}).map((k) => `elevation.${k}`)]), + }); + return canvas; +} + +function layoutOf(canvas: Canvas, root: SceneNode): Promise { + const w = canvas.root.width as number; + const h = canvas.root.height as number; + return computeLayout(renderToHtml(resolveVariables(structuredClone(root), getVariables(canvas)), w, h, canvas), undefined, 25, { width: w, height: h }); +} + +const flatNodes = (n: SceneNode): SceneNode[] => [n, ...(n.children ?? []).flatMap(flatNodes)]; + +function flat(rects: LayoutRect[]): LayoutRect[] { + const out: LayoutRect[] = []; + const walk = (r: LayoutRect) => { out.push(r); r.children?.forEach(walk); }; + rects.forEach(walk); + return out; +} + +/** Warnings from a full stress run, as canvas_stress computes them, and the + * nodes `many` and `empty` touched. */ +async function stress(canvas: Canvas): Promise<{ warnings: string[]; touched: Record }> { + const base = expandInstances(canvas.root, canvas); + const baseline = await layoutOf(canvas, base); + const warnings: string[] = []; + const touched: Record = {}; + for (const p of PERTURBATION_NAMES) { + const run = applyPerturbation(p, base, { type: 'desktop-app' }); + touched[p] = run.touched.length; + if (run.touched.length === 0) continue; + for (const f of compareLayouts(baseline, await layoutOf(canvas, run.root), run.touched, canvas.root.width as number)) { + if (f.severity === 'warning') warnings.push(`${p}:${f.kind}@${f.nodeId}`); + } + } + return { warnings, touched }; +} + +const app = listStructures({ type: 'desktop-app' }).filter((s) => s.surface === 'desktop-app'); +check('six desktop-app realisations and two components', app.filter((s) => s.kind === 'page').length === 6 && app.filter((s) => s.kind === 'component').length === 2, app.map((s) => s.name).join(', ')); + +for (const s of app) { + const component = s.kind === 'component'; + + for (const personality of [undefined, ...PERSONALITY_NAMES]) { + const label = personality ?? 'unthemed'; + const findings = await detailedFindings(stamped(s.name, component, personality)); + check(`${s.name}: detailed mode clean (${label})`, findings.length === 0, findings.slice(0, 4).join(' | ')); + + const long = stamped(s.name, component, personality); + long.root = applyPerturbation('many', long.root, { type: 'desktop-app' }).root; + const longFindings = await detailedFindings(long); + check(`${s.name}: detailed mode clean with every list tripled (${label})`, longFindings.length === 0, longFindings.slice(0, 4).join(' | ')); + + const { warnings, touched } = await stress(stamped(s.name, component, personality)); + check(`${s.name}: full stress run CLEAN (${label})`, warnings.length === 0, warnings.slice(0, 4).join(' | ')); + if (!personality) check(`${s.name}: many and empty touch something`, touched.many > 0 && touched.empty > 0, JSON.stringify(touched)); + } + + // Tripled content scrolls inside its pane: the root keeps the artboard's + // height and no row squashes to make room. + const canvas = stamped(s.name, component); + const base = expandInstances(canvas.root, canvas); + const before = new Map(flat(await layoutOf(canvas, base)).map((r) => [r.nodeId, r])); + const after = flat(await layoutOf(canvas, applyPerturbation('many', base, { type: 'desktop-app' }).root)); + const root = after.find((r) => r.nodeId === canvas.root.id); + check(`${s.name}: the root keeps the window's height after many`, root?.height === canvas.root.height, `${root?.height}`); + const squashed = after.filter((r) => { const b = before.get(r.nodeId); return b !== undefined && r.height < b.height - 1; }); + check(`${s.name}: no node is shorter after many`, squashed.length === 0, squashed.slice(0, 4).map((r) => `${r.nodeId} ${before.get(r.nodeId)!.height}→${r.height}`).join(' | ')); + if (!component) { + // Tripled twice (×9), the content outgrows a 900px pane: it must scroll + // there, with the root and every row still at their own heights. + const twice = applyPerturbation('many', applyPerturbation('many', base, { type: 'desktop-app' }).root, { type: 'desktop-app' }).root; + const nine = flat(await layoutOf(canvas, twice)); + const scrolling = nine.filter((r) => r.scrolls && r.scrollHeight !== undefined && r.clientHeight !== undefined && r.scrollHeight > r.clientHeight + 1); + const grown = nine.find((r) => r.nodeId === canvas.root.id)?.height; + const crushed = nine.filter((r) => { const b = before.get(r.nodeId); return b !== undefined && r.height < b.height - 1; }); + check(`${s.name}: content tripled twice scrolls inside a pane, the window and rows keep their heights`, + scrolling.length > 0 && grown === canvas.root.height && crushed.length === 0, + `scrolling ${scrolling.map((r) => r.nodeId).join(',')} · root ${grown} · ${crushed.slice(0, 3).map((r) => r.nodeId).join(',')}`); + } + + // A narrower window: still clean, nothing past the right edge. + const narrow = stamped(s.name, component, undefined, { width: 1024, height: 768 }); + const narrowFindings = (await detailedFindings(narrow)).filter((f) => f.includes('desktop-app-')); + check(`${s.name}: detailed mode raises no desktop-app finding at 1024×768`, narrowFindings.length === 0, narrowFindings.slice(0, 4).join(' | ')); + const past = flat(await layoutOf(narrow, expandInstances(narrow.root, narrow))).filter((r) => r.x + r.width > 1024 + 1); + check(`${s.name}: nothing reaches past a 1024px window`, past.length === 0, past.slice(0, 4).map((r) => `${r.nodeId} ${r.x + r.width}`).join(' | ')); +} + +// Twins: the layout checks must fail on the defects they exist to catch. +{ + const rows = (n: number): SceneNode[] => Array.from({ length: n }, (_, i) => ({ id: `row-${i}`, type: 'list-row' as const, title: 'Item title' })); + const shellWith = (paneProps: Partial, rootOverflow: boolean): Canvas => { + const canvas = createCanvas('twin', undefined, {}, { type: 'desktop-app' }); + if (rootOverflow) canvas.root.overflow = 'hidden'; + canvas.root.children = [{ + id: 'shell', type: 'frame', width: '100%', height: '100%', layout: 'horizontal', children: [ + { id: 'pane', type: 'frame', layout: 'vertical', width: '100%', minHeight: 0, ...paneProps, children: [{ id: 'list', type: 'frame', layout: 'vertical', children: rows(12) }] }, + ], + }]; + return canvas; + }; + const manyWarnings = async (canvas: Canvas) => { + const base = expandInstances(canvas.root, canvas); + const run = applyPerturbation('many', base, { type: 'desktop-app' }); + return compareLayouts(await layoutOf(canvas, base), await layoutOf(canvas, run.root), run.touched, 1440).filter((f) => f.severity === 'warning'); + }; + check('a scrolling pane (overflow auto) is CLEAN under many', (await manyWarnings(shellWith({ overflow: 'auto' }, true))).length === 0); + check('twin: the same pane with overflow hidden clips under many', (await manyWarnings(shellWith({ overflow: 'hidden' }, true))).some((f) => f.kind === 'clip' && f.nodeId === 'pane')); + + const rootHeight = async (canvas: Canvas) => { + const run = applyPerturbation('many', expandInstances(canvas.root, canvas), { type: 'desktop-app' }); + return flat(await layoutOf(canvas, run.root)).find((r) => r.nodeId === canvas.root.id)?.height; + }; + check('with root overflow hidden the root keeps the window height', (await rootHeight(shellWith({ overflow: 'auto' }, true))) === 900); + check('twin: without it the root grows with the tripled list', ((await rootHeight(shellWith({ overflow: 'auto' }, false))) ?? 0) > 900); + + // The defect this check caught during the build: a table with `overflow` + // directly in a scrolling pane may shrink below its rows. + const squash = async (overflow: 'hidden' | undefined) => { + const canvas = stamped('dashboard-app', false); + const table = flatNodes(canvas.root).find((n) => n.id === 'dba-table')!; + if (overflow) table.overflow = overflow; + const base = expandInstances(canvas.root, canvas); + const before = new Map(flat(await layoutOf(canvas, base)).map((r) => [r.nodeId, r.height])); + const after = flat(await layoutOf(canvas, applyPerturbation('many', base, { type: 'desktop-app' }).root)); + return after.filter((r) => (before.get(r.nodeId) ?? 0) - r.height > 1).map((r) => r.nodeId); + }; + check('dashboard-app\'s table keeps its height under many', (await squash(undefined)).length === 0); + check('twin: with overflow hidden it squashes, and the check sees it', (await squash('hidden')).includes('dba-table')); +} + +for (const s of listStructures().filter((x) => x.kind === 'component' && x.surface === 'any')) { + const canvas = stamped(s.name, false); + const findings = await detailedFindings(canvas, false); + check(`${s.name} (any): detailed mode raises no desktop-app warning or error`, findings.length === 0, findings.slice(0, 4).join(' | ')); + const { warnings } = await stress(canvas); + check(`${s.name} (any): full stress run CLEAN on desktop-app`, warnings.length === 0, warnings.slice(0, 4).join(' | ')); +} + +console.log(allPass ? '\nAll desktop-app pattern-gate tests passed.' : '\nSOME TESTS FAILED'); +await shutdown(); +process.exit(allPass ? 0 : 1); diff --git a/test-patterns.ts b/test-patterns.ts index fa977a6..767338a 100644 --- a/test-patterns.ts +++ b/test-patterns.ts @@ -9,11 +9,11 @@ import './test-env.js'; import { createCanvas } from './src/scene-graph.js'; import { listStructures, applyStructure } from './src/structures.js'; import { getPreset } from './src/presets.js'; -import { evaluateCanvas } from './src/evaluate.js'; +import { evaluateCanvas, contrastRatio, parseColor } from './src/evaluate.js'; import { generateDesignSystem, PERSONALITY_NAMES } from './src/design-language.js'; -import { setVariables } from './src/variables.js'; -import { getCanvasTokens } from './src/workspaces.js'; -import type { Canvas } from './src/types.js'; +import { setVariables, applyPresetTokens, getVariables } from './src/variables.js'; +import { getCanvasTokens, createWorkspace, createProject, setWorkspaceDesignSystem } from './src/workspaces.js'; +import type { Canvas, SceneNode } from './src/types.js'; const BAR = 95; // every pattern must score STRICTLY above this (> 95) // Neutral default (applyStructure's seeded defaults) + every bundled preset. @@ -47,7 +47,8 @@ const mobileFindings = (issues: { rule?: string }[]): string[] => issues.flatMap((i) => (i.rule?.startsWith('mobile-') ? [i.rule] : [])); async function main() { - const pages = listStructures().filter((s) => s.kind === 'page'); + // Phase 31 slice D — the desktop-app realisations have their own gate below. + const pages = listStructures().filter((s) => s.kind === 'page' && s.surface !== 'desktop-app'); console.log(`\nPattern quality gate — ${pages.length} page structures × ${THEMES.length} themes (bar: > ${BAR}, zero tells)\n`); for (const s of pages) { @@ -111,7 +112,157 @@ async function main() { assert(rules.length === 0, `${s.name} on mobile${rules.length ? ' — ' + rules.join(', ') : ''}`); } + await desktopGate(); + console.log(`\n${passed} passed, ${failed} failed`); process.exit(failed > 0 ? 1 : 0); } main(); + +// ── Phase 31 slice D (FR-D3, G2 + G4) — the desktop-app gate ──────────────── +// Every desktop-app realisation, and data-table-app / skeleton-table-app, +// stamped on a desktop-app canvas under the inputs the docs promise agents: +// the five themes (presets merged after the stamp, as apply_preset merges), +// each personality × three seeds generated before the stamp, and a web-pivot +// system inherited from the workspace. Pass = score > 95, zero tells, zero +// desktop-app findings at any severity, zero warnings or errors in any gated +// category, and an active nav-item's label legible on $accent-tint. + +const SEEDS = ['#166534', '#2563EB', '#B45309']; + +/** What each stamp asks of coverage (pinned, and stated in GUIDELINES). */ +const COVERAGE_MISSING: Record = { + 'split-workbench-app': [], + 'list-detail-app': [], + 'editor-inspector-app': ['error'], + 'browser-app': [], + 'dashboard-app': ['empty', 'loading'], + 'settings-app': ['error'], + 'data-table-app': ['empty', 'loading'], + 'skeleton-table-app': ['empty', 'loading'], +}; + +const blocking = (issues: { severity: string; rule?: string; category: string; tell?: string }[]): string[] => + issues.flatMap((i) => (i.severity !== 'info' || i.rule?.startsWith('desktop-app-') || i.category === 'cliche' + ? [`${i.severity}:${i.rule ?? i.tell ?? i.category}`] : [])); + +/** `$text-primary` on `$accent-tint`, light and dark, where the canvas has a tint. */ +function tintContrast(canvas: Canvas): number[] { + const merged = getVariables(canvas); + const ratios: number[] = []; + for (const colors of [merged.colors, merged.dark?.colors ? { ...merged.colors, ...merged.dark.colors } : undefined]) { + const tint = colors?.['accent-tint']; + const ink = colors?.['text-primary']; + const fg = typeof ink === 'string' ? parseColor(ink) : null; + const bg = typeof tint === 'string' ? parseColor(tint) : null; + if (fg && bg) ratios.push(contrastRatio(fg, bg)); + } + return ratios; +} + +/** A desktop-app canvas; a component goes under a root painted as a page is. */ +function appCanvas(name: string, component: boolean): Canvas { + const canvas = createCanvas(name, undefined, {}, { type: 'desktop-app' }); + if (component) canvas.root.fill = '$bg-primary'; + return canvas; +} + +/** G2's pass rule on one canvas. */ +async function verdict(canvas: Canvas, genre?: string): Promise<{ ok: boolean; detail: string }> { + const ev = await evaluateCanvas(canvas, { mode: 'fast', genre, categories: CATEGORIES }); + const bad = blocking(ev.issues); + const weak = tintContrast(canvas).filter((r) => r < 4.5); + const ok = ev.overallScore > BAR && bad.length === 0 && weak.length === 0; + return { ok, detail: `${ev.overallScore}${bad.length ? ' · ' + bad.join(', ') : ''}${weak.length ? ' · tint ' + weak.map((r) => r.toFixed(2)).join('/') : ''}` }; +} + +async function judge(canvas: Canvas, label: string, structure: string, genre?: string) { + const { ok, detail } = await verdict(canvas, genre); + assert(ok, `${structure} @ ${label} — ${detail}`); +} + +async function desktopGate() { + const app = listStructures({ type: 'desktop-app' }).filter((s) => s.surface === 'desktop-app'); + const names = app.map((s) => s.name).sort(); + assert(JSON.stringify(names) === JSON.stringify(Object.keys(COVERAGE_MISSING).sort()), `the desktop-app set is the six realisations and two components (${names.join(', ')})`); + console.log(`\nDesktop-app gate — ${app.length} structures × (${THEMES.length} themes + ${PERSONALITY_NAMES.length}×${SEEDS.length} generated + 1 inherited)\n`); + + for (const s of app) { + const component = s.kind === 'component'; + for (const theme of THEMES) { + const canvas = appCanvas(`gate-${s.name}-${theme}`, component); + applyStructure(canvas, s.name, { replace: true }); + if (theme !== 'default') applyPresetTokens(canvas, getPreset(theme)!.variables, getVariables(canvas)); + await judge(canvas, theme, s.name, theme === 'default' ? undefined : theme); + } + for (const personality of PERSONALITY_NAMES) { + for (const seed of SEEDS) { + const canvas = appCanvas(`gate-${s.name}-${personality}`, component); + setVariables(canvas, generateDesignSystem(seed, personality, { surface: 'desktop-app' }).variables); + applyStructure(canvas, s.name, { replace: true, ...existing(canvas) }); + await judge(canvas, `${personality} ${seed}`, s.name); + } + } + + // A design system generated at workspace scope (the web pivot) and + // inherited by the desktop-app canvas. + const ws = createWorkspace(`gate-ws-${s.name}`); + setWorkspaceDesignSystem(ws.id, generateDesignSystem('#2563EB', 'technical').variables); + const project = createProject(ws.id, `gate-p-${s.name}`)!; + const inherited = createCanvas(`gate-${s.name}-inherited`, project.id, {}, { type: 'desktop-app' }); + if (component) inherited.root.fill = '$bg-primary'; + applyStructure(inherited, s.name, { replace: true, ...existing(inherited) }); + await judge(inherited, 'inherited workspace system', s.name); + + // Coverage is outside the score bar, but what a stamp asks for is pinned. + const covCanvas = appCanvas(`gate-${s.name}-cov`, component); + applyStructure(covCanvas, s.name, { replace: true }); + const missing = (await evaluateCanvas(covCanvas, { mode: 'fast', categories: ['coverage'] })).coverage?.missing ?? []; + assert(JSON.stringify([...missing].sort()) === JSON.stringify([...COVERAGE_MISSING[s.name]].sort()), `${s.name} asks coverage for [${missing.join(', ')}]`); + } + + // Twins: the gate's own predicates must fail on a stamp broken the way a + // realisation could break. + const twoActive = appCanvas('twin-active', false); + applyStructure(twoActive, 'split-workbench-app'); + const navItems = twoActive.root.children![0].children![0].children![1].children!; + navItems[1].active = true; + const twoActiveEv = await evaluateCanvas(twoActive, { mode: 'fast', categories: CATEGORIES }); + assert(blocking(twoActiveEv.issues).some((b) => b.includes('desktop-app-current')), 'twin: a second active nav-item fails the gate'); + const unnamed = appCanvas('twin-unnamed', false); + applyStructure(unnamed, 'split-workbench-app'); + const walk = (n: SceneNode): SceneNode[] => [n, ...(n.children ?? []).flatMap(walk)]; + delete walk(unnamed.root).find((n) => n.id === 'swa-toggle')!.ariaLabel; + assert(blocking((await evaluateCanvas(unnamed, { mode: 'fast', categories: CATEGORIES })).issues).some((b) => b.includes('desktop-app-icon-label')), 'twin: an icon-only button without ariaLabel fails the gate'); + const darkTint = appCanvas('twin-tint', false); + applyStructure(darkTint, 'split-workbench-app'); + darkTint.variables.colors = { ...darkTint.variables.colors, 'accent-tint': '#152A47' }; + applyPresetTokens(darkTint, getPreset('light')!.variables, getVariables(darkTint)); + assert(tintContrast(darkTint).some((r) => r < 4.5) && !(await verdict(darkTint, 'light')).ok, 'twin: a dark $accent-tint left under the light preset fails the gate'); + // An info-level desktop-app finding (a hand-built 28px icon frame) fails it too. + const handBuilt = appCanvas('twin-handbuilt', false); + applyStructure(handBuilt, 'split-workbench-app'); + walk(handBuilt.root).find((n) => n.id === 'swa-header-actions')!.children!.push({ + id: 'hb', type: 'frame', name: 'Hand-built', width: 28, height: 28, layout: 'vertical', alignItems: 'center', justifyContent: 'center', + children: [{ id: 'hb-icon', type: 'icon', icon: 'bell', iconSize: 16, iconColor: '$text-secondary' }], + }); + const hb = await verdict(handBuilt); + assert(!hb.ok && hb.detail.includes('info:desktop-app-handbuilt-target'), `twin: an info-level desktop-app finding fails the gate — ${hb.detail}`); + // So does a cliché tell, whatever its severity. + const slop = appCanvas('twin-slop', false); + applyStructure(slop, 'split-workbench-app'); + walk(slop.root).find((n) => n.id === 'swa-canvas-label')!.content = 'Unlock seamless synergy and supercharge your workflow'; + const sl = await verdict(slop); + assert(!sl.ok && /cliche|slop/.test(sl.detail), `twin: a cliché tell fails the gate — ${sl.detail}`); + + // Components marked for every type stamp on a bare desktop-app canvas with + // no desktop-app warning or error (spec change S7: their infos, such as a + // delta pill read as a small button, are advisories; their score is the + // web gate's). + for (const s of listStructures().filter((x) => x.kind === 'component' && x.surface === 'any')) { + const canvas = appCanvas(`gate-${s.name}-app`, false); + applyStructure(canvas, s.name); + const rules = (await evaluateCanvas(canvas, { mode: 'fast' })).issues.flatMap((i) => (i.rule?.startsWith('desktop-app-') && i.severity !== 'info' ? [i.rule] : [])); + assert(rules.length === 0, `${s.name} on desktop-app${rules.length ? ' — ' + rules.join(', ') : ''}`); + } +} diff --git a/test-scaffold-system.ts b/test-scaffold-system.ts index f20476c..ab6a17e 100644 --- a/test-scaffold-system.ts +++ b/test-scaffold-system.ts @@ -70,10 +70,12 @@ function usedSizes(canvas: Canvas): Map { const structures = listStructures(); /** A structure stamps on a canvas of its own surface (Phase 30 slice E): - * mobile realisations on a phone canvas, everything else on web as before. */ -const typeOf = (surface: string): 'web' | 'mobile' => (surface === 'mobile' ? 'mobile' : 'web'); + * mobile realisations on a phone canvas, desktop-app ones on a window + * (Phase 31 slice D), everything else on web as before. */ +const typeOf = (surface: string): 'web' | 'mobile' | 'desktop-app' => + (surface === 'mobile' || surface === 'desktop-app' ? surface : 'web'); const canvasFor = (name: string, surface: string) => - createCanvas(name, undefined, {}, surface === 'mobile' ? { type: 'mobile' } : undefined); + createCanvas(name, undefined, {}, typeOf(surface) === 'web' ? undefined : { type: typeOf(surface) as 'mobile' | 'desktop-app' }); check('structure library is non-empty', structures.length > 0, `${structures.length} structures`); // ── 1. on the generated scale ──────────────────────────────────────────────── diff --git a/test-structures-mcp.ts b/test-structures-mcp.ts index 081a507..fd8fa1e 100644 --- a/test-structures-mcp.ts +++ b/test-structures-mcp.ts @@ -47,7 +47,7 @@ try { const plain = (await tool('list_structures', {})).data; check('no canvasId or type lists web', names(plain).includes('dashboard') && !names(plain).includes('dashboard-mobile')); check('entries carry anatomy, surface and surfaces', plain.find((s: any) => s.name === 'dashboard')?.anatomy === 'dashboard' - && JSON.stringify(plain.find((s: any) => s.name === 'dashboard')?.surfaces) === '["web","mobile"]'); + && JSON.stringify(plain.find((s: any) => s.name === 'dashboard')?.surfaces) === '["web","mobile","desktop-app"]'); const byCanvas = (await tool('list_structures', { canvasId: phone })).data; check('canvasId of a mobile canvas lists the mobile realisations', names(byCanvas).includes('feed-mobile') && !names(byCanvas).includes('pricing')); check('canvasId of a web canvas lists web', names((await tool('list_structures', { canvasId: web })).data).includes('pricing')); @@ -66,6 +66,17 @@ try { const forced = (await tool('apply_structure', { canvasId: phone, structure: 'dashboard', replace: true, realisation: 'web' })).data; check('realisation "web" stamps the web dashboard on a mobile canvas', forced.applied === 'dashboard' && forced.surface === 'web', forced.applied); + // Phase 31 slice D — a desktop-app canvas lists and stamps its realisations. + const win = (await tool('canvas_create', { name: 'window', type: 'desktop-app' })).data.canvasId; + const appList = names((await tool('list_structures', { canvasId: win })).data); + check('canvasId of a desktop-app canvas lists the desktop-app realisations', ['browser-app', 'data-table-app', 'empty-state'].every((n) => appList.includes(n)) && !appList.includes('dashboard') && !appList.includes('pricing'), appList.join(', ')); + const app = (await tool('apply_structure', { canvasId: win, structure: 'dashboard' })).data; + check('dashboard on a desktop-app canvas stamps dashboard-app', app.applied === 'dashboard-app' && app.surface === 'desktop-app', app.applied); + const appRoot = (await tool('read_nodes', { canvasId: win, maxDepth: 0 })).text; + check('the stamp keeps the root at the window height (overflow hidden)', /"overflow":\s*"hidden"/.test(appRoot), appRoot.slice(0, 200)); + const appRefused = await tool('apply_structure', { canvasId: win, structure: 'pricing', replace: true }); + check('pricing on a desktop-app canvas refuses, listing the desktop-app anatomies', appRefused.isError && /no desktop-app realisation.*split-workbench, list-detail, editor-inspector, browser, dashboard, settings/.test(appRefused.text), appRefused.text); + // A canvas re-declared mobile resolves the same way. await tool('canvas_set_type', { canvasId: web, type: 'mobile' }); check('canvas_set_type to mobile changes what settings resolves to', (await tool('apply_structure', { canvasId: web, structure: 'settings' })).data.applied === 'settings-mobile'); diff --git a/test-structures.ts b/test-structures.ts index ae5d1e1..8a4705a 100644 --- a/test-structures.ts +++ b/test-structures.ts @@ -110,7 +110,7 @@ for (const anatomy of ['dashboard', 'settings', 'auth', 'onboarding', 'feed', 'd const last = nodes[nodes.length - 1]?.type; check(nodes[0]?.type === 'status-bar' && (last === 'home-indicator' || last === 'tab-bar'), `${anatomy}-mobile starts with status-bar, ends with home-indicator or tab-bar (${last})`); } -check(JSON.stringify(byName.get('dashboard')?.surfaces) === '["web","mobile"]', 'dashboard is realised on web and mobile'); +check(JSON.stringify(byName.get('dashboard')?.surfaces) === '["web","mobile","desktop-app"]', 'dashboard is realised on web, mobile and desktop-app'); check(JSON.stringify(byName.get('feed-mobile')?.surfaces) === '["mobile"]', 'feed is realised on mobile only'); check(JSON.stringify(byName.get('empty-state')?.surfaces) === '["web","mobile","desktop-app"]' && byName.get('empty-state')?.surface === 'any', 'an any component counts for every type'); @@ -128,10 +128,11 @@ check(nodeOf('empty-state', 'es-cta')?.type === 'button', 'empty-state\'s action console.log('listStructures({ type }) filters by the surface that covers the type'); const mobileList = listStructures({ type: 'mobile' }).map((s) => s.name); const webList = listStructures({ type: 'web' }).map((s) => s.name); +const appList = listStructures({ type: 'desktop-app' }).map((s) => s.name); check(mobileList.includes('dashboard-mobile') && !mobileList.includes('dashboard') && !mobileList.includes('data-table'), 'mobile listing: realisations, no web-only structures'); check(mobileList.includes('empty-state') && webList.includes('empty-state'), 'an any component is listed for both'); check(webList.includes('dashboard') && !webList.includes('dashboard-mobile'), 'web listing: no mobile realisations'); -check(all.length === new Set([...mobileList, ...webList]).size, 'every structure is listed for some type'); +check(all.length === new Set([...mobileList, ...webList, ...appList]).size, 'every structure is listed for some type'); console.log('resolveStructure — every branch'); check(resolveStructure('dashboard', 'mobile').name === 'dashboard-mobile', 'anatomy name → the mobile realisation on mobile'); @@ -144,6 +145,63 @@ check(throws(() => resolveStructure('dashboard-mobile', 'web'), /mobile realisat check(resolveStructure('dashboard-mobile', 'mobile').name === 'dashboard-mobile', 'a realisation name on its own type is used as is'); check(throws(() => resolveStructure('nope', 'web'), /not found/), 'unknown name → not found'); +console.log('Phase 31 slice D — desktop-app realisations, N-type resolution (FR-D1, G1, G6)'); +const APP_PAGES = ['split-workbench-app', 'list-detail-app', 'editor-inspector-app', 'browser-app', 'dashboard-app', 'settings-app']; +const APP_ANATOMY: Record = { + 'split-workbench-app': 'split-workbench', 'list-detail-app': 'list-detail', 'editor-inspector-app': 'editor-inspector', + 'browser-app': 'browser', 'dashboard-app': 'dashboard', 'settings-app': 'settings', +}; +for (const name of APP_PAGES) { + const s = getStructure(name)!; + check(s?.surface === 'desktop-app' && s.anatomy === APP_ANATOMY[name] && s.kind === undefined && s.axes !== undefined, `${name} realises ${APP_ANATOMY[name]} on desktop-app as a page with axes`); + check(s?.root?.overflow === 'hidden', `${name} keeps the root at the window height (root overflow hidden)`); + check(resolveStructure(APP_ANATOMY[name], 'desktop-app').name === name, `${APP_ANATOMY[name]} on desktop-app resolves to ${name}`); +} +check(getStructure('data-table-app')?.kind === 'component' && getStructure('data-table-app')?.anatomy === 'data-table' && resolveStructure('data-table', 'desktop-app').name === 'data-table-app', 'data-table on desktop-app resolves to data-table-app'); +check(getStructure('skeleton-table-app')?.anatomy === 'skeleton-table' && resolveStructure('skeleton-table', 'desktop-app').name === 'skeleton-table-app', 'skeleton-table on desktop-app resolves to skeleton-table-app'); +check(resolveStructure('data-table', 'web').name === 'data-table' && resolveStructure('dashboard', 'web').name === 'dashboard', 'web keeps its own realisations'); +check(throws(() => resolveStructure('pricing', 'desktop-app'), /^"pricing" has no desktop-app realisation\. Page anatomies with a desktop-app realisation: split-workbench, list-detail, editor-inspector, browser, dashboard, settings\. Pass realisation: "web"/), 'pricing on desktop-app refuses, naming the desktop-app anatomies and realisation: "web"'); +check(throws(() => resolveStructure('feed', 'desktop-app'), /"feed" has no desktop-app realisation\..*Pass realisation: "mobile" to stamp/), 'feed on desktop-app refuses and names realisation: "mobile"'); +for (const anatomy of ['list-detail', 'editor-inspector', 'browser']) { + for (const type of ['web', 'mobile'] as const) { + check(throws(() => resolveStructure(anatomy, type), new RegExp(`"${anatomy}" has no ${type} realisation\\..*Pass realisation: "desktop-app" to stamp`)), `${anatomy} on ${type} refuses and names realisation: "desktop-app"`); + } +} +check(throws(() => resolveStructure('dashboard-app', 'web'), /desktop-app realisation of "dashboard", not a web one/), 'a desktop-app realisation name on web refuses with its force hint'); +check(throws(() => resolveStructure('toolbar', 'desktop-app'), /Component anatomies with a desktop-app realisation: .*data-table/), 'a web-only component on desktop-app refuses, listing data-table among the component anatomies'); +check(APP_PAGES.every((n) => appList.includes(n)) && appList.includes('data-table-app') && appList.includes('skeleton-table-app') && appList.includes('empty-state'), 'the desktop-app listing holds the six realisations, both components and the any components'); +check(!appList.includes('dashboard') && !appList.includes('dashboard-mobile') && !webList.includes('dashboard-app') && !mobileList.includes('dashboard-app'), 'no type lists another type\'s realisation'); +check(JSON.stringify(byName.get('browser-app')?.surfaces) === '["desktop-app"]', 'browser is realised on desktop-app only'); + +const walkAll = (n: SceneNode): SceneNode[] => [n, ...(n.children ?? []).flatMap(walkAll)]; +for (const name of [...APP_PAGES, 'data-table-app', 'skeleton-table-app']) { + const nodes = getStructure(name)!.nodes.flatMap(walkAll); + const panes = nodes.filter((n) => n.overflow === 'auto'); + const unfloored = panes.filter((p) => typeof p.width === 'number' && !(typeof p.minWidth === 'number' && p.minWidth >= p.width)); + check(unfloored.length === 0, `${name}: every fixed-width pane has a matching minWidth${unfloored.length ? ' — ' + unfloored.map((p) => p.id).join(', ') : ''}`); + const icons = nodes.filter((n) => n.type === 'button' && !n.label && n.icon); + check(icons.every((b) => b.ariaLabel && b.color === '$text-secondary'), `${name}: icon-only buttons are named and in $text-secondary`); + const rows = nodes.filter((n) => n.name === 'Row' || n.name === 'Skeleton row' || n.name === 'Toolbar' || n.name === 'Pagination'); + check(rows.every((r) => r.height === 32), `${name}: table toolbar, rows and pager are 32 tall`); +} +check(walkAll(getStructure('editor-inspector-app')!.nodes[0]).find((n) => n.id === 'eia-inspector')?.minWidth === 280, 'the editor inspector keeps a 280px floor beside its 30% width'); +check(walkAll(getStructure('browser-app')!.nodes[0]).find((n) => n.id === 'bra-grid')?.gridColumns === 'repeat(auto-fill, minmax(240px, 1fr))', 'the browser grid\'s columns are at least 240px wide'); + +console.log('Phase 31 slice D — root props on a page stamp (G5)'); +const win = createCanvas('e-win', undefined, {}, { type: 'desktop-app' }); +const stampApp = applyStructure(win, 'dashboard'); +check(stampApp.applied === 'dashboard-app' && win.root.overflow === 'hidden', 'dashboard on a desktop-app canvas stamps dashboard-app and sets root overflow hidden'); +applyStructure(win, 'dashboard', { replace: true, realisation: 'web' }); +check(win.root.overflow === undefined, 'stamping a web page over it with replace removes the root overflow the app stamp set'); +const kept = createCanvas('e-kept', undefined, {}, { type: 'desktop-app' }); +applyStructure(kept, 'settings'); +kept.root.overflow = 'auto'; +applyStructure(kept, 'settings', { replace: true, realisation: 'web' }); +check(kept.root.overflow === 'auto', 'a root overflow the author changed survives the next page stamp'); +const comp = createCanvas('e-comp', undefined, {}, { type: 'desktop-app' }); +applyStructure(comp, 'data-table'); +check(comp.root.overflow === undefined, 'a component stamp writes no root props'); + console.log('applyStructure resolves by the canvas type and realisation forces'); const phone = createCanvas('e-phone', undefined, {}, { type: 'mobile' }); const r1 = applyStructure(phone, 'dashboard');