feat(overlay): storybook the editor's own chrome

The inspector's controls and sections, the whole Design panel, the chat timeline,
diffs, toasts and the device presets — browsable in isolation, and runnable as
tests in real Chromium.

Stories sit next to the code they cover (src/**/*.stories.ts), the same convention
the .test.ts files already follow. Storybook starts through turbo, because the
token package's dist has to exist before its builder runs.
This commit is contained in:
Nayan
2026-08-06 08:45:00 +05:30
parent 13ed93ceca
commit 0736e547f0
11 changed files with 2803 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
import type { StorybookConfig } from "@storybook/html-vite";
/*
* Storybook for the overlay.
*
* The HTML renderer, and not as a fallback — it is the exact shape this code
* already has. Every seam in the overlay hands back an `HTMLElement`
* (`ControlHandle.element`, `renderFill(ctx, node)`, `DesignPanel.element`,
* `toolRow(item)`), which is precisely what an HTML story returns. A React
* renderer would mean a wrapper around each one and React in the dependency
* graph of a package that has deliberately never had it.
*
* What this buys that the test suite cannot: `vitest.config.ts` runs on
* happy-dom, and its own docstring — plus `inspector/test-support.ts`'s — lists
* what that costs. No layout, no native CSS nesting, `@layer` dropped entirely,
* no `CSSStyleDeclaration` iterator. Those are the four things the inspector
* reads. Here they are real, because this is a real browser.
*/
const config: StorybookConfig = {
addons: [
// axe on every story. The overlay hand-wires its ARIA — `role="group"` plus
// a label on segmented groups, `aria-pressed` per cell, `aria-haspopup`
// /`aria-expanded` on selects — and `inspector/a11y.test.ts` asserts a
// sample of it. This checks the rest, on every story, for free.
"@storybook/addon-a11y",
/*
* Opt-in since Storybook 9, and not optional here.
*
* The editor is dark-only chrome, and three of its border tokens are
* `rgba(255,255,255,0.06…0.12)` — on Storybook's default white canvas they
* are invisible, so a hairline that is missing looks exactly like a hairline
* that is there. `preview.ts` defines the two grounds this repo has: the
* editor surface, and the white page the docks float over.
*/
"storybook/backgrounds",
/*
* The browser test tier — see `vitest.browser.config.ts`.
*
* Registered here so the runner and the UI agree on what a story is, but
* deliberately *not* wired into `pnpm test`: that runs from
* `.husky/pre-commit`, and a commit hook that launches Chromium fails on any
* machine that has not downloaded it. `make test-browser` opts in.
*/
"@storybook/addon-vitest",
],
framework: { name: "@storybook/html-vite", options: {} },
/*
* The fonts, which the overlay cannot render honestly without.
*
* `styles/index.ts` declares `@font-face` against `/__airship/fonts/*.woff2`,
* and in production only the proxy serves that path
* (`packages/server/src/proxy.ts`). The files themselves are emitted by
* `@airship/editor-tokens`' postbuild, so this mapping is why the `storybook`
* turbo task depends on that package's `build` — Storybook errors at startup
* on a missing `from`, rather than starting up and rendering everything in
* fallback fonts. Failing loudly is the right trade: the dock is 11px type in
* a 360px column, and it is a different piece of design in Helvetica.
*/
staticDirs: [
{ from: "../../editor-tokens/dist/fonts", to: "/__airship/fonts" },
],
stories: ["../src/**/*.stories.ts"],
};
export default config;
+247
View File
@@ -0,0 +1,247 @@
import type { Preview } from "@storybook/html-vite";
import { PREFIX } from "../src/dom";
import { closeOpenPopover, mountPopoverHost } from "../src/popover-host";
import { setCaptionsEnabled } from "../src/stories/captions";
import { runStoryTeardown } from "../src/stories/lifecycle";
import { overlayCss } from "../src/styles";
import { setRuntimeTokens, setStaticTokens } from "../src/tokens/registry";
/*
* What every story needs around it before it can be looked at honestly.
*
* Each of the four things below is a *silent* failure if skipped: nothing
* throws, the story renders, and what you are looking at is wrong. That is the
* whole reason they are here rather than in each story.
*/
/**
* The overlay stylesheet, as one tag, re-written in place.
*
* Deliberately not `injectStyles()`. That function guards on a module-level
* `injected` flag, and Vite resets module state on HMR — so editing any
* `styles/*.css.ts` clears the flag and appends a *second*
* `<style id="__airship-styles">`. New rules would win on order, but rules you
* had just *deleted* would keep applying from the stale tag, which is the
* failure mode most likely to waste an afternoon during a CSS pass.
*
* The id is load-bearing beyond identifying the tag: `isOwnSheet`
* (`inspector/css-rules.ts`) matches on exactly this string, and it is what
* stops the overlay's own three thousand rules being reported to the CSS pane as
* the inspected page's provenance.
*/
function syncStyles(): void {
const id = `${PREFIX}-styles`;
const tag = document.getElementById(id) ?? document.createElement("style");
tag.id = id;
const css = overlayCss();
if (tag.textContent !== css) {
tag.textContent = css;
}
if (!tag.isConnected) {
document.head.append(tag);
}
}
/**
* A registry with nothing in it.
*
* `setStaticTokens`/`setRuntimeTokens` write module singletons, so one token
* story would otherwise leave a design-token badge on every field of every story
* rendered after it — and, worse, in whichever order Storybook happened to visit
* them. Stories that want tokens seed them themselves.
*/
function resetTokens(): void {
const empty = { framework: "unknown", tokens: [] } as const;
setStaticTokens(empty);
setRuntimeTokens(empty);
}
/**
* Fill in the caption's title from Storybook's own metadata.
*
* The strip renders an empty title slot and this stamps it, rather than each
* story writing its own name into its caption. Two reasons, and the second is
* the real one: it removes ~150 restatements of a name Storybook already knows,
* and it makes the heading structurally incapable of disagreeing with the
* sidebar entry that got you there.
*
* `title.split("/").at(-1)` because the full path is already the breadcrumb
* above the canvas — repeating "Inspector/Sections/" inside the frame spends a
* line on something the reader can see.
*/
function stampTitle(root: HTMLElement, title: string, name: string): void {
const slot = root.querySelector<HTMLElement>("[data-story-title]");
if (slot) {
slot.textContent = `${title.split("/").at(-1) ?? title} · ${name}`;
}
}
const preview: Preview = {
decorators: [
(story, context) => {
/*
* Teardown at entry rather than on unmount.
*
* A popover left open by the previous story is anchored to a control that
* no longer exists, and Storybook's unmount hook is not somewhere to rely
* on for a module singleton. Closing here is idempotent and runs even when
* the previous story crashed.
*
* `runStoryTeardown` is the same contract for the stories that bind
* outside their own DOM — a canvas viewport listening on `window`, a
* `Tooltips` instance on `document`, a `ResizeObserver` held by a
* selection marker. See `stories/lifecycle.ts`.
*/
closeOpenPopover();
runStoryTeardown();
syncStyles();
resetTokens();
// Before `story()`: `stage()` reads this while it builds, and it is called
// from inside `render`, which Storybook hands no context.
setCaptionsEnabled(context.globals.captions !== "off");
/*
* `#__airship-root`, and it has to be exactly that.
*
* The design tokens are emitted scoped rather than on `:root` — see the
* `VARS` block in `styles/index.ts`, which exists so the editor's palette
* cannot leak into the app being edited. A `var(--ap-*)` referenced outside
* that selector list is invalid-at-computed-value-time, and the browser
* drops the whole declaration without a word. Rendering a control outside
* this element does not produce an unstyled control; it produces a
* differently-broken one.
*/
const root = document.createElement("div");
root.id = `${PREFIX}-root`;
root.append(story() as Node);
/*
* Re-parent the popover host into *this* root, every render.
*
* `mountPopoverHost` reuses a cached module-level node and `append`s it,
* which moves it. Called once, the host would stay in the first story's
* subtree and be detached from the document from the second story onward.
* Left to heal itself, `openPopover` mounts it on `document.body` — outside
* the token scope above, so every menu, colour picker and gradient editor
* would open unstyled.
*
* Last child of the root, matching `AirshipApp.mount`.
*/
mountPopoverHost(root);
// After the story has built its DOM, because the slot is inside it.
stampTitle(root, context.title, context.name);
return root;
},
],
globalTypes: {
captions: {
description: "The explanatory strip above each story",
toolbar: {
icon: "info",
items: [
{ title: "Captions on", value: "on" },
{ title: "Captions off", value: "off" },
],
title: "Captions",
},
},
},
/*
* Dark by default, because the editor has no light mode.
*
* Three of the border tokens are `rgba(255,255,255,0.06…0.12)`. On a white
* canvas they are invisible, so a hairline that was never drawn looks exactly
* like one that was — which is the single easiest way for a Storybook to lie
* about this particular UI.
*/
initialGlobals: { backgrounds: { value: "editor" }, captions: "on" },
parameters: {
/*
* Report every axe violation; do not fail on one. Yet.
*
* `"error"` is where this should end up and is one word away. It is not the
* setting today because turning it on lights up 114 of 157 stories, and a
* suite that is permanently red is a suite people learn to ignore — which
* would cost more than the check is worth.
*
* The findings are real, and they are not 421 problems. Nearly all of them
* are four, and every one of the four is in the *product*, not the harness:
*
* - `aria-command-name` (241) — the drag-to-scrub grips. dnd-kit stamps
* `aria-roledescription="draggable"` on `.ctl-glyph` and gives it no
* accessible name. Injected by the library, not hand-written here.
* - `aria-allowed-attr` (55) and `button-name` (28) — `.sect-head` is a
* `<div>` carrying `aria-expanded`, and several icon buttons name
* themselves with `data-tip` (the overlay's own tooltip) rather than
* `aria-label`. `select.ts` already made exactly this correction for the
* select trigger and wrote down why; the rest have not had it yet.
* - `nested-interactive` (49) — the scrub grip is focusable and sits inside
* the field that owns the `<input>`.
*
* The remainder is `color-contrast` (44, mostly `.insp-src`) and
* `scrollable-region-focusable` (4) on the panel body.
*
* ## Read the rate, not the total
*
* The catalogue went from 96 stories to 157, so the total was always going
* to rise; what matters is that the *set of rules* is unchanged and the rate
* fell slightly — about 2.7 findings per story, from 2.9. Anything that adds
* a rule category is a regression however small its count, because the value
* of this list is being able to say "the a11y report is these four known
* problems" and have it stay true.
*
* That bar caught a real regression during the caption work, which is the
* argument for measuring rather than reasoning. The strip was designed with
* no background of its own, on the theory that the backgrounds addon owns the
* ground; axe resolves contrast against the nearest *painted* ancestor,
* found the document's white instead, and reported all four caption lines on
* every story — 189 new `color-contrast` findings, on a report that had
* three. Painting the strip fixed it. To re-measure: flip this to `"error"`,
* run `make test-browser`, and count the rule names in the output.
*
* The one change that would move the total meaningfully is making
* `.sect-head` a `<button aria-expanded>` in `inspector/panel.ts`, which
* clears most of `aria-allowed-attr` and `button-name` at once. That is a
* product change rather than a Storybook one, and doing it in
* `stories/chrome.ts`'s copy alone would make the harness disagree with the
* thing it is a copy of.
*
* `inspector/a11y.test.ts` continues to assert the hand-wired parts —
* `role="group"` on segmented groups, `aria-pressed` per cell,
* `aria-haspopup="menu"` on selects — as hard failures under happy-dom.
*/
a11y: { test: "todo" },
backgrounds: {
options: {
// `canvas` is the substrate the frames sit on in canvas mode; `page` is
// the white the docks float over, for the stories that show a subject
// element as the user's own app would render it.
canvas: { name: "Canvas", value: "#1e1e1e" },
editor: { name: "Editor", value: "#242424" },
page: { name: "Page", value: "#ffffff" },
},
},
/*
* Autodocs off, and not as a matter of taste.
*
* A docs page renders every story in a file onto one document. That means N
* elements all carrying `id="__airship-root"`, N `DesignPanel` instances each
* running a full stylesheet scan on mount, and N calls to `mountPopoverHost`
* moving the one singleton host between them. The last one wins and the rest
* are quietly broken.
*/
docs: { autodocs: false },
},
tags: [],
};
export default preview;
+26
View File
@@ -0,0 +1,26 @@
/*
* Whether stories draw their caption strip.
*
* A module singleton with a toolbar toggle in front of it, which is the same
* shape — and for the same reason — as the token registry `preview.ts` resets
* between stories: `stage()` is called from inside `render()`, which Storybook
* hands no context, and threading a context argument through every one of the
* catalogue's ~150 call sites to carry one boolean would be a worse trade than
* one piece of module state set by the decorator a moment earlier.
*
* It is on by default, and stays on under `make test-browser`. The caption is
* catalogue chrome that renders on every story, so it should be smoke-tested
* like everything else; the toggle exists so a reviewer can look at nothing but
* product UI, and so a future screenshot tier can turn it off with one global
* rather than a rebuild.
*/
let enabled = true;
export function setCaptionsEnabled(next: boolean): void {
enabled = next;
}
export function captionsEnabled(): boolean {
return enabled;
}
+464
View File
@@ -0,0 +1,464 @@
import { hide, place, placeLabel } from "../chrome-layer";
import { cls, el, elementLabel, PREFIX } from "../dom";
import { icon } from "../icons";
import { MIN_DOCK_W } from "../styles/const";
import { localRect, type Surface } from "../surface";
import { captionsEnabled } from "./captions";
import { onStoryTeardown } from "./lifecycle";
/*
* The dock a story renders inside.
*
* This exists because the inspector does not size itself and never has.
* `.__airship-insp` is `flex: 1 1 auto` with no width of its own
* (`styles/inspector.css.ts`); the 360px comes from
* `.__airship-dock-right { width: var(--__airship-right-w, 360px) }` in
* `styles/docks.css.ts`, one level up. A control dropped into a bare `<div>` is
* therefore rendered at whatever width the viewport happens to be, and
* `.__airship-grid` — `repeat(auto-fill, minmax(max(72px, (100% - 8px) / 2), 1fr))`
* — resolves to four or five columns instead of two.
*
* That is not a cosmetic difference. Every judgement anyone would come to
* Storybook to make about this UI is a judgement about density in a 360px
* column: whether two fields fit on a row, whether a label elides, whether the
* glyph and the value crowd each other. A story at 1200px is a picture of a
* panel that does not exist.
*
* So: real classes, real nesting, real width. Nothing here restyles the
* overlay. The single exception is `HARNESS_CSS` below, which is about the page
* the dock is on rather than the dock.
*/
/**
* The one piece of CSS this harness owns.
*
* `.__airship-dock` is `position: fixed` with `top`/`bottom` insets and a
* `z-index` of 2147483600, because in the product it floats over the user's
* running app. In a story that is wrong twice over: it escapes the story's own
* canvas, and it makes the dock as tall as the viewport regardless of how much
* is in it, so eight rows of controls sit in a column of grey.
*
* Neutralising it here, rather than adding a story-only class to `docks.css.ts`,
* keeps the product stylesheet describing the product. The rules are scoped to
* `[data-story-dock]`, which nothing in the overlay ever sets.
*/
const HARNESS_CSS = `
/* The outer column: caption above, stage below. The page-height and the padding
live here rather than on the stage, because the stage is a *row* and a caption
inside it would lay out as a third column beside the page and the dock. */
.${PREFIX}-story-shell {
display: flex;
flex-direction: column;
min-height: 100vh;
padding: 24px;
box-sizing: border-box;
}
.${PREFIX}-story-stage {
display: flex;
align-items: flex-start;
gap: 24px;
flex: 1 1 auto;
/* Without this a tall page pane cannot shrink and pushes the row past the
shell, which puts the dock's own scrollbar outside the window. */
min-height: 0;
}
[data-story-dock] {
position: relative;
inset: auto;
z-index: auto;
max-height: calc(100vh - 48px);
flex: 0 0 auto;
}
/* The page pane: what the user's own app looks like under the dock. Deliberately
plain — anything decorative here competes with the thing being reviewed. */
.${PREFIX}-story-page {
flex: 1 1 auto;
align-self: stretch;
background: #fff;
border-radius: 6px;
padding: 32px;
min-height: 320px;
font: 400 14px/1.5 system-ui, sans-serif;
color: #111;
overflow: auto;
}
/* --- The caption strip -------------------------------------------------- */
/*
* Marginalia *about* the editor, which must never be mistaken for part of it.
*
* Hence \`system-ui\` rather than \`var(--ap-font-sans)\`: set in Inter at the
* editor's own tokens, a two-line block above a panel reads as a panel header,
* and the catalogue would be annotating itself in the voice of the thing it is
* annotating. A different typeface is the cheapest possible signal that this
* text is not shipping to anyone.
*
* Three more choices here are load-bearing rather than cosmetic:
*
* **\`<p>\` only, never a heading.** \`<h2>\`/\`<h3>\` would light up axe's
* \`heading-order\` and \`empty-heading\` — two rule *categories* the overlay's
* current findings do not contain. Adding instances to a category already being
* tracked costs nothing; adding a category costs the ability to say "the a11y
* report is these four known problems".
*
* **It paints its own background**, and that is a correction rather than a
* preference. The first version deliberately painted none, reasoning that the
* backgrounds addon owns the ground and a strip with three possible grounds
* behind it would need three sets of values. That was wrong in a way only
* measurement caught: axe resolves a contrast pair by walking up for the nearest
* *painted* ancestor, and the addon's ground is not one — so it compared this
* text against the document's white and reported every caption line as failing.
* About a hundred and ninety new \`color-contrast\` findings, on a report that
* had three.
*
* Painting it makes the pair self-contained: one ground, one set of colours, the
* same reading under every background the addon offers. Every value below clears
* 8:1 against it, so the strip has room to be restyled without anyone having to
* re-run axe to find out whether it still passes.
*/
.${PREFIX}-story-caption {
max-width: 62ch;
margin: 0 0 20px;
padding: 10px 14px;
border-left: 2px solid #3d3d3d;
border-radius: 0 4px 4px 0;
background: #1c1c1c;
font: 400 12px/1.55 system-ui, -apple-system, sans-serif;
color: #b8b8b8;
}
.${PREFIX}-story-caption-eyebrow {
margin: 0;
font-size: 10px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.${PREFIX}-story-caption-title {
margin: 2px 0 0;
font-weight: 600;
color: #e8e8e8;
}
.${PREFIX}-story-caption-what { margin: 6px 0 0; }
.${PREFIX}-story-caption-try { margin: 4px 0 0; color: #9ec9e8; }
`;
/** Install the harness stylesheet once per document. */
function harnessStyles(): void {
const id = `${PREFIX}-story-css`;
if (document.getElementById(id)) {
return;
}
const tag = document.createElement("style");
tag.id = id;
tag.textContent = HARNESS_CSS;
document.head.append(tag);
}
/**
* The dock header, as `AirshipApp.buildRightDock` builds it.
*
* Included rather than skipped because it is the top 32px of every screenshot
* anyone will take of this panel, and because it is what establishes that the
* thing below it is a dock and not a floating fragment.
*/
function dockHead(label: string): HTMLElement {
return el("div", { class: cls("head") }, [
el("div", { class: cls("brand") }, [
icon("settings", "sm"),
el("span", { class: cls("brand-name"), text: label }),
]),
]);
}
export interface DockOptions {
/** Header label. Defaults to "Design", matching the right dock. */
label?: string;
/**
* Render at `MIN_DOCK_W`, the floor the splitter clamps to.
*
* A named flag rather than `width: 280`, which is what six story files used to
* say. The number is interesting exactly once — in `styles/const.ts`, where it
* is defined — and a story restating it is a story that will still say 280
* after somebody changes the floor to 260.
*/
narrow?: boolean;
/**
* Override the dock width outright. The default is the product's own 360px.
* Prefer `narrow` for the common case; this is for a story that wants some
* third width and has a reason.
*/
width?: number;
}
/** Resolve the two width options to the pixel value `dock()` should apply. */
function dockWidth(opts: DockOptions): number | undefined {
if (opts.width !== undefined) {
return opts.width;
}
return opts.narrow ? MIN_DOCK_W : undefined;
}
/**
* A right dock containing `body`, at the real width.
*
* `body` is whatever plays the part of `DesignPanel.element` — either the panel
* itself (`panelStory`) or the `.insp` scaffold from `inspectorBody` below.
*/
export function dock(body: HTMLElement, opts: DockOptions = {}): HTMLElement {
harnessStyles();
const node = el(
"div",
{
class: `${cls("dock")} ${cls("dock-right")}`,
"data-story-dock": "",
},
[dockHead(opts.label ?? "Design"), body]
);
const width = dockWidth(opts);
if (width !== undefined) {
node.style.setProperty(`--${PREFIX}-right-w`, `${width}px`);
}
return node;
}
/**
* The inspector scaffold, without a `DesignPanel`.
*
* `.insp` → `.insp-body` is the chain that gives the body its scroll and its
* column direction; sections and controls below it inherit both. For the control
* stories, which have no panel to build it for them.
*/
export function inspectorBody(children: HTMLElement[]): HTMLElement {
return el("div", { class: cls("insp") }, [
el("div", { class: cls("insp-body") }, children),
]);
}
/**
* One collapsible section shell, matching `DesignPanel.section`'s markup.
*
* A static copy: the panel's own version carries collapse state keyed on an id,
* and a control story has no panel to hold that state. The classes and the
* nesting are the same, so the padding and the dividers are the ones the product
* draws. Section *stories* use the real thing — see `stories/story-panel.ts`.
*/
export function section(label: string, body: HTMLElement): HTMLElement {
return el("div", { class: cls("sect") }, [
el("div", { "aria-expanded": "true", class: cls("sect-head") }, [
el("span", { class: cls("sect-title"), text: label }),
]),
el("div", { class: cls("sect-body") }, [body]),
]);
}
/**
* The two-column field grid.
*
* The reason the width above matters. Pass `span: "full"` controls as-is — they
* carry `.span2` themselves — and half-width ones in pairs, which is how they
* appear in the panel.
*/
export function grid(children: HTMLElement[]): HTMLElement {
return el("div", { class: cls("grid") }, children);
}
/*
* A labelled full-width row is `labelled()` from `inspector/sections/row.ts`.
* Stories import it straight from there rather than through this module: the
* sections build their word-labelled rows with it, a second copy here would be
* one `.span2` away from drifting, and re-exporting it would make this file a
* barrel for no gain.
*/
// ---------------------------------------------------------------------------
// The caption
// ---------------------------------------------------------------------------
/**
* What a story says about itself, in the canvas.
*
* Every file in this catalogue carries a long comment explaining what its
* stories are for and why they are shaped the way they are, and until now
* Storybook displayed none of it: autodocs is off for reasons `preview.ts` sets
* out, and there is no other surface a `@storybook/html-vite` story can put
* prose on. So a reader arriving at "Inspector/Sections/Stroke · Translucent"
* got a panel, an element, and no way to know what they were supposed to notice.
*
* The rule for writing one, which matters more than the API: **a caption quotes
* the docstring's thesis, it does not summarise it.** The reasoning stays in the
* source comment where it has room to be an argument. This is the sentence
* somebody reads before deciding whether to keep looking.
*/
export interface Caption {
/**
* One line: what to poke, for the stories where poking is the point.
*
* Omitted rather than invented when a story is a picture and nothing more —
* "try: look at it" trains people to stop reading the field.
*/
try?: string;
/** One line: what this story demonstrates. */
what: string;
}
/**
* The strip itself.
*
* The title slot is left *empty* on purpose. `preview.ts` fills it after the
* story renders, from Storybook's own `context.title` and `context.name`, so the
* heading and the sidebar entry cannot disagree. Writing it at the call site
* would mean 150 story names restated in 150 captions, each one rename away from
* lying about which story you are looking at.
*/
function captionStrip(caption: Caption): HTMLElement {
return el("div", { class: cls("story-caption") }, [
el("p", { class: cls("story-caption-eyebrow"), text: "Story" }),
el("p", { class: cls("story-caption-title"), "data-story-title": "" }),
el("p", { class: cls("story-caption-what"), text: caption.what }),
...(caption.try
? [
el("p", {
class: cls("story-caption-try"),
text: `Try: ${caption.try}`,
}),
]
: []),
]);
}
// ---------------------------------------------------------------------------
// The selection marker
// ---------------------------------------------------------------------------
/**
* The product's own selection outline and identity badge, over a story's
* subject.
*
* The inspector is a view *of a node*, and until this existed the page pane
* never said which node — so forty-one stories showed the same page and left the
* reader to infer the subject from the values in the dock, which is exactly
* backwards. Now the difference between `Fill · Solid` and `Fill · Gradient` is
* visible at a glance, in the pane, where it happens.
*
* Deliberately **not** a `SelectionController`. That class is fifteen hundred
* lines over nine collaborators with eight dnd-kit draggables bound to it, and
* what a story needs from it is the *picture*. The picture is two nodes on a
* chrome layer positioned by `place()` and `placeLabel()` — the same two class
* names, the same two functions and the same label format the controller itself
* uses, so the story and the product cannot drift apart on geometry or styling
* without a compiler error.
*
* The eight resize handles are the one thing left out, and that is a decision
* rather than an omission: nothing in a story can be dragged, and drawing grips
* advertises a gesture that is not there.
*/
export function markSelection(node: Element, surface?: Surface): HTMLElement {
harnessStyles();
const layer = el("div", { class: cls("chrome-layer") });
const box = el("div", { class: `${cls("layer")} ${cls("sel-box")}` });
const label = el("div", { class: `${cls("layer")} ${cls("box-label")}` });
layer.append(box, label);
const draw = (): void => {
if (!node.isConnected) {
hide(box);
hide(label);
return;
}
// The element's own box, then converted — same as `drawOutline`. A framed
// subject reports coordinates inside its own document, and `toScreen` is the
// production conversion; a same-document subject is already in screen space,
// which is what makes one code path cover both realms.
const local = localRect(node);
const screen = surface ? surface.toScreen(local) : local;
place(box, screen);
// The element's own size, not its on-screen size — the width you are about
// to edit is 200px whatever the frame is doing.
label.textContent = `${elementLabel(node)} · ${Math.round(local.width)}×${Math.round(local.height)}`;
placeLabel(label, screen, surface?.bounds()?.top ?? 0);
};
/*
* Three passes, because the subject's box is not final when this is called.
*
* The first frame is after Storybook has appended the story and the browser
* has laid it out. `loadingdone` is the one that matters most: the specimens
* are set in system-ui and Inter, and a badge reading 420×61 before the
* webfont lands and 420×64 after would be reporting a measurement of the
* fallback. An event rather than `document.fonts.ready` because it fires for
* every later load too, and because it is disposable — a promise resolving
* into a story that has been unmounted has nothing to hold on to. The observer
* then covers the rest: an image decoding, a frame loading, the dock dragged
* narrower.
*/
requestAnimationFrame(draw);
document.fonts.addEventListener("loadingdone", draw);
const observer = new ResizeObserver(draw);
observer.observe(node);
onStoryTeardown(() => {
observer.disconnect();
document.fonts.removeEventListener("loadingdone", draw);
});
return layer;
}
// ---------------------------------------------------------------------------
// The stage
// ---------------------------------------------------------------------------
export interface StageOptions extends DockOptions {
/** What this story is for. See `Caption`. */
caption?: Caption;
/**
* Content for the page pane beside the dock — the user's app, as the inspector
* sees it. Omit for a dock on its own.
*/
page?: HTMLElement;
}
/**
* The dock, on a ground, optionally beside the page it is inspecting.
*
* This is the top-level wrapper every story returns. The two-pane form is the
* honest picture for anything driven by a real element: the inspector is a view
* of something, and a story that shows the panel without the node it describes
* hides half of what it is doing.
*/
export function stage(body: HTMLElement, opts: StageOptions = {}): HTMLElement {
harnessStyles();
const row = el("div", { class: cls("story-stage") }, [dock(body, opts)]);
if (opts.page) {
row.prepend(el("div", { class: cls("story-page") }, [opts.page]));
}
return shell(opts.caption, row);
}
/**
* A bare stage for the stories that are not dock-shaped — toasts, popover
* shells, canvas chrome. Same ground and padding, no dock.
*/
export function plainStage(
children: HTMLElement[],
caption?: Caption
): HTMLElement {
harnessStyles();
return shell(caption, el("div", { class: cls("story-stage") }, children));
}
/**
* The outer column: caption, then stage.
*
* A selection marker gets prepended to what this returns, ahead of the caption,
* and that ordering is the point. `.chrome-layer` and `.dock` both declare the
* same `z-index`, so DOM order breaks the tie — which is precisely how the
* product arranges it (see the note at the top of `chrome-layer.ts`: the root is
* appended *after* the layer so the docks draw over it). First child means the
* outline runs under the dock rather than over it, as it does in the app. It
* also means Storybook's unmount takes the layer away with the story.
*/
function shell(caption: Caption | undefined, row: HTMLElement): HTMLElement {
const children =
caption && captionsEnabled() ? [captionStrip(caption), row] : [row];
return el("div", { class: cls("story-shell") }, children);
}
+506
View File
@@ -0,0 +1,506 @@
import type {
FileDiff,
JobDiffBundle,
JobHistorySummary,
TimelineItem,
TodoItem,
} from "@airship/protocol";
import type { DesignToken } from "@airship/protocol/tokens";
import { setRuntimeTokens } from "../tokens/registry";
/*
* Data the stories stand things up with.
*
* Kept in one module rather than inline per story for a reason that is about
* honesty rather than tidiness: a design token, a timeline item and a unified
* patch are all shapes the *server* produces, and a story that invents a
* plausible-looking one teaches the reader something that may not be true. These
* are modelled on the real thing — `@airship/protocol`'s types are the contract,
* and TypeScript enforces the shape here the same way it does in production.
*
* `preview.ts` resets the token registry before every story, so anything wanting
* tokens has to ask for them. That is deliberate: token affordances change what
* every field in the panel looks like, and a story that inherited them from
* whichever story ran before it would be a different picture depending on the
* order you clicked.
*/
/**
* A callback that records nothing.
*
* Every control takes an `onChange`, and a story that only wants to look at one
* has nothing to do with the value. Eight files had declared their own copy of
* this line; one export is not tidier so much as it is one fewer thing that can
* quietly become `() => {}` in one file and `() => undefined` in the next while
* Biome argues about which it prefers.
*/
export const noop = (): undefined => undefined;
/**
* The blue a demo design system is built around.
*
* Exported because it is the *same fact* as `--pk-brand-primary` below, and
* before this it was stored twice: nine literal `#0D99FF`s across the colour and
* gradient stories, plus the token's own value. A story that pins a swatch to
* one and the badge to the other is a story about a design system that does not
* match itself — which is a real thing to demonstrate, but not by accident.
*/
export const BRAND = "#0D99FF";
/**
* A small, plausible token set — the shape a Tailwind v4 `@theme` block or a
* hand-rolled custom-property scale actually scans to.
*
* Deliberately not exhaustive. The point is that *some* properties have tokens
* and others do not, because a badge appearing on every field would hide the one
* decision the affordance is asking you to make.
*/
export const TOKENS: DesignToken[] = [
{
category: "spacing",
kind: "css-var",
name: "--pk-space-xs",
origin: "runtime",
values: { "": "8px" },
},
{
category: "spacing",
kind: "css-var",
name: "--pk-space-md",
origin: "runtime",
values: { "": "16px" },
},
{
category: "spacing",
kind: "css-var",
name: "--pk-space-lg",
origin: "runtime",
values: { "": "24px" },
},
{
category: "colors",
kind: "css-var",
name: "--pk-brand-primary",
origin: "runtime",
// `BRAND`, so a story can paint a swatch this colour and have the badge
// light up because the two agree, not because both were typed correctly.
values: { "": BRAND },
},
{
category: "colors",
kind: "css-var",
name: "--pk-surface-raised",
origin: "runtime",
values: { "": "#FFFFFF" },
},
{
// An alias, which is the case `aliasOf` exists for: a design system that
// defines a primitive scale and re-exports it under app-facing names. Both
// names are real, and without this the picker would offer two identical
// entries and the prompt could not say which one the codebase writes.
aliasOf: "--pk-space-md",
category: "spacing",
kind: "css-var",
name: "--pk-gutter",
origin: "runtime",
values: { "": "16px" },
},
{
category: "border-radius",
kind: "css-var",
name: "--pk-radius-md",
origin: "runtime",
values: { "": "8px" },
},
{
// The long name, for the elision the badge and the bound field both have to
// do. Real design systems produce these; `shortName` is what copes.
category: "colors",
kind: "css-var",
name: "--pk-semantic-success-background-subtle",
origin: "runtime",
values: { "": "rgba(46, 204, 113, 0.12)" },
},
];
/**
* Seed the registry for one story.
*
* Call it at the top of `render`. `preview.ts` clears the registry first, so
* this is additive to nothing and cannot leak forward.
*/
export function withTokens(tokens: DesignToken[] = TOKENS): void {
setRuntimeTokens({ framework: "custom", tokens });
}
/**
* A unified diff, as `@airship/core` captures one after an edit.
*
* Two hunks and a rename-free single file, which is the common case the diff
* renderer was built for. It carries a context line with a tab, a deletion, an
* addition and a no-newline marker — between them those cover every branch in
* `parseUnifiedPatch`.
*/
export const PATCH = `--- a/src/components/hero.tsx
+++ b/src/components/hero.tsx
@@ -12,7 +12,7 @@ export function Hero() {
return (
<section className="hero">
<h1 className="hero-title">Ship it visually</h1>
- <button className="rounded px-4 py-2 bg-slate-900 text-white">
+ <button className="rounded-lg px-6 py-3 bg-blue-600 text-white">
Get started
</button>
</section>
@@ -38,4 +38,8 @@ export function Hero() {
.hero-title {
font-size: 2.5rem;
}
+
+.hero button:hover {
+ filter: brightness(1.1);
+}
`;
/** A one-line patch, for the empty-ish end of the diff renderer. */
export const SMALL_PATCH = `--- a/src/app.css
+++ b/src/app.css
@@ -1,3 +1,3 @@
.card {
- padding: 12px;
+ padding: 16px;
}
`;
/** The two-hunk patch as a `FileDiff`, which is what `renderDiff` takes. */
export const DIFF: FileDiff = {
additions: 5,
deletions: 1,
file: "src/components/hero.tsx",
isDeleted: false,
isNew: false,
patch: PATCH,
};
/** A one-line change, for the short end of the renderer. */
export const SMALL_DIFF: FileDiff = {
additions: 1,
deletions: 1,
file: "src/app.css",
isDeleted: false,
isNew: false,
patch: SMALL_PATCH,
};
/** A brand-new file — `isNew` changes the header, not the body. */
export const NEW_DIFF: FileDiff = {
additions: 3,
deletions: 0,
file: "src/components/badge.tsx",
isDeleted: false,
isNew: true,
patch: `--- /dev/null
+++ b/src/components/badge.tsx
@@ -0,0 +1,3 @@
+export function Badge({ count }: { count: number }) {
+ return <span className="badge">{count}</span>;
+}
`,
};
export const TODOS: TodoItem[] = [
{ content: "Find where the hero button is defined", status: "completed" },
{ content: "Update the padding and radius", status: "completed" },
{ content: "Check the mobile frame still fits", status: "in_progress" },
{ content: "Run the type check", status: "pending" },
];
/**
* One agent turn, as the socket delivers it.
*
* Every branch the row renderers have: a tool that succeeded, one that is still
* pending, one that failed, a thinking block, assistant prose with markdown, and
* a todo list. `startedAt` is ms since job start — relative, so a persisted
* bundle stays diffable and clock-agnostic, which is also why these are stable
* numbers rather than anything derived from the clock.
*/
export const TIMELINE: TimelineItem[] = [
{
estimatedTokens: 340,
id: "t0",
kind: "thinking",
startedAt: 120,
text: "The hero button is probably a Tailwind-styled element. I should find the component first rather than guessing at the class names.",
},
{
args: { path: "src", pattern: "hero" },
endedAt: 940,
id: "t1",
kind: "tool",
name: "Grep",
phase: "ok",
result: { text: "3 files · 11 matches" },
startedAt: 400,
title: "Grep(hero)",
},
{
args: { file_path: "src/components/hero.tsx" },
endedAt: 1310,
id: "t2",
kind: "tool",
name: "Read",
phase: "ok",
result: {
detail:
' 10 | export function Hero() {\n 11 | return (\n 12 | <section className="hero">\n 13 | <h1 className="hero-title">Ship it visually</h1>\n 14 | <button className="rounded px-4 py-2 bg-slate-900 text-white">',
droppedLines: 196,
text: "Read 214 lines",
truncated: true,
},
startedAt: 950,
title: "Read(src/components/hero.tsx)",
},
{
args: { file_path: "src/components/hero.tsx" },
endedAt: 1980,
id: "t3",
kind: "tool",
name: "Edit",
phase: "ok",
result: { text: "+5 −1" },
startedAt: 1320,
title: "Edit(src/components/hero.tsx)",
},
{ id: "t4", kind: "todos", startedAt: 2000, todos: TODOS },
{
args: { command: "pnpm typecheck" },
endedAt: 5400,
id: "t5",
kind: "tool",
name: "Bash",
phase: "error",
result: {
detail:
"src/components/hero.tsx:14:9 - error TS2322: Type 'string' is not assignable to type 'number'.\n\n14 <Badge count=\"3\" />\n ~~~~~",
text: "exit 2 · 1 error",
},
startedAt: 2010,
title: "Bash(pnpm typecheck)",
},
{
args: { file_path: "src/components/hero.tsx" },
id: "t6",
kind: "tool",
name: "Edit",
// Still running: no `endedAt`, no `result`. The row has to say so without
// implying a result it does not have.
phase: "pending",
startedAt: 5410,
title: "Edit(src/components/hero.tsx)",
},
{
id: "t7",
kind: "text",
startedAt: 5500,
streaming: true,
text: "I've updated the hero button to use a **larger radius** and the blue-600 background. One type error came back from `pnpm typecheck` — `count` wants a number, so I'm fixing that now.",
},
];
// ---------------------------------------------------------------------------
// Finished jobs
// ---------------------------------------------------------------------------
/**
* What the agent hands back when an edit lands.
*
* `JobDiffBundle` is a `JobHistorySummary` plus the heavy fields, and the split
* matters: the server's `toSummary()` strips `timeline` before a bundle rides in
* a history listing, so the two shapes are genuinely different objects in
* production rather than one object read two ways.
*/
export const BUNDLE: JobDiffBundle = {
additions: 6,
agent: "claude",
completedAt: 1_733_000_012_400,
createdAt: 1_733_000_000_000,
deletions: 2,
diffs: [DIFF, SMALL_DIFF],
filesChanged: 2,
followUps: [
"Make the same change to the secondary button",
"Add a focus ring that matches the new radius",
"Check the mobile frame at 393px",
],
jobId: "job-1",
prompt: "Make the hero button rounder and use the brand blue",
promptPreview: "Make the hero button rounder and use the brand blue",
status: "done",
summary:
"Updated the hero button to a **larger radius** and the `blue-600` background.\n\n- Padding is now `px-6 py-3`\n- Added a `:hover` brightness lift\n\nThe secondary button is untouched — say the word and I'll match it.",
target: {
displayName: "Hero",
source: { file: "src/components/hero.tsx", line: 14 },
tagName: "button",
},
timeline: TIMELINE,
usage: { costUsd: 0.0412, inputTokens: 18_400, outputTokens: 1260 },
};
/**
* The same job, with tokens reported and no price.
*
* Codex does this, and so does Claude under subscription auth. The meta line
* used to be gated on the dollar figure, so this shape silently dropped the file
* and ±line counts along with the cost — a bundle that had done real work
* reporting nothing about it.
*/
export const BUNDLE_NO_COST: JobDiffBundle = {
...BUNDLE,
agent: "codex",
jobId: "job-2",
usage: { inputTokens: 18_400, outputTokens: 1260 },
};
/** A failed job, which puts the error class on the bubble. */
export const BUNDLE_FAILED: JobDiffBundle = {
...BUNDLE,
additions: 0,
deletions: 0,
diffs: [],
error:
"The dev server returned 500 while re-rendering src/components/hero.tsx. No changes were written.",
filesChanged: 0,
followUps: undefined,
jobId: "job-3",
status: "failed",
summary: undefined,
usage: undefined,
};
/**
* A failure with nothing to say about itself.
*
* `bundle.error || "Edit failed."` — an empty string is falsy, so this reaches
* the fallback. Worth its own fixture because an agent that dies without a
* message is the case a `??` would have got wrong.
*/
export const BUNDLE_FAILED_SILENT: JobDiffBundle = {
...BUNDLE_FAILED,
error: "",
jobId: "job-4",
};
/** Five files from one edit — the case every diff being folded shut exists for. */
export const BUNDLE_MANY: JobDiffBundle = {
...BUNDLE,
additions: 24,
deletions: 11,
diffs: [
DIFF,
SMALL_DIFF,
NEW_DIFF,
{ ...SMALL_DIFF, file: "src/components/nav.tsx" },
{ ...SMALL_DIFF, file: "src/styles/tokens.css" },
],
filesChanged: 5,
jobId: "job-5",
};
/**
* A history listing, as the threads drawer receives one.
*
* Three independent conversations, one of which was refined twice — `job-b2`
* and `job-b3` chain through `parentJobId`, which is what `groupThreads` folds
* into a single three-edit thread. Without a chain in the fixture the grouping
* is untestable and the story is a flat list pretending to be a tree.
*
* The timestamps are fixed offsets from `HISTORY_NOW` rather than from the
* clock, so the four `relativeTime` bands are pinned rather than sampled.
*/
export const HISTORY_NOW = 1_733_000_600_000;
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
export const HISTORY: JobHistorySummary[] = [
{
additions: 6,
agent: "claude",
completedAt: HISTORY_NOW - 30_000,
createdAt: HISTORY_NOW - 42_000,
deletions: 2,
filesChanged: 2,
jobId: "job-a",
promptPreview: "Make the hero button rounder and use the brand blue",
status: "done",
target: {
displayName: "Hero",
source: { file: "src/components/hero.tsx", line: 14 },
tagName: "button",
},
},
{
additions: 3,
agent: "claude",
completedAt: HISTORY_NOW - 5 * MINUTE,
createdAt: HISTORY_NOW - 5 * MINUTE - 20_000,
deletions: 1,
filesChanged: 1,
jobId: "job-b1",
promptPreview: "Tighten the card grid to three columns",
status: "done",
target: {
displayName: "CardGrid",
source: { file: "src/components/card-grid.tsx", line: 8 },
tagName: "div",
},
},
{
additions: 2,
agent: "claude",
completedAt: HISTORY_NOW - 4 * MINUTE,
createdAt: HISTORY_NOW - 4 * MINUTE - 15_000,
deletions: 2,
filesChanged: 1,
jobId: "job-b2",
parentJobId: "job-b1",
promptPreview: "Actually make the gap smaller too",
status: "done",
target: {
displayName: "CardGrid",
source: { file: "src/components/card-grid.tsx", line: 8 },
tagName: "div",
},
},
{
additions: 1,
agent: "claude",
createdAt: HISTORY_NOW - 3 * HOUR,
deletions: 0,
filesChanged: 1,
jobId: "job-b3",
parentJobId: "job-b2",
promptPreview: "And drop the shadow",
status: "running",
target: {
displayName: "CardGrid",
source: { file: "src/components/card-grid.tsx", line: 8 },
tagName: "div",
},
},
{
additions: 0,
agent: "codex",
completedAt: HISTORY_NOW - 6 * DAY,
createdAt: HISTORY_NOW - 6 * DAY - 90_000,
deletions: 0,
error: "Could not resolve src/components/footer.tsx",
filesChanged: 0,
jobId: "job-c",
promptPreview: "Centre the footer links",
status: "failed",
target: { displayName: null, source: null, tagName: "footer" },
},
];
@@ -0,0 +1,292 @@
import { design } from "@airship/editor-tokens";
import type { Meta, StoryObj } from "@storybook/html-vite";
import { cls, el } from "../dom";
import { plainStage } from "./chrome";
/*
* The palette and the type ramp, straight from `@airship/editor-tokens`.
*
* This page earns its place twice. It is the catalogue entry for the token set
* every other story renders through — `EDITOR.md` is the source of truth, and
* this is what that file actually looks like — and it is the canary for the two
* pieces of setup in `.storybook/preview.ts` that fail silently.
*
* If the swatches are transparent, `#__airship-root` is not wrapping the story
* and every `var(--ap-*)` in the overlay is being dropped as
* invalid-at-computed-value-time. If the type below renders in Helvetica,
* `staticDirs` is not serving `/__airship/fonts/*` and the whole editor is being
* previewed in the wrong face at the wrong metrics.
*
* The group → prefix pairs mirror `GROUPS` in `@airship/editor-tokens`' `css.ts`,
* which is what decides the emitted variable names. They are listed rather than
* imported because that table is not exported; a group renamed there shows up
* here as a page of transparent swatches, which is loud enough.
*/
const meta: Meta = {
title: "Foundations/Tokens",
};
export default meta;
const COLOUR_GROUPS = [
["Surface", "surface", design.surface],
["Border", "border", design.border],
["Text", "text", design.text],
["Icon", "icon", design.icon],
["Blue", "blue", design.blue],
["Semantic", "semantic", design.semantic],
] as const satisfies readonly (readonly [
string,
string,
Record<string, string>,
])[];
/** A labelled swatch: the emitted var, resolved by the browser. */
function swatch(name: string, cssVar: string): HTMLElement {
return el("div", { style: "display: grid; gap: 6px;" }, [
el("div", {
style: `height: 44px; border-radius: 4px; background: var(${cssVar});
border: 1px solid var(--ap-border-default);`,
}),
el("div", {
style:
"font: 400 11px var(--ap-font-sans); color: var(--ap-text-primary);",
text: name,
}),
el("div", {
style:
"font: 400 10px var(--ap-font-mono); color: var(--ap-text-tertiary);",
text: cssVar,
}),
]);
}
function grid(children: HTMLElement[]): HTMLElement {
return el(
"div",
{
style: `display: grid; gap: 16px; padding: 16px;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));`,
},
children
);
}
function heading(label: string): HTMLElement {
return el("h2", {
style: `margin: 24px 16px 0; font: 600 12px var(--ap-font-sans);
letter-spacing: .06em; text-transform: uppercase;
color: var(--ap-text-secondary);`,
text: label,
});
}
/**
* The setup assertions, run from inside the browser tier.
*
* This `play` is the guard that makes the whole catalogue trustworthy. Every
* failure mode in `.storybook/preview.ts` is *silent*: a story with no
* `#__airship-root` around it still renders, still passes a smoke test, and is
* simply the wrong picture — every `var(--ap-*)` dropped as
* invalid-at-computed-value-time, with nothing thrown and nothing logged. So the
* one thing that must never be checked by eye is checked here, on every run.
*
* It lives on this story rather than in a setup file because since Storybook
* 10.3 the vitest plugin applies `preview.ts` itself, and a hand-rolled
* `setProjectAnnotations` now conflicts with that. An assertion inside the run
* is the more honest check anyway: it proves the decorator *reached the story*,
* not merely that a config file was loaded.
*/
async function assertSetup(root: HTMLElement): Promise<void> {
const scope =
root.closest("#__airship-root") ?? root.querySelector("#__airship-root");
if (!scope) {
throw new Error(
"No #__airship-root around the story — the preview decorator did not run, " +
"so every --ap-* token is being dropped. See .storybook/preview.ts."
);
}
const read = (name: string) =>
getComputedStyle(scope).getPropertyValue(name).trim();
for (const token of [
"--ap-surface-panel",
"--ap-text-primary",
"--ap-space-md",
]) {
if (!read(token)) {
throw new Error(
`${token} resolved to nothing — the token scope is broken.`
);
}
}
if (!document.getElementById("__airship-styles")) {
throw new Error("The overlay stylesheet is not in the document.");
}
await document.fonts.ready;
for (const family of ["Inter", "JetBrains Mono"]) {
if (!document.fonts.check(`12px "${family}"`)) {
throw new Error(
`${family} is not loaded — staticDirs is not serving /__airship/fonts/*, ` +
"so the dock is being previewed at the wrong metrics."
);
}
}
/*
* The caption's title is stamped by the decorator, not written by the story,
* so a broken stamp is the same class of silent failure as the three above: a
* caption renders, reads correctly, and is headed by an empty line on every
* story in the catalogue. Checking it here means one story fails loudly rather
* than ~150 stories looking slightly unfinished.
*/
const title = scope.querySelector<HTMLElement>("[data-story-title]");
if (!title?.textContent?.trim()) {
throw new Error(
"The caption title is empty — the preview decorator did not stamp it. " +
"See `stampTitle` in .storybook/preview.ts."
);
}
}
/** Every colour group the token package emits, in the order it emits them. */
export const Colour: StoryObj = {
play: ({ canvasElement }) => assertSetup(canvasElement),
render: () =>
plainStage(
[
el(
"div",
{},
COLOUR_GROUPS.flatMap(([label, prefix, values]) => [
heading(label),
grid(
Object.keys(values).map((key) =>
swatch(key, `--ap-${prefix}-${key}`)
)
),
])
),
],
{
try: "if any swatch is transparent, the token scope is broken and every other story in this catalogue is lying to you",
what: "Every colour group `@airship/editor-tokens` emits, resolved by the browser rather than transcribed.",
}
),
};
/**
* The type ramp in the real faces.
*
* Inter and JetBrains Mono are self-hosted and served here from
* `@airship/editor-tokens/dist/fonts` — the same binaries the proxy serves in
* production. A fallback face is the tell that `staticDirs` is not resolving,
* and at these sizes it is unmistakable: the ramp tops out at 14px and the dock
* is built on the 10px and 11px steps.
*/
export const Type: StoryObj = {
render: () =>
plainStage(
[
el("div", { style: "padding: 16px; display: grid; gap: 14px;" }, [
...Object.entries(design.fontSize).map(([key, px]) =>
el("div", { style: "display: grid; gap: 2px;" }, [
el("div", {
style:
"font: 400 10px var(--ap-font-mono); color: var(--ap-text-tertiary);",
text: `--ap-font-size-${key} · ${px}px`,
}),
el("div", {
style: `font-family: var(--ap-font-sans);
font-size: var(--ap-font-size-${key});
color: var(--ap-text-primary);`,
text: "Auto layout · Fill · Stroke · 1440×900",
}),
])
),
el("div", {
style: `font-family: var(--ap-font-mono); font-size: 11px;
color: var(--ap-text-primary); padding-top: 8px;`,
text: "display: flex; gap: 12px; padding: 8px 16px;",
}),
]),
],
{
try: "if this is Helvetica rather than Inter, `staticDirs` is not serving the fonts and the dock is being previewed at the wrong metrics",
what: "The type ramp in the real faces — the same self-hosted binaries the proxy serves in production.",
}
),
};
/**
* The scalar ramps — spacing, radius, and the control heights the dock is built
* on. These are emitted with a `px` suffix (see `PX_PREFIXES` in `css.ts`), so a
* bar that renders at zero width means the suffix is missing rather than the
* token.
*/
export const Scale: StoryObj = {
render: () => {
const ramp = (
label: string,
prefix: string,
values: Record<string, number>
): HTMLElement[] => [
heading(label),
el(
"div",
{ style: "display: grid; gap: 6px; padding: 16px;" },
Object.keys(values).map((key) =>
el(
"div",
{
style:
"display: grid; grid-template-columns: 140px 1fr; align-items: center; gap: 12px;",
},
[
el("span", {
style:
"font: 400 10px var(--ap-font-mono); color: var(--ap-text-tertiary);",
text: `--ap-${prefix}-${key}`,
}),
el("span", {
style: `height: 12px; background: var(--ap-blue-500);
border-radius: 2px; width: var(--ap-${prefix}-${key});`,
}),
]
)
)
),
];
return plainStage(
[
el("div", {}, [
...ramp("Spacing", "space", design.spacing),
...ramp("Radius", "radius", design.rounded),
]),
],
{
what: "The scalar ramps. These are emitted with a `px` suffix, so a bar at zero width means the suffix is missing rather than the token.",
}
);
},
};
/**
* A bare `cls()`-prefixed node, for checking the reset applies.
*
* `base.css.ts` scopes its reset to the root; this is the smallest thing that
* proves the stylesheet reached the document at all.
*/
export const Reset: StoryObj = {
render: () =>
plainStage(
[
el("div", {
class: cls("insp-multi"),
text: "Reset applied to this node",
}),
],
{
what: "The smallest thing that proves the overlay stylesheet reached the document at all.",
}
),
};
+56
View File
@@ -0,0 +1,56 @@
/*
* Teardown for stories that own more than their own DOM.
*
* Most of the catalogue needs nothing here: Storybook removes the node a story
* returned, and a control that lives entirely inside it goes with it. The
* exceptions are the ones that reach outward — `CanvasViewport.bind()` listens
* on `window` in capture phase, `Tooltips` binds four document-level listeners
* and mounts into the popover host, `FrameManager` writes `localStorage`, and
* `markSelection` holds a `ResizeObserver` on a node that is about to be
* discarded. None of those are undone by removing an element.
*
* A leaked listener is not a crash. It is the next story reacting to a wheel
* event meant for a viewport that no longer exists, or a tooltip appearing over
* a panel that never registered one — a story showing something that is not
* true, which is the failure mode this whole catalogue is built to avoid.
*/
const pending: (() => void)[] = [];
/**
* Register a disposer to run before the next story renders.
*
* Call it as soon as the thing exists, not at the end of `render`: a story that
* throws halfway through building a canvas has already bound a viewport, and the
* disposer registered before the throw is the only one that will ever run.
*/
export function onStoryTeardown(dispose: () => void): void {
pending.push(dispose);
}
/**
* Run every registered disposer, once.
*
* At story *entry* rather than on unmount, for the reason `preview.ts` already
* gives for `closeOpenPopover()`: Storybook's unmount hook is not somewhere to
* rely on for module state, and entry is idempotent and runs even when the
* previous story crashed before it finished building.
*
* `splice(0)` empties the queue before running anything, so a disposer that
* itself registers one — plausible, since these are constructors' own cleanup
* paths — queues for the next story instead of looping here.
*/
export function runStoryTeardown(): void {
for (const dispose of pending.splice(0)) {
try {
dispose();
} catch {
/*
* A story that failed to clean up is not worth failing the next one over.
* Swallowed rather than logged: this runs 96 times in a `test-browser`
* pass, and a warning nobody can act on is noise in a log people need to
* be able to read.
*/
}
}
}
+280
View File
@@ -0,0 +1,280 @@
import { cls, el } from "../dom";
import { DesignPanel } from "../inspector/panel";
import type { SectionContext } from "../inspector/sections/context";
import { harness, selectionOf } from "../inspector/test-support";
import type { Surface } from "../surface";
import { type Caption, markSelection, stage } from "./chrome";
import { withTokens } from "./fixtures";
import { pendingFrame, type SubjectName, subject } from "./subjects";
/*
* Standing a `DesignPanel` up for a story, and rendering one section of it.
*
* This is the only file in the catalogue that reaches into `DesignPanel`'s
* private members, and it is deliberately the only one. The idiom is the one
* `panel-refresh.test.ts` already uses — `panel as unknown as Internals` — and
* the guard below is what keeps it from being a landmine.
*
* ## Why a section story drives the real panel
*
* Every section is `render<Name>(ctx: SectionContext, node: Element)`, and
* `SectionContext` has 23 members. The obvious two ways to supply one are both
* worse than this:
*
* **A hand-written fake context** would be about 150 lines and would silently
* diverge. `seed()` is `Mixed`-aware across a multi-selection; `gate()` reads the
* pending edit *before* computed style, so a gate does not delete the row whose
* own edit just failed to paint; `repaintScope()` has disposal semantics that
* exist because sections were leaking controls on every repaint. A fake
* reproduces the shapes and not the behaviour, and nothing tells you when it
* stops matching.
*
* **Borrowing the real `ctx` and rendering the section into a bare div** looks
* cheaper and misbehaves in six ways, all of them quiet. `ctx.rerender` is
* `() => this.renderBody()`, which destroys every registered control and clears
* the panel's own body — so the story's DOM survives with dead controls inside
* it. Overriding `ctx.rerender` does not help, because `applyToken`, `setScope`,
* `setState` and `reshapeIfNeeded` all call `renderBody()` directly. There would
* be no `beginScanPass()` bracket, so `matchedRules` runs uncached and its 24ms
* budget truncates at a different rule on each of the up-to-four calls one
* section makes — leaving two consumers disagreeing about which rules matched.
* `ctx.register` pushes into `panel.controls` with nothing ever clearing it, so
* `reseed()` writes into detached DOM. `section()` keys collapse state on an id
* that the panel's own body has already claimed. And `tokenCache` is only reset
* inside `renderBodyInner`, so badges go stale across repaints.
*
* ## What this does instead
*
* `renderSections` is a TypeScript `private` — a plain prototype method, not a
* `#private` field — and its entire body is sixteen
* `this.bodyEl.append(render*(this.ctx, node))` calls. An instance property
* shadows it. The section is then rendered by the *real* `renderBodyInner`, so
* every hazard above is handled by the code that already handles it: the real
* teardown runs, the real `beginScanPass()` try/finally wraps the pass,
* `controls` and `tokenCache` are reset, scroll and caret are restored, and the
* open popover is closed against its vanishing anchor.
*
* The cost is one cast against three private names, guarded at runtime so a
* rename fails loudly at story load rather than rendering an empty dock.
*/
/** The private surface this module depends on. See the note above. */
interface PanelInternals {
bodyEl: HTMLElement;
ctx: SectionContext;
renderSections: (node: Element) => void;
}
/**
* The cast, in one place, checked.
*
* Without the guard this is a silent failure: shadowing a method that no longer
* exists adds an unused property, `renderBodyInner` calls whatever `panel.ts`
* renamed it to, and the story renders the *whole* panel while claiming to be
* one section. Throwing here turns a refactor into a red story instead of a
* quietly wrong one.
*/
function internals(panel: DesignPanel): PanelInternals {
const inner = panel as unknown as Partial<PanelInternals>;
if (typeof inner.renderSections !== "function") {
throw new Error(
"DesignPanel.renderSections is no longer a method — the section stories " +
"shadow it to render one section at a time. See stories/story-panel.ts."
);
}
if (!(inner.bodyEl instanceof HTMLElement)) {
throw new Error("DesignPanel.bodyEl is no longer an element.");
}
return inner as PanelInternals;
}
/** One section renderer, as the sections all declare themselves. */
export type SectionRenderer = (
ctx: SectionContext,
node: Element
) => HTMLElement;
export interface SectionStoryOptions {
/** What this story is for. Rendered above the stage. See `Caption`. */
caption?: Caption;
/** Put the subject in its own document. See `frameSubject`. */
frame?: boolean;
/** Render the dock at `MIN_DOCK_W`, the floor the splitter clamps to. */
narrow?: boolean;
/**
* Seed the token registry before building.
*
* Replaces the two-line `render` body that five files had each written out —
* `withTokens(); return sectionStory(…)` — which worked, but put an imperative
* side effect in front of the thing the story is declaring. `preview.ts`
* clears the registry before every story, so this is additive to nothing and
* cannot leak forward.
*/
tokens?: boolean;
/** An explicit dock width, for a story that wants some third value. */
width?: number;
}
/**
* A story showing one section of the real panel, driven by a real element.
*
* The section renders inside the panel's own body, below the Scope and Align
* rows that `renderBodyInner` always appends. Those stay: Scope and State govern
* what every control below them writes to, so a section shown without them is
* missing the context that decides what its edits mean.
*/
export function sectionStory(
render: SectionRenderer,
name: SubjectName,
opts: SectionStoryOptions = {}
): HTMLElement {
return build(name, opts, (node, surface) => {
const panel = new DesignPanel(harness().deps);
// Before `setSelection`, which is what triggers the first `renderBody`.
const inner = internals(panel);
inner.renderSections = (target: Element) => {
inner.bodyEl.append(render(inner.ctx, target));
};
panel.setSelection(selectionOf(node, surface ? { surface } : {}));
return panel;
});
}
export interface PanelStoryOptions extends SectionStoryOptions {
/** Extra nodes for a multi-selection, by selector within the subject page. */
extra?: string[];
/** Start on a tab other than Design. */
tab?: "css" | "dom";
}
/**
* The whole panel, as the right dock, beside the page it is inspecting.
*
* No shadowing here — this is `DesignPanel` doing exactly what it does in the
* product, with `harness()` supplying the collaborators that would otherwise
* need a socket, a stage and a live selection controller.
*/
export function panelStory(
name: SubjectName,
opts: PanelStoryOptions = {}
): HTMLElement {
return build(name, opts, (node, surface, page) => {
const panel = new DesignPanel(harness().deps);
panel.setSelection(selectionOf(node, surface ? { surface } : {}));
if (opts.extra?.length) {
const extra = opts.extra
.map((selector) => page.querySelector(selector))
.filter((n): n is Element => n !== null);
panel.setExtra(extra);
}
if (opts.tab) {
selectTab(panel, opts.tab);
}
return panel;
});
}
/** An empty panel — no selection, which is its own designed state. */
export function emptyPanelStory(caption?: Caption): HTMLElement {
const panel = new DesignPanel(harness().deps);
panel.setSelection(null);
// Through `stage()` rather than a bare `dock()`, so the empty state is
// captioned like everything else. There is no page pane, because the premise
// of this story is that there is nothing selected to show one for.
return stage(panel.element, { caption });
}
/**
* Click a tab by its label.
*
* Through the DOM rather than by writing `panel.tab`, because the tab strip's
* click handler is what re-renders the body — setting the field alone would
* leave the panel showing the Design tab while claiming to be on CSS.
*/
function selectTab(panel: DesignPanel, tab: "css" | "dom"): void {
const label = tab === "css" ? "css" : "dom";
const buttons = [...panel.element.querySelectorAll<HTMLElement>("button")];
const target = buttons.find(
(b) => (b.textContent ?? "").trim().toLowerCase() === label
);
if (!target) {
throw new Error(`No ${tab} tab in the panel's tab strip.`);
}
target.click();
}
/** Builds the panel once the subject exists. */
type MakePanel = (
node: HTMLElement,
surface: Surface | undefined,
page: ParentNode
) => DesignPanel;
/**
* Assemble a story, same-document or cross-realm.
*
* **Both paths seed after mount**, and the same-document one used to be
* synchronous. That was a quiet lie about every number in the panel.
*
* The old order was: build the specimen, append it to `document.body` so it is
* measurable, construct the panel — which seeds from the box it measures right
* there — and only *then* hand the page to `stage()`, which re-parents it into
* `.__airship-story-page`, a flex child several hundred pixels narrower with a
* different font and its own padding. Everything geometric had already been
* read: Position's X and Y, Size's Hug/Fill decision, the measured width in the
* selection badge. The story then displayed those numbers beside a rendering of
* the element at a different size, and `sections/layout.stories.ts` claimed in
* its header to be "the only place the geometry sections are shown real
* numbers".
*
* The frame path could never be synchronous, for a different reason with the
* same shape: **moving an iframe in the DOM reloads it**, so writing the subject
* before Storybook appends the story would leave a blank pane and a `Surface`
* aimed at a document that no longer exists — silently, since the panel would go
* on reading the now-empty page and reporting it correctly.
*
* So both wait one animation frame. Storybook's HTML renderer appends what
* `render` returns synchronously, so by the first frame the story is in its
* final place and the specimen is laid out where the reader can see it. The cost
* is one frame of an empty `.insp` shell — a panel that is about to exist,
* rather than a flash of the wrong thing.
*/
function build(
name: SubjectName,
opts: SectionStoryOptions,
makePanel: MakePanel
): HTMLElement {
if (opts.tokens) {
withTokens();
}
const slot = el("div", { class: cls("insp") });
const common = {
caption: opts.caption,
narrow: opts.narrow,
width: opts.width,
};
if (!opts.frame) {
const built = subject(name);
const node = stage(slot, { ...common, page: built.page });
node.prepend(markSelection(built.node));
requestAnimationFrame(() => {
slot.replaceWith(makePanel(built.node, undefined, built.page).element);
});
return node;
}
const { fill, frame } = pendingFrame();
const node = stage(slot, { ...common, page: frame });
requestAnimationFrame(() => {
const built = fill(name);
slot.replaceWith(makePanel(built.node, built.surface, built.page).element);
// After `fill`, because the node does not exist until the frame is written.
node.prepend(markSelection(built.node, built.surface));
});
return node;
}
@@ -0,0 +1,124 @@
import { describe, expect, it } from "vitest";
import { hasText } from "../inspector/descriptors";
import {
hasBackgroundImage,
isImage,
isRasterImage,
isSvgChild,
isSvgRoot,
isVideo,
} from "../inspector/element-kind";
import { buildSpecimenIn, type SubjectName } from "./subjects";
/*
* Do the specimens reach the branches they claim to?
*
* `SpecimenSpec.covers` is prose, and prose does not fail. This is what makes it
* answerable — and it exists because the two bugs it would have caught were both
* live for a long time and both invisible from the outside:
*
* - the gradient specimen resolved `.tiles`, the grid *container*, which paints
* nothing. `Inspector/Sections/Fill · Gradient` rendered an empty section, and
* an empty Fill section is a legitimate state for an element with no fill —
* so the panel was correctly reporting the wrong element.
* - the SVG-child specimen resolved the `<svg>` root, where `isSvgChild` is
* false by definition. Two stories claimed to demonstrate the most
* aggressively gated path in `renderSections`, and that path had no coverage
* anywhere in the catalogue.
*
* Only the *structural* predicates are asserted here. `hasFill`, `hasStroke` and
* `hasBounds` read computed style, and happy-dom does not apply the specimen
* stylesheet — those are the browser tier's job, which is the same division of
* labour `test-support.ts` already documents.
*/
/** Build a specimen and hand back the node a story would be pointed at. */
function nodeFor(name: SubjectName): HTMLElement {
const { node, page } = buildSpecimenIn(document, name);
// Mounted, because `closest()` walks to the root and `hasText` reads children.
document.body.append(page);
return node;
}
describe("specimens", () => {
it("marks exactly one subject each", () => {
const names: SubjectName[] = [
"badge",
"button",
"card",
"hero",
"icon",
"image",
"note",
"paragraph",
"path",
"tile",
"tiles",
"title",
"video",
];
for (const name of names) {
const { page } = buildSpecimenIn(document, name);
expect(page.querySelectorAll("[data-subject]")).toHaveLength(1);
}
});
it("puts the gradient specimen on a tile, not on the grid", () => {
// The bug: `.tiles` is the container and has no background at all.
expect(nodeFor("tile").classList.contains("tile")).toBe(true);
expect(nodeFor("tiles").classList.contains("tiles")).toBe(true);
});
it("separates the SVG root from an SVG child", () => {
const root = nodeFor("icon");
const child = nodeFor("path");
expect(isSvgRoot(root)).toBe(true);
expect(isSvgChild(root)).toBe(false);
expect(isSvgRoot(child)).toBe(false);
// The branch that had no coverage while two stories claimed to be it.
expect(isSvgChild(child)).toBe(true);
});
it("distinguishes the three routes into the Media section", () => {
const image = nodeFor("image");
expect(isImage(image)).toBe(true);
expect(isRasterImage(image)).toBe(true);
const video = nodeFor("video");
expect(isVideo(video)).toBe(true);
// The distinction the section gates `alt`/`loading`/`decoding` on.
expect(isRasterImage(video)).toBe(false);
// The non-media route: a gradient scrim over a `url()`, which the
// whole-value version of this predicate reported as no image at all.
expect(hasBackgroundImage(nodeFor("hero"))).toBe(true);
});
it("reaches hasText by both of its arms", () => {
// The TEXTY tag set.
expect(hasText(nodeFor("title"))).toBe(true);
// The text-node scan, on a tag that is not in the set.
const note = nodeFor("note");
expect(note.tagName).toBe("DIV");
expect(hasText(note)).toBe(true);
// And a container of elements only, which is neither.
expect(hasText(nodeFor("tiles"))).toBe(false);
});
it("declares siblings where a scope choice is the point", () => {
// `scopeLevels` only offers a class when more than one element carries it,
// so a specimen wanting a meaningful Scope row has to bring company.
const card = buildSpecimenIn(document, "card");
expect(card.page.querySelectorAll(".card").length).toBeGreaterThan(1);
const button = buildSpecimenIn(document, "button");
expect(button.page.querySelectorAll(".btn").length).toBeGreaterThan(1);
const tile = buildSpecimenIn(document, "tile");
expect(tile.page.querySelectorAll(".tile").length).toBeGreaterThan(1);
});
it("throws rather than guessing when a specimen marks nothing", () => {
// The failure mode the marker replaced: a selector table that could drift
// from the markup silently. This one cannot be wrong quietly.
expect(() => buildSpecimenIn(document, "nope" as SubjectName)).toThrow();
});
});
+683
View File
@@ -0,0 +1,683 @@
import type { ElementContext } from "@airship/protocol";
import { contextOf } from "../inspector/test-support";
import type { Surface } from "../surface";
/*
* The elements the inspector inspects.
*
* These are the actual subject of every section and panel story. The inspector
* is a *view of a node* — it reads computed style, walks the stylesheets that
* matched, measures the box — so a story that shows the panel without saying
* what it is pointed at is showing an opinion with no premise.
*
* They are *real DOM in a real browser*, which is the whole reason this exists
* alongside the happy-dom suite. `getBoundingClientRect` returns a measured box
* with no `sizeOf()` patch; `getComputedStyle` resolves shorthands, percentages
* and inherited values properly; and the stylesheet below is parsed by a real
* CSS parser, so the nesting, `@layer` and `@supports` that happy-dom drops
* entirely are genuinely there for `matchedRules` to walk.
*
* ## One specimen per story, not one page for all of them
*
* This module used to build a single two-card demo page and hand out nodes from
* it by selector. Every panel and section story rendered that whole page beside
* the dock, so forty-one stories were the same picture with a few rows different
* several hundred pixels to the right — and since nothing marked which node the
* panel was pointed at, telling them apart meant reading the values and working
* backwards.
*
* It also went quietly wrong three times, which is the more serious charge. The
* `SELECTOR` map was a second place to state which element a story was about,
* and it drifted from the prose: `grid` resolved `.tiles`, the *container*, so
* the story captioned "a tile painted with a gradient" pointed at an element
* with no background at all and rendered an empty Fill section, and the one
* captioned "a tile with a translucent border" was byte-identical to the story
* named `None` three lines above it. `icon` resolved the `<svg>` root, so the
* two stories claiming to demonstrate `isSvgChild` — the most aggressively gated
* path in `renderSections` — demonstrated the opposite branch, and that path had
* no coverage anywhere.
*
* Both classes of bug are gone by construction now: a specimen carries its own
* subject as a `[data-subject]` marker in the markup, so the element a story
* points at is stated once, in the same string as the element itself.
*
* ## The constraint that shapes the stylesheet
*
* **The rules must stay bare class selectors.** `scopeLevels` only offers a
* class scope when the matched selector is a single bare class (`SIMPLE_CLASS`
* in `inspector/cascade.ts`) *and* more than one element in the document carries
* it. Scoping this sheet under `.specimen` — the obvious way to keep specimens
* from bleeding into each other — would turn every rule into a descendant
* selector, `SIMPLE_CLASS` would reject all of them, and the Scope row would
* silently collapse to "This element" on every story in the catalogue. There is
* nothing to bleed into anyway: one specimen renders at a time.
*
* The second half of that rule is why `SpecimenSpec.siblings` exists. A scope is
* only meaningful when the class is shared, so a specimen that wants the Scope
* row to mean something *declares* the element it shares with, rather than
* happening to have one because it was cropped out of a bigger page.
*/
/**
* The specimen stylesheet.
*
* Deliberately written the way a real app's is, not the way a fixture usually
* is: cascade layers, native nesting, a `:hover` rule, a media query, an
* `@supports` block and shared classes that several elements match. Every one of
* those is a branch in `inspector/css-rules.ts`'s walker, and `test-support.ts`
* has to fake all of them with a synthetic CSSOM because happy-dom parses none.
*
* One sheet for all thirteen specimens rather than one each. The at-rules are
* properties of the *sheet*, so sharing it keeps every specimen exercising all
* of them; splitting it would make `@layer` ordering and the `scopeLevels`
* element counts depend on which sheet happened to be injected. A specimen
* carrying rules for classes it does not use is what a real app's stylesheet
* does anyway, and it exercises the walker's non-match filtering, which is work
* it genuinely has to do.
*/
export const PAGE_CSS = `
@layer base, components;
@layer base {
.specimen { color: #111; font: 400 14px/1.5 system-ui, sans-serif; }
a { color: #0d6efd; }
}
@layer components {
.card {
display: flex;
flex-direction: column;
gap: 12px;
padding: 20px 24px;
border-radius: 12px;
border: 1px solid rgba(0, 0, 0, 0.08);
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06), 0 8px 24px rgba(0, 0, 0, 0.08);
max-width: 420px;
& .card-title {
margin: 0;
font-size: 20px;
font-weight: 650;
letter-spacing: -0.01em;
}
& .card-body { margin: 0; color: #555; }
}
.card--wide { max-width: 640px; }
.note {
padding: 12px 16px;
border-radius: 8px;
background: #f4f6f8;
color: #444;
max-width: 420px;
}
.btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 18px;
border: 0;
border-radius: 8px;
background: #0d6efd;
color: #fff;
font: 600 14px system-ui, sans-serif;
cursor: pointer;
transition: filter .15s ease;
&:hover { filter: brightness(1.08); }
&:active { filter: brightness(0.94); }
}
.btn--ghost { background: #6c757d; }
.badge {
position: absolute;
top: -8px;
right: -8px;
display: grid;
place-items: center;
min-width: 22px;
height: 22px;
padding: 0 6px;
border-radius: 999px;
background: #dc3545;
color: #fff;
font: 700 11px system-ui, sans-serif;
}
.tiles {
display: grid;
grid-template-columns: repeat(3, minmax(80px, 1fr));
grid-auto-rows: 72px;
gap: 12px;
max-width: 420px;
}
.tile {
border-radius: 8px;
background: linear-gradient(160deg, #e9f2ff, #cfe2ff);
border: 1px solid rgba(13, 110, 253, 0.2);
}
.hero {
display: flex;
flex-direction: column;
gap: 8px;
justify-content: flex-end;
width: 420px;
height: 200px;
padding: 24px;
border-radius: 12px;
color: #fff;
background-size: cover;
background-position: center;
}
.shot {
border-radius: 8px;
background: #cfe2ff;
object-fit: cover;
}
.clip {
border-radius: 8px;
background: #212529;
object-fit: contain;
}
.chev { color: #fff; }
.stack { display: flex; flex-wrap: wrap; gap: 16px; align-items: flex-start; }
}
/* A media query and a feature query, both of which the walker reports as
provenance with their condition text. Neither changes what any story is about;
they are here so the branch that renders a conditional rule is always live. */
@media (max-width: 600px) {
.card { padding: 16px; }
}
@supports (display: grid) {
.tiles { grid-auto-rows: 72px; }
}
`;
/**
* A 1×1 transparent GIF.
*
* A data URI rather than a file, because the Media section reads `naturalWidth`
* and an image that has not loaded reports zero — which would make the section's
* intrinsic-size row read as broken rather than as empty. Inline data loads
* synchronously enough to be measured.
*/
const PIXEL =
"data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
/**
* The chevron, with the marker on whichever node a specimen is about — or on
* neither, for the specimens where the graphic is scenery.
*
* `"none"` is load-bearing rather than tidy. The button specimen is *about the
* button*, and it embeds this graphic; marking the `<svg>` as well gave that
* specimen two `[data-subject]` nodes, and `buildSpecimenIn` takes the first
* match — so it resolved correctly only because the button happens to come first
* in document order. `subjects.test.ts` asserts exactly one marker per specimen
* for this reason.
*/
function chevron(subjectOn: "none" | "path" | "svg"): string {
return `
<svg class="chev" width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"
${subjectOn === "svg" ? "data-subject" : ""}>
<path d="M2 8h12M9 3l5 5-5 5" fill="none" stroke="currentColor"
stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
${subjectOn === "path" ? "data-subject" : ""}/>
</svg>`;
}
/** One `.tile` of six, with the marker on the nth. */
function tileGrid(subjectIndex: number | null): string {
const cells = Array.from({ length: 6 }, (_, i) =>
i === subjectIndex
? '<div class="tile" data-subject></div>'
: '<div class="tile"></div>'
).join("");
return `<div class="tiles"${subjectIndex === null ? " data-subject" : ""}>${cells}</div>`;
}
/** One self-contained fragment with exactly one inspected node. */
export interface SpecimenSpec {
/**
* Which branches this specimen exists to reach.
*
* Prose, and load-bearing rather than decorative: it is what a reviewer checks
* the set against when `shapeKey` grows a term or `renderSections` grows a
* gate. A branch nothing claims is a branch with no story.
*/
covers: string;
/** A noun phrase for a caption: "a pricing card", "the arrow inside a button". */
label: string;
/** The fragment. Exactly one node carries `data-subject`. */
markup: string;
/**
* Markup rendered alongside, inside the same wrapper.
*
* How a specimen *declares* its scope choice instead of inheriting one by
* accident. See the note at the top about `scopeLevels` and shared classes.
*/
siblings?: string;
/**
* The parent's layout, which decides `isFlexChild` — a `shapeKey` term, and
* what makes Size offer Hug/Fill rather than Fixed.
*
* `stack` is a wrapping flex row, `block` an ordinary block container, and
* `none` puts the markup straight into the page with no wrapper at all, for
* the specimens that bring their own.
*/
wrap?: "block" | "none" | "stack";
}
/*
* The catalogue.
*
* `satisfies` rather than a `Record<SubjectName, …>` annotation, so `SubjectName`
* can be derived from the keys below and a story naming a specimen that does not
* exist is a type error rather than a runtime throw.
*/
const SPECIMENS = {
/** The absolutely-positioned case, which is what Constraints exists for. */
badge: {
covers:
"position:absolute → the Constraints section · display:grid on a tiny box · negative insets on two edges",
label: "a notification badge",
markup: `
<article class="card" style="position: relative;">
<h3 class="card-title">Inbox</h3>
<p class="card-body">Three unread.</p>
<span class="badge" data-subject>3</span>
</article>`,
wrap: "stack",
},
/** A button: inline-flex, no border at all, and real interactive states. */
button: {
covers:
"display:inline-flex · hasStroke:false (border:0), so Stroke is at its emptiest · `:hover` and `:active` rules, so the State picker has something to offer · a shared class with two members",
label: "a button",
markup: `
<button class="btn" type="button" data-subject>
${chevron("none")}
Get started
</button>`,
siblings: `
<button class="btn btn--ghost" type="button">Learn more</button>`,
wrap: "stack",
},
/** The fullest ordinary case: a flex box with a fill, a border and a bound. */
card: {
covers:
"display:flex · a wrapping flex parent · isFlexChild · hasFill · hasStroke · hasBounds (max-width) · a shared class with two members, so Scope has a real choice",
label: "a card",
markup: `
<article class="card" data-subject>
<h3 class="card-title">Weekly digest</h3>
<p class="card-body">Every Monday, the five things that changed.</p>
</article>`,
// The `.card--wide` half of the pair is what makes the Scope row meaningful:
// an edit here can be written to this element or to `.card`, and the second
// option only exists because a second element shares the class.
siblings: `
<article class="card card--wide">
<h3 class="card-title">Release notes</h3>
<p class="card-body">What shipped, and what it means for your project.</p>
</article>`,
wrap: "stack",
},
/**
* A hero with a darkened photograph behind it.
*
* Reaches Media by the route that is not a media element: `hasBackgroundImage`
* over a *two-layer* background, a gradient scrim over a `url()`. That exact
* shape is the one the predicate had to be rewritten for — a whole-value test
* reported no background image the moment any layer was a gradient — and it
* had no story.
*/
hero: {
covers:
"hasBackgroundImage across a two-layer background (gradient scrim over url()) → Media on an element that is not a media element",
label: "a hero panel",
markup: `
<section class="hero" data-subject
style="background-image: linear-gradient(rgba(0,0,0,.55), rgba(0,0,0,.15)), url(${PIXEL});">
<h3 class="card-title" style="color: #fff;">Ship on Fridays</h3>
</section>`,
wrap: "block",
},
/** The `<svg>` element, which lays out like any other box. */
icon: {
covers:
"isSvgRoot → the Vector section *plus* the box sections, because an <svg> has a box like anything else",
label: "an icon",
markup: `
<button class="btn" type="button">
${chevron("svg")}
Get started
</button>`,
wrap: "stack",
},
/** A raster image — the only kind that owns `alt`, `loading` and `decoding`. */
image: {
covers:
"isImage and isRasterImage → Media, with the three <img>-only attrs",
label: "an image",
markup: `
<img class="shot" src="${PIXEL}" width="180" height="110" alt="A placeholder"
loading="lazy" decoding="async" data-subject>`,
wrap: "stack",
},
/**
* Text on a tag that is not in `TEXTY`.
*
* `hasText` has two arms — the tag set, and a scan for a non-empty text child —
* and `title` only reaches the first. A `<div>` with words in it is the far
* more common shape in a real app, and it is the arm that would silently stop
* working if the scan were dropped.
*/
note: {
covers: "hasText via the text-node scan rather than the TEXTY tag set",
label: "a note",
markup: `<div class="note" data-subject>Frames report their own innerWidth.</div>`,
wrap: "block",
},
/** Prose, for the stories that are about setting type. */
paragraph: {
covers:
"hasText · an inherited colour the element does not declare · hasFill:false, so the Fill section is at its emptiest",
label: "a paragraph",
markup: `
<article class="card">
<h3 class="card-title">Weekly digest</h3>
<p class="card-body" data-subject>Every Monday, the five things that
changed — what shipped, what broke, and what is worth a second look
before the week gets away from you.</p>
</article>`,
wrap: "stack",
},
/**
* A shape inside an SVG — the most aggressively gated node in the panel.
*
* `isSvgChild` suppresses Position, Constraints, Auto layout, Spacing, Text,
* Fill and Stroke outright, because a `<path>` has no box, no padding and no
* text flow. Two stories claimed to be this case and pointed at the `<svg>`
* root instead, where the predicate is false by definition — so the branch was
* uncovered while appearing twice in the sidebar.
*/
path: {
covers:
"isSvgChild → seven sections suppressed at once, leaving Vector and Appearance",
label: "the arrow inside a button",
markup: `
<button class="btn" type="button">
${chevron("path")}
Get started
</button>`,
wrap: "stack",
},
/**
* A grid *item* with a gradient and a translucent border.
*
* The specimen two stories always meant and never got. Fill's gradient story
* and Stroke's alpha story both asked for `grid`, which resolved the container
* — no background, no border — so one rendered an empty section and the other
* was indistinguishable from the story for an element with no border at all.
*/
tile: {
covers:
"a gradient fill, so the Fill swatch shows a ramp and opens the gradient editor · a translucent border, so Stroke's alpha row has something to say · a grid item · six elements sharing one class",
label: "one tile of six",
markup: tileGrid(0),
wrap: "block",
},
/** A grid container that paints nothing itself. */
tiles: {
covers:
"display:grid on a block child, so isFlexChild is false while display is neither flex nor inline · hasText, hasFill and hasStroke all false at once",
label: "a tile grid",
markup: tileGrid(null),
wrap: "block",
},
/** A heading: `hasText` through the tag, and a nested rule as provenance. */
title: {
covers:
"hasText via the TEXTY tag set · a nested rule (`.card { & .card-title }`) as the matched provenance",
label: "a card heading",
markup: `
<article class="card">
<h3 class="card-title" data-subject>Weekly digest</h3>
<p class="card-body">Every Monday, the five things that changed.</p>
</article>`,
wrap: "stack",
},
/**
* A video, which is media without being an image.
*
* `isMedia` is true and `isRasterImage` is false, so Media renders `object-fit`
* and `object-position` and withholds `alt`/`loading`/`decoding` — attributes a
* `<video>` does not have and that writing to it would silently do nothing.
* Nothing covered this before.
*/
video: {
covers: "isVideo → Media without the three <img>-only attrs",
label: "a video",
markup: `
<video class="clip" width="180" height="110" muted playsinline
poster="${PIXEL}" data-subject></video>`,
wrap: "stack",
},
} satisfies Record<string, SpecimenSpec>;
/** Every specimen, by the name a story asks for. */
export type SubjectName = keyof typeof SPECIMENS;
/**
* The same table, widened.
*
* `satisfies` checks each entry against `SpecimenSpec` while keeping the keys
* literal, which is what makes `SubjectName` a closed union and a misspelled
* specimen a compile error. The cost is that it also keeps each *value* at its
* own literal type, so an entry with no `siblings` has no such property to read.
* One widened alias fixes that without giving up either half.
*/
const SPECS: Record<SubjectName, SpecimenSpec> = SPECIMENS;
/** The spec behind a name — for captions, and for asserting coverage. */
export function specimen(name: SubjectName): SpecimenSpec {
return SPECS[name];
}
/** The built fragment, plus the node a story is pointed at. */
export interface Subject {
/** The element the inspector selects. */
node: HTMLElement;
/** The whole fragment, for the story's page pane. */
page: HTMLElement;
}
/**
* Build a specimen in a given document.
*
* Parameterised by `Document` because the cross-realm path needs the same
* fragment inside an iframe, and building it in the shell to serialise and
* re-parse it — which is what this module used to do — is a round trip that buys
* nothing and loses anything that is not expressible as HTML.
*
* Returned **detached**. The caller mounts it, and everything that measures runs
* afterwards; see the note in `story-panel.ts` about seeding after mount.
*
* `data-subject` rides on the inspected element and is invisible to everything
* the panel renders: `contextOf` reports classes, tag and text; the DOM tab
* labels through `elementLabel`; the CSS pane lists declarations; and Media
* reads `alt`, `loading` and `decoding` by name.
*/
export function buildSpecimenIn(doc: Document, name: SubjectName): Subject {
const spec = SPECS[name];
const page = doc.createElement("div");
page.className = "specimen";
const wrap = spec.wrap ?? "stack";
const body = spec.markup + (spec.siblings ?? "");
page.innerHTML =
`<style>${PAGE_CSS}</style>` +
(wrap === "none" ? body : `<div class="${wrap}">${body}</div>`);
const node = page.querySelector<HTMLElement>("[data-subject]");
if (!node) {
throw new Error(
`Specimen "${name}" declares no [data-subject] node — the marker is how a ` +
"story says which element it is about. See stories/subjects.ts."
);
}
return { node, page };
}
/** One specimen in the story's own document. */
export function subject(name: SubjectName): Subject {
return buildSpecimenIn(document, name);
}
// ---------------------------------------------------------------------------
// The cross-realm case
// ---------------------------------------------------------------------------
/** A subject in its own document, plus the `Surface` that describes it. */
export interface FrameSubject extends Subject {
surface: Surface;
}
/**
* An empty frame, and the function that fills it once it has been mounted.
*
* Two steps rather than one, and the reason is a browser rule with teeth:
* **moving an iframe in the DOM reloads it.** A frame written to while it is
* still detached — or while it sits somewhere other than where the story will
* finally put it — is wiped the moment Storybook appends the story to the
* canvas, and what is left is a blank white pane and a `Surface` pointing at a
* document that no longer exists. Nothing throws; the panel simply reads an
* empty page and reports it accurately.
*
* So `frame` goes into the story's DOM first, and `fill` runs after Storybook
* has mounted it.
*/
export interface PendingFrame {
fill: (name: SubjectName) => FrameSubject;
frame: HTMLIFrameElement;
}
/**
* The same specimens, in their own document, with a `Surface` pointed at them.
*
* This exists for one specific and non-obvious reason. `stubSurface()` in
* `test-support.ts` returns `doc: document` — which under happy-dom is a clean
* empty document, and in Storybook is the *preview iframe*, carrying Storybook's
* own stylesheets. `matchedRules` walks `doc.styleSheets`, and `isOwnSheet` skips
* the overlay's sheet but knows nothing about Storybook's. So a CSS-pane story on
* a same-document subject would list Storybook's reset as the element's
* provenance, which is worse than useless: it is a plausible wrong answer.
*
* Putting the subject in its own document fixes it exactly, and does so by being
* more faithful rather than less — this is the production topology. In canvas
* mode the app runs in frame iframes while the overlay runs in the shell, which
* is why `realm.ts` exists at all. The panel resolves `getComputedStyle` against
* the node's own window and duck-types its `instanceof` checks, so it handles
* this natively.
*/
export function pendingFrame(): PendingFrame {
const frame = document.createElement("iframe");
// Named, because the a11y pass checks `frame-title` and an unnamed frame is a
// real finding rather than a harness artefact — the canvas frames want one too.
frame.title = "The page being inspected";
frame.style.cssText =
"width: 100%; height: 100%; min-height: 420px; border: 0; background: #fff;";
const fill = (name: SubjectName): FrameSubject => {
const doc = frame.contentDocument;
const win = frame.contentWindow;
if (!(doc && win)) {
throw new Error("iframe has no document — was it mounted first?");
}
// `document.write` rather than `srcdoc`: srcdoc loads asynchronously, and
// the caller needs the subject measurable in the same tick it is handed
// back so the panel can seed from a real box.
doc.open();
doc.write("<!doctype html><html><head></head><body></body></html>");
doc.close();
const built = buildSpecimenIn(doc, name);
doc.body.style.margin = "0";
doc.body.style.padding = "24px";
doc.body.append(built.page);
return { ...built, surface: frameSurface(frame, doc, win) };
};
return { fill, frame };
}
/**
* A `Surface` over one frame.
*
* Only the members the panel actually reaches for are real; the rest answer
* honestly for a static, unzoomed frame. This mirrors `stubSurface()`'s approach
* and its rationale — implement what is used, and let the type document the
* rest — but differs in the one member that matters here, `doc`.
*/
function frameSurface(
frame: HTMLIFrameElement,
doc: Document,
win: Window
): Surface {
const offset = () => frame.getBoundingClientRect();
return {
bounds: () => {
const r = offset();
return { height: r.height, left: r.left, top: r.top, width: r.width };
},
doc,
elementAtScreen: (point) => {
const r = offset();
return doc.elementFromPoint(point.x - r.left, point.y - r.top);
},
extract: (target: Element) =>
Promise.resolve({
context: contextOf(target) as ElementContext,
source: null,
}),
id: "story-frame",
isLive: true,
// 1:1 — the canvas zoom is a separate concern and none of these stories
// exercise it. A scaled frame would need `toScreen`/`toLocal` to multiply.
scale: 1,
scanTokens: () => ({ framework: "unknown", tokens: [] }),
toLocal: (point) => {
const r = offset();
return { x: point.x - r.left, y: point.y - r.top };
},
toScreen: (rect) => {
const r = offset();
return { ...rect, left: rect.left + r.left, top: rect.top + r.top };
},
win,
};
}
+57
View File
@@ -0,0 +1,57 @@
import { storybookTest } from "@storybook/addon-vitest/vitest-plugin";
import { playwright } from "@vitest/browser-playwright";
import { defineConfig } from "vitest/config";
/*
* The browser tier: every story, run as a test, in real Chromium.
*
* ## Why this is a second file rather than a `projects` array
*
* The obvious shape is one `vitest.config.ts` with two projects — happy-dom for
* the unit tests, a browser project for the stories. It is the wrong shape here
* for a reason outside vitest entirely: `.husky/pre-commit` runs `pnpm test`,
* which reaches `vitest run` with no project filter, which would run *both*.
* Every commit would launch Chromium, and on a machine that has not downloaded
* it the hook would fail and block the commit. This repo has no CI — `make
* check` is documented in the Makefile as "what CI should run" — so that hook is
* the only gate there is, and making it depend on a browser download is a bad
* trade for a catalogue.
*
* Separate file, separate script, separate turbo task, not wired into `test`.
* `make test-browser` opts in; `make browsers` fetches the browser.
*
* ## What it adds that the unit suite cannot
*
* `vitest.config.ts`'s own docstring, and `inspector/test-support.ts`'s, both
* list what happy-dom cannot do: no layout, no native CSS nesting, `@layer`
* dropped entirely, no `CSSStyleDeclaration` iterator. Those are the four things
* the inspector reads. Here they are real — which makes this the complement to
* the unit suite rather than a second copy of it.
*
* Every story becomes a smoke test that it renders without throwing, every
* `play` function becomes an interaction test, and the `a11y` parameter in
* `preview.ts` makes an axe violation fail the run rather than merely appear in
* a panel.
*
* ## What is deliberately absent
*
* No `test.include`: `main.ts`'s `stories` glob is the single index, and passing
* one here is ignored with a warning. No `setupFiles` either — since Storybook
* 10.3 the plugin applies `preview.ts`'s annotations itself, and a hand-rolled
* `setProjectAnnotations` now conflicts with that rather than enabling it. The
* risk that setup file was guarding against — stories running *without* the
* decorator, rendering unstyled, and passing anyway — is covered instead by the
* `play` assertions on `Foundations/Tokens`, which check the token scope and the
* fonts from inside the run.
*/
export default defineConfig({
plugins: [storybookTest({ configDir: ".storybook" })],
test: {
browser: {
enabled: true,
headless: true,
instances: [{ browser: "chromium" }],
provider: playwright(),
},
},
});