Rule 61 - Storybook
How to write story files, story chrome, and demo content.
Stories
61.1. Every component, utility, foundation, and pattern MUST
have a {name}.stories.js file in its directory.
61.2. The default export MUST include argTypes and args wherever the file's stories take args (every component and form-control file, and any utility whose stories forward args), and MUST include component wherever the file's stories render a canonical {name}.twig. A foundation, pattern or showcase file whose stories take no args declares neither. A subject that ships no such template -
a Utility, a Foundation, a Pattern, a template-less component whose
spec authors its markup per
Rule 53.20, or a composition-story file
whose renders go through composition partials per
Rule 63 - has no
component to name and declares none.
The default export MUST NOT carry tags: ['autodocs'],
parameters.docs.description, or parameters.docs.spec - component
documentation lives in the co-located .mdx file per Rule 61.29.
A JSDoc comment above the default export MUST NOT be used for
component description; put prose in the MDX file instead. A pattern
or a showcase ships no MDX (Rule 61.29), so a plain block comment
above its default export MAY describe what the composition
demonstrates.
import Button from './button.twig';import buttonSpec from './button.spec.js';import { storyFor } from '../../tools/storybook-chrome/story-helpers.js';const story = storyFor(buttonSpec, {args: { content: 'Launch' },});export default {title: 'Components/Button',component: Button,...story.meta,};
61.3. Story title MUST start with a valid sidebar prefix:
Foundation/…, Utilities/…, Components/…, Form controls/…,
Patterns/…. Storybook-only pages MAY also use
Tools/… or stand alone as top-level entries listed in the
Rule 52.4 allow-list
(none ships today).
Each prefix maps to a source folder per
Rule 52.2. The sidebar
order is Foundation, Components, Form controls, Utilities,
Patterns, then Tools, as declared by the storySort comparator
in .storybook/preview.js.
Components, Form controls, Utilities, Patterns, and Tools
MUST be flat alphabetical lists. Foundation is the exception: it
follows the curated reading order the comparator declares - the
token reference first (Colors, Primitive tokens,
Semantic tokens, Typography), Options last, everything else
alphabetical between them. A reader meets the substrate in the
order it builds on itself, which alphabetical ordering would
scatter.
61.4. Every component MUST have a Playground story - a sandbox
with one instance, all props as args, full controls panel. The
Playground story is reachable from the Storybook sidebar so
the controls panel stays exercisable; the MDX docs page (Rule
61.29) MUST NOT embed it.
// Correct - Playground stays in the sidebar.export const Playground = {render: (args) => Component(args),};
Container components (e.g. header, footer) - components whose
own twig is just a slot wrapper and whose every named story IS
already a sandbox - MAY opt out of the Playground requirement
with a leading // lint-playground: off comment. The opt-out is
file-level and only suppresses Rule 61.4; all other story rules
still apply.
61.5. Default arg values MUST be declared in the meta-level args
on the default export so that every story inherits them
automatically. Individual stories MUST only override the args they
change. The Playground story SHOULD NOT redeclare args that match
the meta defaults. Every render function MUST accept args and
spread them into the rendered output; hardcoded per-instance values
are permitted only for props that genuinely vary per instance
within the story (e.g. unique id or per-slot label). A render
that ignores args silently breaks controls and state props
(is_disabled, is_required, is_invalid) for that story.
export default {title: 'Components/Range',component: Range,argTypes: {/* … */},args: {label: sentence({ index: 7 }),value: 50,min: 0,max: 100,step: 1,is_disabled: false,classes: [],attributes: {},},};export const Playground = {render: (args) => Range(args),};export const Disabled = {args: { label: 'Locked control', is_disabled: true },render: (args) => Range(args),};
61.6. Hiding component-specific controls via
parameters: { controls: { include: [...] } } is permitted only
on utility, foundation, and showcase stories where the point is to
demonstrate a layout, a swatch grid or a JavaScript API
(announcement's Api story) rather than to interact with a
component's props. Component multi-instance stories MUST keep
every control exposed so reviewers can toggle state props
(is_disabled, is_required, is_invalid, helper, min, max) across
every instance. Combine this with 61.5 - render spreads args
into each instance.
61.7. Every single-instance story MUST accept all meta-level args
via its render function and MUST forward them to the component.
Any control declared in argTypes MUST affect every single-instance
story's output; stories MUST NOT hardcode values that shadow
meta-level controls. Story-specific fixed values belong in the
story's args declaration (Rule 61.5). Multi-instance and showcase
stories are exempt - see Rule 61.6.
// Correct - meta-level args flow through every storyexport const Default = {render: ({ levels, ...args }) => Breadcrumb({ links: demoLinks(levels), ...args }),};// Correct - fixed values live in `args`, remaining args still forwardexport const CustomDivider = {args: { attributes: { style: "--breadcrumb-divider: '/'" } },render: ({ levels, ...args }) => Breadcrumb({ links: demoLinks(levels), ...args }),};// Wrong - hardcoded values shadow the Storybook controlsexport const Default = {render: () => Breadcrumb({ links: demoLinks(4) }),};
A story that owns a slot outright - composing it from demo content rather
than from the arg - MUST declare that slot in the storyFor() demo map,
whose ergonomic control replaces the generated one at the same position.
Overwriting the slot in the render while its generated control still
stands reads to the editor as a broken input: the arg commits, the canvas
does not move, and nothing says why.
The demo map changes the panel only. The prop stays in the spec, in
{name}.spec.json, and in the MDX API table, so the component's contract
is unchanged.
// Correct - the demo entry replaces the raw image control with the// toggle that actually drives the slot, and builds the value.const story = storyFor(cardSpec, {demo: { image: { default: true, build: (on) => (on ? cardImage(0) : '') } },});// Wrong - the generated `image` control still stands while the render// overwrites the slot, so whatever is typed into it is discarded.function buildArgs({ with_image: withImage, ...rest }) {return { ...rest, image: withImage ? cardImage(0) : '' };}
A stories file whose renders cannot apply the controls handle (a rich-HTML showcase) MAY opt out of the apply check with a leading // lint-story-theme-apply: off comment that states why. The opt-out is file-level.
61.8. A component MUST NOT have a dedicated classless story.
Per Rule 11.4, the element form
and the class-based form are visually identical, so a Classless
story duplicates the Playground sandbox and fragments the
canonical reference. The element form is exercised by the
component's element selectors in CSS and verified by the
Playground story - no additional story is REQUIRED or
PERMITTED. On a component whose spec declares the mirrored
styling value (Rule 53.21), the
automatically injected Mirror class switch (on by default)
demonstrates both forms in place.
// Wrong - duplicates Playground and fragments the canonical reference.export const Classless = {render: () => `<article><img src="…"><h3>Title</h3><p>Body text.</p></article>`,};
61.9. Content-slot props MUST NOT expose raw object or array
inputs as Storybook controls. Use a boolean with_{prop} toggle
for object slots (image, icon, etc.) and an integer range control
(min: 0, max: 10) for array slots (tags, meta, actions,
options, items). The conversion from the ergonomic control to the
underlying prop lives in the storyFor() demo map (Rule 61.7),
whose build function replaces the generated control and produces
the prop value; a render that converts the value itself leaves the
generated control standing.
The classes and attributes passthrough props declared by
Rule 31.7 and Rule 31.8 are EXEMPT - consumers need direct control
over value class lists and arbitrary HTML attributes. The
exemption extends to any prop whose name ends in _classes or
_attributes (e.g. trigger_classes, column_attributes)
because those props are structural passthroughs to a nested
element.
// Wrong - raw object/array controls expose internal shapes.argTypes: {image: { control: 'object' },tags: { control: 'object' },},args: {image: { url: '/hero.png', alt: 'Rocket' },tags: ['Apollo', 'Lunar'],},// Correct - the demo map owns the toggle and the range, and builds the prop.const story = storyFor(cardSpec, {demo: {image: { default: true, build: (on) => (on ? cardImage(0) : null) },tags: { max: 10, default: 2, description: 'Number of demo tags.', build: (count) => tags({ count }) },},});export const Playground = {render: (args) => Card(story.apply(args)),};
61.10. Components with behavior MUST have interaction tests via
play functions. A play that drives more than one user action
MUST wrap each action and its assertions in a named step(); a
play that only asserts the rendered state needs none. Tests use
semantic queries (getByRole) and MUST NOT use sleep. The check
counts the userEvent calls a play makes directly; a helper the
play calls is a unit of its own.
import { expect, userEvent, within, step } from 'storybook/test';export const ExclusiveMode = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);await step('Opens the first item', async () => {await userEvent.click(canvas.getAllByRole('button')[0]);await expect(canvas.getAllByRole('group')[0]).toHaveAttribute('open');});},};
61.32. A control over a fixed set of options MUST take its control
type from optionsControl(options) in semetrika-spec.
Writing control: 'select', control: 'radio', or
control: 'inline-radio' - in either the string form or the
control: { type: … } object form - is a violation.
The helper sums the rendered character width of every option's label
and returns inline-radio at or below INLINE_RADIO_MAX_LABEL_CHARS,
select above it. One threshold governs every option control in the
system, so the panel reads consistently and the budget moves in one
edit. A hand-picked control type encodes one author's judgement of
one option list at one moment, and the panel drifts as lists grow.
The helper returns the control and options pair, so an argType
spreads it and adds only its own name and description. It also labels
the empty option a visual capability prepends, which otherwise draws a
radio chip with no target.
The generated controls already route through it - argTypesFor()
covers every enum prop and visual capability a spec declares, so a
component whose controls come from its spec needs nothing here. This
rule governs the argTypes a story writes by hand.
// Correct - the helper picks the control from the label width.argTypes: {shape: { ...optionsControl(['none', 'pill']), name: 'Shape', description: 'Badge shape.' },},// Wrong - a hardcoded control type.argTypes: {shape: { control: 'inline-radio', options: ['none', 'pill'], name: 'Shape' },},
61.35. A story MUST name a capability value through the target
component's capability arg, never as a string literal in a classes
array. On the file's own component the value spreads as
...story.values([c.Size.sm]); on a composed component it spreads as
...valuesFor(buttonSpec, [c.Fill.outline]) with the composed spec
imported. Both take their words as one array, the shape
Capability.X.use([...]) takes in a spec. Both resolve the word against the target's spec and throw
on a word it does not declare, where a classes literal is never
validated: a typo, a renamed value, or a word the target never
declared produces no class and fails silently. The violation is
resolved against the component the call targets, not the enclosing
file - a Button(...) call inside another component's stories checks
against Button's spec.
The classes array carries only words the capability system does not
route: utility classes (inline, gap-1), child classes of a
composed component (badge-icon), and enum-prop words, which travel
through their own prop. A passthrough to a nested element
(trigger_classes, or any *_classes prop) has no capability arg to
route through, so a capability value there MUST be named as its spec
symbol (trigger_classes: [c.Size.sm]) - the property access throws
on a typo where a literal stays silent.
Two further shapes fail outright: a canonical capability value in
classes that the target component does not declare (a dead word -
the class matches none of the target's selectors), and a classes
word declared by nothing at all - no capability value, no enum-prop
word of the target, no utility or foundation class, no child class of
a known component (the shape that rendered drawers with no edge
anchoring when classes: ['start'] named an Alignment value that
does not exist).
A line that must keep a literal for a documented reason carries a
// capability-literal: <reason> marker, trailing or on the line
directly above, following the // demo-literal: precedent of Rule
61.33; the linter honors the marker and the reviewer judges the
reason. Genuine outliers include a composition showcase that
hand-builds its class list to demonstrate class composition, and
markup built as a no-JS fallback where no component call exists.
Dynamic class lists built from variables are outside the automated
check - only quoted literals are scanned.
// Correct - the value routes through the capability arg.export const Accent = {args: { ...story.values([c.Emphasis.accent]) },render: (args) => Card(story.apply(args)),};// Correct - a composed component resolves against its own spec.Button({ content: demoText.action.signin, ...valuesFor(buttonSpec, [c.Fill.outline, c.Size.sm]) });// Correct - a nested-element passthrough names the words from the spec.args: { trigger_classes: [c.Fill.outline, c.Size.sm] },// Wrong - unchecked literals; a typo renders nothing and says nothing.export const Accent = {args: { classes: ['accent'] },};Button({ content: demoText.action.signin, classes: ['outline', 'sm'] });
Story chrome
61.11. Story chrome is Storybook-only CSS for layout and previews. It MUST NOT be shipped as part of the design system.
61.12. Story chrome MUST use --story-* variables. Design tokens
MUST NOT be used in story chrome. Chrome MUST NOT use
var(--token, fallback) syntax. The fallback is a leak: it
tolerates a missing chrome variable AND disguises a design-token
reference. Chrome variables MUST be declared on :root in
src/tools/storybook-chrome/stories.css or a sibling
stories-*.css.
A demo whose subject is the token it reads opts the rules that
read it out between a /* lint-chrome-tokens: off <reason> */
comment and a /* lint-chrome-tokens: on */ comment, the reason
naming the token it mirrors. Two pieces of chrome do: the options
showcase (src/foundation/options/options.stories.css) reads the
--option-* values it demonstrates, and the body rail in
stories.css reads the --layout-* and --container-* tokens
whose geometry it frames, so the rail cannot drift from the layout
it stands in for.
/* Correct */.story-grid {gap: var(--story-spacing);}/* Wrong */.story-grid {gap: var(--space-x-4);}/* Wrong - fallback hides a missing chrome variable AND a token leak. */.story-grid {gap: var(--background-color-neutral, #fff);}
61.13. All story chrome classes MUST use the story- prefix.
Per-component chrome class names MUST further start with
story-{component} - the bare story-{component} for the one
wrapper a file needs, story-{component}-{part} for the rest - so
per-component ownership is unambiguous (.story-collapsible and
.story-sidenav-viewport-scroll live beside their components).
61.14. Shared chrome MUST live in
src/tools/storybook-chrome/stories.css or a sibling
src/tools/storybook-chrome/stories-*.css. Chrome JS MUST live
in src/tools/storybook-chrome/. Per-component chrome lives in
{name}.stories.css next to the component.
61.15. Before declaring a new .story-* class anywhere - shared
chrome OR per-component *.stories.css - contributors MUST check
src/tools/storybook-chrome/README.md
(the canonical chrome inventory). Existing chrome MUST be re-used wherever it
fits. Inventing a duplicate of an existing primitive (a second
"control bar", a second "panel", a second "page surface") is a
violation. Add a new class only when no existing chrome can express
the intent; document its purpose with a leading CSS comment so the
inventory generator can pick it up.
The per-component table of that README lists every .story-*
class a *.stories.css names, by full name, one row per file; a
trailing * stands for a family that shares a prefix
(.story-options-*).
61.28. Helper text inside a chrome surface - page heading,
section description, instructional copy that explains what the
story is showing - MUST live inside a .story-docs wrapper (the
Level 3 doc surface defined in
Rule 62.3). Bare
<h1> / <h2> / <p> tags as direct children of a chrome
surface (.story-canvas, .story-canvas-full, etc.) are a
violation. The .story-docs wrapper is the single source of
help-block typography across every story so the heading +
description rhythm stays identical regardless of which surface
contains them. Build the wrapper via buildDocs(title, desc) (or
buildPage(title, desc) which uses buildDocs internally) from
src/tools/storybook-chrome/story-helpers.js - desc accepts
HTML so inline <code> references render correctly.
// Correct - heading + description wrapped in `.story-docs`.render: () => {const fragment = document.createDocumentFragment();fragment.appendChild(buildDocs('Elevation', 'Five tiers of shadow depth.'));fragment.appendChild(buildList());return fragment;};// Wrong - bare h1 + p inside the chrome surface.render: () => `<h1>Elevation</h1><p>Five tiers of shadow depth.</p>${buildList()}`;
61.25. Canvas-level chrome (width sizers, flex containers, viewport
simulations) MUST be applied via the canvas story parameter rather
than by wrapping render output in a chrome <div>. The canvas
parameter accepts a space-separated string of chrome class names that
are added to #storybook-root by the .storybook/preview.js
decorator. Valid classes are declared in
src/tools/storybook-chrome/stories.css and cataloged, by level, in
the canonical inventory
src/tools/storybook-chrome/README.md.
All chrome names are plain kebab (no BEM -- modifiers). Canonical
vocabulary:
- Containers (canvas surface family):
.story-canvas(the default surface, auto-applied when a story requests no other),.story-canvas-fluid,.story-canvas-full(+.story-canvas-full-body),.story-canvas-scroll(+.story-canvas-scroll-top-bar/.story-canvas-scroll-bottom-bar/.story-canvas-scroll-markerand its-top/-middle/-bottompositions),.story-canvas-viewport,.story-canvas-viewport-inline(+.story-canvas-viewport-inner),.story-body-rail-left/.story-body-rail-right. - Width values (t-shirt scale):
.story-w-xs(20rem),.story-w-sm(24rem),.story-w-md(40rem),.story-w-lg(48rem),.story-w-xl(50rem),.story-w-xxl(60rem),.story-w-xxxl(80rem). Adding a future width slots into the same naming scheme. - Layout primitives:
.story-row(horizontal flex),.story-stack(vertical flex), with gap modifiers.story-row-gap-sm/-md/-lgand.story-stack-gap-sm/-md/-lg(default gap is 0.5rem). Row also accepts.story-row-justify-start/-center/-end/-between; stack also accepts.story-stack-align-center. - Form grid, compass:
.story-form-grid,.story-specimen-grid,.story-compass(+.story-compass-bounded).
The legacy constrain parameter and the constrain() JS helper
MUST NOT be used - the chrome-class approach is the only supported
mechanism.
// Correct - chrome classes applied to the canvas root.export default {title: 'Components/Progress',parameters: { canvas: 'story-w-xs' },};export const Determinate = {parameters: { canvas: 'story-w-xs story-stack story-stack-gap-lg' },render: (args) => bars.map(...).join(''),};// Wrong - wrapper div for canvas layout.export const Determinate = {render: () => `<div class="story-stack story-stack-gap-lg">${bars}</div>`,};// Wrong - legacy constrain parameter.parameters: { constrain: '20rem' }
61.26. Every story MUST be centered in the canvas by default.
.storybook/preview.js declares layout: 'centered' for the whole
preview, so a story inherits centering without declaring anything -
see Rule 61.31 for the parameter itself.
Centering is delivered by the canvas surface sizing itself to the
story. .story-canvas declares no width, so under the centered
layout #storybook-root shrinks to the rendered content and
Storybook's own margin: auto centers it. A story that needs a
defined working width - a fluid or full-width demonstration, a wide
table, a column grid - MUST state that width with a story-w-*
sizer on the canvas parameter instead of leaning on the surface's
own cap.
Exceptions: a story whose subject renders the page surface itself
uses layout: 'fullscreen' with canvas: 'body'; a foundation whose
content exceeds the viewport uses 'fullscreen' or 'padded'; token
and scale demonstrations MAY use 'fullscreen'. A story MUST NOT
introduce a wrapper <div> to position itself (alignment, centering,
flex/grid layout); that is canvas-level chrome and belongs on the
canvas parameter per Rule 61.25. A layout-utility class (container,
grid, flex, a spacing or sizing word) on an element the render
authors is the same violation. Stories MUST return the component's own
root directly (or a string/fragment of sibling components for
composition showcases) so the canvas parameter and layout can do
the positioning. A Level 2 content atom rendered on purpose per
Rule 62.2 (story-label,
story-badge, story-panel, story-placeholder, story-region,
the util track) and a story-docs block are content, not
positioning, and pass the check.
A pattern's surface follows what its partial roots in, rather than what the pattern is about. A partial rooting in a band component - section or collection, each of which spans the viewport and holds its own content column - renders the page surface, so its story requests layout: 'fullscreen' with canvas: 'body' and lets the band span. A partial rooting in a component that occupies a content column - a form, a card - states its own width with a story-w-* sizer, and that sizer is one pattern's working width rather than a shared surface choice. newsletter-signup roots in a section band and contact-form roots in a form, so the two sit on different surfaces while both being forms.
// Correct - centering is inherited; the sizer states the width the// story actually needs.export default {parameters: { canvas: 'story-w-xxl' },};export const Controls = {parameters: { layout: 'padded', canvas: 'story-stack story-stack-gap-lg' },render: () => [Textfield(controls.apply({ label: 'Text' })),Textarea(controls.apply({ label: 'Message' })),].join(''),};// Wrong - wrapper div centered via inline/class styling.export const Controls = {render: () => {const wrapper = document.createElement('div');wrapper.className = 'story-stack';wrapper.innerHTML = [...].join('');return wrapper;},};
A story that must carry a chrome class inside its render for a documented reason opts out of the check with a leading // lint-story-chrome: off comment that states the reason. The opt-out is file-level.
61.36. A render that places component instances side by side MUST
join them with '', never with ' '. Every template emits its own
leading and trailing whitespace, so the text node between two
rendered roots is whitespace-only with or without the separator and
collapses to the same single space. The separator draws nothing, and
a mark that draws nothing should have one spelling rather than two.
Spacing between specimens is canvas chrome's job per Rule 61.25. A
row of specimens that needs a gap declares story-row with a gap
modifier on the canvas parameter, where the gap is a named value
instead of a side effect of a text node.
This governs joins that build markup from component calls. A join
that builds a class attribute, a space-separated id list for
aria-describedby, or an accessible name keeps its space, which is
the separator those grammars require. A join whose values are
demo-section partials rather than component calls assembles a page
instead of a row, and is not covered. A label interleaved with
component instances does not make a join one of those: the
instances are still siblings, and the separator between them still
draws nothing.
// Correct - instances joined with '', gap declared as chrome.export const Sizes = {parameters: { canvas: 'story-row story-row-gap-md' },render: (args) => SIZES.map((size) => Button(story.apply({ ...args, ...story.values([size]) }))).join(''),};// Correct - the space belongs to the attribute's grammar.const classAttr = classes.length ? ` class="${classes.join(' ')}"` : '';const describedBy = ids.join(' ');// Wrong - a separator standing in for spacing between instances.export const Sizes = {render: (args) => SIZES.map((size) => Button(story.apply({ ...args, ...story.values([size]) }))).join(' '),};
61.31. A story MUST NOT restate parameters.layout: 'centered'.
The preview already declares it for every story, so a second
declaration says nothing and hides the one case that does mean
something: a 'centered' that overrides a 'fullscreen' or
'padded' set on the same file's default export. Only that
overriding form is PERMITTED.
// Wrong - restates the preview-level default.export default {title: 'Patterns/Contact form',parameters: { layout: 'centered', canvas: 'story-w-md' },};// Correct - the parameter carries no information, so it is absent.export default {title: 'Patterns/Contact form',parameters: { canvas: 'story-w-md' },};// Correct - overrides the file's own 'fullscreen' default.export default {parameters: { layout: 'fullscreen' },};export const EventToast = {parameters: { layout: 'centered' },};
61.27. All shared chrome --story-* variables MUST be declared
on :root in src/tools/storybook-chrome/stories.css.
Component-scoped chrome variables MUST be prefixed with the
component name (--story-{component}-…) and MAY be declared on
:root in the component's stories.css or on the component's own
chrome wrapper class. A per-component file MAY set a shared
variable the atom it composes reads (--story-region-bg under
.story-paddings-stack); every variable it declares of its own
carries the prefix, and every var(--story-*) a chrome stylesheet
reads names a declared variable.
Color scheme
61.30. Stories MUST NOT define a per-story theme arg. The active
color scheme is selected at page level via the Storybook
Backgrounds toolbar (Light / Dark), which the canvas decorator
in .storybook/preview.js translates into data-color-scheme on
the iframe <html> (see Rule 24). Per-story dark wrappers and the
old per-component data-theme attribute MUST NOT be reintroduced.
Demo content
61.16. All placeholder content MUST use the space-exploration theme - real missions, real people, real agencies. Lorem Ipsum and fake brands MUST NOT be used.
61.17. Content MUST come from src/tools/demo-content/demo-content.js, or from a story-local demoSet() / demoPool() built with src/tools/demo-content/demo-content.core.js for data only one story needs (Rule 61.33). Space content MUST NOT be hardcoded inline. A story-local pool holds structural data - codes, labels, values, indexes. A sentence or a paragraph is prose and comes from sentence(), paragraph() or a demoText entry, so the space theme of 61.16 lives in one place.
61.18. Interaction tests and showcases MUST use deterministic mode
({ index: N }). Multi-instance stories SHOULD use sequential
mode. Random mode ({ random: true }) is NOT RECOMMENDED.
61.19. { html: true } MAY be added for pre-wrapped HTML output.
61.20. Demo images MUST live in .storybook/static/demo/ with
demo- prefix and MUST be public-domain space imagery.
61.33. Demo content is code, never literals. A component or pattern
story MUST NOT pass a string literal as the value of a
content-bearing key (content, title, label, legend,
helper, placeholder, supertitle, caption, question,
answer, quote, alt, trigger_label, summary). Content
reads from the helpers and
registries in src/tools/demo-content/demo-content.js, referenced
as importable code - demoText.action.print,
demoFields.callsign.label - never through a string key, so a
misspelled reference throws at the access site and tooling can
track renames. Genuinely story-specific demo data is declared once,
at module scope, with demoSet() or demoPool() from
src/tools/demo-content/demo-content.core.js - the same shapes the
library uses, so the machine name exists exactly once and a
misspelled reference fails at module load.
Outside the rule: Storybook boundary strings (story name:,
argTypes labels, descriptions and option lists, table.category),
the meta title, spec and capability values, icon symbol names,
config attributes (name:, ids, data-* values), and composed
template literals whose dynamic part already reads from code.
Annotation copy addressed to the reviewer is a boundary string too:
a demo control label (Start, Reset), a scroll-marker or
placeholder caption that says what the canvas shows, and a trigger
label that names the mechanism under demo (Click to expand). A
line that must keep a literal for a documented reason carries a
// demo-literal: <reason> marker, trailing or on the line directly
above; the linter honors the marker and the reviewer judges the
reason.
// Wrong - the label spells demo content inline.args: { label: 'Callsign', placeholder: 'e.g. Eagle' },// Correct - the vocabulary entry is the single source, referenced as code.args: { label: demoFields.callsign.label, placeholder: demoFields.callsign.placeholder },// Correct - story-specific data declared once via the core factory.const ORDERS = demoPool([{ code: 'dmy', label: 'Day / month / year' }]);
Test policy
61.21. Every component MUST have at least one interaction test that verifies the component renders without errors.
61.22. Components with JS behavior MUST have interaction tests
covering: initial state, user-triggered state change (e.g. click
opens accordion), keyboard operation (Enter, Space, Escape) where
the component binds a key handler of its own, and the no-JS
fallback per Rule 41. A
component whose keys come from the element (<dialog> answering
Escape, <details> answering Enter) or from a shared utility with
its own keyboard tests (close, collapsible) covers them through
its state-change test.
61.23. Form controls MUST test: focus via keyboard, disabled
state, checked/selected state where applicable, and
aria-invalid styling where the component supports validation.
The check reads the spec: is_disabled needs a disabled
assertion, is_checked a checked one, is_invalid an
aria-invalid one, and a bound control (is_disabled beside a
name or value prop) a keyboard focus test - userEvent.tab()
followed by toHaveFocus().
61.24. Interaction tests MUST assert against the DOM, not
internal JS state. Tests MUST use semantic queries (getByRole,
getByLabelText). querySelector MAY be used only when no
semantic equivalent exists.
61.34. The Playground story's play function MUST hold for
every combination its controls can reach. Each assertion is either
invariant across the whole arg space, or derived from the args
the play receives. A value read off the default args - an item
count, a class word, a role an intent switches, a label the
control panel owns, a boolean state a toggle owns - MUST NOT be
written as a literal.
The Playground is the sandbox a reader opens to exercise the
controls, and its play runs on every load, including one whose args
arrived in the URL. A literal that only matches the defaults turns
the first control change into a red Interactions panel and a
console error, so the sandbox punishes the interaction it exists
for and every arg-carrying link opens in a failed state.
Three shapes carry the derivation:
- Derive what varies -
expect(items).toHaveLength(args.levels).selectedValues(...)fromsrc/tools/storybook-chrome/story-helpers.jsreturns the value words an arg set renders as classes, dropping an unset capability and thenoneoption. - Guard what a control removes -
if (args.has_close) { … }, or an earlyexpect(root).toBeNull()where clearing a required slot leaves the template rendering nothing. - Reset what outlives the render. A component that persists
state - consent writes its decision to
localStorage- clears that state in a story-levelbeforeEach, so a second visit starts where the first one did.
Reaching the subject through the element rather than the role is
PERMITTED under 61.24 where a control moves it out of the
accessibility tree: an emptied alt makes an image presentational,
an emptied label leaves a <form> or a landmark unnamed, and a
password type drops an input out of the textbox role.
Named stories are outside this rule. A named story declares its own args, so nothing a reader touches can move them, and its assertions stay literal.
The automated half of the rule reads the component's spec and flags a
toHaveClass word or a toHaveAttribute value that spells one of the
values the spec declares, because those are the two positions where a
literal carries the component's own vocabulary. The same word used as an
ARIA role or a CSS keyword sits outside them and is not flagged. Every
other shape - an item count, a demo-content label, a boolean state - is
not enumerable from the spec and stays review-only.
// Wrong - the span form and the count are the defaults, so exercising// either control fails the sandbox.play: async ({ canvasElement }) => {const badge = canvasElement.querySelector('.badge');await expect(badge.tagName).toBe('SPAN');await expect(badge.querySelectorAll('a')).toHaveLength(4);},// Correct - both expectations come from the args.play: async ({ args, canvasElement }) => {const badge = canvasElement.querySelector('.badge');await expect(badge.tagName).toBe(args.with_url ? 'A' : 'SPAN');for (const word of selectedValues(args.size, args.intent)) {await expect(badge).toHaveClass(word);}},
Documentation surface
61.29. Every Component and every Utility MUST ship a co-located
{name}.mdx file alongside {name}.stories.js. Foundations and
Patterns MUST NOT ship one.
The split follows what each type puts in the sidebar. An MDX file
adds a Docs entry beside the stories, which is what a Component
or Utility needs: several named stories plus one page that
introduces them. A Foundation or a Pattern is a single story, so an
MDX there adds a second entry that says the same thing twice.
A Foundation carries its prose inside the story instead, built with
buildPage() from src/tools/storybook-chrome/story-helpers.js; a
Pattern is a composition that demonstrates itself and carries no
prose at all.
The MDX file is the single source of component-level documentation -
description prose, usage guidance, accessibility notes, progressive
enhancement notes, and embedded examples. Editorial content MUST
NOT live in JSDoc comments, parameters.docs.description.component,
or parameters.docs.spec on the default export. The autodocs
mechanism (tags: ['autodocs']) MUST NOT be used.
The MDX file MUST:
- Import blocks from
@storybook/addon-docs/blocksand the stories module as a namespace (import * as FooStories from './foo.stories.js'). - Bind to the meta via
<Meta of={FooStories} />. - Render
<Title />and<Subtitle />at the top. - Use
## Headingfor top-level sections in this exact order: Usage, API, Examples, Accessibility, Dependencies, Progressive enhancement, Related. Sections without content MUST be omitted entirely - no empty headings, no placeholder prose. Sections MUST NOT be reordered or renamed. This is the complete set for a Component; a Utility MAY add the API-surface sections defined after this list. - Carry the contract in an
APIsection rendered by theApiSectionblock, never as authored prose. The block reads the published{name}.spec.jsonand emits one table per surface it declares - slots, props, class words, data attributes, events - so the page states the contract the component actually ships. The docs-site plugin renders the same sections as markdown when it stages the page, so both surfaces publish one contract. A hand-written prop, class or attribute table MUST NOT appear anywhere in the MDX file, because a second copy of the contract drifts from the spec the moment either changes. A table of editorial guidance - when to reach for one value over another - is not a contract table and belongs underUsage. The section is REQUIRED wherever a contract exists to render, so only a subject exempt from Rule 53.1 omits it. - Embed each non-Playground story under a
### {Title}heading inside the Examples section via<Canvas of={FooStories.{Name}} />. A### {Title}heading without an embedded canvas MUST NOT be written - if there is no story to embed, drop the heading.
A UTILITY's public API extends past what the spec declares, so a utility doc page MAY additionally use up to five API-surface sections. All five sit between Examples and Accessibility, in this exact order:
Data attributes- thedata-*attributes the consumer authors to opt elements in and configure the behavior (Rule 12).State- the attributes the script sets at runtime (namespaceddata-*state per Rule 24.4, or ARIA it syncs) that consumers observe or style.Events- the custom events the utility emits or listens for (Rule 43).Public API- thewindow.Semetrika.{name}surface beyond the standardinit/destroypair (Rule 42.15).Tokens- the--{utility}-*tokens and--option-*flags the utility exposes for consumer override.
The full utility order is therefore: Usage, API, Examples, Data attributes, State, Events, Public API, Tokens, Accessibility, Dependencies, Progressive enhancement, Related.
The first three overlap the API section without being replaced by it. The generated tables publish what the spec models - the data-* hooks and states in one Attributes table separated by a Set by column, and the custom events by direction. They do not reach an event's bubbling, cancelability or detail shape, the ARIA attributes a script keeps in sync, a native platform attribute or event the utility opts into, or an init marker (which Rule 44.5 excludes from the spec by design). A Data attributes, State or Events section therefore carries what the spec cannot express and MUST NOT restate a row the generated table already publishes. The omission and no-rename rules apply unchanged - a section with nothing to say is dropped, and a qualifier belongs in the section's prose, not its heading (## State, never ## State (in section mode)). Everything else lives inside the shared sections: a class-grammar or naming reference is a ### subsection of Usage, and every value or mode demonstration is a ### canvas under Examples - demo groups MUST NOT be promoted to their own ## sections. A Component MUST NOT use the five utility sections - a component's prop and capability surface is declared in its spec (Rule 53), and the API section publishes it.
The MDX file MUST NOT embed the Playground story or its
controls table. The Playground story remains in
{name}.stories.js and stays reachable from the Storybook
sidebar; the docs page focuses on prose and named-example
canvases instead of duplicating the sandbox.
import { Meta, Title, Subtitle, Canvas } from '@storybook/addon-docs/blocks';import { ApiSection } from '../../../.storybook/docs/api-section.js';import * as ButtonStories from './button.stories.js';import buttonSpec from './button.spec.json';<Meta of={ButtonStories} /><Title /><Subtitle />Interactive button with intent, fill, and size variants.## Usage**When to use**- Triggering an action on the current page.## API<ApiSection of={buttonSpec} />## Examples### IntentsThe four intent variants composed via class.<Canvas of={ButtonStories.Intents} />## Accessibility- WCAG 2.2 AA.- Visible focus ring on keyboard focus.
Reference
The on-brand demo content vocabulary is in
src/tools/demo-content/README.md.
61.4, 61.5, 61.7, 61.8, 61.9, 61.10, 61.12, 61.13, 61.15, 61.17, 61.21, 61.23, 61.27, 61.25, 61.26, 61.36, 61.31, 61.30, 61.32, 61.33, 61.35, 61.34 by yarn cli 61 (findMissingPlaygroundStory, findPlaygroundRenderWithoutArgs, analyzeStoryThemeApply, findShadowedControls, findMirrorStories, findObjectControls, findStepLessPlays, findDesignTokenReadsInChrome, findPerComponentChromeViolations, runChromeCheck, findProsePools, findPlaylessStories, findFormControlStateGaps, findUnprefixedChromeVariables, findUndeclaredChromeReads, findLegacyConstrain, findChromeInRender, findFrameworkWrappersInRender, findSeparatorJoins, findRedundantCenteredLayout, findThemeStories, findHardcodedOptionControls, findLiteralDemoContent, findCapabilityLiteralClasses, findHardcodedPlaygroundValues in packages/cli/src/rules/61.js). 61.1-61.3, 61.6, 61.11, 61.14, 61.16, 61.18-61.20, 61.22, 61.24, 61.28, 61.29 are review only. See enforcement.md.