From d66727aad2ab030d7b8c3dc9a0b96ff75e08416d Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sun, 15 Nov 2026 19:39:52 +0100 Subject: [PATCH 1/4] Pin the slice E overlay contracts in the Phase 31 spec --- docs/specs/PHASE-31-SPEC.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 07008ab..dfabd7e 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -284,6 +284,16 @@ One profile ships, keyed by id so a second size is one table row later. Values i - `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. - `canvas_add_variant` docstring and GUIDELINES: the overlay states. +**Slice E — contracts pinned before build (2026-11-15; frozen at the commit that adds this block).** No pre-freeze verifier: slice E adds no pass/fail rule that depends on earlier runs or state and no gate over generated output (FR-C9's overlay clause reads the canvas alone). +- **K1: the layer.** `renderToHtml` collects every overlay node (`tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer`, after instance expansion) instead of rendering it in place, and emits them after the root, in tree order, inside one `
`: `position: absolute; left: 0; top: 0; width: 100%; max-width: ; height: ; pointer-events: none`, with `body { position: relative }` emitted only when the layer exists, so a canvas without overlays renders byte-identical HTML. The layer box is the artboard at the root's origin: authored `x`/`y` are offsets from the root's top-left (root coordinates), and the viewport-anchored defaults (a centred modal, a full scrim, a bottom-centre toast, a right-pinned drawer) resolve against that box, on every type (render never depends on type). An overlay nested in another overlay is lifted too and becomes its own member of the layer. The layer has no z-index; each member carries its kind's (`OVERLAY_Z` in `src/primitives.ts`: popover and menu 400, scrim 500, modal and drawer 510, toast 600, tooltip 800), so all of them stack above content (`fixed` 10, `sticky` 5, a sheet 30). An overlay's own `position`, `right` and `bottom` are ignored; `effectivePosition` reports `absolute` for it, so rules treat it as out of flow (the detailed overlap check skips it). Overlays get `pointer-events: auto`. +- **K2: the walker places overlays.** `computeLayout` from the document root (no `rootNodeId`, or the root's id) appends the layer's overlay rects to the root's `children`, so every detailed rule, stress and `snapshot_layout` see them, at root level whatever their authored parent. A `rootNodeId` inside an overlay walks that overlay. A modal or drawer with a scrim records `scrim: { x, y, width, height }` on its rect (a new `LayoutRect` field). +- **K3: the primitives' props.** `tooltip`: `text` (max width 240, wraps; children are not rendered, slice F warns on them). `popover`: a container (children render with the usual `layout`/`gap`/`padding`, default vertical, padding 12); width = a numeric `width`, else `size` xs 192 / sm 320 / md 480 / lg 640, default sm. `menu`: a container of `menu-row`s and `divider`s, vertical, padding 4, `min-width` 192, width = a numeric `width`, else its content. `modal`: `title`, `size` sm 480 / md 640 / lg 960 (default md; a numeric `width` wins), `actions: [{ label, variant? }]`, `closeLabel` (default "Close"), body children (vertical, gap default 12); centred in the layer unless `x` or `y` is set (then its top-left is there), `max-height` the layer less 64 with the body scrolling; always renders its scrim. Actions render as `sm` buttons, right-aligned, non-filled ones (`secondary`, `ghost`, and an action with no variant, which renders `secondary`) first in authored order, then the filled ones (`primary`, `destructive`) in authored order, so the filled action is rightmost. The header close button is an icon-only ghost `sm` button (32×32, `x` glyph) named by `closeLabel`. `toast`: `text`, `tone` neutral (default) / success / warning / danger (a leading tone glyph in the tone's colour on a surface panel; the text keeps `$text-primary`), `action?: { label }` (a ghost `xs` button); bottom-centre 24px above the layer's bottom edge unless `x` or `y` is set; `role="status"`, or `role="alert"` for danger. `drawer`: a container pinned to the layer's right edge, full height, width = a numeric `width`, else `size` sm 320 (default) / md 480, `scrim?: boolean` (default false), padding 16, vertical. `anchor?: string` (a node id) on every overlay, never rendered. New `SceneNode` props: `text`, `anchor`, `closeLabel`, `actions`, `tone`, `action`, `scrim`; the `size` union is unchanged (drawer and popover reuse it). +- **K4: defaults.** `applyControlDefaults` gives every overlay `fill` (`$bg-surface`), `stroke` (`$border`), `color` (`$text-primary`), `secondaryColor` (`$text-secondary`), a radius (`radius-md` 8 for popover, menu, toast; `radius-lg` 12 for modal; 4 for tooltip; drawer 0) and `shadows` from `$elevation.overlay` when the canvas has it (else a fixed fallback shadow), explicit props winning. A tooltip inverts: `fill` `$text-primary`, `color` `$bg-surface`. Each modal action gets `fill` / `color` / `stroke` by variant as a `button` would, and a toast's action `color` the accent; a toast's `iconColor` follows its tone (`$success`, `$warning`, `$danger`, neutral `$text-secondary`). `$token` refs in `actions[].fill/color/stroke` and `action.color` resolve. The renderer falls back to the neutral palette for an unthemed overlay (inside a component), so nothing renders invisible. +- **K5: deferred clauses this slice owns.** (a) FR-C9: an undeclared canvas holding an overlay primitive warns like one holding a desktop-app primitive; an explicit `web` or `mobile` canvas holding only overlays raises nothing. (b) Terms "Pane": `modal` and `drawer` are panes for `desktop-app-current` and `desktop-app-primary-count`. (c) FR-C8: a modal's `actions` with `variant: "primary"` count as primaries in the modal's region (a `destructive` action is not a primary, as for `button`). (d) Terms "Clickable primitive": the census measures a modal's close button (32×32) and actions (32 tall) and a toast's action (24 tall), under the overlay's node id; none is ever below 24 by construction. `modal` and `toast` do not join `CLICKABLE_PRIMITIVES` (a frame in a modal body is still judged by FR-C2). +- **K6: FR-E3 is docs plus a pin.** `canvas_add_variant` already accepts any state name and the coverage report's `states` already lists every designed variant; the docstring, `INSTRUCTIONS`, GOTCHAS and GUIDELINES recommend `menu-open`, `comment-open`, `confirm-delete` and `toast` by name, and a test pins that a `confirm-delete` variant is listed and coverage raises nothing for missing overlay states. No new report field. +- **K7: stress.** `PRIMITIVE_TEXT_PROPS` gains `tooltip.text`, `toast.text`, `toast.action.label`, `modal.title` and `modal.actions[].label`. The modal title truncates with a `title` attribute; tooltip and toast text wrap. +- **K8: the inputs the layer must survive** (hard rule 6, the verifier's list): each of the six kinds; authored as a root child, inside a `sticky` bar, inside a `fixed` bar, inside an `overflow: "auto"` and an `overflow: "hidden"` pane, inside an animated / blurred ancestor, inside a component instance, and inside another overlay; with and without authored `x`/`y`; light and dark themes; themed, unthemed, and unthemed inside a component; `web`, `mobile` and `desktop-app` canvases; a root narrower than the capture width; a root with `overflow` hidden, auto and unset; artboard and full-page captures; `computeLayout` with and without a `rootNodeId`. Evaluate consumers: the detailed overlap check, the 24px census, panes, primary count, FR-C9 by type and declaration source, stress's text props. + **Slice F: overlay rules (FR-F1)** - `src/evaluate.ts`: `desktop-app-overlay`; fast bounds from authored rects, detailed bounds from rendered rects. From caa66c97bd24981af8ad0841139920c57f48e5a6 Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sun, 15 Nov 2026 19:57:56 +0100 Subject: [PATCH 2/4] Render overlays in one layer above the content (Phase 31 slice E) --- README.md | 27 +++- VISION.md | 2 +- docs/GUIDELINES.md | 29 +++- docs/specs/PHASE-31-SPEC.md | 7 + src/desktop-app-rules.ts | 45 +++--- src/evaluate.ts | 8 +- src/index.ts | 22 ++- src/primitives.ts | 59 +++++++- src/renderer.ts | 175 ++++++++++++++++++++++- src/screenshot.ts | 20 ++- src/stress.ts | 6 + src/types.ts | 37 ++++- src/variables.ts | 63 +++++++++ test-overlays-render.ts | 200 ++++++++++++++++++++++++++ test-overlays.ts | 272 ++++++++++++++++++++++++++++++++++++ 15 files changed, 930 insertions(+), 42 deletions(-) create mode 100644 test-overlays-render.ts create mode 100644 test-overlays.ts diff --git a/README.md b/README.md index 48d1a84..ef90fac 100644 --- a/README.md +++ b/README.md @@ -310,7 +310,7 @@ R("nodeId", { type: "text", content: "Replaced" }) **Returns** `{ ok, nodeIds, results }`. `nodeIds` maps each bound variable to the node ID it created — e.g. `{ "header": "n_a1b2" }` — so you can target those nodes in later calls (bindings only live within a single call). `results` lists each op's outcome in order; an op that succeeded but will not fully take effect carries a `warning` (a `shadow` beside an active `shadows`, a chart `highlight` entry outside the series data). If the call wrote a `fontFamily` nothing can serve yet (not cached, registered, or system/generic), a `Font warnings` content item names it — a cache-only check with no network call, so it's a heads-up, not exhaustive. -**Node types:** `frame`, `text`, `rectangle`, `ellipse`, `image`, `icon`, `path`, `component`, `instance`, `toggle`, `checkbox`, `radio`, `select`, `chart`, `skeleton` (loading-placeholder block — token-derived neutral fill; pulses subtly in the live viewer, always static in screenshots/exports so diffs stay deterministic; `pulse: false` opts a block out), the mobile primitives `status-bar`, `home-indicator`, `nav-bar`, `tab-bar`, `button`, `list-row`, `sheet` (see [Mobile primitives](#mobile-primitives)), and the desktop-app primitives `link`, `text-input`, `nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`, `divider` (see [Desktop-app primitives](#desktop-app-primitives)) +**Node types:** `frame`, `text`, `rectangle`, `ellipse`, `image`, `icon`, `path`, `component`, `instance`, `toggle`, `checkbox`, `radio`, `select`, `chart`, `skeleton` (loading-placeholder block — token-derived neutral fill; pulses subtly in the live viewer, always static in screenshots/exports so diffs stay deterministic; `pulse: false` opts a block out), the mobile primitives `status-bar`, `home-indicator`, `nav-bar`, `tab-bar`, `button`, `list-row`, `sheet` (see [Mobile primitives](#mobile-primitives)), and the desktop-app primitives `link`, `text-input`, `nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`, `divider` (see [Desktop-app primitives](#desktop-app-primitives)), and the overlays `tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer` (see [Overlays](#overlays)) **Properties:** `fill`, `gradient`, `stroke`, `strokeWidth`, `strokeStyle`, `borderTop`, `borderRight`, `borderBottom`, `borderLeft`, `cornerRadius`, `width`, `height`, `minWidth`, `minHeight`, `maxWidth`, `layout` (`"horizontal"` | `"vertical"` | `"grid"`), `gap`, `rowGap`, `gridColumns`, `gridColumn`, `gridRow`, `padding`, `alignItems`, `justifyContent`, `fontSize`, `fontFamily`, `fontWeight`, `color`, `content`, `textAlign`, `lineHeight`, `letterSpacing` (px), `textDecoration`, `textTransform`, `textOverflow` (`"ellipsis"` — designed single-line truncation; `canvas_stress` reports clips behind it as info), `tabularNums`, `fontVariationSettings`, `src`, `objectFit`, `opacity`, `shadow` (CSS string, or `"$elevation."` referencing an elevation token), `shadows`, `blur`, `backdropBlur`, `backdropFilter`, `overflow`, `wrap`, `position` (`"absolute"` | `"relative"` | `"fixed"` | `"sticky"`), `x`, `y`, `bottom`, `right`, `icon`, `iconSize`, `iconColor`, `iconStyle`, `checked`, `disabled`, `value`, `d`, `viewBox`, `strokeLinecap`, `strokeLinejoin`, `strokeDasharray`, `animation`, `transition` (object, or `"$motion."` referencing a motion token), `kind`, `series`, `segments`, `innerRatio`, `centerValue`, `centerLabel`, `sparkKind`, `xDomain`, `yDomain`, `curve`, `gridlines`, `xLabels`, `yLabels`, `componentId`, `overrides`, `safeArea` (`{ top, bottom }`, document root only — insets the renderer adds to the root's top and bottom padding; `canvas_create` with `type: "mobile"` writes the device's), `name` (a readable label — `find_nodes` and component overrides match on it), `pulse` (skeleton only), `responsive` (`"stack"` | `"wrap"`) @@ -397,6 +397,25 @@ Application screens (`type: "desktop-app"`) are built from eight primitives on t `fill`, `stroke`, `color`, `iconColor` and `secondaryColor` override the token defaults (`tabs.fill` is the contained variant's active background). A canvas that holds a `nav-item`, `tabs`, `tree-row`, `menu-row` or `property-row` must declare its type (`desktop-app-artboard`). +#### Overlays + +Six overlays draw screen states: an open menu, a comment popover, a confirm dialog, a toast. Put each in a state variant (`canvas_add_variant` with `menu-open`, `comment-open`, `confirm-delete` or `toast`); coverage lists those states and never demands them. Wherever an overlay sits in the tree, it renders in one layer after the content, so a pane never clips it and a sticky bar never covers it. `x` / `y` are offsets from the root's top-left, not from the parent. Layers are fixed by kind, with no z-index property: `popover` and `menu` 400, the modal's scrim 500, `modal` and `drawer` 510, `toast` 600, `tooltip` 800. `anchor` names the node that opens an overlay, for the rules; it is never rendered. Colours come from `$bg-surface`, `$border`, `$text-primary` and `$text-secondary`, depth from `$elevation.overlay`. + +| Type | Key props | What it is | +|---|---|---| +| `tooltip` | `text`, `x`, `y` | A short hint, inverted, wrapping at 240px; never renders children | +| `popover` | `x`, `y`, `size` (`xs` 192 / `sm` 320 / `md` 480 / `lg` 640), children | A panel (vertical, 12px padding by default) for a comment box or a filter form | +| `menu` | `x`, `y`, children (`menu-row`s, `divider`s) | A menu at least 192 wide, hugging its rows | +| `modal` | `title`, `size` (`sm` 480 / `md` 640 / `lg` 960), `actions: [{ label, variant? }]`, `closeLabel`, children | Centred over its own full scrim, with a close button named "Close"; actions right-aligned, the filled one (`primary` or `destructive`) rightmost, an action with no variant `secondary` | +| `toast` | `text`, `tone` (`neutral` / `success` / `warning` / `danger`), `action: { label }` | Bottom-centre, 24px above the artboard's edge; the tone colours a leading glyph | +| `drawer` | `size` (`sm` 320 / `md` 480), `scrim`, children | A panel pinned to the right edge at full height | + +``` +I(variant, { type: "modal", title: "Delete \"Checkout\"?", actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }] }) +``` + +A modal and a drawer are panes of their own for the wayfinding and primary-count rules; a modal's close button and actions and a toast's action are pointer targets. An undeclared canvas holding an overlay warns until it declares a type (`desktop-app-artboard`); web and mobile canvases may hold overlays freely. + ### `find_nodes` Find nodes by what they are — property values, text content, or name — instead of hand-tracking ids. Read-only; the query twin of `replace_matching_properties`. @@ -897,16 +916,16 @@ Every result also carries a **`surface`** field: `{ type, device, source, rulesO | `mobile-type-floor` | typography | warning | Text below 11px, `$body` below 16px, or prose of five or more words below 13px (copy of twelve or more words at 13–15px is an info). | | `mobile-one-column` | usability | info | Prose set side by side in a horizontal or grid frame: two or more children each holding eight or more words. | | `mobile-artboard` | structure | warning / info | Runs on every type. A mobile canvas 500px or wider warns, and any other size than the device's is an info. An undeclared canvas narrower than 500px warns until `canvas_set_type` declares it; one declared `web` gets an info. | -| `desktop-app-artboard` | structure | warning / info | Runs on every type. Warns on a desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for. Also warns on a canvas that holds a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) and was never declared, or is declared `mobile`; one declared `web` gets an info. Primitives inside an instance count. | +| `desktop-app-artboard` | structure | warning / info | Runs on every type. Warns on a desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for. Also warns on a canvas that holds a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) and was never declared, or is declared `mobile`; one declared `web` gets an info. An undeclared canvas holding an overlay (`tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer`) warns too; declared web or mobile, overlays alone raise nothing. Primitives inside an instance count. | | `type-scale-ratio` | typography | warning | On by default: adjacent font sizes stepping by a ratio below 1.1 or above 2.0 (pinned typography tokens skip it). The desktop-app ruleset turns it off, since dense apps step 12 / 13 / 14 on purpose; it then appears in `rulesOff`, and `desktop-app-type-ladder` judges the sizes instead. | | `desktop-app-target` | usability | warning / error | Desktop-app only: the 24px floor (the `usability` row under Categories below), under its rule id. Fast mode warns on a target under 24px in either dimension; detailed mode errors when its 24px circle reaches a neighbour. An unlabelled `link` with no width (or `"auto"`) is measured at its glyphs (14px wide, 30 with `external`), on web too. | | `desktop-app-handbuilt-target` | usability | info | Desktop-app only: a frame below 32px holding one icon, an icon plus a label of up to three words, or (bordered and padded) one such label alone, the shape an imported text button takes. Frames inside a clickable primitive or a `property-row` are never counted. Rebuild it as a `button` or `link` if it is clickable. | | `desktop-app-icon-label` | usability | warning | Desktop-app only: an icon-only `button` or `link` with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`. | -| `desktop-app-current` | usability | warning / info | Desktop-app only: in one pane (a frame with `overflow: "auto"`, or the root; each node belongs to its nearest), two active `nav-item`s at one depth, or two or more with none active (give each navigation region its own scrolling pane); a `tabs` node with no active tab or more than one; two active `tree-row`s under one parent. A tree with a current row that nests past two levels is an info. | +| `desktop-app-current` | usability | warning / info | Desktop-app only: in one pane (a frame with `overflow: "auto"`, a `modal`, a `drawer`, or the root; each node belongs to its nearest), two active `nav-item`s at one depth, or two or more with none active (give each navigation region its own scrolling pane); a `tabs` node with no active tab or more than one; two active `tree-row`s under one parent. A tree with a current row that nests past two levels is an info. | | `desktop-app-type-ladder` | typography | warning | Desktop-app only, replacing `type-scale-ratio`: adjacent sizes a < b step by at most 4px while a ≤ 16, else by a ratio of 1.1 to 2.5 (pinned token pairs skip). Also text below 11px, prose of five or more words below 12px, and a `$body` text below 13px. | | `desktop-app-row-rhythm` | consistency | warning / info | Desktop-app only, on detected tables: a header row more than 1px off the one-line body rows warns; a body row off its siblings is an info (title-over-subtitle rows compared only with each other); detailed mode adds a cell off its column's left edge as an info. Fast mode reads authored heights only. | | `desktop-app-truncation` | usability | warning / info | Desktop-app only: a truncating column header warns; a hand-built ellipsis with no `title` is an info. Detailed mode: a `tabs` node whose every label is cut warns, and an ellipsis leaving fewer than four characters is an info. | -| `desktop-app-primary-count` | structure | info | Desktop-app only: two or more primary `button`s in one pane (any variant but `secondary`, `ghost` or `destructive` renders filled, so it counts; no variant included). Primaries inside three or more same-shaped sibling frames, such as a card grid, don't count. | +| `desktop-app-primary-count` | structure | info | Desktop-app only: two or more primary `button`s in one pane (any variant but `secondary`, `ghost` or `destructive` renders filled, so it counts; no variant included). A modal's `actions` with `variant: "primary"` count in the modal's pane. Primaries inside three or more same-shaped sibling frames, such as a card grid, don't count. | Repeated findings fold in this result: three or more warnings or infos with the same severity, category, rule (or tell) and theme come back as one entry when they also share their message — on its shape for members that carry a fix (each fix op holds its node's specifics), word for word apart from quoted node text for members without one. The entry keeps the first one's message and adds `nodeIds` (distinct), `count` and, when they had fixes, `fixes: [{ nodeId, op }]`. Errors never fold, and `canvas_autofix` works from the unfolded list. diff --git a/VISION.md b/VISION.md index 3a1077b..863690f 100644 --- a/VISION.md +++ b/VISION.md @@ -568,7 +568,7 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 - [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 - [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 +- [x] Slice E — overlays: one overlay layer at the root with a fixed ladder, and the `tooltip`, `popover`, `menu`, `modal`, `toast` and `drawer` primitives, with overlay screen states as variants - [ ] 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 - [ ] Slice H — state checks: focus rings, active indicators, disabled renders and control boundaries checked analytically on every interactive primitive, without being drawn diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index c641f50..28ccc77 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -75,14 +75,15 @@ None of these rules has a mechanical fix, so `canvas_autofix` never proposes one ## The desktop-app ruleset -A `desktop-app` canvas is judged as an application, not a page. Its vocabulary is in [Desktop-app vocabulary](#desktop-app-vocabulary) and its layouts in [Starting an application screen](#starting-an-application-screen-desktop-app-realisations); 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), and its screen states in [Overlays](#overlays-screen-states); the overlay rules and element states come in later slices of Phase 31. Each finding from these rules names its rule in a `rule` field, and the `surface` report lists them in `rulesOn`. Only `desktop-app-artboard` runs on web and mobile; the other `desktop-app-*` rules run on desktop-app canvases only. Errors and warnings block the directive (the gate on presenting); infos never do. Fast mode is the loop; before presenting, also run `canvas_evaluate({ canvasId, mode: "detailed" })`, which measures rendered rows, column edges and truncation. Nodes inside a component instance are judged as rendered and reported on the instance. None of these rules has a mechanical fix, so `canvas_autofix` proposes none. -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). +Two terms the rules share. A **pane** is a frame that scrolls on its own (`overflow: "auto"`), a `modal`, a `drawer`, or the root; every node belongs to its nearest pane. App panes scroll independently, so give each navigation region (a rail, a sidebar, a list) its own pane. **Prose** is text of five or more words, where a word holds letters and no digits (figures and their units are not words). - **`type-scale-ratio` is off.** On web and mobile, adjacent font sizes must step by a ratio between 1.1 and 2.0, and a pair outside that warns with `rule: "type-scale-ratio"`. Dense apps step 12 / 13 / 14 on purpose, so the desktop-app ruleset turns that rule off and replaces it with `desktop-app-type-ladder` below; it is listed in the `surface` report's `rulesOff`. Pinned typography tokens still skip the check on every type. - **`desktop-app-artboard`** (structure; a base rule, so it runs on every type). - A desktop-app canvas narrower than 1024px, the narrowest window the desktop-app layouts are built for, **warns**. Resize the root to the window (`U("document", { width: 1440, height: 900 })`), or declare the type the canvas really is. - A canvas that holds a desktop-app primitive (`nav-item`, `tabs`, `tree-row`, `menu-row`, `property-row`) must say what it is: never declared **warns** until `canvas_set_type` declares it either way; declared `mobile` **warns** (those primitives are built for a pointer and a dense window, not a phone); declared `web` gets an **info**. Primitives inside a component instance count, and the finding names the first one found. + - A canvas that holds an overlay (`tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer`) and was never declared **warns** the same way. Declared `web` or `mobile`, overlays alone raise nothing: pages and phones use them too. - **`desktop-app-target`** (usability). [The 24px floor](#the-24px-floor-web-and-desktop-app) under its rule id: a target below 24px in either dimension **warns** in fast mode, and is an **error** in detailed mode when its 24px circle reaches a neighbour. Web runs the same check without the id, including this: a `link` with no label and no width (or `"auto"`) hugs its glyphs, so it is measured at 14px wide (30 with `external`) and 24 tall; a px width is measured as written, a fluid or token width is not measured. Give it a label, or keep its neighbours out of its circle. - **`desktop-app-handbuilt-target`** (usability, info). A frame below 32px in either dimension that holds one icon, an icon plus a label of three words or fewer, or, when it has a border (`stroke`) and padding, one such label alone (the shape an imported text button takes). It never blocks, because a frame can't say it is decorative. If it is clickable, rebuild it as a `button` (`xs` or `sm`; icon-only with `ariaLabel`) or a `link`. Fast mode estimates a missing height from the icon or the label's line box plus padding; detailed mode measures the render. Fast mode honours `minWidth` / `minHeight` and adds up an icon stacked over a caption when both sit directly in the frame. A frame inside a clickable primitive or a `property-row` is never hand-built. - **`desktop-app-icon-label`** (usability, **warning**). An icon-only `button` or `link` (no `label`, an `icon`) with no `ariaLabel`, or a `collapsed` `nav-item` with a blank `label`: an action with no name for a screen reader or a tooltip. @@ -93,7 +94,7 @@ Two terms the rules share. A **pane** is a frame that scrolls on its own (`overf - **`desktop-app-type-ladder`** (typography, **warning**), replacing `type-scale-ratio`. For each pair of adjacent distinct sizes a < b: it passes when a ≤ 16 and b − a ≤ 4, else when b / a is between 1.1 and 2.5. So 12 / 13 / 14 and 14 → 32 pass and 13 → 36 warns. A pair of pinned typography token sizes skips the check. Sizes are read as rendered (`"14px"` counts; a `clamp()` reads as its minimum). Separately: any text below 11px, prose below 12px, and a text whose `fontSize` is `$body` resolving below 13px each warn, one finding per text. - **`desktop-app-row-rhythm`** (consistency), on detected tables. A header row (its content is text, plus icons and controls such as a select-all checkbox; a first row holding a control counts only when its text is styled apart from the next row's, since a row-select data row looks the same) more than 1px taller or shorter than the one-line body rows **warns**, as Carbon sets them equal. A body row more than 1px off its siblings is an **info**; rows with a title over a subtitle are compared only with each other. Detailed mode adds a cell whose left edge is more than 1px off its column as an **info**. Fast mode reads authored `height`s only, so rows sized by padding are judged in detailed mode. - **`desktop-app-truncation`** (usability). A column header text with `textOverflow: "ellipsis"` **warns**: a header is never cut. A hand-built text with an ellipsis and no `title` is an **info**, since the full text must be reachable (primitives add their own `title`). Detailed mode adds: a `tabs` node whose every label is cut **warns** (tabs shrink to fit their tablist, so too many tabs in too little width leaves nothing readable), and an ellipsis that leaves fewer than four visible characters, on a text or a primitive's label, is an **info**. -- **`desktop-app-primary-count`** (structure, info). Two or more primary `button`s in one pane. Any variant but `secondary`, `ghost` or `destructive` renders filled with the accent, so it counts (no variant included); a disabled one doesn't. Primaries inside three or more same-shaped sibling frames (a grid of cards) are each card's own and don't count. +- **`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. A modal is a region of its own: its `actions` with `variant: "primary"` count there with any primary in its body (a `destructive` action is not a primary), never against the page behind it. 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). @@ -122,6 +123,27 @@ Build application screens from these primitives, never from hand-built frames: a 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. +### Overlays (screen states) + +An overlay is a **screen state**: the same screen with a menu open, a comment popover up, a confirm dialog or a toast. Design it as a state variant, not on the base screen: `canvas_add_variant({ canvasId, state: "confirm-delete" })` clones the screen, then insert the overlay into the clone. The recommended state names are `menu-open`, `comment-open`, `confirm-delete` and `toast`. Coverage lists every designed state in `coverage.states` and never demands an overlay state: an overlay is a design choice, not a data obligation. + +Wherever you insert an overlay in the tree, it renders in **one overlay layer** after the content: a menu authored inside a sticky toolbar or a scrolling pane is never clipped by the pane and never sits under a sticky or fixed bar. So insert it where it belongs logically (a menu beside the button that opens it) and name that node in `anchor` (rules read it; it is never rendered). Three things follow: + +- **`x` / `y` are root coordinates**: offsets from the root's top-left, not from the parent. The layer is the artboard box, so a centred modal and a bottom toast sit in the artboard. +- **Layers are fixed by kind**, and there is no `zIndex` property: `popover` and `menu` 400, the modal's scrim 500, `modal` and `drawer` 510, `toast` 600, `tooltip` 800. Everything in the layer sits above all content (`fixed` 10, `sticky` 5, a sheet 30). A menu inside a modal therefore renders under the modal. +- **`snapshot_layout` lists every overlay as a child of the root**, at root coordinates, and a modal (or a drawer with a scrim) carries `scrim: { x, y, width, height }`. The detailed overlap check never counts an overlay as overlapping its siblings. + +The six overlays take their colours from `$bg-surface`, `$border`, `$text-primary` and `$text-secondary`, and their depth from `$elevation.overlay` (a fallback shadow without it); `fill`, `stroke` and `color` override. + +- **`tooltip`** `{ text, x, y }` is a short hint, inverted (`$text-primary` fill, `$bg-surface` text), wrapping at 240px. Text only: it never renders children. +- **`popover`** `{ x, y, size?: "xs" | "sm" | "md" | "lg", children }` is a panel 192 / 320 / 480 / 640 wide (320 by default; a numeric `width` wins), vertical with 12px padding by default; `layout`, `gap` and `padding` apply as on a frame. A comment box or a filter form. +- **`menu`** `{ x, y, children }` holds `menu-row`s and `divider`s: 4px padding, at least 192 wide, hugging its rows. +- **`modal`** `{ title, size?: "sm" | "md" | "lg", actions?: [{ label, variant? }], closeLabel?, children }` is 480 / 640 / 960 wide (640 by default), centred over its own full scrim (`x` / `y` place its top-left instead). Its header holds the title and a close button named "Close" (`closeLabel` renames it). The body holds the children (vertical, 12px gap) and scrolls when tall. `actions` render right-aligned as 32px buttons; an action with no variant renders `secondary`, and the filled ones (`primary`, `destructive`) render rightmost. For a delete confirmation: `actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }]`. +- **`toast`** `{ text, tone?: "neutral" | "success" | "warning" | "danger", action?: { label } }` sits bottom-centre, 24px above the artboard's bottom edge (`x` / `y` place it). The tone colours a leading glyph; the text stays `$text-primary`. `danger` renders `role="alert"`. +- **`drawer`** `{ size?: "sm" | "md", scrim?, children }` is a 320 / 480 panel pinned to the right edge at full height, 16px padding; `scrim: true` dims what is behind it. + +A modal's close button and actions (32 tall) and a toast's action (24 tall) are pointer targets. A modal and a drawer are panes: navigation and primary buttons inside them are judged apart from the page behind. + ### Lists that lead with a mark are not tables (every type) A list whose every row starts with a mark (an icon, a dot, or a small image) is navigation, not data: a sidebar of projects with an identity dot, a name and a count. Table detection skips it, so `coverage` never asks for an empty or loading state for your navigation, and `canvas_stress` perturbs its labels as ordinary text. A table with a text header row still detects, even when every data row leads with an avatar. @@ -419,6 +441,7 @@ The happy path of one static frame with ideal data is half a design. Real UX liv | `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` (`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 | +| `menu-open` / `comment-open` / `confirm-delete` / `toast` | an overlay (`menu`, `popover`, `modal`, `toast`) | Screen states: the same screen with an overlay up. Coverage lists them and never demands them; see [Overlays](#overlays-screen-states) | **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. diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index dfabd7e..904fd86 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -294,6 +294,13 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **K7: stress.** `PRIMITIVE_TEXT_PROPS` gains `tooltip.text`, `toast.text`, `toast.action.label`, `modal.title` and `modal.actions[].label`. The modal title truncates with a `title` attribute; tooltip and toast text wrap. - **K8: the inputs the layer must survive** (hard rule 6, the verifier's list): each of the six kinds; authored as a root child, inside a `sticky` bar, inside a `fixed` bar, inside an `overflow: "auto"` and an `overflow: "hidden"` pane, inside an animated / blurred ancestor, inside a component instance, and inside another overlay; with and without authored `x`/`y`; light and dark themes; themed, unthemed, and unthemed inside a component; `web`, `mobile` and `desktop-app` canvases; a root narrower than the capture width; a root with `overflow` hidden, auto and unset; artboard and full-page captures; `computeLayout` with and without a `rootNodeId`. Evaluate consumers: the detailed overlap check, the 24px census, panes, primary count, FR-C9 by type and declaration source, stress's text props. +**Slice E — as built (recorded 2026-11-15; read this before slice F).** No spec change; K1 to K8 held. Decisions the contracts did not settle: +- **L1: centring without a transform.** A centred modal is `inset: 0; margin: auto; height: fit-content` in the layer, a default toast `left: 0; right: 0; bottom: 24px; margin: 0 auto; width: max-content`, so no overlay carries a transform (a transform would make an overlay the containing block of anything `fixed` inside it, and blurs text at half pixels). +- **L2: what the walker sees inside an overlay.** The modal body is a `data-fs-slot`, so its children are placed; the header, the close button and the actions render under the modal's id with no node ids of their own, like a tab bar's tabs (slice A D12). A tooltip, a modal and a toast carry `data-fs-primitive`, so their own labels (the modal title, the action labels) are recorded when cut; popover, menu and drawer are containers whose children are ordinary nodes. +- **L3: roles.** `tooltip` renders `role="tooltip"`, `menu` `role="menu"`, `popover` and `drawer` `role="dialog"` (a drawer with a scrim adds `aria-modal`), `modal` `role="dialog" aria-modal="true"` labelled by its title, `toast` `role="status"` (`role="alert"` for danger). +- **L4: overlays are not reuse.** `REUSE_PRIMITIVES` (the structure advisory's reuse count) is unchanged: one modal on a screen-state variant is not a repeated component. +- **L5: a menu inside a modal renders under it** (400 below 510), as the ladder fixes; the docs say so. Slice F's rules may want to flag it. + **Slice F: overlay rules (FR-F1)** - `src/evaluate.ts`: `desktop-app-overlay`; fast bounds from authored rects, detailed bounds from rendered rects. diff --git a/src/desktop-app-rules.ts b/src/desktop-app-rules.ts index 27148d5..36e7116 100644 --- a/src/desktop-app-rules.ts +++ b/src/desktop-app-rules.ts @@ -4,7 +4,7 @@ import type { EvaluationIssue } from './evaluate.js'; import type { LayoutRect } from './screenshot.js'; import type { SceneNode } from './types.js'; -import { CLICKABLE_PRIMITIVES, DESKTOP_APP_PRIMITIVES, tabsItems } from './primitives.js'; +import { CLICKABLE_PRIMITIVES, DESKTOP_APP_PRIMITIVES, OVERLAY_TYPES, modalActions, tabsItems } from './primitives.js'; import { fontPx, paddingSides, proseWords } from './mobile-rules.js'; import { shapeHash } from './shape-hash.js'; import { windowProfile, DEFAULT_WINDOW, WINDOW_PROFILES, type SurfaceDeclaration, type WindowProfile } from './surfaces.js'; @@ -13,8 +13,10 @@ import { windowProfile, DEFAULT_WINDOW, WINDOW_PROFILES, type SurfaceDeclaration * narrower than its window's minimum warns (slice A). A canvas that holds a * desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) * must say it is one (slice B): undeclared warns, an explicit `web` gets an - * info, an explicit `mobile` warns. The overlay clause lands with the - * overlay primitives (slice E). Reads the tree with instances expanded. */ + * info, an explicit `mobile` warns. An undeclared canvas holding an overlay + * primitive warns too (slice E); overlays alone never trip the web or mobile + * cases, since pages and phones use them. Reads the tree with instances + * expanded. */ export function checkDesktopArtboard(root: SceneNode, surface: SurfaceDeclaration): EvaluationIssue[] { if (surface.type !== 'desktop-app') return checkAppPrimitivesDeclared(root, surface); const profile = windowProfile(surface.device ?? DEFAULT_WINDOW) ?? WINDOW_PROFILES[DEFAULT_WINDOW]; @@ -31,24 +33,27 @@ export function checkDesktopArtboard(root: SceneNode, surface: SurfaceDeclaratio }]; } -function firstAppPrimitive(root: SceneNode): SceneNode | undefined { - if (DESKTOP_APP_PRIMITIVES.has(root.type)) return root; +function firstOf(root: SceneNode, types: ReadonlySet): SceneNode | undefined { + if (types.has(root.type)) return root; for (const c of root.children ?? []) { - const hit = firstAppPrimitive(c); + const hit = firstOf(c, types); if (hit) return hit; } return undefined; } function checkAppPrimitivesDeclared(root: SceneNode, surface: SurfaceDeclaration): EvaluationIssue[] { - const hit = firstAppPrimitive(root); + const app = firstOf(root, DESKTOP_APP_PRIMITIVES); + // Only an undeclared canvas is asked about an overlay. + const hit = app ?? (surface.source === 'default' ? firstOf(root, OVERLAY_TYPES) : undefined); if (!hit) return []; const what = `a ${hit.type}${hit.name ? ` ("${hit.name}")` : ''}`; + const kind = app ? 'a desktop-app primitive' : 'an overlay primitive'; const base = { category: 'structure', rule: 'desktop-app-artboard', nodeId: hit.id, nodeName: hit.name } as const; if (surface.source === 'default') { return [{ ...base, severity: 'warning', - message: `This canvas holds ${what}, a desktop-app primitive, but never declared its type, so it is judged as a web page.`, + message: `This canvas holds ${what}, ${kind}, but never declared its type, so it is judged as a web page.`, suggestion: 'Declare it: canvas_set_type({ type: "desktop-app" }) for an application screen (a tool you work in), or canvas_set_type({ type: "web" }) if it really is a page you read.', }]; } @@ -96,13 +101,13 @@ function parents(root: SceneNode): Map { return out; } -/** A pane: a frame that scrolls on its own (overflow "auto"), or the root. - * (`modal` and `drawer` join with the overlay primitives, slice E.) */ +/** A pane: a frame that scrolls on its own (overflow "auto"), a `modal`, a + * `drawer`, or the root. */ function paneOf(n: SceneNode, parentOf: Map): SceneNode { let cur = parentOf.get(n) ?? null; let last = n; while (cur) { - if (cur.type === 'frame' && cur.overflow === 'auto') return cur; + if ((cur.type === 'frame' && cur.overflow === 'auto') || cur.type === 'modal' || cur.type === 'drawer') return cur; last = cur; cur = parentOf.get(cur) ?? null; } @@ -564,8 +569,8 @@ const REPEAT_MIN = 3; /** More than one primary button in one region (the nearest pane) is an info. * A primary inside one of three or more same-shaped sibling frames (shape - * hash without names) is not counted. A modal's primary action joins with the - * overlays (slice E). */ + * hash without names) is not counted. A modal is a region of its own, and its + * `primary` actions count there (a destructive action is not a primary). */ export function checkPrimaryCount(ctx: DesktopContext): EvaluationIssue[] { const issues: EvaluationIssue[] = []; const parentOf = parents(ctx.root); @@ -580,16 +585,20 @@ export function checkPrimaryCount(ctx: DesktopContext): EvaluationIssue[] { } return false; }; - const byPane = new Map(); + const byPane = new Map>(); + const add = (pane: SceneNode, node: SceneNode, label: string) => byPane.set(pane, [...(byPane.get(pane) ?? []), { node, label }]); for (const n of parentOf.keys()) { + if (n.type === 'modal') { + for (const a of modalActions(n)) if (a.variant === 'primary') add(n, n, String(a.label).trim()); + continue; + } if (!isPrimary(n) || n.disabled === true || repeated(n)) continue; - const pane = paneOf(n, parentOf); - byPane.set(pane, [...(byPane.get(pane) ?? []), n]); + add(paneOf(n, parentOf), n, String(n.label ?? n.ariaLabel ?? nameOf(n))); } for (const [pane, buttons] of byPane) { if (buttons.length < 2) continue; - issues.push(issue('structure', 'desktop-app-primary-count', 'info', buttons[1], - `${buttons.length} primary buttons share ${pane === ctx.root ? 'the screen' : `pane "${nameOf(pane)}"`} (${buttons.map((b) => `"${b.label ?? b.ariaLabel ?? nameOf(b)}"`).slice(0, 5).join(', ')}) — one primary per region tells the user what to do next.`, + issues.push(issue('structure', 'desktop-app-primary-count', 'info', buttons[1].node, + `${buttons.length} primary buttons share ${pane === ctx.root ? 'the screen' : `${pane.type === 'modal' ? 'modal' : 'pane'} "${nameOf(pane)}"`} (${buttons.map((b) => `"${b.label}"`).slice(0, 5).join(', ')}) — one primary per region tells the user what to do next.`, 'Keep one primary; make the others variant "secondary" or "ghost". A button with no variant renders as primary.')); } return issues; diff --git a/src/evaluate.ts b/src/evaluate.ts index 8a84a4e..e1f47c2 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -12,7 +12,7 @@ import { getIconSvg, parseIconRef } from './icons.js'; import { storedGenre } from './genre.js'; import { relaxedByPreset, relaxedByGenre, canonicalGenre, genreRulesets, activeRulesets, composeRulesets, resolveSurface, deviceProfile, DEVICE_PROFILES, DEFAULT_DEVICE, MOBILE_RULES, DESKTOP_APP_RULES, DEFAULT_WINDOW, WINDOW_PROFILES, windowProfile, type SurfaceType } from './surfaces.js'; import { checkArtboard, checkHandbuiltTargets, checkOneColumn, checkSafeAreaDetailed, checkSafeAreaFast, checkTabBars, checkTypeFloor, paddingSides, type MobileContext } from './mobile-rules.js'; -import { CHROME_EDGE, FAB_SIZE, NAV_ACTION, TAPPABLE_PRIMITIVES, CLICKABLE_PRIMITIVES, CONTROL_OWNERS, LIST_ROW_HEIGHT, MENU_ROW_HEIGHT, NAV_ITEM_HEIGHT, PROPERTY_ROW_HEIGHT, buttonBox, desktopTargets, effectivePosition, listRowMinHeight, navActions, pinsBottom, tabItemBox, tabItems } from './primitives.js'; +import { CHROME_EDGE, FAB_SIZE, NAV_ACTION, TAPPABLE_PRIMITIVES, CLICKABLE_PRIMITIVES, CONTROL_OWNERS, LIST_ROW_HEIGHT, MENU_ROW_HEIGHT, NAV_ITEM_HEIGHT, PROPERTY_ROW_HEIGHT, buttonBox, desktopTargets, overlayTargets, effectivePosition, listRowMinHeight, navActions, pinsBottom, tabItemBox, tabItems } from './primitives.js'; // --- Types --- @@ -2066,6 +2066,12 @@ export function pointerTargets(entries: NodeEntry[], rootWidth: number): Pointer for (const t of desktopTargets(node)) { targets.push({ node, what: t.what, w: t.w ?? Infinity, h: t.h, disabled: t.disabled }); } + } else { + // Phase 31 slice E — a modal's close button and actions, a toast's + // action: drawn by the overlay under its own id, 24px or more. + for (const t of overlayTargets(node)) { + targets.push({ node, what: t.what, w: t.w ?? Infinity, h: t.h, disabled: t.disabled }); + } } } return targets; diff --git a/src/index.ts b/src/index.ts index 95645c4..0ba557a 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. 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). +Application screens: canvas_create({ type: "desktop-app" }) for a tool you work in — an editor, an admin console, a file browser, a viewer: persistent chrome, panes, dense controls, a current selection, in a browser tab or a native window. The test is what the user does: a page you read and scroll is "web", a tool you work in is "desktop-app". It gets the window artboard (1440×900 for the default device "window-1440", no insets); generate_design_system pivots its type on 14px (13 for data-dense); its ruleset turns OFF type-scale-ratio (the adjacent font-size ratio check — dense apps step 12/13/14 on purpose), and desktop-app-artboard (on every type) WARNS when a desktop-app canvas is narrower than 1024px, and when a canvas holding a desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) never declared its type or is declared mobile (declared web gets an info); an undeclared canvas holding an overlay (tooltip, popover, menu, modal, toast, drawer) warns too, while web and mobile canvases may hold overlays freely. Build app screens from the desktop-app primitives (batch_design lists them): link, text-input, nav-item, tabs, tree-row, menu-row, property-row, divider, plus button size "xs" (24px) with ariaLabel for icon-only buttons and links — never hand-built frames, which no target rule can measure. A nav-item's dotColor is an identity dot and never counts as a competing accent. Start an app screen from a desktop-app realisation: apply_structure on a desktop-app canvas resolves the anatomy name to it — split-workbench → split-workbench-app, dashboard → dashboard-app, settings → settings-app, and three app-only anatomies: list-detail → list-detail-app (navigation, a searchable list, a detail pane with a "nothing selected" placeholder), editor-inspector → editor-inspector-app (a work area beside a 70/30 inspector of tabs and property-rows), browser → browser-app (a filter bar over an adaptive card grid); data-table → data-table-app (32px toolbar, header, rows and pager; stamp it into a pane at least 480px wide, not a 300px side panel) and skeleton-table → skeleton-table-app (its loading state). Each is built from the primitives and gated: > 95 with no warning, error, tell or desktop-app finding in fast and detailed mode under the presets, every personality and an inherited system, canvas_stress CLEAN at 1440, 1280 and 1024 wide, data-table stamped into a pane at least 480px wide clean too — so a fresh stamp is READY TO PRESENT unless coverage asks for a state. They fill the window: the stamp sets root overflow "hidden" (the root keeps the artboard height) and every pane is overflow "auto", so long content scrolls inside its pane — keep new content inside a pane, and never give a pane's direct child a fixed height or an overflow (the pane squashes it instead of scrolling). Coverage still asks for states: dashboard-app and data-table-app need "empty" + "loading", editor-inspector-app and settings-app (forms) need "error". toolbar, toggle-row, segmented-control and breadcrumb stay web-only (realisation: "web" forces one). On web and desktop-app every pointer target — the four controls and the clickable primitives (button, list-row, tab-bar tabs, nav-bar actions, link, text-input, nav-item, each tab of a tabs, tree-row, menu-row; inline text links are exempt) — meets the 24px WCAG 2.5.8 floor or its spacing exception (nothing else within a 24px circle around it): detailed mode runs that circle test (ERROR on failure), fast mode WARNS on anything under 24 and names detailed mode. The desktop-app ruleset (each finding carries its "rule"; canvas_evaluate lists them) adds: name every icon-only button and link (ariaLabel); mark exactly one current place — one active nav-item per pane — a frame with overflow "auto", so give a rail and a sidebar each their own (a parent may stay active over its active child), one active tab per tabs, one active row per tree; a dense type ladder (desktop-app-type-ladder, replacing type-scale-ratio: 12/13/14 steps are fine, nothing below 11px, prose ≥12px, $body ≥13px); table header rows as tall as their body rows; column headers never truncated; one primary button per pane (info); and frames shaped like small buttons are named as hand-built targets (info) — rebuild them as button or link. Before presenting a desktop-app screen run mode "detailed" too: it measures rendered rows, column edges and truncation (a tablist whose every label is cut warns). Overlays (tooltip, popover, menu, modal, toast, drawer) are screen states: add a variant ("menu-open", "comment-open", "confirm-delete", "toast") with canvas_add_variant and insert the overlay there; wherever it sits in the tree it renders in one layer above all content, stacked by kind (no z-index exists), at x / y in ROOT coordinates; a modal and a drawer are panes of their own (one active nav-item, one primary — a modal's "primary" action counts). 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. @@ -125,6 +125,7 @@ const GOTCHAS = [ 'The bar: craft beautiful UI/UX a designer would sign off on, and polish to it YOURSELF — start from a pattern, use the whole toolkit (icons/fonts/controls/components), and run canvas_evaluate → resolve EVERY comment → re-evaluate until CLEAN (zero blocking issues) BEFORE presenting. Readiness turns on blocking findings, not the score — the score is always reported and worth climbing toward (aim for > 95), but a clean, sub-bar design is still READY. The evaluate result\'s "directive" field says when it\'s safe to present. Never show the user an unpolished design.', 'Icons: Lucide ({ type: "icon", icon: "search" }) and Material Symbols (icon: "material:check", iconStyle outlined/rounded/sharp, "-fill" suffix for filled) render by name — never fake them with Unicode glyphs. Spelling differs by set: Lucide hyphenates ("chevron-right"), Material keeps underscores AND needs the prefix ("material:chevron_right") — a bare "chevron_right" is looked up in Lucide and renders nothing; canvas_evaluate warns on any icon that resolves in neither set. Casing: use textTransform: "uppercase", not uppercased content.', 'Controls: toggle / checkbox / radio / select are real node types with checked / disabled / value, token-styled — never assemble them from frames + ellipses. For application screens (type "desktop-app") use the desktop-app primitives — link, text-input, nav-item, tabs, tree-row, menu-row, property-row, divider, button size "xs" — never hand-built frames: a frame is not a measured target.', + 'Overlays: tooltip / popover / menu / modal / toast / drawer render in one layer above ALL content whatever their parent (never clipped by a pane, never under a sticky bar), stacked by kind (popover/menu 400 < scrim 500 < modal/drawer 510 < toast 600 < tooltip 800 — a menu inside a modal renders under it). x / y are ROOT coordinates, not offsets from the parent. Put each in a screen-state variant (canvas_add_variant "menu-open" / "comment-open" / "confirm-delete" / "toast"), not on the base screen.', 'Bulk edits & queries: replace_matching_properties changes a property across every node matching a value predicate in one call (scope/type filters; dryRun previews the match set); find_nodes is the read-only twin — locate nodes by property/text/name and get ids + paths instead of guessing from read_nodes trees. canvas_autofix apply: true writes the whole mechanical fix set in one call.', 'Component scaffolds: apply_structure with kind "component" structures (data-table, form-field, toolbar, stat-card, toggle-row, the state scaffolds empty-state, skeleton-table, skeleton-card, skeleton-stat-card — plus the Phase 28 dashboard micro-patterns: kpi-card, status-chip, segmented-control, breadcrumb, initials-avatar, all on the tint pair) + targetId stamps reusable fragments with re-keyed IDs — build tables/forms from these, not node-by-node.', 'Charts: the chart node type is data-driven ({ kind: "line"|"bar"|"donut"|"sparkline", series: [{ data, stroke, highlight?, barGradient?, … }], segments? for donuts, gridlines?, xLabels? }) — it does the value→coordinate math, dashes mark projected vs actual, highlight (an index or an array of indices) renders the selected bar solid over muted siblings, donuts take segments + centerValue/centerLabel, sparklines are axis-free with the latest point emphasized. Never hand-compute path d-strings, conic-hack a donut, or hand-place sparkline bars.', @@ -248,10 +249,10 @@ server.tool( The clone is a full canvas (re-keyed node IDs, same project, tokens/components/fonts copied, provenance/genre carried over — feedback and critique stay behind) named " · " and stamped with metadata.variant = { of, state }. The result's idMap maps every base node id to its clone, so follow-up edits target the right nodes immediately: delete the data rows, stamp an empty-state scaffold, adjust copy. Adding a variant to a canvas that is itself a variant links to the ROOT base (variants never nest); one canvas per state per base — a duplicate state errors instead of forking. -state is a free string; "empty", "loading", and "error" are the recommended vocabulary (they're what the viewer groups and what coverage checks will look for). canvas_list shows the designed states on the base row (variants: [{ state, canvasId }]).`, +state is a free string; "empty", "loading", and "error" are the recommended vocabulary for data states (they're what the viewer groups and what coverage checks will look for). For SCREEN STATES — the same screen with an overlay open — use "menu-open", "comment-open", "confirm-delete" or "toast": clone the screen, then insert the menu / popover / modal / toast into the variant (it renders above everything, see batch_design's Overlays). Coverage lists every designed state in coverage.states and never demands an overlay state: an overlay is a design choice, not a data obligation. canvas_list shows the designed states on the base row (variants: [{ state, canvasId }]).`, { canvasId: z.string().describe('The base canvas to clone (a variant id also works — it resolves to the root base)'), - state: z.string().min(1).describe('The state this variant designs — "empty", "loading", "error" recommended; free string accepted'), + state: z.string().min(1).describe('The state this variant designs — "empty", "loading", "error" for data states; "menu-open", "comment-open", "confirm-delete", "toast" for overlay states; free string accepted'), }, async ({ canvasId, state }) => { try { @@ -561,8 +562,8 @@ Use "document" to reference the root node. Bind results to reuse IDs: header=I(" Concatenate bindings: U(header+"/childId", {...}) Returns { ok, nodeIds, results }: nodeIds maps each bound variable to the node ID it created (e.g. { "header": "n_a1b2" }) — record it and use those IDs to target nodes in later calls (bindings only live within a single call). results lists each op's outcome in order. If the call wrote a fontFamily nothing can serve yet (not cached, not registered, not system/generic), an extra "Font warnings" content item names it — cache-only check, no network, so it can't catch everything set_fonts/network resolution would. -Node types: frame, text, rectangle, ellipse, image, icon, path, component, instance, toggle, checkbox, radio, select, chart, skeleton, status-bar, home-indicator, nav-bar, tab-bar, button, list-row, sheet, link, text-input, nav-item, tabs, tree-row, menu-row, property-row, divider -Properties: fill, gradient, stroke, strokeWidth, strokeStyle, borderTop, borderRight, borderBottom, borderLeft, cornerRadius, width, height, minWidth, minHeight, maxWidth, layout ("horizontal"|"vertical"|"grid"), gap (0 = flush, never flagged as off-scale), rowGap, gridColumns, gridColumn, gridRow, padding, alignItems, justifyContent, fontSize, fontFamily, fontWeight, color, content, textAlign, lineHeight, letterSpacing (px), textDecoration, textTransform ("uppercase" etc. — don't bake casing into content), textOverflow ("ellipsis" — designed single-line truncation for labels that must survive hostile-length content; canvas_stress reports clips behind it as info, not warnings), tabularNums (fixed-width digits so number columns align — table scaffolds and chart ticks carry it by default), fontVariationSettings (variable-font axes, e.g. '"wght" 650'), src, objectFit, opacity, shadow, shadows (plural wins — a \`shadow\` written where \`shadows\` is set is ignored, and the op result carries a warning saying so), blur, backdropBlur, backdropFilter, overflow, wrap, position ("absolute"|"relative"|"fixed"|"sticky"), x, y, bottom, right, icon, iconSize, iconColor, iconStyle, checked, disabled, value, pulse, d, viewBox, strokeLinecap, strokeLinejoin, strokeDasharray, animation, transition (object, or the string "$motion." referencing a motion token), kind, series, segments, innerRatio, centerValue, centerLabel, sparkKind, xDomain, yDomain, curve, gridlines, xLabels, yLabels, componentId, overrides, safeArea ({ top, bottom }, document root only — insets the renderer adds to the root's top/bottom padding; canvas_create type "mobile" writes the device's), responsive, and the mobile primitives' props: time, appearance, title, subtitle, leading, trailing, largeTitle, items, variant, fab, label, iconPosition, size, divider, detent, grabber, secondaryColor, badgeColor, and the desktop-app primitives' props: ariaLabel, external, links, count, dotColor, active, depth, collapsed, expanded, shortcut, destructive, submenu, labelWidth, placeholder, rows, error, orientation, inset +Node types: frame, text, rectangle, ellipse, image, icon, path, component, instance, toggle, checkbox, radio, select, chart, skeleton, status-bar, home-indicator, nav-bar, tab-bar, button, list-row, sheet, link, text-input, nav-item, tabs, tree-row, menu-row, property-row, divider, tooltip, popover, menu, modal, toast, drawer +Properties: fill, gradient, stroke, strokeWidth, strokeStyle, borderTop, borderRight, borderBottom, borderLeft, cornerRadius, width, height, minWidth, minHeight, maxWidth, layout ("horizontal"|"vertical"|"grid"), gap (0 = flush, never flagged as off-scale), rowGap, gridColumns, gridColumn, gridRow, padding, alignItems, justifyContent, fontSize, fontFamily, fontWeight, color, content, textAlign, lineHeight, letterSpacing (px), textDecoration, textTransform ("uppercase" etc. — don't bake casing into content), textOverflow ("ellipsis" — designed single-line truncation for labels that must survive hostile-length content; canvas_stress reports clips behind it as info, not warnings), tabularNums (fixed-width digits so number columns align — table scaffolds and chart ticks carry it by default), fontVariationSettings (variable-font axes, e.g. '"wght" 650'), src, objectFit, opacity, shadow, shadows (plural wins — a \`shadow\` written where \`shadows\` is set is ignored, and the op result carries a warning saying so), blur, backdropBlur, backdropFilter, overflow, wrap, position ("absolute"|"relative"|"fixed"|"sticky"), x, y, bottom, right, icon, iconSize, iconColor, iconStyle, checked, disabled, value, pulse, d, viewBox, strokeLinecap, strokeLinejoin, strokeDasharray, animation, transition (object, or the string "$motion." referencing a motion token), kind, series, segments, innerRatio, centerValue, centerLabel, sparkKind, xDomain, yDomain, curve, gridlines, xLabels, yLabels, componentId, overrides, safeArea ({ top, bottom }, document root only — insets the renderer adds to the root's top/bottom padding; canvas_create type "mobile" writes the device's), responsive, and the mobile primitives' props: time, appearance, title, subtitle, leading, trailing, largeTitle, items, variant, fab, label, iconPosition, size, divider, detent, grabber, secondaryColor, badgeColor, and the desktop-app primitives' props: ariaLabel, external, links, count, dotColor, active, depth, collapsed, expanded, shortcut, destructive, submenu, labelWidth, placeholder, rows, error, orientation, inset, and the overlays' props: text, anchor, closeLabel, actions, tone, action, scrim Charts: { type: "chart", kind: "line"|"bar"|"donut"|"sparkline", series: [{ data: [210, 450, 648], stroke: "$accent", strokeDasharray?: "6 4", area?, points?, highlight?: [2] (a lone index 2 works too; null clears it; an entry that isn't an index into data renders no emphasis and the op result warns), barGradient? }], yDomain?: [0, 2700], curve?: "smooth", gridlines?: 4, xLabels?: ["Jan", ..., "Dec"] (spread evenly; one per bar on a bar chart centres each under its bar; tick labels keep their size at any chart width, so width: "100%" is safe; an x label wider than its slot (its bar, or halfway to the nearest labelled tick) truncates with an ellipsis, so on a narrow chart keep labels short and leave line-chart ticks empty ("") to give them room), yLabels? } — the node does ALL the value→coordinate math (multi-series in one node; x = data index, a shorter series stops early against a longer one; domains auto from data, bars floor at 0). Dash the projected/forecast series, solid the actuals; highlight: [i] renders those bars solid over muted siblings (the selected-day treatment) and barGradient fades the muted bars inside the SVG. DONUT: kind "donut" + segments: [{ value, color: "$chart-1", label? }] + innerRatio? + centerValue/centerLabel — data-bound slices from 12 o\'clock clockwise, center figure rendered tabular; compose the legend yourself from frames + $chart-* dots. SPARKLINE: kind "sparkline" (+ sparkKind "bar"|"line") — axis-free mini-trend for KPI cards, latest point emphasized by default (override with series.highlight). NEVER hand-compute path d-strings, absolutely-position tick labels, fake a donut with conic gradients, or hand-place sparkline bars. @@ -602,6 +603,15 @@ Desktop-app primitives (application screens — canvas_create type "desktop-app" 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). +Overlays (screen states — put one in a state variant made with canvas_add_variant, e.g. "menu-open", "comment-open", "confirm-delete", "toast"): wherever you insert an overlay in the tree, it renders in ONE overlay layer above all content — never clipped by a scrolling or clipping pane, never under a sticky or fixed bar — stacked by kind, never by a z-index (there is none): popover and menu 400, the modal's scrim 500, modal and drawer 510, toast 600, tooltip 800 (so a menu authored inside a modal renders under it). x / y are offsets from the ROOT's top-left (root coordinates), not from the parent; the layer is the artboard box. Insert it wherever it belongs logically (a menu beside the button that opens it) and set anchor: "" (read by rules, never rendered). Colours default from $bg-surface / $border / $text-primary / $text-secondary and $elevation.overlay depth; fill / stroke / color override. + - tooltip { text, x, y } — inverted ($text-primary fill), wraps at 240px; text only, never children. + - popover { x, y, size?: "xs"|"sm"|"md"|"lg" (192/320/480/640, default 320) or width, children } — a panel (vertical, padding 12 by default; layout / gap / padding apply as on a frame): a comment box, a filter form. + - menu { x, y, children: menu-row and divider nodes } — padding 4, at least 192 wide, hugs its rows. + - modal { title, size?: "sm"|"md"|"lg" (480/640/960, default md), actions?: [{ label, variant? }], closeLabel?, children } — centred over its own full scrim (x / y place its top-left instead); a header with the title and a close button named "Close" (closeLabel renames it); the body holds the children (vertical, gap 12) and scrolls when tall; actions render right-aligned as 32px buttons, an action with no variant as "secondary", the filled ones ("primary", "destructive") rightmost. A modal is a region of its own for the primary-count and wayfinding rules. + - toast { text, tone?: "neutral"|"success"|"warning"|"danger", action?: { label } } — bottom-centre, 24px above the artboard's bottom edge (x / y place it); the tone colours a leading glyph, the text stays $text-primary. + - drawer { size?: "sm"|"md" (320/480) or width, scrim?: false, children } — pinned to the right edge, full height, padding 16; scrim: true dims what is behind it. +A modal's close button and actions and a toast's action are pointer targets (32 / 32 / 24 tall). snapshot_layout lists every overlay under the root, and a modal (or a drawer with a scrim) carries its scrim's rect. + Responsive layout (author desktop-first, adapt down): - responsive: "stack" — on a horizontal container, flips to vertical below 768px (multi-column layouts that should stack on mobile) - responsive: "wrap" — children wrap to the next line instead of overflowing (card grids, tag rows) @@ -892,7 +902,7 @@ server.tool( // --- snapshot_layout --- server.tool( 'snapshot_layout', - 'Get computed bounding boxes for all nodes by rendering the canvas in a browser. Returns { nodeId, x, y, width, height } for each node — plus, on any node whose content exceeds its box, overflow data: scrollWidth/clientWidth/scrollHeight/clientHeight and an ellipsis flag when a designed text-overflow truncation is active (the same capture canvas_stress uses to detect clipping). On a primitive: truncated: true when one of its own labels is cut by its ellipsis, and labels ([{ chars, scrollWidth, clientWidth }], one per own label, in order) on every tabs node and on any primitive with a cut label.', + 'Get computed bounding boxes for all nodes by rendering the canvas in a browser. Returns { nodeId, x, y, width, height } for each node — plus, on any node whose content exceeds its box, overflow data: scrollWidth/clientWidth/scrollHeight/clientHeight and an ellipsis flag when a designed text-overflow truncation is active (the same capture canvas_stress uses to detect clipping). On a primitive: truncated: true when one of its own labels is cut by its ellipsis, and labels ([{ chars, scrollWidth, clientWidth }], one per own label, in order) on every tabs node and on any primitive with a cut label. Overlays (tooltip, popover, menu, modal, toast, drawer) render in a layer after the root: from the root they are listed as the root\'s last children wherever they sit in the tree, at root coordinates; a modal (or a drawer with scrim: true) also carries scrim: { x, y, width, height }, the rect its scrim covers. A nodeId inside an overlay walks that overlay.', { canvasId: z.string().describe('Canvas ID'), nodeId: z.string().optional().describe('Root node ID to start from'), diff --git a/src/primitives.ts b/src/primitives.ts index cb8eae8..de53fc9 100644 --- a/src/primitives.ts +++ b/src/primitives.ts @@ -51,6 +51,59 @@ export const CONTROL_OWNERS = new Set(['property-row', 'nav-item', 'menu-row', ' /** The desktop-app primitives — on a canvas that never declared desktop-app, * their presence asks for a declaration (desktop-app-artboard). */ export const DESKTOP_APP_PRIMITIVES = new Set(['nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row']); +// Phase 31 slice E — overlays. The renderer lifts them into one layer after +// the content; the layer order is fixed by kind (Atlassian's ladder). +export const OVERLAY_TYPES = new Set(['tooltip', 'popover', 'menu', 'modal', 'toast', 'drawer']); +export const OVERLAY_Z = { popover: 400, menu: 400, scrim: 500, modal: 510, drawer: 510, toast: 600, tooltip: 800 } as const; +export const TOOLTIP_MAX_WIDTH = 240; +export const MENU_MIN_WIDTH = 192; +export const POPOVER_WIDTH = { xs: 192, sm: 320, md: 480, lg: 640 } as const; +export const MODAL_WIDTH = { sm: 480, md: 640, lg: 960 } as const; +export const DRAWER_WIDTH = { sm: 320, md: 480 } as const; +/** The modal's header close button and its actions (sm buttons), and a + * toast's action (an xs button). */ +export const MODAL_CONTROL = 32; +export const TOAST_ACTION = 24; + +/** A modal's width: a numeric width, else its size (default md). */ +export function modalWidth(n: SceneNode): number { + return isNum(n.width) ? n.width : MODAL_WIDTH[n.size === 'sm' || n.size === 'lg' ? n.size : 'md']; +} + +/** A popover's width: a numeric width, else its size (default sm). */ +export function popoverWidth(n: SceneNode): number { + return isNum(n.width) ? n.width : POPOVER_WIDTH[n.size === 'xs' || n.size === 'md' || n.size === 'lg' ? n.size : 'sm']; +} + +/** A drawer's width: a numeric width, else its size (default sm). */ +export function drawerWidth(n: SceneNode): number { + return isNum(n.width) ? n.width : DRAWER_WIDTH[n.size === 'md' ? 'md' : 'sm']; +} + +/** A modal's actions that render (a blank label is skipped), in rendered + * order: the non-filled ones (no variant renders secondary) as authored, then + * the filled ones (primary, destructive), so the filled action is rightmost. */ +export function modalActions(n: SceneNode): Array[number]> { + const all = Array.isArray(n.actions) ? n.actions.filter((a) => !!a && typeof a === 'object' && hasText(a.label)) : []; + const filled = (a: { variant?: string }) => a.variant === 'primary' || a.variant === 'destructive'; + return [...all.filter((a) => !filled(a)), ...all.filter(filled)]; +} + +/** The pointer targets an overlay renders under its own node id: a modal's + * close button and actions, a toast's action. */ +export function overlayTargets(n: SceneNode): Array<{ what: string; w?: number; h: number; disabled: boolean }> { + if (n.type === 'modal') { + return [ + { what: 'modal close button', w: MODAL_CONTROL, h: MODAL_CONTROL, disabled: false }, + ...modalActions(n).map((a) => ({ what: `modal action "${String(a.label).trim()}"`, h: MODAL_CONTROL, disabled: false })), + ]; + } + if (n.type === 'toast' && n.action && typeof n.action === 'object' && hasText(n.action.label)) { + return [{ what: `toast action "${String(n.action.label).trim()}"`, h: TOAST_ACTION, disabled: false }]; + } + return []; +} + /** Chrome a pinned position reserves room for, and the edge it pins to. */ export const CHROME_EDGE: Record = { 'status-bar': 'top', 'home-indicator': 'bottom', 'tab-bar': 'bottom' }; @@ -59,10 +112,12 @@ const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFin /** A label prop that renders: a non-blank string or a finite number. */ const hasText = (v: unknown): boolean => (typeof v === 'string' && v.trim() !== '') || isNum(v); -/** A node's position as rendered: pinned chrome defaults to `fixed`, and a - * sheet is always `fixed`. */ +/** A node's position as rendered: pinned chrome defaults to `fixed`, a + * sheet is always `fixed`, and an overlay is `absolute` in the overlay layer. */ export function effectivePosition(n: SceneNode): SceneNode['position'] { if (n.type === 'sheet') return 'fixed'; // always an overlay; its position prop is ignored + // Phase 31 slice E — lifted into the overlay layer, out of flow. + if (OVERLAY_TYPES.has(n.type)) return 'absolute'; return n.position ?? (Object.hasOwn(CHROME_EDGE, n.type) ? 'fixed' : undefined); } diff --git a/src/renderer.ts b/src/renderer.ts index 512850e..e56bf0b 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -7,6 +7,7 @@ import { buttonHeight, chromeHeight, chromeReservation, effectivePosition, listRowMinHeight, navBarHeight, rootInsets, LINK_MIN_HEIGHT, LINK_ICON, LINK_EXTERNAL, NAV_ITEM_HEIGHT, TABS_HEIGHT, TREE_ROW_HEIGHT, TREE_INDENT, MENU_ROW_HEIGHT, PROPERTY_ROW_HEIGHT, PROPERTY_LABEL_WIDTH, tabsItems, textInputHeight, textInputRows, + OVERLAY_TYPES, OVERLAY_Z, TOOLTIP_MAX_WIDTH, MENU_MIN_WIDTH, drawerWidth, modalActions, modalWidth, popoverWidth, } from './primitives.js'; /** Build a `background: …` declaration from a node's `gradient`. @@ -96,6 +97,9 @@ interface RenderCtx { rootChild?: boolean; /** Rendering a direct child of a sheet, whose panel scrolls: it never shrinks. */ sheetChild?: boolean; + /** Phase 31 slice E — overlays met while rendering, lifted into the overlay + * layer after the content (shared by every derived context). */ + overlays: SceneNode[]; } export function renderToHtml(root: SceneNode, width = 1440, height = 900, canvas?: Canvas, opts?: RenderOptions): string { @@ -103,8 +107,9 @@ export function renderToHtml(root: SceneNode, width = 1440, height = 900, canvas const expand = (n: SceneNode) => (n.type === 'instance' && n.componentId && canvas ? resolveInstance(n, canvas) ?? n : n); const columnWidth = Math.min(typeof root.width === 'number' ? root.width : width, width); const designWidth = typeof root.width === 'number' && root.width > 0 ? root.width : DESIGN_WIDTH; - const rc: RenderCtx = { canvas, registered, bodyWidth: width, columnWidth, insets: rootInsets(root), reservation: chromeReservation(root, expand), designWidth }; - const body = renderNode(root, rc); + const overlays: SceneNode[] = []; + const rc: RenderCtx = { canvas, registered, bodyWidth: width, columnWidth, insets: rootInsets(root), reservation: chromeReservation(root, expand), designWidth, overlays }; + const body = renderNode(root, rc) + overlayLayer(rc, height); const responsiveCss = buildRendererStylesheet(root, canvas); // Phase 24 slice B — the pulse keyframes exist ONLY when the caller opts in // (the live viewer). Without them the fs-skeleton class is inert, so every @@ -138,7 +143,7 @@ ${preconnect} @@ -596,6 +601,12 @@ function renderNode(node: SceneNode, rc: RenderCtx): string { if (resolved) return renderNode(resolved, rc); } + // Phase 31 slice E — an overlay renders in the overlay layer, not here. + if (OVERLAY_TYPES.has(node.type)) { + rc.overlays.push(node); + return ''; + } + // Phase 30 slice D — mobile primitives: fixed anatomy, own builders. const primitive = renderPrimitive(node, rc); if (primitive !== undefined) return primitive; @@ -1477,6 +1488,164 @@ function renderDivider(node: SceneNode, rc: RenderCtx, attrs: string): string { return `
`; } +// ── Phase 31 slice E — the overlay layer ──────────────────────────────────── +// Overlays never render where they sit in the tree: renderNode collects them +// and the layer renders them after the content, so a menu authored inside a +// sticky bar or a scrolling pane is never clipped or out-stacked. The layer is +// the artboard box at the root's origin; authored x / y are offsets from the +// root's top-left. The layer has no z-index, so each overlay's own (fixed by +// kind) stacks it above every content layer (fixed 10, sticky 5, sheet 30). + +const SCRIM_COLOR = 'rgba(0, 0, 0, 0.4)'; +const OVERLAY_SHADOW = '0 8px 10px -4px rgba(15, 23, 42, 0.06), 0 20px 25px -5px rgba(15, 23, 42, 0.14)'; +const TONE_ICON = { neutral: 'info', success: 'circle-check', warning: 'triangle-alert', danger: 'circle-alert' } as const; +const TONE_FALLBACK = { neutral: FALLBACK.secondary, success: '#16A34A', warning: '#D97706', danger: FALLBACK.danger } as const; + +function overlayLayer(rc: RenderCtx, height: number): string { + if (!rc.overlays.length) return ''; + const layerRc: RenderCtx = { ...rc, rootChild: false, sheetChild: false }; + let html = ''; + // Rendering an overlay's children can collect nested overlays: they join the + // queue and render as members of the layer too. + for (let i = 0; i < rc.overlays.length; i++) html += renderOverlay(rc.overlays[i], layerRc); + const box = css(['position: absolute', 'left: 0', 'top: 0', 'width: 100%', `max-width: ${rc.columnWidth}px`, `height: ${height}px`, 'pointer-events: none']); + return `\n
${html}
`; +} + +const num = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); + +/** Authored x / y in root coordinates (each defaults to 0). */ +function placedAt(node: SceneNode): string[] { + return [`left: ${num(node.x) ? node.x : 0}px`, `top: ${num(node.y) ? node.y : 0}px`]; +} + +function overlayShadow(node: SceneNode): string { + return boxShadowCss(node.shadows, node.shadow) ?? OVERLAY_SHADOW; +} + +function radiusOf(node: SceneNode, fallback: number): number { + return typeof node.cornerRadius === 'number' ? node.cornerRadius : fallback; +} + +function scrimHtml(node: SceneNode): string { + return `
`; +} + +function renderOverlay(node: SceneNode, rc: RenderCtx): string { + const dataAttr = ` data-node-id="${node.id}" data-fs-overlay="${node.type}"`; + switch (node.type) { + case 'tooltip': return renderTooltip(node, `${dataAttr} data-fs-primitive role="tooltip"`); + case 'modal': return renderModal(node, rc, `${dataAttr} data-fs-primitive role="dialog" aria-modal="true"`); + case 'toast': return renderToast(node, rc, `${dataAttr} data-fs-primitive role="${node.tone === 'danger' ? 'alert' : 'status'}"`); + default: return renderOverlayContainer(node, rc, dataAttr); + } +} + +function renderTooltip(node: SceneNode, attrs: string): string { + const box = css([ + 'position: absolute', ...placedAt(node), `z-index: ${OVERLAY_Z.tooltip}`, 'pointer-events: auto', 'box-sizing: border-box', + 'width: max-content', `max-width: ${TOOLTIP_MAX_WIDTH}px`, 'padding: 4px 8px', `border-radius: ${radiusOf(node, 4)}px`, + `background-color: ${node.fill ?? FALLBACK.text}`, `color: ${node.color ?? FALLBACK.surface}`, + 'font-size: 12px', 'line-height: 16px', 'overflow-wrap: anywhere', `box-shadow: ${overlayShadow(node)}`, + node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ]); + // Text only: a tooltip's children never render (slice F warns on them). + return `${escapeHtml(text(node.text))}`; +} + +/** popover / menu / drawer: containers whose children render with the usual + * layout props; only the placement and the defaults are the overlay's. */ +function renderOverlayContainer(node: SceneNode, rc: RenderCtx, attrs: string): string { + const drawer = node.type === 'drawer'; + const menu = node.type === 'menu'; + const width = drawer ? drawerWidth(node) : node.type === 'popover' ? popoverWidth(node) : num(node.width) ? node.width : undefined; + const layout: SceneNode = { + ...node, position: undefined, x: undefined, y: undefined, right: undefined, bottom: undefined, + width, height: drawer ? undefined : node.height, layout: node.layout ?? 'vertical', + padding: node.padding ?? (menu ? 4 : drawer ? 16 : 12), + stroke: drawer ? undefined : node.stroke ?? FALLBACK.border, fill: node.fill ?? FALLBACK.surface, + cornerRadius: node.cornerRadius ?? (drawer ? 0 : 8), + }; + const box = css([ + buildStyles(layout, rc), 'position: absolute', 'box-sizing: border-box', 'pointer-events: auto', + `z-index: ${OVERLAY_Z[drawer ? 'drawer' : menu ? 'menu' : 'popover']}`, + ...(drawer ? ['top: 0', 'bottom: 0', 'right: 0', 'overflow-y: auto', `border-left: 1px solid ${node.stroke ?? FALLBACK.border}`] : placedAt(node)), + menu && width === undefined ? 'width: max-content' : undefined, + menu ? `min-width: ${MENU_MIN_WIDTH}px` : undefined, + `box-shadow: ${overlayShadow(node)}`, + ]); + const role = menu ? ' role="menu"' : ' role="dialog"'; + const scrim = drawer && node.scrim === true ? scrimHtml(node) : ''; + return `${scrim}${renderChildren(node, rc)}`; +} + +/** A modal action's colours: its own, else what a button of that variant + * draws. No variant renders secondary. */ +function actionButton(node: SceneNode, a: NonNullable[number]): SceneNode { + const variant = a.variant ?? 'secondary'; + const filled = variant === 'primary' || variant === 'destructive'; + const fill = a.fill ?? (filled ? (variant === 'destructive' ? FALLBACK.danger : FALLBACK.accent) : 'transparent'); + const stroke = a.stroke ?? (variant === 'secondary' ? node.stroke ?? FALLBACK.border : undefined); + return { + id: node.id, type: 'button', size: 'sm', label: String(a.label).trim(), variant, maxWidth: 240, fill, + color: a.color ?? (filled ? '#FFFFFF' : variant === 'ghost' ? FALLBACK.accent : node.color ?? FALLBACK.text), + ...(stroke ? { stroke } : {}), + }; +} + +function renderModal(node: SceneNode, rc: RenderCtx, attrs: string): string { + const title = text(node.title); + if (title) attrs += ` aria-label="${escapeAttr(title)}"`; + const placed = num(node.x) || num(node.y); + const box = css([ + 'position: absolute', `z-index: ${OVERLAY_Z.modal}`, 'pointer-events: auto', 'box-sizing: border-box', + 'display: flex', 'flex-direction: column', `width: ${modalWidth(node)}px`, 'max-width: calc(100% - 32px)', 'max-height: calc(100% - 64px)', + ...(placed ? placedAt(node) : ['inset: 0', 'margin: auto', 'height: fit-content']), + `background-color: ${node.fill ?? FALLBACK.surface}`, `border: 1px solid ${node.stroke ?? FALLBACK.border}`, + `border-radius: ${radiusOf(node, 12)}px`, `box-shadow: ${overlayShadow(node)}`, `color: ${node.color ?? FALLBACK.text}`, 'overflow: hidden', + node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ]); + const close = renderButton({ + id: node.id, type: 'button', size: 'sm', icon: 'x', variant: 'ghost', fill: 'transparent', + color: node.secondaryColor ?? FALLBACK.secondary, ariaLabel: text(node.closeLabel) || 'Close', + }, rc, ' tabindex="0" data-focusable data-fs-modal-close'); + const header = `
${title ? titledLabel(title, 'font-size: 16px; font-weight: 600; line-height: 24px') : ''}
${close}
`; + const actions = modalActions(node); + const [pt, pr, pb, pl] = node.padding !== undefined ? paddingCss(node.padding) : ['8px', '20px', actions.length ? '8px' : '20px', '20px']; + // data-fs-slot: the layout walker steps through it, so the body's nodes are placed. + const body = `
${renderChildren(node, rc)}
`; + const footer = actions.length + ? `
${actions.map((a) => renderButton(actionButton(node, a), rc, ' tabindex="0" data-focusable')).join('')}
` + : ''; + return `${scrimHtml(node)}${header}${body}${footer}`; +} + +function renderToast(node: SceneNode, rc: RenderCtx, attrs: string): string { + const tone = node.tone === 'success' || node.tone === 'warning' || node.tone === 'danger' ? node.tone : 'neutral'; + const placed = num(node.x) || num(node.y); + const label = node.action && typeof node.action === 'object' ? text(node.action.label) : ''; + const box = css([ + 'position: absolute', `z-index: ${OVERLAY_Z.toast}`, 'pointer-events: auto', 'box-sizing: border-box', + ...(placed ? placedAt(node) : ['left: 0', 'right: 0', 'bottom: 24px', 'margin: 0 auto']), + 'width: max-content', 'max-width: min(480px, calc(100% - 32px))', 'min-height: 40px', + 'display: flex', 'align-items: center', 'gap: 10px', label ? 'padding: 8px 8px 8px 12px' : 'padding: 8px 12px', + `background-color: ${node.fill ?? FALLBACK.surface}`, `border: 1px solid ${node.stroke ?? FALLBACK.border}`, + `border-radius: ${radiusOf(node, 8)}px`, `box-shadow: ${overlayShadow(node)}`, `color: ${node.color ?? FALLBACK.text}`, + 'font-size: 14px', 'line-height: 20px', + node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, + ]); + const glyph = `${iconHtml(TONE_ICON[tone], 16, node.iconColor ?? TONE_FALLBACK[tone])}`; + const message = `${escapeHtml(text(node.text))}`; + const action = label + ? renderButton({ id: node.id, type: 'button', size: 'xs', label, variant: 'ghost', fill: 'transparent', color: node.action?.color ?? FALLBACK.accent, maxWidth: 160 }, rc, ' tabindex="0" data-focusable') + : ''; + return `${glyph}${message}${action}`; +} + /** The four authored padding sides as CSS (fluid like every padding). */ function paddingCss(padding: SceneNode['padding']): [string, string, string, string] { const px = (v: unknown) => (typeof v === 'number' ? responsivePadding(v) : '0px'); diff --git a/src/screenshot.ts b/src/screenshot.ts index d61ebd5..4e40fd1 100644 --- a/src/screenshot.ts +++ b/src/screenshot.ts @@ -174,6 +174,8 @@ export interface LayoutRect { /** Phase 30 slice D — a `data-fs-scroll` element (a sheet panel): its * vertical overflow scrolls, it is not a clip. */ scrolls?: boolean; + /** Phase 31 slice E — a modal's (or a drawer's) scrim, as rendered. */ + scrim?: { x: number; y: number; width: number; height: number }; children?: LayoutRect[]; } @@ -210,6 +212,13 @@ const LAYOUT_WALKER_SOURCE = `(function (rootId, depth) { if (own.length > 0 && (result.truncated || el.getAttribute('role') === 'tablist')) result.labels = own; } if (el.hasAttribute('data-fs-scroll')) result.scrolls = true; + if (el.hasAttribute('data-fs-overlay')) { + var scrim = document.querySelector('[data-fs-scrim="' + nodeId + '"]'); + if (scrim) { + var sr = scrim.getBoundingClientRect(); + result.scrim = { x: Math.round(sr.x), y: Math.round(sr.y), width: Math.round(sr.width), height: Math.round(sr.height) }; + } + } if (currentDepth < depth) { var childRects = []; collect(el, currentDepth + 1, childRects); @@ -231,7 +240,16 @@ const LAYOUT_WALKER_SOURCE = `(function (rootId, depth) { var root = document.querySelector(rootSelector); if (!root) return []; var result = getRect(root, 0); - return result ? [result] : []; + if (!result) return []; + // Phase 31 slice E — overlays render in a layer after the root; from the + // document root they are placed as the root's children (root coordinates). + var layer = document.querySelector('[data-fs-overlay-layer]'); + if (layer && depth > 0 && root === document.body.firstElementChild) { + var overlays = []; + collect(layer, 1, overlays); + if (overlays.length > 0) result.children = (result.children || []).concat(overlays); + } + return [result]; })`; export async function computeLayout(html: string, rootNodeId?: string, maxDepth = 10, viewport?: { width: number; height: number }): Promise { diff --git a/src/stress.ts b/src/stress.ts index 17871c9..573b4a2 100644 --- a/src/stress.ts +++ b/src/stress.ts @@ -60,6 +60,12 @@ export const PRIMITIVE_TEXT_PROPS: { type: string; path: string; fixed?: boolean { type: 'menu-row', path: 'shortcut' }, { type: 'property-row', path: 'label' }, { type: 'text-input', path: 'value' }, + // Phase 31 slice E — overlays. + { type: 'tooltip', path: 'text' }, + { type: 'toast', path: 'text' }, + { type: 'toast', path: 'action.label' }, + { type: 'modal', path: 'title' }, + { type: 'modal', path: 'actions[].label' }, ]; /** One perturbable string: a text node's content or a primitive's prop. */ diff --git a/src/types.ts b/src/types.ts index bfc86e4..3bac742 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,7 +12,11 @@ export type NodeType = 'frame' | 'text' | 'rectangle' | 'ellipse' | 'image' | 'i | 'status-bar' | 'home-indicator' | 'nav-bar' | 'tab-bar' | 'button' | 'list-row' | 'sheet' // Phase 31 slice B — desktop-app vocabulary: links, inputs, navigation, // menus and inspector rows (each carries its own hit area), and a hairline. - | 'link' | 'text-input' | 'nav-item' | 'tabs' | 'tree-row' | 'menu-row' | 'property-row' | 'divider'; + | 'link' | 'text-input' | 'nav-item' | 'tabs' | 'tree-row' | 'menu-row' | 'property-row' | 'divider' + // Phase 31 slice E — overlays: lifted out of the tree into one layer after + // the content, stacked by kind (popover/menu, scrim, modal/drawer, toast, + // tooltip), positioned by authored x/y in root coordinates. + | 'tooltip' | 'popover' | 'menu' | 'modal' | 'toast' | 'drawer'; /** Phase 30 slice D — one `nav-bar` action: an icon or a text label. */ export interface NavAction { icon?: string; label?: string } @@ -24,6 +28,14 @@ export interface TabItem { icon: string; label: string; active?: boolean; badge? * it has no icon). */ export interface TabsItem { label: string; count?: string | number; active?: boolean; disabled?: boolean } +/** Phase 31 slice E — one `modal` action. No variant renders "secondary"; + * the filled ones (primary, destructive) render rightmost. Colours default by + * variant as a button's do; explicit ones win. */ +export interface ModalAction { label: string; variant?: 'primary' | 'secondary' | 'ghost' | 'destructive'; fill?: string; color?: string; stroke?: string } + +/** Phase 31 slice E — a `toast`'s action (a ghost text button). */ +export interface ToastAction { label: string; color?: string } + /** Phase 31 slice B — an inline link inside a `text` node's content: * character offsets [start, end). */ export interface TextLink { start: number; end: number } @@ -290,7 +302,7 @@ export interface SceneNode { /** status-bar / home-indicator: "dark" glyphs for a light screen, "light" * for a dark one; absent follows `color` ($text-primary). */ appearance?: 'dark' | 'light'; - /** nav-bar / list-row title; on a `text` node (Phase 31) the tooltip, rendered as the title attribute. */ + /** nav-bar / list-row / modal title; on a `text` node (Phase 31) the tooltip, rendered as the title attribute. */ title?: string; /** list-row secondary line. */ subtitle?: string; @@ -310,7 +322,9 @@ export interface SceneNode { /** button label. */ label?: string; iconPosition?: 'leading' | 'trailing'; - /** button: xs 24 / sm 32 / md 44 / lg 52; tabs and text-input: sm 32 / md 40. */ + /** button: xs 24 / sm 32 / md 44 / lg 52; tabs and text-input: sm 32 / md 40; + * modal: sm 480 / md 640 / lg 960; popover: xs 192 / sm 320 / md 480 / lg 640; + * drawer: sm 320 / md 480. */ size?: 'xs' | 'sm' | 'md' | 'lg'; /** list-row: a hairline under the row from the 16px inset. */ divider?: boolean; @@ -362,6 +376,23 @@ export interface SceneNode { /** divider: inset from both ends (px). */ inset?: number; + // Phase 31 slice E — overlays. + /** tooltip / toast: the message. */ + text?: string; + /** Any overlay: the id of the node that opens it. Read by rules, never + * rendered (overlays are positioned by x/y). */ + anchor?: string; + /** modal: the header close button's accessible name (default "Close"). */ + closeLabel?: string; + /** modal: the footer actions, right-aligned, the filled one rightmost. */ + actions?: ModalAction[]; + /** toast: neutral (default) | success | warning | danger. */ + tone?: 'neutral' | 'success' | 'warning' | 'danger'; + /** toast: one action, a ghost text button. */ + action?: ToastAction; + /** drawer: a scrim behind it (default false; a modal always has one). */ + scrim?: boolean; + // Component / Instance componentId?: string; overrides?: Record>; diff --git a/src/variables.ts b/src/variables.ts index 3b15d2e..d6ddabc 100644 --- a/src/variables.ts +++ b/src/variables.ts @@ -83,6 +83,17 @@ function deepResolve(node: SceneNode, variables: DesignVariables): SceneNode { } } } + // Phase 31 slice E — a modal's actions and a toast's action carry colours. + const tokenIn = (obj: Record, key: string) => { + const value = obj[key]; + if (typeof value !== 'string' || !value.startsWith('$')) return; + const resolved = lookupToken(value.slice(1), variables); + if (resolved !== undefined) obj[key] = resolved; + }; + if (Array.isArray(node.actions)) { + for (const a of node.actions) if (a && typeof a === 'object') for (const k of ['fill', 'color', 'stroke']) tokenIn(a as unknown as Record, k); + } + if (node.action && typeof node.action === 'object') tokenIn(node.action as unknown as Record, 'color'); // Phase 28 slice B — donut segments carry their own colors ($chart-* refs). if (Array.isArray(node.segments)) { for (const s of node.segments) { @@ -155,6 +166,7 @@ function applyControlDefaults(node: SceneNode, v: DesignVariables): void { const PRIMITIVES = new Set([ 'status-bar', 'home-indicator', 'nav-bar', 'tab-bar', 'button', 'list-row', 'sheet', 'link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row', 'divider', + 'tooltip', 'popover', 'menu', 'modal', 'toast', 'drawer', ]); function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { @@ -210,6 +222,48 @@ function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { case 'divider': set('stroke', border); break; + // Phase 31 slice E — overlays: a surface panel at overlay depth. + case 'tooltip': + // Inverted, so it reads against whatever it floats over. + set('fill', text); + set('color', surface); + if (node.cornerRadius === undefined) node.cornerRadius = 4; + setOverlayShadow(node, v); + break; + case 'popover': + case 'menu': + case 'modal': + case 'toast': + case 'drawer': { + set('fill', surface); + set('stroke', border); + set('color', text); + set('secondaryColor', secondary); + if (node.cornerRadius === undefined) { + node.cornerRadius = node.type === 'modal' ? v.radius?.['radius-lg'] ?? 12 : node.type === 'drawer' ? 0 : v.radius?.['radius-md'] ?? 8; + } + setOverlayShadow(node, v); + if (node.type === 'toast') { + const tone = node.tone; + set('iconColor', tone === 'success' ? c.success ?? '#16A34A' : tone === 'warning' ? c.warning ?? '#D97706' : tone === 'danger' ? danger : secondary); + if (node.action && typeof node.action === 'object' && node.action.color === undefined) node.action.color = accent; + } + if (node.type === 'modal' && Array.isArray(node.actions)) { + for (const a of node.actions) { + if (!a || typeof a !== 'object') continue; + const variant = a.variant ?? 'secondary'; + if (variant === 'primary' || variant === 'destructive') { + if (a.fill === undefined) a.fill = variant === 'destructive' ? danger : accent; + if (a.color === undefined) a.color = onFill(a.fill); + } else { + if (a.fill === undefined) a.fill = 'transparent'; + if (a.color === undefined) a.color = variant === 'ghost' ? accent : text; + if (variant === 'secondary' && a.stroke === undefined) a.stroke = border; + } + } + } + break; + } case 'status-bar': case 'home-indicator': set('color', text); @@ -255,6 +309,15 @@ function applyPrimitiveDefaults(node: SceneNode, v: DesignVariables): void { } } +/** An overlay's depth: the design system's `$elevation.overlay` when it has + * one; an explicit shadow or shadows win. (Without the token the renderer + * draws its own fallback shadow.) */ +function setOverlayShadow(node: SceneNode, v: DesignVariables): void { + if (node.shadows !== undefined || node.shadow !== undefined) return; + const overlay = v.elevation?.overlay; + if (Array.isArray(overlay) && overlay.length) node.shadows = structuredClone(overlay); +} + /** * An opaque colour as [r, g, b]: #RGB, #RRGGBB(AA), rgb()/rgba() and hsl()/hsla(), * alpha ignored. Named colours return undefined. (evaluate.ts has its own diff --git a/test-overlays-render.ts b/test-overlays-render.ts new file mode 100644 index 0000000..a7398d6 --- /dev/null +++ b/test-overlays-render.ts @@ -0,0 +1,200 @@ +// Phase 31 slice E — overlays as rendered (Chrome): the layer stacks every +// overlay above content whatever its authored parent (a sticky bar, a fixed +// bar, a scrolling or clipping pane, an animated ancestor), in the ladder's +// order whatever the tree order; nothing is clipped by its authored parent; a +// md modal is 640 wide and centred with a scrim over the viewport (FR-E2's +// acceptance through snapshot_layout's walker); the walker places overlays +// from the document root and from inside an overlay; the detailed overlap +// check skips them; a full-page capture keeps them; long copy stays inside +// the overlays; both themes. +// +// Usage: npx tsx test-overlays-render.ts + +import './test-env.js'; +import { computeLayout, withPage, takeScreenshot, shutdown, type LayoutRect } from './src/screenshot.js'; +import { renderToHtml } from './src/renderer.js'; +import { resolveVariables } from './src/variables.js'; +import { evaluateCanvas } from './src/evaluate.js'; +import { applyPerturbation, compareLayouts } from './src/stress.js'; +import { generateDesignSystem } from './src/design-language.js'; +import type { Canvas, DesignVariables, SceneNode } from './src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +function canvasOf(children: SceneNode[], variables: DesignVariables = {}, root: Partial = {}): Canvas { + return { + id: 'c', name: 'c', projectId: 'p', components: {}, variables, createdAt: '', lastModified: '', + root: { id: 'document', type: 'document', name: 'D', width: 1440, height: 900, fill: '$bg-primary', layout: 'vertical', children, ...root }, + metadata: { surface: { type: 'desktop-app', device: 'window-1440' } }, + } as Canvas; +} +const htmlOf = (c: Canvas, theme?: 'light' | 'dark', w = 1440, h = 900) => renderToHtml(resolveVariables(c.root, c.variables, { theme }), w, h, c); +function flat(rects: LayoutRect[], out = new Map()): Map { + for (const r of rects) { out.set(r.nodeId, r); if (r.children) flat(r.children, out); } + return out; +} +/** The node id of the topmost element at each point. */ +async function topAt(html: string, points: Array<[number, number]>, w = 1440, h = 900): Promise { + return withPage(async (page) => { + await page.setViewport({ width: w, height: h }); + await page.setContent(html, { waitUntil: 'load' }); + return page.evaluate((pts: Array<[number, number]>) => pts.map(([x, y]) => { + const el = document.elementFromPoint(x, y); + const owner = el?.closest('[data-node-id],[data-fs-scrim]'); + return owner?.getAttribute('data-node-id') ?? (owner?.hasAttribute('data-fs-scrim') ? `scrim:${owner.getAttribute('data-fs-scrim')}` : 'none'); + }), points); + }); +} + +const tech = generateDesignSystem('#2563EB', 'technical').variables; + +// ── FR-E1's acceptance: a menu inside a sticky toolbar inside a scrolling +// pane renders above a fixed sibling and is not clipped by the pane. ────────── +{ + const children: SceneNode[] = [ + { id: 'pane', name: 'pane', type: 'frame', overflow: 'auto', height: 200, width: 600, fill: '$bg-surface', children: [ + { id: 'bar', name: 'bar', type: 'frame', position: 'sticky', height: 40, layout: 'horizontal', fill: '$bg-surface', children: [ + { id: 'menu', name: 'menu', type: 'menu', x: 20, y: 150, children: [ + { id: 'r1', name: 'r1', type: 'menu-row', label: 'Rename' }, + { id: 'r2', name: 'r2', type: 'menu-row', label: 'Duplicate' }, + { id: 'r3', name: 'r3', type: 'menu-row', label: 'Delete', destructive: true }, + ] }, + ] }, + { id: 'filler', name: 'filler', type: 'frame', height: 600 }, + ] }, + { id: 'fixed', name: 'fixed', type: 'frame', position: 'fixed', x: 0, y: 140, width: 400, height: 200, fill: '#FDE68A' }, + { id: 'clip', name: 'clip', type: 'frame', overflow: 'hidden', height: 40, width: 100, animation: { name: 'slideUp' }, children: [ + { id: 'pop', name: 'pop', type: 'popover', x: 700, y: 400, children: [{ id: 'pt', name: 'pt', type: 'text', content: 'Popover body', fontSize: 14 }] }, + ] }, + ]; + for (const theme of ['light', 'dark'] as const) { + const html = htmlOf(canvasOf(children, tech), theme); + const rects = flat(await computeLayout(html, undefined, 25, { width: 1440, height: 900 })); + const menu = rects.get('menu'); + check(`${theme}: the menu is placed at its root coordinates`, menu?.x === 20 && menu?.y === 150, JSON.stringify(menu && { x: menu.x, y: menu.y })); + const r3 = rects.get('r3'); + check(`${theme}: the menu's last row extends past the 200px pane, unclipped`, !!r3 && r3.y + r3.height > 200); + const top = await topAt(html, [[60, 170], [60, (r3?.y ?? 0) + 16], [720, 420]]); + check(`${theme}: the menu is above the fixed sibling`, top[0] === 'r1' || top[0] === 'menu', top[0]); + check(`${theme}: the menu's last row is hit-testable below the pane`, top[1] === 'r3', top[1]); + check(`${theme}: a popover inside a clipping, animated frame is visible`, top[2] === 'pop' || top[2] === 'pt', top[2]); + } + // Twin: the same menu as a plain frame stays clipped by its pane. + const frameTwin = htmlOf(canvasOf([{ ...children[0], children: [{ ...(children[0].children![0]), children: [{ id: 'menu', name: 'menu', type: 'frame', position: 'absolute', x: 20, y: 150, width: 192, height: 100, fill: '#FFFFFF' }] }, children[0].children![1]] }, children[1]], tech)); + const twinTop = await topAt(frameTwin, [[60, 260]]); + check('twin: an absolute frame in the same place is clipped by the pane (the fixed bar shows)', twinTop[0] !== 'menu', twinTop[0]); +} + +// ── The ladder, whatever the tree order ───────────────────────────────────── +{ + // Tree order is reversed against the ladder: tooltip first, menu last. + const children: SceneNode[] = [ + { id: 'tip', name: 'tip', type: 'tooltip', text: 'Tooltip on top', x: 640, y: 420 }, + { id: 'toast', name: 'toast', type: 'toast', text: 'A toast over the modal', x: 600, y: 480 }, + { id: 'm', name: 'm', type: 'modal', title: 'Modal', actions: [{ label: 'OK', variant: 'primary' }], children: [{ id: 'mt', name: 'mt', type: 'text', content: 'Body', fontSize: 14 }] }, + { id: 'menu', name: 'menu', type: 'menu', x: 20, y: 20, children: [{ id: 'r1', name: 'r1', type: 'menu-row', label: 'Under the scrim' }] }, + { id: 'content', name: 'content', type: 'frame', position: 'fixed', x: 1200, y: 20, width: 200, height: 100, fill: '#FDE68A' }, + ]; + const html = htmlOf(canvasOf(children, tech)); + const rects = flat(await computeLayout(html, undefined, 25, { width: 1440, height: 900 })); + const m = rects.get('m')!; + const tip = rects.get('tip')!; + const toast = rects.get('toast')!; + const [atTip, atToast, atModal, atMenu, atContent] = await topAt(html, [ + [tip.x + 4, tip.y + 4], [toast.x + 8, toast.y + toast.height - 6], [m.x + 8, m.y + m.height - 8], [40, 30], [1300, 60], + ]); + check('tooltip above modal', atTip === 'tip', atTip); + check('toast above modal', atToast === 'toast', atToast); + check('modal above its scrim', atModal === 'm', atModal); + check('scrim above the menu', atMenu === 'scrim:m', atMenu); + check('scrim above fixed content', atContent === 'scrim:m', atContent); + check('FR-E2: a md modal is 640 wide and centred', m.width === 640 && Math.abs(m.x + m.width / 2 - 720) <= 1 && Math.abs(m.y + m.height / 2 - 450) <= 1, JSON.stringify({ x: m.x, y: m.y, w: m.width, h: m.height })); + check('FR-E2: its scrim covers the viewport', JSON.stringify(m.scrim) === JSON.stringify({ x: 0, y: 0, width: 1440, height: 900 }), JSON.stringify(m.scrim)); + check('the modal body is placed through its slot', rects.has('mt') && rects.get('mt')!.y > m.y && rects.get('mt')!.y < m.y + m.height); + check('twin: a rect without a scrim records none', rects.get('menu')!.scrim === undefined); + // Toast default: bottom-centre, 24 above the artboard's bottom. + const t2 = flat(await computeLayout(htmlOf(canvasOf([{ id: 't', name: 't', type: 'toast', text: 'Saved' }], tech)), undefined, 25, { width: 1440, height: 900 })).get('t')!; + check('toast: bottom-centre by default', Math.abs(t2.x + t2.width / 2 - 720) <= 1 && t2.y + t2.height === 876, JSON.stringify(t2)); + // Drawer: pinned right, full height. + const d = flat(await computeLayout(htmlOf(canvasOf([{ id: 'd', name: 'd', type: 'drawer', size: 'md', scrim: true, children: [{ id: 'dt', name: 'dt', type: 'text', content: 'Filters' }] }], tech)), undefined, 25, { width: 1440, height: 900 })).get('d')!; + check('drawer: right edge, full height, 480 wide, with its scrim', d.x === 960 && d.y === 0 && d.width === 480 && d.height === 900 && d.scrim?.width === 1440, JSON.stringify(d)); +} + +// ── The walker: from a node inside an overlay; with a narrower root ───────── +{ + const html = htmlOf(canvasOf([{ id: 'pop', name: 'pop', type: 'popover', x: 100, y: 100, children: [{ id: 'pt', name: 'pt', type: 'text', content: 'Inside' }] }], tech)); + const sub = await computeLayout(html, 'pop', 5, { width: 1440, height: 900 }); + check('computeLayout(rootNodeId inside the layer) walks that overlay', sub[0]?.nodeId === 'pop' && sub[0].children?.[0]?.nodeId === 'pt'); + const full = await computeLayout(html, 'document', 5, { width: 1440, height: 900 }); + check('computeLayout(the root\'s own id) still places overlays', full[0]?.children?.some((c) => c.nodeId === 'pop') === true); + const depth0 = await computeLayout(html, undefined, 0, { width: 1440, height: 900 }); + check('twin: depth 0 places no children', !depth0[0]?.children); + // A root narrower than the capture: root coordinates follow the root. + const narrow = canvasOf([{ id: 'tip', name: 'tip', type: 'tooltip', text: 'x', x: 10, y: 10 }], tech, { width: 1000 }); + const rects = flat(await computeLayout(htmlOf(narrow), undefined, 5, { width: 1440, height: 900 })); + const rootRect = rects.get('document')!; + check('narrow root: x / y are offsets from the root\'s top-left', rects.get('tip')!.x === rootRect.x + 10 && rects.get('tip')!.y === rootRect.y + 10, JSON.stringify({ root: rootRect.x, tip: rects.get('tip')!.x })); +} + +// ── Detailed evaluate: the overlap check skips overlays ───────────────────── +{ + const bar = (extra: SceneNode[]): Canvas => canvasOf([ + { id: 'bar', name: 'bar', type: 'frame', layout: 'horizontal', height: 48, gap: 8, padding: 8, children: [ + { id: 'b1', name: 'b1', type: 'button', label: 'File', variant: 'ghost', size: 'sm' }, + { id: 'b2', name: 'b2', type: 'button', label: 'Edit', variant: 'ghost', size: 'sm' }, + ...extra, + ] }, + ], tech); + const overlapOf = async (c: Canvas) => (await evaluateCanvas(c, { mode: 'detailed', categories: ['consistency'] })).issues.filter((i) => /overlaps with/.test(i.message)); + const withMenu = await overlapOf(bar([{ id: 'menu', name: 'menu', type: 'menu', x: 8, y: 20, children: [{ id: 'r1', name: 'r1', type: 'menu-row', label: 'Open' }] }])); + check('a menu over its toolbar siblings is not an overlap error', withMenu.length === 0, withMenu.map((i) => i.message).join(' | ')); + const grid = await overlapOf(canvasOf([{ id: 'g', name: 'g', type: 'frame', layout: 'grid', gridColumns: 1, children: [ + { id: 'ga', name: 'ga', type: 'frame', height: 40, gridRow: '1 / 2', gridColumn: '1 / 2', fill: '#EEEEEE' }, + { id: 'gb', name: 'gb', type: 'frame', height: 40, gridRow: '1 / 2', gridColumn: '1 / 2', fill: '#DDDDDD' }, + ] }], tech)); + check('twin: two in-flow frames on one grid cell still overlap', grid.length === 1, String(grid.length)); +} + +// ── Full-page capture keeps the layer ─────────────────────────────────────── +{ + const tall = canvasOf([ + { id: 'long', name: 'long', type: 'frame', height: 1800, fill: '$bg-surface' }, + { id: 'tip', name: 'tip', type: 'tooltip', text: 'Far down', x: 100, y: 1500 }, + ], tech, {}); + const html = htmlOf(tall); + const shotArtboard = await takeScreenshot(html, { width: 1440, height: 900, scale: 1 }); + const shotFull = await takeScreenshot(html, { width: 1440, height: 900, scale: 1, fullPage: true }); + const pngHeight = (b64: string) => Buffer.from(b64, 'base64').readUInt32BE(20); + check('full page grows to the content and still renders', pngHeight(shotFull) >= 1800 && pngHeight(shotArtboard) === 900, `${pngHeight(shotFull)} / ${pngHeight(shotArtboard)}`); + const rects = flat(await computeLayout(html, undefined, 5, { width: 1440, height: 900 })); + check('a tooltip below the artboard sits at its document y', rects.get('tip')?.y === 1500); +} + +// ── Stress: long copy stays inside the overlays ───────────────────────────── +{ + const root = canvasOf([ + { id: 'm', name: 'm', type: 'modal', size: 'sm', title: 'Delete canvas?', actions: [{ label: 'Cancel' }, { label: 'Delete', variant: 'destructive' }], children: [{ id: 'mt', name: 'mt', type: 'text', content: 'This cannot be undone.', fontSize: 14 }] }, + { id: 'tip', name: 'tip', type: 'tooltip', text: 'Copy link', x: 40, y: 40 }, + { id: 'toast', name: 'toast', type: 'toast', text: 'Canvas archived', action: { label: 'Undo' } }, + { id: 'menu', name: 'menu', type: 'menu', x: 900, y: 40, children: [{ id: 'r1', name: 'r1', type: 'menu-row', label: 'Rename', shortcut: 'F2' }] }, + ], tech, {}).root; + const resolve = (r: SceneNode) => resolveVariables(r, tech); + const baseline = await computeLayout(renderToHtml(resolve(root), 1440, 900), undefined, 25, { width: 1440, height: 900 }); + for (const name of ['long-text', 'i18n'] as const) { + const { root: pert, touched } = applyPerturbation(name, root, { type: 'desktop-app' }); + const after = await computeLayout(renderToHtml(resolve(pert), 1440, 900), undefined, 25, { width: 1440, height: 900 }); + const warnings = compareLayouts(baseline, after, touched, 1440).filter((f) => f.severity === 'warning'); + check(`${name}: no clip or overflow warnings on the overlays`, warnings.length === 0, JSON.stringify(warnings.slice(0, 4))); + const r = flat(after); + check(`${name}: the tooltip wraps within 240`, (r.get('tip')?.width ?? 999) <= 240); + check(`${name}: the toast stays within the artboard`, (r.get('toast')?.x ?? -1) >= 0 && (r.get('toast')!.x + r.get('toast')!.width) <= 1440); + } +} + +await shutdown(); +console.log(allPass ? '\nAll checks passed.' : '\nSome checks FAILED.'); +process.exit(allPass ? 0 : 1); diff --git a/test-overlays.ts b/test-overlays.ts new file mode 100644 index 0000000..26ea850 --- /dev/null +++ b/test-overlays.ts @@ -0,0 +1,272 @@ +// Phase 31 slice E — overlays without Chrome: the six overlay types are lifted +// out of the tree into one layer after the content (nested ones too, and ones +// inside instances), a canvas without overlays renders no layer, the layer +// ladder's z-indexes by kind, colours default from tokens (and fall back +// unthemed), modal actions render with the filled one rightmost, the deferred +// rule clauses (FR-C9's overlay clause, modal/drawer panes, a modal's primary +// action, the overlay targets in the 24px census), stress reaches the overlay +// copy, and FR-E3: an overlay state variant is listed and never demanded. +// Rendered geometry and stacking live in test-overlays-render.ts (Chrome). +// +// Usage: npx tsx test-overlays.ts + +import './test-env.js'; +import { evaluateCanvas } from './src/evaluate.js'; +import { renderToHtml } from './src/renderer.js'; +import { resolveVariables } from './src/variables.js'; +import { applyPerturbation } from './src/stress.js'; +import { createCanvas, addVariant, listCanvases, getCanvas } from './src/scene-graph.js'; +import { OVERLAY_TYPES, OVERLAY_Z, effectivePosition, modalActions, modalWidth, overlayTargets, popoverWidth, drawerWidth } from './src/primitives.js'; +import { checkCurrent, checkPrimaryCount } from './src/desktop-app-rules.js'; +import { WINDOW_PROFILES } from './src/surfaces.js'; +import type { Canvas, SceneNode } from './src/types.js'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +type Surface = { type: 'web' | 'mobile' | 'desktop-app'; device?: string }; +const app: Surface = { type: 'desktop-app', device: 'window-1440' }; +function canvasWith(children: SceneNode[], surface?: Surface, colors?: Record, components: Record = {}): Canvas { + return { + id: 'c', name: 'c', projectId: 'p', components, createdAt: '', lastModified: '', + variables: colors ? { colors } : {}, + root: { id: 'document', type: 'document', name: 'Document', width: 1440, height: 900, fill: '#FFFFFF', layout: 'vertical', padding: 24, gap: 8, children }, + ...(surface ? { metadata: { surface } } : {}), + } as Canvas; +} +const htmlOf = (c: Canvas, theme?: 'light' | 'dark') => renderToHtml(resolveVariables(c.root, c.variables, { theme }), 1440, 900, c); +const layerOf = (html: string) => { + const at = html.indexOf('
0; +} +const contentOf = (html: string) => { + const at = html.indexOf('
= {}): SceneNode => ({ + id: 'm', name: 'Confirm', type: 'modal', title: 'Delete canvas?', + actions: [{ label: 'Delete', variant: 'destructive' }, { label: 'Cancel' }], + children: [{ id: 'mt', name: 'mt', type: 'text', content: 'This cannot be undone.', fontSize: 14 }], ...extra, +}); + +// ── K1: the layer ─────────────────────────────────────────────────────────── +{ + const plain = htmlOf(canvasWith([{ id: 'b', name: 'b', type: 'button', label: 'Save' }], app)); + check('no overlay: no layer and no body position', !plain.includes('data-fs-overlay-layer') && !plain.includes('body { position: relative; }')); + const withOne = htmlOf(canvasWith([{ id: 'b', name: 'b', type: 'button', label: 'Save' }, { id: 'tip', name: 'tip', type: 'tooltip', text: 'Saves now', x: 10, y: 20 }], app)); + check('twin: an overlay adds the layer and body position', withOne.includes('data-fs-overlay-layer') && withOne.includes('body { position: relative; }')); + check('the overlay is lifted out of the content', !contentOf(withOne).includes('data-node-id="tip"') && layerOf(withOne).includes('data-node-id="tip"')); + check('the button stays in the content', contentOf(withOne).includes('data-node-id="b"') && !layerOf(withOne).includes('data-node-id="b"')); + check('authored x / y are root coordinates', /data-node-id="tip"[^>]*style="[^"]*left: 10px; top: 20px/.test(withOne)); + check('the layer is the artboard box', /data-fs-overlay-layer style="position: absolute; left: 0; top: 0; width: 100%; max-width: 1440px; height: 900px; pointer-events: none"/.test(withOne)); + + // Every kind, each nested somewhere awkward: a sticky bar, a fixed bar, a + // scrolling and a clipping pane, an animated ancestor, another overlay. + const deep = canvasWith([ + { id: 'sticky', name: 'sticky', type: 'frame', position: 'sticky', height: 48, children: [ + { id: 'menu', name: 'menu', type: 'menu', x: 16, y: 44, children: [{ id: 'r1', name: 'r1', type: 'menu-row', label: 'Rename' }] }, + ] }, + { id: 'fixed', name: 'fixed', type: 'frame', position: 'fixed', height: 40, children: [{ id: 'tip', name: 'tip', type: 'tooltip', text: 'Hi' }] }, + { id: 'scroll', name: 'scroll', type: 'frame', overflow: 'auto', height: 200, children: [ + { id: 'pop', name: 'pop', type: 'popover', x: 100, y: 100, children: [{ id: 'inner-tip', name: 'inner-tip', type: 'tooltip', text: 'Nested' }] }, + ] }, + { id: 'clip', name: 'clip', type: 'frame', overflow: 'hidden', height: 100, animation: { name: 'slideUp' }, children: [{ id: 'toast', name: 'toast', type: 'toast', text: 'Saved' }] }, + { id: 'drawer', name: 'drawer', type: 'drawer', scrim: true, children: [modal()] }, + ], app); + const html = htmlOf(deep); + const layer = layerOf(html); + const lifted = ['menu', 'tip', 'pop', 'inner-tip', 'toast', 'drawer', 'm']; + check('every overlay renders in the layer, nested ones too', lifted.every((id) => layer.includes(`data-node-id="${id}"`)), lifted.filter((id) => !layer.includes(`data-node-id="${id}"`)).join(',')); + check('no overlay renders in the content', lifted.every((id) => !contentOf(html).includes(`data-node-id="${id}"`))); + check('each overlay renders exactly once', lifted.every((id) => html.split(`data-node-id="${id}"`).length === 2)); + check('a menu\'s rows render inside it', /data-node-id="menu"[^]*data-node-id="r1"/.test(layer)); + check('a nested tooltip is its own layer member, not inside the popover', !inside(layer, 'pop', 'inner-tip') && !inside(html, 'sticky', 'menu') && !inside(html, 'scroll', 'pop')); + check('twin: the menu\'s row is inside the menu', inside(layer, 'menu', 'r1')); + const z = (id: string) => Number(new RegExp(`data-node-id="${id}"[^>]*z-index: (\\d+)`).exec(layer)?.[1]); + check('the ladder: menu/popover 400, modal/drawer 510, toast 600, tooltip 800', + z('menu') === 400 && z('pop') === 400 && z('m') === 510 && z('drawer') === 510 && z('toast') === 600 && z('tip') === 800, + ['menu', 'pop', 'm', 'drawer', 'toast', 'tip'].map((id) => `${id}=${z(id)}`).join(' ')); + check('scrims at 500 (modal always, drawer with scrim)', /data-fs-scrim="m"[^>]*z-index: 500/.test(layer) && /data-fs-scrim="drawer"[^>]*z-index: 500/.test(layer)); + const noScrim = layerOf(htmlOf(canvasWith([{ id: 'drawer', name: 'drawer', type: 'drawer' }], app))); + check('twin: a drawer without scrim draws none', !noScrim.includes('data-fs-scrim')); + check('OVERLAY_Z matches the spec ladder', OVERLAY_Z.popover === 400 && OVERLAY_Z.menu === 400 && OVERLAY_Z.scrim === 500 && OVERLAY_Z.modal === 510 && OVERLAY_Z.drawer === 510 && OVERLAY_Z.toast === 600 && OVERLAY_Z.tooltip === 800); + check('an overlay ignores its own position prop', !/data-node-id="tip"[^>]*position: fixed/.test(htmlOf(canvasWith([{ id: 'tip', name: 'tip', type: 'tooltip', text: 'x', position: 'fixed', right: 4 } as SceneNode], app)))); + check('effectivePosition: overlays are absolute', [...OVERLAY_TYPES].every((t) => effectivePosition({ id: 'x', type: t as SceneNode['type'], position: 'fixed' }) === 'absolute')); + check('twin: a frame keeps its position', effectivePosition({ id: 'x', type: 'frame', position: 'fixed' }) === 'fixed'); + + // An overlay inside a component instance is lifted from the expanded tree. + const comp: SceneNode = { id: 'card', name: 'Card', type: 'component', children: [{ id: 'ctip', name: 'ctip', type: 'tooltip', text: 'From a component', x: 5, y: 5 }] }; + const inst = htmlOf(canvasWith([{ id: 'i1', name: 'i1', type: 'instance', componentId: 'card' }], app, undefined, { card: comp })); + check('an overlay inside an instance renders in the layer', layerOf(inst).includes('From a component') && !contentOf(inst).includes('From a component')); + + // Render never depends on type. + const types = (['web', 'mobile', 'desktop-app'] as const).map((type) => htmlOf(canvasWith([modal()], { type }))); + check('the layer renders the same on every type', types[0] === types[1] && types[1] === types[2]); + + // A root narrower than the capture width: the layer takes the root's column. + const narrow = canvasWith([{ id: 'tip', name: 'tip', type: 'tooltip', text: 'x' }], app); + narrow.root.width = 1100; + check('the layer is capped at the root\'s column', layerOf(renderToHtml(narrow.root, 1440, 900, narrow)).includes('max-width: 1100px')); +} + +// ── K3: anatomy ───────────────────────────────────────────────────────────── +{ + const layer = layerOf(htmlOf(canvasWith([modal()], app))); + const order = [...layer.matchAll(/]*>([^<]*)<\/span>/g)].map((m) => m[1]); + check('modal actions: the filled action is rightmost', order.indexOf('Cancel') >= 0 && order.indexOf('Cancel') < order.indexOf('Delete'), order.join(' | ')); + const ordered = modalActions(modal({ actions: [{ label: 'Save', variant: 'primary' }, { label: 'Discard', variant: 'ghost' }, { label: 'Later' }, { label: ' ' }] })); + check('modalActions: non-filled first in authored order, filled last, blanks skipped', ordered.map((a) => a.label).join(',') === 'Discard,Later,Save'); + check('modal close button: named "Close" by default', /data-fs-modal-close[^>]*aria-label="Close"/.test(layer)); + check('closeLabel names it', /data-fs-modal-close[^>]*aria-label="Dismiss"/.test(layerOf(htmlOf(canvasWith([modal({ closeLabel: 'Dismiss' })], app))))); + check('modal: role dialog, aria-modal, labelled by its title', /role="dialog" aria-modal="true" aria-label="Delete canvas\?"/.test(layer)); + check('modal: centred unless placed', /data-node-id="m"[^>]*inset: 0; margin: auto/.test(layer)); + check('twin: a placed modal is not centred', !/data-node-id="m"[^>]*inset: 0; margin: auto/.test(layerOf(htmlOf(canvasWith([modal({ x: 40, y: 60 })], app))))); + check('modal widths: sm 480 / md 640 / lg 960 / numeric wins', modalWidth({ id: 'a', type: 'modal', size: 'sm' }) === 480 && modalWidth({ id: 'a', type: 'modal' }) === 640 && modalWidth({ id: 'a', type: 'modal', size: 'lg' }) === 960 && modalWidth({ id: 'a', type: 'modal', width: 500 }) === 500); + check('popover widths: default 320, xs 192, numeric wins', popoverWidth({ id: 'a', type: 'popover' }) === 320 && popoverWidth({ id: 'a', type: 'popover', size: 'xs' }) === 192 && popoverWidth({ id: 'a', type: 'popover', width: 250 }) === 250); + check('drawer widths: default 320, md 480', drawerWidth({ id: 'a', type: 'drawer' }) === 320 && drawerWidth({ id: 'a', type: 'drawer', size: 'md' }) === 480); + check('modal body is a walkable slot', /data-fs-slot[^>]*>[^]*data-node-id="mt"/.test(layer)); + const tipKids = layerOf(htmlOf(canvasWith([{ id: 'tip', name: 'tip', type: 'tooltip', text: 'Hint', children: [{ id: 'kid', name: 'kid', type: 'text', content: 'Child text' }] }], app))); + check('a tooltip renders its text and never its children', tipKids.includes('Hint') && !tipKids.includes('Child text')); + const menu = layerOf(htmlOf(canvasWith([{ id: 'menu', name: 'menu', type: 'menu', children: [{ id: 'r', name: 'r', type: 'menu-row', label: 'Open' }] }], app))); + check('menu: role menu, min width 192, hugs its content', /role="menu"/.test(menu) && /min-width: 192px/.test(menu) && /width: max-content/.test(menu)); + const toastDanger = layerOf(htmlOf(canvasWith([{ id: 't', name: 't', type: 'toast', text: 'Failed', tone: 'danger' }], app))); + const toastOk = layerOf(htmlOf(canvasWith([{ id: 't', name: 't', type: 'toast', text: 'Saved', tone: 'success', action: { label: 'Undo' } }], app))); + check('toast: danger is role alert, others role status', /role="alert"/.test(toastDanger) && /role="status"/.test(toastOk) && !/role="alert"/.test(toastOk)); + check('toast: bottom-centre by default', /bottom: 24px; margin: 0 auto/.test(toastOk)); + check('toast: the action renders as a focusable button', /tabindex="0" data-focusable[^>]*>[^]*Undo/.test(toastOk)); +} + +// ── K4: defaults ──────────────────────────────────────────────────────────── +{ + const themed = resolveVariables(canvasWith([ + modal({ actions: [{ label: 'Delete', variant: 'destructive' }, { label: 'Keep', variant: 'primary' }, { label: 'Cancel' }, { label: 'Help', variant: 'ghost' }] }), + { id: 'tip', name: 'tip', type: 'tooltip', text: 'x' }, + { id: 'toast', name: 'toast', type: 'toast', text: 'x', tone: 'warning', action: { label: 'Undo' } }, + { id: 'pop', name: 'pop', type: 'popover' }, + ], app, TOKENS).root, { colors: TOKENS, elevation: { overlay: [{ x: 0, y: 4, blur: 8, color: 'rgba(0,0,0,0.2)' }] } }); + const byId = (id: string) => themed.children!.find((n) => n.id === id)!; + const m = byId('m'); + check('modal: surface, border, text from tokens', m.fill === TOKENS['bg-surface'] && m.stroke === TOKENS.border && m.color === TOKENS['text-primary']); + check('modal: radius-lg fallback 12', m.cornerRadius === 12); + const acts = Object.fromEntries((m.actions ?? []).map((a) => [a.label, a])); + check('destructive action: $danger fill', acts.Delete.fill === TOKENS.danger); + check('primary action: $accent fill', acts.Keep.fill === TOKENS.accent); + check('no-variant action: transparent, text colour, border', acts.Cancel.fill === 'transparent' && acts.Cancel.color === TOKENS['text-primary'] && acts.Cancel.stroke === TOKENS.border); + check('ghost action: accent text, no border', acts.Help.color === TOKENS.accent && acts.Help.stroke === undefined); + check('overlay shadow from $elevation.overlay', JSON.stringify(m.shadows) === JSON.stringify([{ x: 0, y: 4, blur: 8, color: 'rgba(0,0,0,0.2)' }])); + const tip = byId('tip'); + check('tooltip inverts: text-primary fill, surface text', tip.fill === TOKENS['text-primary'] && tip.color === TOKENS['bg-surface']); + const toast = byId('toast'); + check('toast: tone colours the glyph; action takes the accent', toast.iconColor === TOKENS.warning && toast.action?.color === TOKENS.accent); + check('popover: radius-md fallback 8', byId('pop').cornerRadius === 8); + const explicit = resolveVariables(canvasWith([modal({ fill: '#000000', actions: [{ label: 'Go', variant: 'primary', fill: '$danger' }] })], app, TOKENS).root, { colors: TOKENS }); + check('explicit fill wins; $token refs inside actions resolve', explicit.children![0].fill === '#000000' && explicit.children![0].actions![0].fill === TOKENS.danger); + const noElevation = resolveVariables(canvasWith([modal()], app, TOKENS).root, { colors: TOKENS }); + check('without $elevation.overlay no shadows are set (renderer fallback)', noElevation.children![0].shadows === undefined); + // Unthemed and inside a component (which skips resolveVariables): neutral fallbacks, never invisible. + const unthemed = layerOf(renderToHtml(canvasWith([modal(), { id: 'tip', name: 'tip', type: 'tooltip', text: 'x' }]).root, 1440, 900)); + check('unthemed modal: white surface, grey border, dark text', /data-node-id="m"[^>]*background-color: #FFFFFF; border: 1px solid #D1D5DB/.test(unthemed)); + check('unthemed tooltip: dark fill, light text', /data-node-id="tip"[^>]*background-color: #111827; color: #FFFFFF/.test(unthemed)); + check('unthemed destructive action: red fill', /background-color: #DC2626/.test(unthemed)); + check('unthemed overlay: fallback shadow', /data-node-id="m"[^>]*box-shadow: 0 8px 10px/.test(unthemed)); + const dark = htmlOf(canvasWith([modal()], app, TOKENS), 'dark'); + check('dark theme renders without throwing', dark.includes('data-node-id="m"')); +} + +// ── K5: the deferred clauses ──────────────────────────────────────────────── +{ + const art = async (children: SceneNode[], surface?: Surface) => (await evaluateCanvas(canvasWith(children, surface), { mode: 'fast', categories: ['structure'] })).issues.filter((i) => i.rule === 'desktop-app-artboard'); + const overlayOnly: SceneNode[] = [modal()]; + const undeclared = await art(overlayOnly); + check('FR-C9: undeclared + overlay warns', undeclared.length === 1 && undeclared[0].severity === 'warning' && /an overlay primitive/.test(undeclared[0].message), undeclared.map((i) => i.message).join(' | ')); + check('FR-C9: explicit web + overlay only raises nothing', (await art(overlayOnly, { type: 'web' })).length === 0); + check('FR-C9: explicit mobile + overlay only raises nothing', (await art(overlayOnly, { type: 'mobile', device: 'iphone-390' })).length === 0); + check('FR-C9: desktop-app + overlay raises nothing', (await art(overlayOnly, app)).length === 0); + check('twin: undeclared without any overlay or app primitive raises nothing', (await art([{ id: 'b', name: 'b', type: 'button', label: 'Go' }])).length === 0); + const both = await art([{ id: 'nav', name: 'nav', type: 'nav-item', label: 'Home', active: true }, modal()], { type: 'mobile', device: 'iphone-390' }); + check('FR-C9: mobile + nav-item + overlay still warns for the nav-item', both.length === 1 && both[0].nodeId === 'nav'); + const tipOnly = await art([{ id: 'tip', name: 'tip', type: 'tooltip', text: 'x' }]); + check('FR-C9: every overlay kind trips the undeclared case (tooltip)', tipOnly.length === 1); + + const ctxOf = (children: SceneNode[]) => ({ root: canvasWith(children, app).root, profile: WINDOW_PROFILES['window-1440'] }); + const navs = (prefix: string, activeIdx: number): SceneNode[] => [0, 1].map((i) => ({ id: `${prefix}${i}`, name: `${prefix}${i}`, type: 'nav-item', label: `Item ${i}`, ...(i === activeIdx ? { active: true } : {}) })); + const inDrawer = checkCurrent(ctxOf([...navs('a', 0), { id: 'dr', name: 'dr', type: 'drawer', children: navs('b', 0) }])); + check('panes: a drawer\'s nav-items are their own group', inDrawer.length === 0, inDrawer.map((i) => i.message).join(' | ')); + const sameGroup = checkCurrent(ctxOf([...navs('a', 0), { id: 'fr', name: 'fr', type: 'frame', children: navs('b', 0) }])); + check('twin: the same items in a plain frame share the root\'s group (warns)', sameGroup.length === 1); + const inModal = checkCurrent(ctxOf([...navs('a', 0), modal({ children: navs('b', 0) })])); + check('panes: a modal\'s nav-items are their own group', inModal.length === 0); + + const prim = (children: SceneNode[]) => checkPrimaryCount(ctxOf(children)); + const pageAndModal = prim([{ id: 'save', name: 'save', type: 'button', label: 'Save', variant: 'primary' }, modal({ actions: [{ label: 'Confirm', variant: 'primary' }] })]); + check('FR-C8: one primary on the page and one in a modal\'s actions: silent', pageAndModal.length === 0); + const twoInModal = prim([modal({ actions: [{ label: 'Confirm', variant: 'primary' }], children: [{ id: 'b2', name: 'b2', type: 'button', label: 'Also', variant: 'primary' }] })]); + check('twin: a modal action plus a primary in its body is the info', twoInModal.length === 1 && /modal "Confirm"/.test(twoInModal[0].message), twoInModal.map((i) => i.message).join(' | ')); + const twoActions = prim([modal({ actions: [{ label: 'A', variant: 'primary' }, { label: 'B', variant: 'primary' }] })]); + check('FR-C8: two primary actions in one modal are the info', twoActions.length === 1); + const destructive = prim([modal({ actions: [{ label: 'Delete', variant: 'destructive' }], children: [{ id: 'b3', name: 'b3', type: 'button', label: 'Go', variant: 'primary' }] })]); + check('FR-C8: a destructive action is not a primary', destructive.length === 0); + const inDrawerPrim = prim([{ id: 'p1', name: 'p1', type: 'button', label: 'One' }, { id: 'dr', name: 'dr', type: 'drawer', children: [{ id: 'p2', name: 'p2', type: 'button', label: 'Two' }] }]); + check('panes: a drawer is its own region for primaries', inDrawerPrim.length === 0); + + check('census: modal close + actions, 32 tall', JSON.stringify(overlayTargets(modal()).map((t) => t.h)) === '[32,32,32]'); + check('census: a toast action is 24 tall; no action, no target', overlayTargets({ id: 't', type: 'toast', action: { label: 'Undo' } })[0]?.h === 24 && overlayTargets({ id: 't', type: 'toast' }).length === 0); + const usab = (await evaluateCanvas(canvasWith([modal(), { id: 't', name: 't', type: 'toast', text: 'x', action: { label: 'Undo' } }], app), { mode: 'fast', categories: ['usability'] })).issues; + check('census: overlay targets never fall below the floor', !usab.some((i) => /24px floor/.test(i.message))); + // A frame in a modal body is still judged by FR-C2 (modal is not a clickable primitive). + const hand = (await evaluateCanvas(canvasWith([modal({ children: [{ id: 'hb', name: 'hb', type: 'frame', padding: 4, children: [{ id: 'hi', name: 'hi', type: 'icon', icon: 'x', iconSize: 16 }] }] })], app), { mode: 'fast', categories: ['usability'] })).issues.filter((i) => i.rule === 'desktop-app-handbuilt-target'); + check('FR-C2 still names a hand-built icon frame inside a modal body', hand.length === 1); +} + +// ── K7: stress reaches the overlay copy ───────────────────────────────────── +{ + const root = canvasWith([ + modal(), { id: 'tip', name: 'tip', type: 'tooltip', text: 'Copy link' }, + { id: 'toast', name: 'toast', type: 'toast', text: 'Saved', action: { label: 'Undo' } }, + ], app).root; + const { root: pert, touched } = applyPerturbation('long-text', root, { type: 'desktop-app' }); + const get = (id: string) => pert.children!.find((n) => n.id === id)!; + check('long-text touches modal, tooltip and toast', ['m', 'tip', 'toast'].every((id) => touched.includes(id)), touched.join(',')); + check('modal title and action labels lengthen', get('m').title!.length > 'Delete canvas?'.length && get('m').actions!.every((a) => a.label.length > 6)); + check('tooltip text and toast text + action lengthen', get('tip').text!.length > 'Copy link'.length && get('toast').text!.length > 5 && get('toast').action!.label.length > 4); +} + +// ── K6 / FR-E3: an overlay state is listed and never demanded ─────────────── +{ + const base = createCanvas('Detail', undefined, {}, app); + base.root.children = [{ id: 'body', name: 'body', type: 'text', content: 'Canvas detail' }]; + const { canvas: variant } = addVariant(base.id, 'confirm-delete'); + check('the confirm-delete variant exists', !!getCanvas(variant.id)); + const row = listCanvases().find((r) => r.id === base.id); + check('canvas_list shows it on the base', !!row?.variants?.some((v) => v.state === 'confirm-delete')); + const states = row?.variants?.map((v) => v.state) ?? []; + const r = await evaluateCanvas(getCanvas(base.id)!, { mode: 'fast', designedStates: states }); + check('coverage lists the overlay state', r.coverage?.states.includes('confirm-delete') === true); + check('coverage raises nothing for missing overlay states', !r.issues.some((i) => i.category === 'coverage')); + const none = await evaluateCanvas(getCanvas(base.id)!, { mode: 'fast', designedStates: [] }); + check('twin: without the variant coverage still raises nothing (no demand)', !none.issues.some((i) => i.category === 'coverage') && none.coverage?.missing.length === 0); +} + +console.log(allPass ? '\nAll checks passed.' : '\nSome checks FAILED.'); +process.exit(allPass ? 0 : 1); From 7b64232cc7021083374d94cd31097ca2a26c509f Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sun, 15 Nov 2026 20:33:07 +0100 Subject: [PATCH 3/4] Fix the slice E verify round 1 findings --- README.md | 10 ++-- VISION.md | 1 + docs/GUIDELINES.md | 19 +++++--- docs/specs/PHASE-31-SPEC.md | 2 + src/desktop-app-rules.ts | 9 ++-- src/evaluate.ts | 13 +++-- src/index.ts | 8 +-- src/mobile-rules.ts | 25 +++++++--- src/renderer.ts | 27 +++++++++-- test-overlays-render.ts | 55 +++++++++++++++++++++ test-overlays.ts | 97 ++++++++++++++++++++++++++++++++++++- 11 files changed, 229 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index ef90fac..f2cb894 100644 --- a/README.md +++ b/README.md @@ -208,7 +208,7 @@ Clone a screen into a linked **state variant** — the empty / loading / error v | Param | Type | Description | |-------|------|-------------| | `canvasId` | string | The base canvas (a variant id also works — it resolves to the root base; variants never nest) | -| `state` | string | The state this variant designs — `empty` / `loading` / `error` recommended; free string accepted | +| `state` | string | The state this variant designs — `empty` / `loading` / `error` for data states, `menu-open` / `comment-open` / `confirm-delete` / `toast` for overlay states; free string accepted | Returns `{ canvasId, name, state, of, idMap }` — `idMap` maps every base node id to its clone, so follow-up edits target the right nodes immediately. One canvas per state per base (a duplicate state errors). The viewer shows a screen and its variants as one card with state chips; `canvas_list` rolls designed states onto the base row. @@ -399,7 +399,7 @@ Application screens (`type: "desktop-app"`) are built from eight primitives on t #### Overlays -Six overlays draw screen states: an open menu, a comment popover, a confirm dialog, a toast. Put each in a state variant (`canvas_add_variant` with `menu-open`, `comment-open`, `confirm-delete` or `toast`); coverage lists those states and never demands them. Wherever an overlay sits in the tree, it renders in one layer after the content, so a pane never clips it and a sticky bar never covers it. `x` / `y` are offsets from the root's top-left, not from the parent. Layers are fixed by kind, with no z-index property: `popover` and `menu` 400, the modal's scrim 500, `modal` and `drawer` 510, `toast` 600, `tooltip` 800. `anchor` names the node that opens an overlay, for the rules; it is never rendered. Colours come from `$bg-surface`, `$border`, `$text-primary` and `$text-secondary`, depth from `$elevation.overlay`. +Six overlays draw screen states: an open menu, a comment popover, a confirm dialog, a toast. Put each in a state variant (`canvas_add_variant` with `menu-open`, `comment-open`, `confirm-delete` or `toast`); coverage lists those states and never demands them. Wherever an overlay sits in the tree, it renders in one layer after the content, so a pane never clips it and a sticky bar never covers it. `x` / `y` are offsets from the root's top-left, not from the parent. Layers are fixed by kind, with no z-index property: `popover` and `menu` 400, the modal's scrim 500, `modal` and `drawer` 510, `toast` 600, `tooltip` 800. `anchor` names the node that opens an overlay; it is never rendered (the overlay rules of a later release read it). Colours come from `$bg-surface`, `$border`, `$text-primary` and `$text-secondary`, depth from `$elevation.overlay`. | Type | Key props | What it is | |---|---|---| @@ -411,10 +411,10 @@ Six overlays draw screen states: an open menu, a comment popover, a confirm dial | `drawer` | `size` (`sm` 320 / `md` 480), `scrim`, children | A panel pinned to the right edge at full height | ``` -I(variant, { type: "modal", title: "Delete \"Checkout\"?", actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }] }) +I("document", { type: "modal", title: "Delete \"Checkout\"?", actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }] }) ``` -A modal and a drawer are panes of their own for the wayfinding and primary-count rules; a modal's close button and actions and a toast's action are pointer targets. An undeclared canvas holding an overlay warns until it declares a type (`desktop-app-artboard`); web and mobile canvases may hold overlays freely. +A modal and a drawer are panes of their own for `desktop-app-current` and `desktop-app-primary-count`; a modal's close button and actions and a toast's action are pointer targets. An undeclared canvas holding an overlay warns until it declares a type (`desktop-app-artboard`); web and mobile canvases may hold overlays freely. ### `find_nodes` @@ -506,7 +506,7 @@ Get computed bounding boxes via browser rendering. | `nodeId` | string? | Root node to start from | | `maxDepth` | number? | Max depth (default 10) | -Returns `{ nodeId, x, y, width, height, children? }` per node — plus, on any node whose content exceeds its box, overflow data (`scrollWidth`/`clientWidth`/`scrollHeight`/`clientHeight` and an `ellipsis` flag for designed truncation): the same capture `canvas_stress` uses to detect clipping. On a primitive, `truncated: true` when one of its own labels is cut by its ellipsis, and `labels` (`[{ chars, scrollWidth, clientWidth }]`, one per own label, in order) on every `tabs` node and on any primitive with a cut label. +Returns `{ nodeId, x, y, width, height, children? }` per node — plus, on any node whose content exceeds its box, overflow data (`scrollWidth`/`clientWidth`/`scrollHeight`/`clientHeight` and an `ellipsis` flag for designed truncation): the same capture `canvas_stress` uses to detect clipping. On a primitive, `truncated: true` when one of its own labels is cut by its ellipsis, and `labels` (`[{ chars, scrollWidth, clientWidth }]`, one per own label, in order) on every `tabs` node and on any primitive with a cut label. Overlays (`tooltip`, `popover`, `menu`, `modal`, `toast`, `drawer`) render in a layer after the root: from the root they are listed as its last children wherever they sit in the tree, at root coordinates, and a modal (or a drawer with `scrim: true`) carries `scrim: { x, y, width, height }`, the rect its scrim covers. ### `generate_scale` diff --git a/VISION.md b/VISION.md index 863690f..c8399bb 100644 --- a/VISION.md +++ b/VISION.md @@ -556,6 +556,7 @@ The mobile attempt (2026-09-07) built one iOS screen end to end on v2.2.0 and go All seven slices are merged and the acceptance re-run passed. The phase is closed. - [ ] Follow-up — `link` and `text-input` join the mobile 44px touch census. Phase 31 slice B added both primitives for app screens; on a phone canvas they are not measured today, so a 32px text-input passes silently. +- [ ] Follow-up — overlay controls on a phone. Phase 31 slice E's `modal` close button and actions (32px) and `toast` action (24px) are drawn at fixed pointer sizes and are not in the mobile 44px touch census, so a modal on a phone canvas passes silently; meeting 44px needs a size option on the overlay (render never depends on type), and the census then measures it. Until then the docs send phone dialogs to `sheet`. _Full spec-driven breakdown in [`docs/specs/PHASE-30-SPEC.md`](docs/specs/PHASE-30-SPEC.md). Deliberately out of scope: an Android profile, tablet and other types, a tappable flag on frames, a thumb-reach rule, interaction and flows, mobile import, and mobile commerce archetypes (those come next, on the anatomy/realisation split this phase creates)._ diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index 28ccc77..c6ed552 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -100,7 +100,7 @@ Start an application screen from a desktop-app realisation, not a web page: see ### The 24px floor (web and desktop-app) -On web and desktop-app canvases every pointer target is measured against WCAG 2.5.8's 24px floor: the four controls (toggle, checkbox, radio, select) and the clickable primitives (`button`, `list-row`, each `tab-bar` tab and the FAB, each `nav-bar` action, and the [desktop-app vocabulary](#desktop-app-vocabulary): `link`, `text-input`, `nav-item`, each tab of a `tabs` node, `tree-row`, `menu-row`). Inline text links and `divider`s are not targets. A lone control first grows to its padded row, two levels up, as before, and a control that is the only target directly inside a `property-row`, `nav-item`, `menu-row` or `list-row` (no link, input or button beside it) is measured by that row's box; a disabled target is neither measured nor in anyone's way; nodes inside a component instance are judged as rendered and reported on the instance. What is still below 24px passes only by WCAG's **spacing exception**: a 24px circle centred on it must reach no other target's box and no other undersized target's circle (circles that only touch pass; a target nested inside another is not its neighbour). Spacing needs rendered positions, so: +On web and desktop-app canvases every pointer target is measured against WCAG 2.5.8's 24px floor: the four controls (toggle, checkbox, radio, select) and the clickable primitives (`button`, `list-row`, each `tab-bar` tab and the FAB, each `nav-bar` action, and the [desktop-app vocabulary](#desktop-app-vocabulary): `link`, `text-input`, `nav-item`, each tab of a `tabs` node, `tree-row`, `menu-row`), a modal's close button and actions, and a toast's action. Inline text links and `divider`s are not targets. A lone control first grows to its padded row, two levels up, as before, and a control that is the only target directly inside a `property-row`, `nav-item`, `menu-row` or `list-row` (no link, input or button beside it) is measured by that row's box; a disabled target is neither measured nor in anyone's way; nodes inside a component instance are judged as rendered and reported on the instance. What is still below 24px passes only by WCAG's **spacing exception**: a 24px circle centred on it must reach no other target's box and no other undersized target's circle (circles that only touch pass; a target nested inside another is not its neighbour). Spacing needs rendered positions, so: - **Detailed mode** (`canvas_evaluate({ canvasId, mode: "detailed" })`) runs the circle test and is the authority: a failure is an **error** that names the neighbour it reaches. - **Fast mode** cannot see spacing, so a target below 24px is a **warning** that names the exception and detailed mode. It blocks presenting until you grow the target or a detailed run clears it. @@ -127,22 +127,25 @@ Repeated desktop-app primitives count as component reuse. On an unthemed canvas, An overlay is a **screen state**: the same screen with a menu open, a comment popover up, a confirm dialog or a toast. Design it as a state variant, not on the base screen: `canvas_add_variant({ canvasId, state: "confirm-delete" })` clones the screen, then insert the overlay into the clone. The recommended state names are `menu-open`, `comment-open`, `confirm-delete` and `toast`. Coverage lists every designed state in `coverage.states` and never demands an overlay state: an overlay is a design choice, not a data obligation. -Wherever you insert an overlay in the tree, it renders in **one overlay layer** after the content: a menu authored inside a sticky toolbar or a scrolling pane is never clipped by the pane and never sits under a sticky or fixed bar. So insert it where it belongs logically (a menu beside the button that opens it) and name that node in `anchor` (rules read it; it is never rendered). Three things follow: +Wherever you insert an overlay in the tree, it renders in **one overlay layer** after the content: a menu authored inside a sticky toolbar or a scrolling pane is never clipped by the pane and never sits under a sticky or fixed bar. So insert it where it belongs logically (a menu beside the button that opens it) and set `anchor` to that node's id (it is never rendered; the overlay rules of a later release read it). Four things follow: -- **`x` / `y` are root coordinates**: offsets from the root's top-left, not from the parent. The layer is the artboard box, so a centred modal and a bottom toast sit in the artboard. -- **Layers are fixed by kind**, and there is no `zIndex` property: `popover` and `menu` 400, the modal's scrim 500, `modal` and `drawer` 510, `toast` 600, `tooltip` 800. Everything in the layer sits above all content (`fixed` 10, `sticky` 5, a sheet 30). A menu inside a modal therefore renders under the modal. +- **`x` / `y` are root coordinates**: offsets from the root's top-left, not from the parent. To open a menu under a button, read the button's box with `snapshot_layout` and use its `x` and its `y` plus its height, whatever toolbar it sits in. The layer is the artboard box, so a centred modal and a bottom toast sit in the artboard. +- **Overlays nest freely**: an overlay inside another overlay (a tooltip in a modal, a submenu `menu` in a `menu`) is lifted too and stacks by its own kind, so a tooltip shows above a modal and a menu below it. +- **Layers are fixed by kind**, and there is no `zIndex` property: `popover` and `menu` 400, the scrim of a modal or a drawer 500, `modal` and `drawer` 510, `toast` 600, `tooltip` 800. Everything in the layer sits above all content (`fixed` 10, `sticky` 5, a sheet 30). A menu inside a modal therefore renders under the modal. - **`snapshot_layout` lists every overlay as a child of the root**, at root coordinates, and a modal (or a drawer with a scrim) carries `scrim: { x, y, width, height }`. The detailed overlap check never counts an overlay as overlapping its siblings. The six overlays take their colours from `$bg-surface`, `$border`, `$text-primary` and `$text-secondary`, and their depth from `$elevation.overlay` (a fallback shadow without it); `fill`, `stroke` and `color` override. -- **`tooltip`** `{ text, x, y }` is a short hint, inverted (`$text-primary` fill, `$bg-surface` text), wrapping at 240px. Text only: it never renders children. +- **`tooltip`** `{ text, x, y }` is a short hint, inverted (`$text-primary` fill, `$bg-surface` text, so light on a dark theme), wrapping at 240px. Text only: it never renders children. - **`popover`** `{ x, y, size?: "xs" | "sm" | "md" | "lg", children }` is a panel 192 / 320 / 480 / 640 wide (320 by default; a numeric `width` wins), vertical with 12px padding by default; `layout`, `gap` and `padding` apply as on a frame. A comment box or a filter form. - **`menu`** `{ x, y, children }` holds `menu-row`s and `divider`s: 4px padding, at least 192 wide, hugging its rows. -- **`modal`** `{ title, size?: "sm" | "md" | "lg", actions?: [{ label, variant? }], closeLabel?, children }` is 480 / 640 / 960 wide (640 by default), centred over its own full scrim (`x` / `y` place its top-left instead). Its header holds the title and a close button named "Close" (`closeLabel` renames it). The body holds the children (vertical, 12px gap) and scrolls when tall. `actions` render right-aligned as 32px buttons; an action with no variant renders `secondary`, and the filled ones (`primary`, `destructive`) render rightmost. For a delete confirmation: `actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }]`. -- **`toast`** `{ text, tone?: "neutral" | "success" | "warning" | "danger", action?: { label } }` sits bottom-centre, 24px above the artboard's bottom edge (`x` / `y` place it). The tone colours a leading glyph; the text stays `$text-primary`. `danger` renders `role="alert"`. +- **`modal`** `{ title, size?: "sm" | "md" | "lg", actions?: [{ label, variant? }], closeLabel?, children }` is 480 / 640 / 960 wide (640 by default), centred over its own scrim, which always covers the artboard (`x` / `y` place the modal's top-left instead). It is never taller than the artboard less 64px. Its header holds the title and a close button named "Close" (`closeLabel` renames it). The body holds the children (vertical, 12px gap) and scrolls when tall, between the header and the actions. `actions` render right-aligned as 32px buttons; an action with no variant renders `secondary`, and the filled ones (`primary`, `destructive`) render rightmost. For a delete confirmation: `actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }]`. +- **`toast`** `{ text, tone?: "neutral" | "success" | "warning" | "danger", action?: { label } }` sits bottom-centre, 24px above the artboard's bottom edge (`x` / `y` place its top-left instead); it hugs its text up to 480px. The tone colours a leading glyph (`$success`, `$warning`, `$danger`, neutral `$text-secondary`; `iconColor` overrides); the text stays `$text-primary`. `danger` renders `role="alert"`. - **`drawer`** `{ size?: "sm" | "md", scrim?, children }` is a 320 / 480 panel pinned to the right edge at full height, 16px padding; `scrim: true` dims what is behind it. -A modal's close button and actions (32 tall) and a toast's action (24 tall) are pointer targets. A modal and a drawer are panes: navigation and primary buttons inside them are judged apart from the page behind. +A modal's close button and actions (32 tall) and a toast's action (24 tall) are pointer targets. They are sized for a pointer, so on a phone use a `sheet` for a dialog. A modal and a drawer are panes: navigation and primary buttons inside them are judged apart from the page behind. + +On a canvas whose root declares a `safeArea` or pins a `tab-bar` (a phone), a centred modal, a default toast and a drawer keep clear of them: the modal stays 16px past the insets and pinned chrome, the toast sits 16px above the tab bar or home indicator, and the drawer's padding grows past them, so the safe-area rules skip those three. A popover, a menu, a tooltip, and a modal or toast you place with `x` / `y` are checked like any positioned content. A `fullPage` capture grows the page, but the overlay layer stays the artboard: a scrim dims the first screen only. ### Lists that lead with a mark are not tables (every type) diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 904fd86..1a15a1e 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -300,6 +300,8 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **L3: roles.** `tooltip` renders `role="tooltip"`, `menu` `role="menu"`, `popover` and `drawer` `role="dialog"` (a drawer with a scrim adds `aria-modal`), `modal` `role="dialog" aria-modal="true"` labelled by its title, `toast` `role="status"` (`role="alert"` for danger). - **L4: overlays are not reuse.** `REUSE_PRIMITIVES` (the structure advisory's reuse count) is unchanged: one modal on a screen-state variant is not a repeated component. - **L5: a menu inside a modal renders under it** (400 below 510), as the ladder fixes; the docs say so. Slice F's rules may want to flag it. +- **Verify round 1 fixes** (each loosening proved red on caa66c9 and green on the fix, with its nearest keep-cases unchanged). (a) The halo tell (`gradient-glow`) fired on every overlay of a generated design system, because `$elevation.overlay` is a deep blue-black ink (saturation 0.43, lightness 0.11) at blur 25: a coloured glow now also needs lightness above 0.2, so dark ink of any hue reads as a shadow; indigo, dark red (0.31) and deep violet (0.27) glows and the white bloom still fire. (b) A `menu`'s `menu-row`s counted as desktop-app primitives, so a menu on an explicit web canvas raised FR-C9's info and on mobile its warning, against K5(a): a `menu-row` inside a `menu` now belongs to the overlay; one outside a menu, and any other app primitive inside a menu, still counts. (c) A modal's box stood in for its buttons in the 24px circle test, so a small target near any part of a modal was an error: a modal's targets are never a neighbour (its scrim covers everything outside it); a toast keeps its box, as a tab bar does (slice A D12). (d) On a phone the viewport-anchored overlays ignored the insets: a centred modal now keeps 32px from each edge, or 16px past the root's declared `safeArea` and pinned chrome when larger; a default toast sits 16px above them (else 24); a drawer's padding grows past them. Render still reads only the scene (`root.safeArea` and the pinned chrome's reach). The mobile safe-area walks skip a drawer and an unplaced modal or toast, as they skip a sheet, so a modal body's scrolled-out paragraphs no longer warn; placed overlays are checked, and fast mode now reads an overlay's `y` as root coordinates instead of adding its parents'. (e) A popover, menu or drawer outside a theme fell back to black text; it now takes the neutral `#111827`, as modal and toast do. +- **Not fixed (follow-up, VISION):** a modal's 32px controls and a toast's 24px action are not in the mobile 44px census, the same gap slice B left for `link` and `text-input`; the docs send phone dialogs to `sheet`. **Accepted as specced:** a `fullPage` capture grows the page while the layer stays the artboard, so a scrim dims the first screen only (K1; the docs say so). **Slice F: overlay rules (FR-F1)** - `src/evaluate.ts`: `desktop-app-overlay`; fast bounds from authored rects, detailed bounds from rendered rects. diff --git a/src/desktop-app-rules.ts b/src/desktop-app-rules.ts index 36e7116..8cba60b 100644 --- a/src/desktop-app-rules.ts +++ b/src/desktop-app-rules.ts @@ -33,10 +33,13 @@ export function checkDesktopArtboard(root: SceneNode, surface: SurfaceDeclaratio }]; } -function firstOf(root: SceneNode, types: ReadonlySet): SceneNode | undefined { - if (types.has(root.type)) return root; +/** The first node of one of `types`, depth first. A `menu-row` inside a + * `menu` belongs to the overlay (pages and phones open menus too), so it is + * never counted as a desktop-app primitive. */ +function firstOf(root: SceneNode, types: ReadonlySet, inMenu = false): SceneNode | undefined { + if (types.has(root.type) && !(inMenu && root.type === 'menu-row')) return root; for (const c of root.children ?? []) { - const hit = firstOf(c, types); + const hit = firstOf(c, types, inMenu || root.type === 'menu'); if (hit) return hit; } return undefined; diff --git a/src/evaluate.ts b/src/evaluate.ts index e1f47c2..098dee8 100644 --- a/src/evaluate.ts +++ b/src/evaluate.ts @@ -1356,7 +1356,10 @@ function tellGradientGlow(ctx: ClicheCtx): EvaluationIssue[] { const rgb = parseColor(color); if (!rgb) return false; const { s, l } = rgbToHsl(rgb); - if (s > 0.25) return true; // colored glow + // A coloured glow is a saturated colour you can see. Ink darker than 20% + // lightness (the generated $elevation.* use a deep blue-black) reads as a + // shadow, whatever its hue. + if (s > 0.25 && l > 0.2) return true; // colored glow if (l > 0.85 && parseAlpha(color) < 1) return true; // white bloom / halo return false; }; @@ -2124,8 +2127,12 @@ function checkPointerTargets( continue; } const c = centre(rect); - const unplaced = live.find((o) => !nested(o.node, t.node) && !rects.has(o.node.id)); - const blocker = live.find((o) => { + // A modal's own targets are never a neighbour: its scrim covers everything + // outside it, and what is inside is nested. (Its box would stand in for + // its buttons, as a shared id does.) + const neighbours = live.filter((o) => o.node.type !== 'modal'); + const unplaced = neighbours.find((o) => !nested(o.node, t.node) && !rects.has(o.node.id)); + const blocker = neighbours.find((o) => { if (nested(o.node, t.node)) return false; const r = rects.get(o.node.id); if (!r) return false; diff --git a/src/index.ts b/src/index.ts index 0ba557a..7f6a557 100644 --- a/src/index.ts +++ b/src/index.ts @@ -600,17 +600,17 @@ Desktop-app primitives (application screens — canvas_create type "desktop-app" - 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. 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. +Of these, only property-row renders children; link, text-input, nav-item, tabs, tree-row, menu-row and divider draw their own anatomy and drop any children you give them (of the overlays below, popover, menu, modal and drawer render children; tooltip and toast do not). 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). -Overlays (screen states — put one in a state variant made with canvas_add_variant, e.g. "menu-open", "comment-open", "confirm-delete", "toast"): wherever you insert an overlay in the tree, it renders in ONE overlay layer above all content — never clipped by a scrolling or clipping pane, never under a sticky or fixed bar — stacked by kind, never by a z-index (there is none): popover and menu 400, the modal's scrim 500, modal and drawer 510, toast 600, tooltip 800 (so a menu authored inside a modal renders under it). x / y are offsets from the ROOT's top-left (root coordinates), not from the parent; the layer is the artboard box. Insert it wherever it belongs logically (a menu beside the button that opens it) and set anchor: "" (read by rules, never rendered). Colours default from $bg-surface / $border / $text-primary / $text-secondary and $elevation.overlay depth; fill / stroke / color override. +Overlays (screen states — put one in a state variant made with canvas_add_variant, e.g. "menu-open", "comment-open", "confirm-delete", "toast"): wherever you insert an overlay in the tree, it renders in ONE overlay layer above all content — never clipped by a scrolling or clipping pane, never under a sticky or fixed bar — stacked by kind, never by a z-index (there is none): popover and menu 400, the modal's scrim 500, modal and drawer 510, toast 600, tooltip 800 (so a menu authored inside a modal renders under it). x / y are offsets from the ROOT's top-left (root coordinates), not from the parent; the layer is the artboard box. Insert it wherever it belongs logically (a menu beside the button that opens it) and set anchor: "" (never rendered; the overlay rules of a later release read it). To open a menu under a button, its y is the button's ROOT y plus its height: read both from snapshot_layout. Colours default from $bg-surface / $border / $text-primary / $text-secondary and $elevation.overlay depth; fill / stroke / color override. - tooltip { text, x, y } — inverted ($text-primary fill), wraps at 240px; text only, never children. - popover { x, y, size?: "xs"|"sm"|"md"|"lg" (192/320/480/640, default 320) or width, children } — a panel (vertical, padding 12 by default; layout / gap / padding apply as on a frame): a comment box, a filter form. - menu { x, y, children: menu-row and divider nodes } — padding 4, at least 192 wide, hugs its rows. - modal { title, size?: "sm"|"md"|"lg" (480/640/960, default md), actions?: [{ label, variant? }], closeLabel?, children } — centred over its own full scrim (x / y place its top-left instead); a header with the title and a close button named "Close" (closeLabel renames it); the body holds the children (vertical, gap 12) and scrolls when tall; actions render right-aligned as 32px buttons, an action with no variant as "secondary", the filled ones ("primary", "destructive") rightmost. A modal is a region of its own for the primary-count and wayfinding rules. - toast { text, tone?: "neutral"|"success"|"warning"|"danger", action?: { label } } — bottom-centre, 24px above the artboard's bottom edge (x / y place it); the tone colours a leading glyph, the text stays $text-primary. - drawer { size?: "sm"|"md" (320/480) or width, scrim?: false, children } — pinned to the right edge, full height, padding 16; scrim: true dims what is behind it. -A modal's close button and actions and a toast's action are pointer targets (32 / 32 / 24 tall). snapshot_layout lists every overlay under the root, and a modal (or a drawer with a scrim) carries its scrim's rect. +A modal's close button and actions and a toast's action are pointer targets (32 / 32 / 24 tall), sized for a pointer: on a phone use a sheet for a dialog. On a root with a safeArea or a pinned tab-bar, a centred modal, a default toast and a drawer keep clear of the insets and the tab bar. snapshot_layout lists every overlay under the root, and a modal (or a drawer with a scrim) carries its scrim's rect. Responsive layout (author desktop-first, adapt down): - responsive: "stack" — on a horizontal container, flips to vertical below 768px (multi-column layouts that should stack on mobile) @@ -2152,7 +2152,7 @@ THE HEURISTIC DIRECTIVE IS THE PRESENTATION GATE. mode: "llm" adds optional dept The result's "genre" field (present whenever cliche ran) makes the genre decision auditable: { active, source ("explicit" param | "provenance" stamp | null), relaxed (tells skipped, by the genre and by the applied preset), notRelaxed ([{ tell, relaxedBy }] — tells still flagging that a DIFFERENT genre would relax), byPreset ({ preset, relaxed } — present when the applied preset relaxed tells on its own, e.g. the material preset) }. active is the canonical genre: an alias reports as its canonical name ("dashboard" → "data", "checkout" → "commerce"). If the score is pinned by tells listed in notRelaxed, the genre is probably wrong — genre follows what the screen is FOR (read screens with the user's own figures → "data"; a screen you complete a purchase on → "commerce"; the Material style → "material" (an editor or admin console is a type, not a genre: declare it with canvas_create / canvas_set_type type "desktop-app")), not what it contains. -The result's "surface" field (always present) reports the canvas TYPE and the rules it selected: { type ("web" | "mobile" | "desktop-app"), device (the profile: a phone such as "iphone-390" on mobile, a window such as "window-1440" on desktop-app, null on web), source ("declared" by canvas_create type / canvas_set_type, or "default" — never declared, judged as web), rulesOn (rule ids the composed type + genre + preset rulesets turned on), rulesOff (rule ids they turned off), conflicts (ids both enabled and disabled — those stay ON) }. On a web canvas rulesOn is ["desktop-app-artboard", "mobile-artboard"] (the base rules, on for every type). On a desktop-app canvas rulesOff lists "type-scale-ratio" (the adjacent font-size ratio check, which tags its warnings with that rule id on web and mobile; dense apps step 12/13/14 on purpose), and desktop-app-artboard (structure, every type) WARNS when a desktop-app canvas is narrower than its window's 1024px minimum, and when a canvas holding a desktop-app primitive (nav-item, tabs, tree-row, menu-row, property-row) never declared its type or is declared mobile — a canvas declared web gets an info instead. On a desktop-app canvas rulesOn also lists the desktop-app ruleset, each finding tagged with its "rule": desktop-app-target (usability: the 24px floor above, named — fast WARNING, detailed ERROR when the 24px circle reaches a neighbour; an unlabelled link with no width (or "auto") measures its glyphs, 14px wide or 30 with external, on web too), desktop-app-handbuilt-target (usability info, never blocks: a frame below 32px holding one icon, an icon plus a label of ≤3 words, or a bordered padded frame holding one such label — the shape an imported text button takes; never inside a clickable primitive; rebuild it as a button or link if clickable), desktop-app-icon-label (usability WARNING: an icon-only button or link with no ariaLabel, a collapsed nav-item with a blank label), desktop-app-current (usability WARNING: in one pane — a frame with overflow "auto", or the root; each node belongs to its nearest, so give each navigation region its own pane — two active nav-items at one depth, or two or more nav-items with none active; a tabs node with no active tab or more than one; two active tree-rows under one parent; info: a tree with a current row nesting past two levels), desktop-app-type-ladder (typography WARNING, replaces type-scale-ratio: adjacent sizes a(); const holds = (n: SceneNode) => isContent(n, ctx) || holdsFlowContent(n, ctx); const visit = (n: SceneNode, parent: SceneNode | undefined): void => { - if (n.type === 'sheet') return; + if (selfInset(n)) return; if (parent && isPositioned(n) && !PINNED_CHROME.has(n.type)) { const position = effectivePosition(n); if (position === 'fixed' && fixedUnpinned(n, ctx)) { @@ -328,8 +336,11 @@ export function checkSafeAreaFast(ctx: MobileContext): EvaluationIssue[] { checkPlaced(n, h !== undefined ? ctx.height - n.bottom - h : undefined, n.bottom); } } else { - const base = parent === ctx.root ? 0 : placedY.get(parent); - const y = base !== undefined && isNum(n.y) ? base + n.y : undefined; + // An overlay's x / y are root coordinates (it renders in the overlay + // layer, whatever its parent), and an absent y renders at 0. + const overlay = OVERLAY_TYPES.has(n.type); + const base = parent === ctx.root || overlay ? 0 : placedY.get(parent); + const y = base !== undefined && (isNum(n.y) || overlay) ? base + (isNum(n.y) ? n.y : 0) : undefined; if (y === undefined) { if (holds(n)) unplaceable = true; } else { @@ -377,7 +388,7 @@ export function checkSafeAreaFast(ctx: MobileContext): EvaluationIssue[] { // the first or last content for good. let unresolved = false; (function bars(n: SceneNode) { - if (n.type === 'sheet') return; + if (selfInset(n)) return; if (n !== ctx.root && effectivePosition(n) === 'fixed' && !PINNED_CHROME.has(n.type) && !fixedUnpinned(n, ctx) && holds(n)) { const bottomBar = pinsBottom(n); const topBar = !bottomBar && pinsTop(n); @@ -441,7 +452,7 @@ export function checkSafeAreaDetailed(ctx: MobileContext, layout: LayoutRect[]): const sticky: Array<{ node: SceneNode; rect: LayoutRect; content: Array<{ node: SceneNode; rect: LayoutRect }> }> = []; const visit = (n: SceneNode, positioned: boolean, stuck: typeof sticky[number] | undefined, clipped: boolean): void => { - if (n.type === 'sheet') return; + if (selfInset(n)) return; const r = rects.get(n.id); if (isContentNode(n, r)) { if (r && r.width > 0 && r.height > 0) { @@ -493,7 +504,7 @@ export function checkSafeAreaDetailed(ctx: MobileContext, layout: LayoutRect[]): a.y < top + b.height && a.y + a.height > top && a.x < b.x + b.width && a.x + a.width > b.x; const scroll = docBottom - ctx.height; (function bars(n: SceneNode) { - if (n.type === 'sheet') return; + if (selfInset(n)) return; const r = rects.get(n.id); // A fixed node under a blurred or animated ancestor pins to that ancestor, // not the screen, so it is not a bar at the scroll's ends. diff --git a/src/renderer.ts b/src/renderer.ts index e56bf0b..5d4e62f 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -100,6 +100,10 @@ interface RenderCtx { /** Phase 31 slice E — overlays met while rendering, lifted into the overlay * layer after the content (shared by every derived context). */ overlays: SceneNode[]; + /** Phase 31 slice E — what a viewport-anchored overlay keeps clear of at + * each edge: the root's declared safeArea, or the pinned chrome's reach, + * whichever is larger (0 on a canvas with neither). */ + clear: { top: number; bottom: number }; } export function renderToHtml(root: SceneNode, width = 1440, height = 900, canvas?: Canvas, opts?: RenderOptions): string { @@ -108,7 +112,10 @@ export function renderToHtml(root: SceneNode, width = 1440, height = 900, canvas const columnWidth = Math.min(typeof root.width === 'number' ? root.width : width, width); const designWidth = typeof root.width === 'number' && root.width > 0 ? root.width : DESIGN_WIDTH; const overlays: SceneNode[] = []; - const rc: RenderCtx = { canvas, registered, bodyWidth: width, columnWidth, insets: rootInsets(root), reservation: chromeReservation(root, expand), designWidth, overlays }; + const reservation = chromeReservation(root, expand); + const safe = root.type === 'document' ? usableSafeArea(root.safeArea) : {}; + const clear = { top: Math.max(safe.top ?? 0, reservation.top), bottom: Math.max(safe.bottom ?? 0, reservation.bottom) }; + const rc: RenderCtx = { canvas, registered, bodyWidth: width, columnWidth, insets: rootInsets(root), reservation, designWidth, overlays, clear }; const body = renderNode(root, rc) + overlayLayer(rc, height); const responsiveCss = buildRendererStylesheet(root, canvas); // Phase 24 slice B — the pulse keyframes exist ONLY when the caller opts in @@ -1564,12 +1571,17 @@ function renderOverlayContainer(node: SceneNode, rc: RenderCtx, attrs: string): width, height: drawer ? undefined : node.height, layout: node.layout ?? 'vertical', padding: node.padding ?? (menu ? 4 : drawer ? 16 : 12), stroke: drawer ? undefined : node.stroke ?? FALLBACK.border, fill: node.fill ?? FALLBACK.surface, - cornerRadius: node.cornerRadius ?? (drawer ? 0 : 8), + color: node.color ?? FALLBACK.text, cornerRadius: node.cornerRadius ?? (drawer ? 0 : 8), }; + // A drawer runs the artboard's full height: its padding clears the safe + // area and pinned chrome at each end, as a sheet's does. + const [pt, , pb] = paddingCss(layout.padding); const box = css([ buildStyles(layout, rc), 'position: absolute', 'box-sizing: border-box', 'pointer-events: auto', `z-index: ${OVERLAY_Z[drawer ? 'drawer' : menu ? 'menu' : 'popover']}`, ...(drawer ? ['top: 0', 'bottom: 0', 'right: 0', 'overflow-y: auto', `border-left: 1px solid ${node.stroke ?? FALLBACK.border}`] : placedAt(node)), + drawer && rc.clear.top > 0 ? `padding-top: calc(${pt} + ${rc.clear.top}px)` : undefined, + drawer && rc.clear.bottom > 0 ? `padding-bottom: calc(${pb} + ${rc.clear.bottom}px)` : undefined, menu && width === undefined ? 'width: max-content' : undefined, menu ? `min-width: ${MENU_MIN_WIDTH}px` : undefined, `box-shadow: ${overlayShadow(node)}`, @@ -1597,10 +1609,14 @@ function renderModal(node: SceneNode, rc: RenderCtx, attrs: string): string { const title = text(node.title); if (title) attrs += ` aria-label="${escapeAttr(title)}"`; const placed = num(node.x) || num(node.y); + // Centred between the edges, 32px clear of each, or 16px past the safe + // area and pinned chrome on a phone. + const top = Math.max(32, rc.clear.top ? rc.clear.top + 16 : 0); + const bottom = Math.max(32, rc.clear.bottom ? rc.clear.bottom + 16 : 0); const box = css([ 'position: absolute', `z-index: ${OVERLAY_Z.modal}`, 'pointer-events: auto', 'box-sizing: border-box', - 'display: flex', 'flex-direction: column', `width: ${modalWidth(node)}px`, 'max-width: calc(100% - 32px)', 'max-height: calc(100% - 64px)', - ...(placed ? placedAt(node) : ['inset: 0', 'margin: auto', 'height: fit-content']), + 'display: flex', 'flex-direction: column', `width: ${modalWidth(node)}px`, 'max-width: calc(100% - 32px)', `max-height: calc(100% - ${top + bottom}px)`, + ...(placed ? placedAt(node) : [`top: ${top}px`, `bottom: ${bottom}px`, 'left: 0', 'right: 0', 'margin: auto', 'height: fit-content']), `background-color: ${node.fill ?? FALLBACK.surface}`, `border: 1px solid ${node.stroke ?? FALLBACK.border}`, `border-radius: ${radiusOf(node, 12)}px`, `box-shadow: ${overlayShadow(node)}`, `color: ${node.color ?? FALLBACK.text}`, 'overflow: hidden', node.opacity !== undefined ? `opacity: ${node.opacity}` : undefined, @@ -1630,7 +1646,8 @@ function renderToast(node: SceneNode, rc: RenderCtx, attrs: string): string { const label = node.action && typeof node.action === 'object' ? text(node.action.label) : ''; const box = css([ 'position: absolute', `z-index: ${OVERLAY_Z.toast}`, 'pointer-events: auto', 'box-sizing: border-box', - ...(placed ? placedAt(node) : ['left: 0', 'right: 0', 'bottom: 24px', 'margin: 0 auto']), + // 24px above the bottom edge, or 16px above the safe area and pinned chrome. + ...(placed ? placedAt(node) : ['left: 0', 'right: 0', `bottom: ${rc.clear.bottom ? rc.clear.bottom + 16 : 24}px`, 'margin: 0 auto']), 'width: max-content', 'max-width: min(480px, calc(100% - 32px))', 'min-height: 40px', 'display: flex', 'align-items: center', 'gap: 10px', label ? 'padding: 8px 8px 8px 12px' : 'padding: 8px 12px', `background-color: ${node.fill ?? FALLBACK.surface}`, `border: 1px solid ${node.stroke ?? FALLBACK.border}`, diff --git a/test-overlays-render.ts b/test-overlays-render.ts index a7398d6..b7c1ec5 100644 --- a/test-overlays-render.ts +++ b/test-overlays-render.ts @@ -195,6 +195,61 @@ const tech = generateDesignSystem('#2563EB', 'technical').variables; } } +// ── Round 1 fixes: neighbours and phones ──────────────────────────────────── +{ + // A modal's box is never a 24px-circle neighbour (its scrim covers what is outside). + const C = (children: SceneNode[]): Canvas => ({ ...canvasOf(children, {}, { layout: 'none', fill: '#FFFFFF' }) }); + const at = (x: number, y: number): SceneNode => ({ id: 'w', name: 'w', type: 'frame', position: 'absolute', x, y, width: 18, height: 18, children: [{ id: 'cb', name: 'cb', type: 'checkbox' }] }); + const small = async (children: SceneNode[]) => (await evaluateCanvas(C(children), { mode: 'detailed', categories: ['usability'] })).issues.filter((i) => /24px/.test(i.message)); + const m: SceneNode = { id: 'm', name: 'm', type: 'modal', title: 'T', actions: [{ label: 'OK', variant: 'primary' }], children: [{ id: 'mt', name: 'mt', type: 'text', content: 'Body' }] }; + check('a small target 11px from a modal\'s box is not blocked by it', (await small([at(382, 420), m])).length === 0); + const toastNear = await small([at(382, 840), { id: 't', name: 't', type: 'toast', text: 'Saved', action: { label: 'Undo' }, x: 400, y: 830 }]); + check('twin: the same target beside a toast still errors', toastNear.length === 1 && toastNear[0].severity === 'error'); + const pageNear = await small([at(382, 420), { id: 'wb', name: 'wb', type: 'frame', position: 'absolute', x: 400, y: 410, children: [{ id: 'b', name: 'b', type: 'button', label: 'Go', size: 'sm' }] }]); + check('twin: the same target beside a page button still errors', pageNear.length === 1 && pageNear[0].severity === 'error'); + + // Phones: the anchored overlays keep clear, and the safe-area rule skips them. + const phone = (children: SceneNode[]): Canvas => ({ + ...canvasOf(children, {}, { width: 390, height: 844, safeArea: { top: 47, bottom: 34 }, fill: '#FFFFFF' }), + metadata: { surface: { type: 'mobile', device: 'iphone-390' } }, + } as Canvas); + const safe = async (c: Canvas, mode: 'fast' | 'detailed') => (await evaluateCanvas(c, { mode, categories: ['usability'] })).issues.filter((i) => i.rule === 'mobile-safe-area'); + const tall: SceneNode = { id: 'm', name: 'm', type: 'modal', title: 'Long', children: Array.from({ length: 40 }, (_, i) => ({ id: `p${i}`, name: `p${i}`, type: 'text', content: `Paragraph ${i} of a long modal body.`, fontSize: 16 })) }; + const tallCanvas = phone([tall]); + check('phone: a tall centred modal raises no safe-area finding (detailed)', (await safe(tallCanvas, 'detailed')).length === 0); + const mr = flat(await computeLayout(renderToHtml(tallCanvas.root, 390, 844, tallCanvas), undefined, 5, { width: 390, height: 844 })).get('m')!; + check('phone: the modal stays 16px past the insets', mr.y === 63 && mr.y + mr.height === 794, JSON.stringify({ y: mr.y, bottom: mr.y + mr.height })); + const drawerCanvas = phone([{ id: 'd', name: 'd', type: 'drawer', children: [{ id: 'dt', name: 'dt', type: 'text', content: 'Filters', fontSize: 16 }] }]); + check('phone: a drawer\'s content clears the status bar, and no safe-area finding', (await safe(drawerCanvas, 'detailed')).length === 0 + && flat(await computeLayout(renderToHtml(drawerCanvas.root, 390, 844, drawerCanvas), undefined, 5, { width: 390, height: 844 })).get('dt')!.y >= 47); + const tabCanvas = phone([{ id: 'tab', name: 'tab', type: 'tab-bar', items: [{ icon: 'house', label: 'Home', active: true }, { icon: 'user', label: 'Me' }] }, { id: 't', name: 't', type: 'toast', text: 'Saved' }]); + const tr = flat(await computeLayout(renderToHtml(tabCanvas.root, 390, 844, tabCanvas), undefined, 5, { width: 390, height: 844 })); + check('phone: a default toast sits above the tab bar', tr.get('t')!.y + tr.get('t')!.height <= tr.get('tab')!.y, JSON.stringify({ toast: tr.get('t')!.y + tr.get('t')!.height, tab: tr.get('tab')!.y })); + const pop = phone([{ id: 'pop', name: 'pop', type: 'popover', x: 20, y: 10, children: [{ id: 'pt', name: 'pt', type: 'text', content: 'Hi there', fontSize: 16 }] }]); + check('twin: a popover placed under the status bar warns (fast)', (await safe(pop, 'fast')).some((i) => i.nodeId === 'pt')); + check('twin: a popover placed under the status bar warns (detailed)', (await safe(pop, 'detailed')).some((i) => i.nodeId === 'pt')); + const nested = phone([{ id: 'fr', name: 'fr', type: 'frame', position: 'absolute', x: 0, y: 300, width: 390, height: 100, children: [ + { id: 'pop2', name: 'pop2', type: 'popover', x: 20, y: 10, children: [{ id: 'pt2', name: 'pt2', type: 'text', content: 'Hi there', fontSize: 16 }] }, + ] }]); + check('fast mode reads a nested overlay\'s y as root coordinates (warns at y 10, not 310)', (await safe(nested, 'fast')).some((i) => i.nodeId === 'pt2')); +} + +// ── Round 1 mutation gaps (rendered) ──────────────────────────────────────── +{ + const long = 'A tooltip with enough words in it to wrap well past its maximum width of two hundred and forty pixels'; + const html = htmlOf(canvasOf([ + { id: 'tip', name: 'tip', type: 'tooltip', text: long, x: 10, y: 10 }, + { id: 'pop', name: 'pop', type: 'popover', x: 400, y: 100, children: [{ id: 'pt', name: 'pt', type: 'text', content: 'In' }] }, + ], tech)); + const r = flat(await computeLayout(html, undefined, 5, { width: 1440, height: 900 })); + check('a long tooltip wraps at 240 (not narrower)', r.get('tip')!.width >= 236 && r.get('tip')!.width <= 240, String(r.get('tip')!.width)); + const sub = await computeLayout(html, 'pop', 5, { width: 1440, height: 900 }); + check('twin: walking from an overlay does not append the other overlays', !(sub[0]?.children ?? []).some((c) => c.nodeId === 'tip')); + const narrow = { ...canvasOf([{ id: 'm', name: 'm', type: 'modal', title: 'Narrow', children: [] }], tech, { width: 390, height: 844 }) } as Canvas; + const m = flat(await computeLayout(renderToHtml(resolveVariables(narrow.root, tech), 390, 844, narrow), undefined, 3, { width: 390, height: 844 })).get('m')!; + check('a modal wider than the artboard keeps 16px each side', m.x === 16 && m.width === 358, JSON.stringify({ x: m.x, w: m.width })); +} + await shutdown(); console.log(allPass ? '\nAll checks passed.' : '\nSome checks FAILED.'); process.exit(allPass ? 0 : 1); diff --git a/test-overlays.ts b/test-overlays.ts index 26ea850..4d0df18 100644 --- a/test-overlays.ts +++ b/test-overlays.ts @@ -19,6 +19,7 @@ import { createCanvas, addVariant, listCanvases, getCanvas } from './src/scene-g import { OVERLAY_TYPES, OVERLAY_Z, effectivePosition, modalActions, modalWidth, overlayTargets, popoverWidth, drawerWidth } from './src/primitives.js'; import { checkCurrent, checkPrimaryCount } from './src/desktop-app-rules.js'; import { WINDOW_PROFILES } from './src/surfaces.js'; +import { generateDesignSystem } from './src/design-language.js'; import type { Canvas, SceneNode } from './src/types.js'; let allPass = true; @@ -140,8 +141,8 @@ const modal = (extra: Partial = {}): SceneNode => ({ check('modal close button: named "Close" by default', /data-fs-modal-close[^>]*aria-label="Close"/.test(layer)); check('closeLabel names it', /data-fs-modal-close[^>]*aria-label="Dismiss"/.test(layerOf(htmlOf(canvasWith([modal({ closeLabel: 'Dismiss' })], app))))); check('modal: role dialog, aria-modal, labelled by its title', /role="dialog" aria-modal="true" aria-label="Delete canvas\?"/.test(layer)); - check('modal: centred unless placed', /data-node-id="m"[^>]*inset: 0; margin: auto/.test(layer)); - check('twin: a placed modal is not centred', !/data-node-id="m"[^>]*inset: 0; margin: auto/.test(layerOf(htmlOf(canvasWith([modal({ x: 40, y: 60 })], app))))); + check('modal: centred unless placed', /data-node-id="m"[^>]*left: 0; right: 0; margin: auto/.test(layer)); + check('twin: a placed modal is not centred', !/data-node-id="m"[^>]*left: 0; right: 0; margin: auto/.test(layerOf(htmlOf(canvasWith([modal({ x: 40, y: 60 })], app))))); check('modal widths: sm 480 / md 640 / lg 960 / numeric wins', modalWidth({ id: 'a', type: 'modal', size: 'sm' }) === 480 && modalWidth({ id: 'a', type: 'modal' }) === 640 && modalWidth({ id: 'a', type: 'modal', size: 'lg' }) === 960 && modalWidth({ id: 'a', type: 'modal', width: 500 }) === 500); check('popover widths: default 320, xs 192, numeric wins', popoverWidth({ id: 'a', type: 'popover' }) === 320 && popoverWidth({ id: 'a', type: 'popover', size: 'xs' }) === 192 && popoverWidth({ id: 'a', type: 'popover', width: 250 }) === 250); check('drawer widths: default 320, md 480', drawerWidth({ id: 'a', type: 'drawer' }) === 320 && drawerWidth({ id: 'a', type: 'drawer', size: 'md' }) === 480); @@ -239,6 +240,98 @@ const modal = (extra: Partial = {}): SceneNode => ({ check('FR-C2 still names a hand-built icon frame inside a modal body', hand.length === 1); } +// ── Round 1 fixes ─────────────────────────────────────────────────────────── +{ + // The generated overlay elevation is a shadow, not a glow (the halo tell). + const glow = async (color: string) => (await evaluateCanvas(canvasWith([{ id: 'f', name: 'f', type: 'frame', width: 200, height: 100, shadows: [{ x: 0, y: 20, blur: 25, color }] }], app), { mode: 'fast', categories: ['cliche'] })).issues.filter((i) => i.tell === 'gradient-glow').length; + check('halo tell: the generated deep-ink overlay shadow is not a glow', await glow('rgba(16, 24, 40, 0.14)') === 0); + check('twin: a saturated dark red shadow (lightness .31) still is', await glow('rgba(127, 29, 29, 0.5)') === 1); + check('twin: an indigo glow still is', await glow('rgba(99, 102, 241, 0.5)') === 1); + const themedModal = canvasWith([modal()], app); + const ds = generateDesignSystem('#2563EB', 'technical').variables; + themedModal.variables = ds; + const tells = (await evaluateCanvas(themedModal, { mode: 'fast', categories: ['cliche'] })).issues.filter((i) => i.tell === 'gradient-glow'); + check('a modal on a generated design system raises no halo tell', tells.length === 0, tells.map((i) => i.nodeId).join(',')); + + // A menu's rows belong to the menu: pages and phones open menus too. + const art = async (children: SceneNode[], surface?: Surface) => (await evaluateCanvas(canvasWith(children, surface), { mode: 'fast', categories: ['structure'] })).issues.filter((i) => i.rule === 'desktop-app-artboard'); + const menu: SceneNode = { id: 'menu', name: 'menu', type: 'menu', children: [{ id: 'r', name: 'r', type: 'menu-row', label: 'Open' }] }; + check('FR-C9: a menu on an explicit web canvas raises nothing', (await art([menu], { type: 'web' })).length === 0); + check('FR-C9: a menu on an explicit mobile canvas raises nothing', (await art([menu], { type: 'mobile', device: 'iphone-390' })).length === 0); + const loose = await art([{ id: 'fr', name: 'fr', type: 'frame', children: [{ id: 'r3', name: 'r3', type: 'menu-row', label: 'x' }] }], { type: 'mobile', device: 'iphone-390' }); + check('twin: a menu-row outside a menu on mobile still warns', loose.length === 1 && loose[0].severity === 'warning'); + const navInMenu = await art([{ ...menu, children: [{ id: 'nv', name: 'nv', type: 'nav-item', label: 'x' }] }], { type: 'mobile', device: 'iphone-390' }); + check('twin: a nav-item inside a menu on mobile still warns', navInMenu.length === 1 && navInMenu[0].nodeId === 'nv'); + const undeclaredMenu = await art([menu]); + check('an undeclared canvas with a menu warns on the menu (the overlay clause)', undeclaredMenu.length === 1 && undeclaredMenu[0].nodeId === 'menu'); + + // A popover / menu / drawer falls back to the neutral text colour, as modal and toast do. + const unthemed = layerOf(renderToHtml(canvasWith([{ id: 'pop', name: 'pop', type: 'popover' }]).root, 1440, 900)); + check('unthemed popover: #111827 text', /data-node-id="pop"[^>]*color: #111827/.test(unthemed)); + + // On a phone (safeArea, pinned tab bar) the viewport-anchored overlays keep clear. + const phone = (children: SceneNode[]) => { + const c = canvasWith(children, { type: 'mobile', device: 'iphone-390' }); + c.root.width = 390; c.root.height = 844; c.root.safeArea = { top: 47, bottom: 34 }; + return renderToHtml(c.root, 390, 844, c); + }; + const tab: SceneNode = { id: 'tab', name: 'tab', type: 'tab-bar', items: [{ icon: 'house', label: 'Home', active: true }, { icon: 'user', label: 'Me' }] }; + check('phone: a centred modal clears the insets (top 63, bottom 50)', /data-node-id="m"[^>]*max-height: calc\(100% - 113px\); top: 63px; bottom: 50px/.test(layerOf(phone([modal()])))); + check('phone: a default toast sits 16px above the tab bar', /data-node-id="t"[^>]*bottom: 99px/.test(layerOf(phone([tab, { id: 't', name: 't', type: 'toast', text: 'Saved' }])))); + check('phone: a drawer pads past the insets', /data-node-id="d"[^>]*padding-top: calc\([^)]*\+ 47px\); padding-bottom: calc\([^)]*\+ 34px\)/.test(layerOf(phone([{ id: 'd', name: 'd', type: 'drawer' }])))); + const desk = layerOf(htmlOf(canvasWith([modal(), { id: 't', name: 't', type: 'toast', text: 'Saved' }, { id: 'd', name: 'd', type: 'drawer' }], app))); + check('twin: on a window they keep the 32 / 24 defaults and no extra padding', /data-node-id="m"[^>]*top: 32px; bottom: 32px/.test(desk) && /data-node-id="t"[^>]*bottom: 24px/.test(desk) && !/data-node-id="d"[^>]*padding-top: calc/.test(desk)); +} + +// ── Round 1 mutation gaps ─────────────────────────────────────────────────── +{ + const un = (children: SceneNode[]) => layerOf(renderToHtml(canvasWith(children).root, 1440, 900)); + // Unthemed modal actions: the renderer's own fallbacks (no resolveVariables). + const bare = un([modal({ actions: [{ label: 'Later' }] })]); + check('unthemed bare action: secondary (transparent, bordered, dark text)', /background-color: transparent; border: 1px solid #D1D5DB; color: #111827[^"]*">]*>Later/.test(bare), bare.match(/
(<[^>]*>)?Later/)?.[0]?.slice(0, 200)); + const filled = un([modal({ actions: [{ label: 'Go', variant: 'primary' }] })]); + check('twin: an unthemed primary action is filled, white text, no border', /background-color: #2563EB; color: #FFFFFF[^"]*">]*>Go/.test(filled)); + // Scrim, aria-modal, tooltip box, toast anatomy. + const tip = un([{ id: 'tip', name: 'tip', type: 'tooltip', text: 'x' }]); + check('tooltip: 4px 8px padding, radius 4', /data-node-id="tip"[^>]*padding: 4px 8px; border-radius: 4px/.test(tip)); + check('scrim: rgba(0, 0, 0, 0.4)', /data-fs-scrim="m"[^>]*background-color: rgba\(0, 0, 0, 0.4\)/.test(un([modal()]))); + const dr = un([{ id: 'd', name: 'd', type: 'drawer', scrim: true }]); + check('drawer with scrim: aria-modal', /data-node-id="d"[^>]*role="dialog" aria-modal="true"/.test(dr)); + check('twin: drawer without scrim: no aria-modal', !/aria-modal/.test(un([{ id: 'd', name: 'd', type: 'drawer' }]))); + check('drawer: radius 0, a left border only', /data-node-id="d"[^>]*border-radius: 0px[^"]*border-left: 1px solid #D1D5DB/.test(dr) && !/data-node-id="d"[^>]*border: 1px/.test(dr)); + check('default paddings: menu 4, popover 12, drawer 16', /data-node-id="mn"[^>]*padding: 4px/.test(un([{ id: 'mn', name: 'mn', type: 'menu' }])) + && /data-node-id="pp"[^>]*padding: 12px/.test(un([{ id: 'pp', name: 'pp', type: 'popover' }])) && /data-node-id="d"[^>]*padding: 16px/.test(dr)); + check('popover renders 320 wide by default', /data-node-id="pp"[^>]*width: 320px/.test(un([{ id: 'pp', name: 'pp', type: 'popover' }]))); + check('a root-child popover at height 100% keeps its height (no root flex)', /data-node-id="pp"[^>]*height: 100%/.test(un([{ id: 'pp', name: 'pp', type: 'popover', height: '100%' }])) && !/data-node-id="pp"[^>]*flex: 1 1 auto/.test(un([{ id: 'pp', name: 'pp', type: 'popover', height: '100%' }]))); + const toastPlaced = un([{ id: 't', name: 't', type: 'toast', text: 'x', x: 40, y: 60 }]); + check('a placed toast sits at its x / y', /data-node-id="t"[^>]*left: 40px; top: 60px/.test(toastPlaced) && !/data-node-id="t"[^>]*bottom: 24px/.test(toastPlaced)); + const withAction = un([{ id: 't', name: 't', type: 'toast', text: 'x', action: { label: 'Undo' } }]); + check('toast padding: 8 8 8 12 with an action, 8 12 without', /data-node-id="t"[^>]*padding: 8px 8px 8px 12px/.test(withAction) && /data-node-id="t"[^>]*padding: 8px 12px/.test(un([{ id: 't', name: 't', type: 'toast', text: 'x' }]))); + const success = un([{ id: 't', name: 't', type: 'toast', text: 'x', tone: 'success' }]); + check('success toast: the circle-check glyph in green', success.includes('lucide-circle-check') && /stroke="#16A34A"/.test(success), success.match(/]*>/)?.[0]); + check('neutral toast: the info glyph', un([{ id: 't', name: 't', type: 'toast', text: 'x' }]).includes('lucide-info')); + // Census: a toast action with no label is no target. + check('census: a blank toast action is no target', overlayTargets({ id: 't', type: 'toast', action: { label: ' ' } }).length === 0 && overlayTargets({ id: 't', type: 'toast', action: {} as never }).length === 0); + // Defaults: tokens inside actions / action, success tone, explicit shadow, pale accent. + const t2 = resolveVariables(canvasWith([ + modal({ actions: [{ label: 'A', variant: 'secondary', color: '$danger', stroke: '$accent' }] }), + { id: 'toast', name: 'toast', type: 'toast', text: 'x', tone: 'success', action: { label: 'Undo', color: '$danger' } }, + modal({ id: 'm2', shadows: [{ x: 0, y: 1, blur: 2, color: '#000000' }] }), + ], app, TOKENS).root, { colors: TOKENS, elevation: { overlay: [{ x: 0, y: 9, blur: 9, color: 'rgba(0,0,0,0.3)' }] } }); + const k = (id: string) => t2.children!.find((n) => n.id === id)!; + check('$token refs resolve in actions[].color / .stroke and action.color', k('m').actions![0].color === TOKENS.danger && k('m').actions![0].stroke === TOKENS.accent && k('toast').action!.color === TOKENS.danger); + check('success toast glyph: $success', k('toast').iconColor === TOKENS.success); + check('an explicit shadow wins over $elevation.overlay', k('m2').shadows!.length === 1 && k('m2').shadows![0].blur === 2); + const pale = resolveVariables(canvasWith([modal({ actions: [{ label: 'Go', variant: 'primary' }] })], app, { ...TOKENS, accent: '#FDE68A' }).root, { colors: { ...TOKENS, accent: '#FDE68A' } }); + check('a pale accent gives a primary action dark text', pale.children![0].actions![0].color !== '#FFFFFF', pale.children![0].actions![0].color); + // Drawer as a region: two primaries inside it are the info. + const ctx = { root: canvasWith([{ id: 'dr', name: 'dr', type: 'drawer', children: [{ id: 'p1', name: 'p1', type: 'button', label: 'A' }, { id: 'p2', name: 'p2', type: 'button', label: 'B' }] }], app).root, profile: WINDOW_PROFILES['window-1440'] }; + check('twin: two primaries inside one drawer are the info', checkPrimaryCount(ctx).length === 1); + // Every overlay kind ignores its own position. + const pos = un([...OVERLAY_TYPES].map((t, i) => ({ id: `o${i}`, name: `o${i}`, type: t as SceneNode['type'], text: 'x', position: 'fixed' as const }))); + check('no overlay kind renders its own position: fixed', !/data-fs-overlay[^>]*position: fixed/.test(pos)); +} + // ── K7: stress reaches the overlay copy ───────────────────────────────────── { const root = canvasWith([ From 042ce731c720241ba07d9b53bc132b661356936a Mon Sep 17 00:00:00 2001 From: Victor Velazquez Date: Sun, 15 Nov 2026 20:50:30 +0100 Subject: [PATCH 4/4] Check overlays against the safe area when the render does not clear it --- docs/GUIDELINES.md | 4 ++-- docs/specs/PHASE-31-SPEC.md | 1 + src/mobile-rules.ts | 30 ++++++++++++++++++++---------- test-overlays-render.ts | 7 +++++++ 4 files changed, 30 insertions(+), 12 deletions(-) diff --git a/docs/GUIDELINES.md b/docs/GUIDELINES.md index c6ed552..0cc2fbb 100644 --- a/docs/GUIDELINES.md +++ b/docs/GUIDELINES.md @@ -139,13 +139,13 @@ The six overlays take their colours from `$bg-surface`, `$border`, `$text-primar - **`tooltip`** `{ text, x, y }` is a short hint, inverted (`$text-primary` fill, `$bg-surface` text, so light on a dark theme), wrapping at 240px. Text only: it never renders children. - **`popover`** `{ x, y, size?: "xs" | "sm" | "md" | "lg", children }` is a panel 192 / 320 / 480 / 640 wide (320 by default; a numeric `width` wins), vertical with 12px padding by default; `layout`, `gap` and `padding` apply as on a frame. A comment box or a filter form. - **`menu`** `{ x, y, children }` holds `menu-row`s and `divider`s: 4px padding, at least 192 wide, hugging its rows. -- **`modal`** `{ title, size?: "sm" | "md" | "lg", actions?: [{ label, variant? }], closeLabel?, children }` is 480 / 640 / 960 wide (640 by default), centred over its own scrim, which always covers the artboard (`x` / `y` place the modal's top-left instead). It is never taller than the artboard less 64px. Its header holds the title and a close button named "Close" (`closeLabel` renames it). The body holds the children (vertical, 12px gap) and scrolls when tall, between the header and the actions. `actions` render right-aligned as 32px buttons; an action with no variant renders `secondary`, and the filled ones (`primary`, `destructive`) render rightmost. For a delete confirmation: `actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }]`. +- **`modal`** `{ title, size?: "sm" | "md" | "lg", actions?: [{ label, variant? }], closeLabel?, children }` is 480 / 640 / 960 wide (640 by default), centred over its own scrim, which always covers the artboard (`x` / `y` place the modal's top-left instead). It is never taller than the artboard less 64px (less the insets on a phone). Its header holds the title and a close button named "Close" (`closeLabel` renames it). The body holds the children (vertical, 12px gap) and scrolls when tall, between the header and the actions. `actions` render right-aligned as 32px buttons; an action with no variant renders `secondary`, and the filled ones (`primary`, `destructive`) render rightmost. For a delete confirmation: `actions: [{ label: "Cancel" }, { label: "Delete", variant: "destructive" }]`. - **`toast`** `{ text, tone?: "neutral" | "success" | "warning" | "danger", action?: { label } }` sits bottom-centre, 24px above the artboard's bottom edge (`x` / `y` place its top-left instead); it hugs its text up to 480px. The tone colours a leading glyph (`$success`, `$warning`, `$danger`, neutral `$text-secondary`; `iconColor` overrides); the text stays `$text-primary`. `danger` renders `role="alert"`. - **`drawer`** `{ size?: "sm" | "md", scrim?, children }` is a 320 / 480 panel pinned to the right edge at full height, 16px padding; `scrim: true` dims what is behind it. A modal's close button and actions (32 tall) and a toast's action (24 tall) are pointer targets. They are sized for a pointer, so on a phone use a `sheet` for a dialog. A modal and a drawer are panes: navigation and primary buttons inside them are judged apart from the page behind. -On a canvas whose root declares a `safeArea` or pins a `tab-bar` (a phone), a centred modal, a default toast and a drawer keep clear of them: the modal stays 16px past the insets and pinned chrome, the toast sits 16px above the tab bar or home indicator, and the drawer's padding grows past them, so the safe-area rules skip those three. A popover, a menu, a tooltip, and a modal or toast you place with `x` / `y` are checked like any positioned content. A `fullPage` capture grows the page, but the overlay layer stays the artboard: a scrim dims the first screen only. +On a canvas whose root declares a `safeArea` or pins a `tab-bar` (a phone), a centred modal, a default toast and a drawer keep clear of them: the modal stays 16px past the insets and pinned chrome, the toast sits 16px above the tab bar or home indicator, and the drawer's padding grows past them, so the safe-area rules skip those three when that clearance covers the insets they judge by (on a phone root without a `safeArea` or pinned chrome they are still checked). A popover, a menu, a tooltip, and a modal or toast you place with `x` / `y` are checked like any positioned content. A `fullPage` capture grows the page, but the overlay layer stays the artboard: a scrim dims the first screen only. ### Lists that lead with a mark are not tables (every type) diff --git a/docs/specs/PHASE-31-SPEC.md b/docs/specs/PHASE-31-SPEC.md index 1a15a1e..8e47a41 100644 --- a/docs/specs/PHASE-31-SPEC.md +++ b/docs/specs/PHASE-31-SPEC.md @@ -301,6 +301,7 @@ One profile ships, keyed by id so a second size is one table row later. Values i - **L4: overlays are not reuse.** `REUSE_PRIMITIVES` (the structure advisory's reuse count) is unchanged: one modal on a screen-state variant is not a repeated component. - **L5: a menu inside a modal renders under it** (400 below 510), as the ladder fixes; the docs say so. Slice F's rules may want to flag it. - **Verify round 1 fixes** (each loosening proved red on caa66c9 and green on the fix, with its nearest keep-cases unchanged). (a) The halo tell (`gradient-glow`) fired on every overlay of a generated design system, because `$elevation.overlay` is a deep blue-black ink (saturation 0.43, lightness 0.11) at blur 25: a coloured glow now also needs lightness above 0.2, so dark ink of any hue reads as a shadow; indigo, dark red (0.31) and deep violet (0.27) glows and the white bloom still fire. (b) A `menu`'s `menu-row`s counted as desktop-app primitives, so a menu on an explicit web canvas raised FR-C9's info and on mobile its warning, against K5(a): a `menu-row` inside a `menu` now belongs to the overlay; one outside a menu, and any other app primitive inside a menu, still counts. (c) A modal's box stood in for its buttons in the 24px circle test, so a small target near any part of a modal was an error: a modal's targets are never a neighbour (its scrim covers everything outside it); a toast keeps its box, as a tab bar does (slice A D12). (d) On a phone the viewport-anchored overlays ignored the insets: a centred modal now keeps 32px from each edge, or 16px past the root's declared `safeArea` and pinned chrome when larger; a default toast sits 16px above them (else 24); a drawer's padding grows past them. Render still reads only the scene (`root.safeArea` and the pinned chrome's reach). The mobile safe-area walks skip a drawer and an unplaced modal or toast, as they skip a sheet, so a modal body's scrolled-out paragraphs no longer warn; placed overlays are checked, and fast mode now reads an overlay's `y` as root coordinates instead of adding its parents'. (e) A popover, menu or drawer outside a theme fell back to black text; it now takes the neutral `#111827`, as modal and toast do. +- **After verify round 2 (3b)** (proved red on 7b64232 and green on the fix; not re-verified by an agent). Fix (d) skipped a drawer and an unplaced modal or toast on every mobile canvas, but the render keeps clear only of a declared `safeArea` and pinned chrome, so on a phone root without either a tall modal over the status bar and a drawer's text under it went silent (both warned on caa66c9). The safe-area walks now skip them only when that clearance (the renderer's `clear`) covers the insets the rule judges by; a toast needs only the bottom. Left as found: a placed modal's `max-height` also subtracts the clearance on a phone, so it scrolls a little earlier than it must; the glow line (lightness 0.2) leaves a very dark saturated glow (`#0B1B4F`, blur 40) on a near-black surface unflagged. - **Not fixed (follow-up, VISION):** a modal's 32px controls and a toast's 24px action are not in the mobile 44px census, the same gap slice B left for `link` and `text-input`; the docs send phone dialogs to `sheet`. **Accepted as specced:** a `fullPage` capture grows the page while the layer stays the artboard, so a scrim dims the first screen only (K1; the docs say so). **Slice F: overlay rules (FR-F1)** diff --git a/src/mobile-rules.ts b/src/mobile-rules.ts index ee126d8..e691afb 100644 --- a/src/mobile-rules.ts +++ b/src/mobile-rules.ts @@ -117,12 +117,22 @@ function indexFor(ctx: MobileContext): TreeIndex { return index; } -/** Overlays the renderer itself keeps clear of the safe area and pinned - * chrome: a sheet, a drawer, and a modal or toast left at its default place - * (no x / y). The safe-area walks skip them and what they hold. */ -function selfInset(n: SceneNode): boolean { - return n.type === 'sheet' || n.type === 'drawer' - || ((n.type === 'modal' || n.type === 'toast') && !isNum(n.x) && !isNum(n.y)); +/** Overlays the renderer itself keeps clear of the insets: a sheet always; + * a drawer, and a modal or toast left at its default place (no x / y), only + * when the render's clearance (the root's declared safeArea or the pinned + * chrome's reach, the renderer's `clear`) covers the insets this rule + * judges by. The safe-area walks skip them and what they hold. */ +function selfInset(n: SceneNode, ctx: MobileContext): boolean { + if (n.type === 'sheet') return true; + const unplaced = !isNum(n.x) && !isNum(n.y); + if (n.type !== 'drawer' && !((n.type === 'modal' || n.type === 'toast') && unplaced)) return false; + const insets = insetsFor(ctx); + const declared = ctx.root.type === 'document' ? usableSafeArea(ctx.root.safeArea) : {}; + const reach = chromeReservation(ctx.root); + const clearTop = Math.max(declared.top ?? 0, reach.top); + const clearBottom = Math.max(declared.bottom ?? 0, reach.bottom); + // A toast only meets the bottom edge. + return clearBottom >= insets.bottom && (n.type === 'toast' || clearTop >= insets.top); } /** Inside a sheet (a modal overlay the renderer pads): skipped by the @@ -320,7 +330,7 @@ export function checkSafeAreaFast(ctx: MobileContext): EvaluationIssue[] { const placedY = new Map(); const holds = (n: SceneNode) => isContent(n, ctx) || holdsFlowContent(n, ctx); const visit = (n: SceneNode, parent: SceneNode | undefined): void => { - if (selfInset(n)) return; + if (selfInset(n, ctx)) return; if (parent && isPositioned(n) && !PINNED_CHROME.has(n.type)) { const position = effectivePosition(n); if (position === 'fixed' && fixedUnpinned(n, ctx)) { @@ -388,7 +398,7 @@ export function checkSafeAreaFast(ctx: MobileContext): EvaluationIssue[] { // the first or last content for good. let unresolved = false; (function bars(n: SceneNode) { - if (selfInset(n)) return; + if (selfInset(n, ctx)) return; if (n !== ctx.root && effectivePosition(n) === 'fixed' && !PINNED_CHROME.has(n.type) && !fixedUnpinned(n, ctx) && holds(n)) { const bottomBar = pinsBottom(n); const topBar = !bottomBar && pinsTop(n); @@ -452,7 +462,7 @@ export function checkSafeAreaDetailed(ctx: MobileContext, layout: LayoutRect[]): const sticky: Array<{ node: SceneNode; rect: LayoutRect; content: Array<{ node: SceneNode; rect: LayoutRect }> }> = []; const visit = (n: SceneNode, positioned: boolean, stuck: typeof sticky[number] | undefined, clipped: boolean): void => { - if (selfInset(n)) return; + if (selfInset(n, ctx)) return; const r = rects.get(n.id); if (isContentNode(n, r)) { if (r && r.width > 0 && r.height > 0) { @@ -504,7 +514,7 @@ export function checkSafeAreaDetailed(ctx: MobileContext, layout: LayoutRect[]): a.y < top + b.height && a.y + a.height > top && a.x < b.x + b.width && a.x + a.width > b.x; const scroll = docBottom - ctx.height; (function bars(n: SceneNode) { - if (selfInset(n)) return; + if (selfInset(n, ctx)) return; const r = rects.get(n.id); // A fixed node under a blurred or animated ancestor pins to that ancestor, // not the screen, so it is not a bar at the scroll's ends. diff --git a/test-overlays-render.ts b/test-overlays-render.ts index b7c1ec5..b37bc59 100644 --- a/test-overlays-render.ts +++ b/test-overlays-render.ts @@ -219,6 +219,13 @@ const tech = generateDesignSystem('#2563EB', 'technical').variables; check('phone: a tall centred modal raises no safe-area finding (detailed)', (await safe(tallCanvas, 'detailed')).length === 0); const mr = flat(await computeLayout(renderToHtml(tallCanvas.root, 390, 844, tallCanvas), undefined, 5, { width: 390, height: 844 })).get('m')!; check('phone: the modal stays 16px past the insets', mr.y === 63 && mr.y + mr.height === 794, JSON.stringify({ y: mr.y, bottom: mr.y + mr.height })); + // Without a declared safeArea (or pinned chrome) the render keeps only 32px + // clear, so the rule still judges the overlay against the device insets. + const undeclared = { ...tallCanvas, root: { ...tallCanvas.root, safeArea: undefined } } as Canvas; + check('phone without a safeArea: a tall modal still raises the safe-area finding', (await safe(undeclared, 'detailed')).length > 0); + const bareDrawer = phone([{ id: 'd', name: 'd', type: 'drawer', children: [{ id: 'dt', name: 'dt', type: 'text', content: 'Filters', fontSize: 16 }] }]); + bareDrawer.root.safeArea = undefined; + check('phone without a safeArea: a drawer\'s content under the status bar warns', (await safe(bareDrawer, 'detailed')).some((i) => i.nodeId === 'dt')); const drawerCanvas = phone([{ id: 'd', name: 'd', type: 'drawer', children: [{ id: 'dt', name: 'dt', type: 'text', content: 'Filters', fontSize: 16 }] }]); check('phone: a drawer\'s content clears the status bar, and no safe-area finding', (await safe(drawerCanvas, 'detailed')).length === 0 && flat(await computeLayout(renderToHtml(drawerCanvas.root, 390, 844, drawerCanvas), undefined, 5, { width: 390, height: 844 })).get('dt')!.y >= 47);