Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 3

Lab: A Themed Button, Field and Dialog Kit in Storybook

Build a three-component kit on the token system, document every state as a story, and let computed-style, axe and stylelint checks keep it honest.

Contentsand lesson path

What you will learn

  • Define design tokens (color, spacing, type scale, radius, motion) as CSS custom properties and use them for theming, including dark mode and reduced motion.
  • Choose a scalable styling approach (CSS Modules, utility-first CSS such as Tailwind, or cascade layers) and justify its trade-offs in specificity control, shipped CSS and team workflow.
  • Build reusable, accessible components with typed variant APIs and document every state in a component workshop such as Storybook.

Prerequisites: CSS Cascade & Box Model

01. Goal and setup

This lab assembles the pieces of the previous lessons into a working kit: a Button, a TextField and a Dialog, styled only through design tokens, documented story by story, and guarded by three checks that run without a human eye — computed styles read back from a real browser, axe running the WCAG A and AA rules on two stories, and a stylelint rule that refuses raw colours outside the token file.

You need: Node 22 and npm. The install lines pin the versions this lab was last run with: React 19.3.1, Storybook 10.6.9 with the @storybook/react-vite framework, Vite 8.4, stylelint 18.1, TypeScript 7.0 and Playwright 1.64.1 with @axe-core/playwright 4.14.1 for the checks (the browser binary comes from Playwright's own install, the last line below). The pins matter for the verify output: the field ids it prints come from React's useId(), whose format has changed between React releases. Nothing is installed globally; everything lives in the project folder.

Create the project and install:

Terminal
mkdir atlas-kit && cd atlas-kit
npm init -y
npm install [email protected] [email protected]
npm install -D [email protected] @vitejs/[email protected] [email protected] \
  @storybook/[email protected] [email protected] [email protected] \
  @types/[email protected] @types/[email protected] [email protected] \
  @axe-core/[email protected]
npx playwright install chromium
Project layout
atlas-kit/
├── .storybook/
│   ├── main.js          story discovery and framework
│   └── preview.js       imports tokens.css once for all stories
├── stories/             one stories file per component
├── src/
│   ├── tokens.css       the only file with raw values
│   ├── button.tsx  button.css
│   ├── text-field.tsx  text-field.css
│   └── dialog.tsx  dialog.css
└── stylelint.config.mjs

Copy the two-layer tokens.css from the tokens lesson — palette and scales on :root, semantic roles on :root, a dark block on [data-theme='dark'], and the reduced-motion override. Add one spacing step the text field uses, --space-3: 0.75rem;, to the scales block (without it, var(--space-3) is undefined, the field's whole padding declaration is invalid at computed-value time, and the padding silently becomes 0). Then add the semantic roles the new components need: --color-danger: #c92a2a; and --color-danger-soft: #ffe3e3; for errors, and --color-scrim: rgba(0, 0, 0, 0.45); for modal backdrops (in dark mode: --color-danger: #ff8787;, --color-danger-soft: #4a1515;, --color-scrim: rgba(0, 0, 0, 0.65);). Before writing a component, measure the pairs the kit will actually render:

JavaScript · contrast-check.mjs
function luminance([r, g, b]) {
  const channel = (v) => {
    const s = v / 255;
    return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
  };
  return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
}

function contrast(hexA, hexB) {
  const parse = (h) => h.match(/[0-9a-f]{2}/gi).map((x) => parseInt(x, 16));
  const [hi, lo] = [luminance(parse(hexA)), luminance(parse(hexB))]
    .sort((a, b) => b - a);
  return (hi + 0.05) / (lo + 0.05);
}

const pairs = [
  ['light: on-primary on primary', '#ffffff', '#1a5ec2'],
  ['light: on-primary on danger', '#ffffff', '#c92a2a'],
  ['light: danger text on surface', '#c92a2a', '#ffffff'],
  ['light: primary-ink on primary-soft', '#144a9b', '#dbe9fc'],
  ['dark: ink on surface', '#aacbf8', '#1c242e'],
  ['dark: on-primary on primary', '#0e1319', '#8ab9f4'],
  ['dark: on-primary on danger', '#0e1319', '#ff8787'],
  ['dark: danger text on surface', '#ff8787', '#1c242e'],
];
for (const [label, a, b] of pairs) {
  const ratio = contrast(a, b).toFixed(2);
  console.log(`${label.padEnd(36)} ${ratio}:1  AA normal text`);
}
Expected output · node contrast-check.mjs
light: on-primary on primary         6.13:1  AA normal text
light: on-primary on danger          5.46:1  AA normal text
light: danger text on surface        5.46:1  AA normal text
light: primary-ink on primary-soft   6.88:1  AA normal text
dark: ink on surface                 9.40:1  AA normal text
dark: on-primary on primary          9.17:1  AA normal text
dark: on-primary on danger           8.05:1  AA normal text
dark: danger text on surface         6.76:1  AA normal text

02. Step 1: the Button and its variants

TypeScript · src/button.tsx
import type { ComponentProps } from 'react';
import './button.css';

export interface ButtonProps extends ComponentProps<'button'> {
  variant?: 'primary' | 'secondary' | 'danger';
}

export function Button({
  variant = 'primary',
  type = 'button',
  className,
  ...rest
}: ButtonProps) {
  const classes = ['button', className].filter(Boolean).join(' ');
  return <button type={type} data-variant={variant} className={classes} {...rest} />;
}
CSS · src/button.css
.button {
  padding: var(--space-2) var(--space-4);
  border: 0;
  border-radius: var(--radius-md);
  font: inherit;
  cursor: pointer;
  background: var(--color-primary);
  color: var(--color-on-primary);
  transition: background var(--motion-fast) var(--motion-ease);
}
.button:focus-visible {
  outline: 2px solid var(--color-focus);
  outline-offset: 2px;
}
.button[data-variant='secondary'] {
  background: var(--color-primary-soft);
  color: var(--color-primary-ink);
}
.button[data-variant='danger'] {
  background: var(--color-danger);
  color: var(--color-on-primary);
}
.button[disabled] { opacity: 0.5; cursor: not-allowed; }

The variant rides on a data-variant attribute rather than extra classes, so the stylesheet branches on a single documented axis and TypeScript keeps invalid variants out at compile time. Two details are load-bearing. font: inherit makes the button text match its surroundings instead of the browser default, and the :focus-visible ring is styled from --color-focus — deleting it without a replacement is not an option, because keyboard users navigate by it. Note what the component does not do: no hex values, no margins, no width. Margins belong to the layout around a button, not to the button.

03. Step 2: the TextField and its error state

TypeScript · src/text-field.tsx
import { useId } from 'react';
import type { ComponentProps } from 'react';
import './text-field.css';

type InputProps = Omit<ComponentProps<'input'>, 'className' | 'id'>;

export interface TextFieldProps extends InputProps {
  label: string;
  error?: string;
}

export function TextField({ label, error, ...rest }: TextFieldProps) {
  const id = useId();
  return (
    <div className="field">
      <label className="field__label" htmlFor={id}>
        {label}
      </label>
      <input
        id={id}
        className="field__input"
        aria-invalid={error ? true : undefined}
        aria-describedby={error ? `${id}-error` : undefined}
        {...rest}
      />
      {error ? (
        <p className="field__error" id={`${id}-error`}>
          {error}
        </p>
      ) : null}
    </div>
  );
}
CSS · src/text-field.css
.field {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}
.field__label {
  font-size: var(--text-sm);
  color: var(--color-ink);
  font-weight: 500;
}
.field__input {
  padding: var(--space-2) var(--space-3);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  font: inherit;
  background: var(--color-surface);
  color: var(--color-ink);
}
.field__input:focus-visible {
  outline: 2px solid var(--color-focus);
  outline-offset: 2px;
}
.field__input[aria-invalid='true'] {
  border-color: var(--color-danger);
}
.field__error {
  margin: 0;
  font-size: var(--text-sm);
  color: var(--color-danger);
}

The label is a required prop wired to the input with useId(), so a TextField without a label does not compile — the accessible name is part of the API, not a convention. The error state shows the non-colour rule in action: the message is real text linked to the input through aria-describedby, the input sets aria-invalid, and the red border is an extra cue, never the only one. Styles mirror the button: token colours, a visible focus ring, --color-danger for the border and message.

04. Step 3: the Dialog on the native element

TypeScript · src/dialog.tsx
import { useEffect, useId, useRef } from 'react';
import type { ReactNode } from 'react';
import { Button } from './button';
import './dialog.css';

export interface DialogProps {
  open: boolean;
  onClose: () => void;
  title: string;
  children: ReactNode;
}

export function Dialog({ open, onClose, title, children }: DialogProps) {
  const ref = useRef<HTMLDialogElement>(null);
  const titleId = useId();
  useEffect(() => {
    const dialog = ref.current;
    if (!dialog) return;
    if (open && !dialog.open) dialog.showModal();
    if (!open && dialog.open) dialog.close();
  }, [open]);
  return (
    <dialog ref={ref} aria-labelledby={titleId} className="dialog"
      onClose={onClose}>
      <h2 className="dialog__title" id={titleId}>{title}</h2>
      {children}
      <div className="dialog__actions">
        <Button variant="secondary" onClick={onClose}>Cancel</Button>
        <Button onClick={onClose}>Confirm</Button>
      </div>
    </dialog>
  );
}
CSS · src/dialog.css
.dialog {
  min-width: 20rem;
  padding: var(--space-4);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  background: var(--color-surface);
  color: var(--color-ink);
}
/* ::backdrop inherits from the dialog, so tokens reach it too. */
.dialog::backdrop {
  background: var(--color-scrim);
}

The native <dialog> element with showModal() gives the kit the hard parts of a modal for free: focus moves inside, the rest of the page becomes inert to Tab, the Escape key closes it (firing the close event the component forwards through onClose), and ::backdrop exists to dim the page. The title is linked with aria-labelledby, so screen readers announce which dialog opened.

05. Step 4: document every state as a story

JavaScript · .storybook/main.js and preview.js
// main.js
export default {
  stories: ['../stories/**/*.stories.@(js|jsx|ts|tsx)'],
  framework: '@storybook/react-vite',
};

// preview.js — tokens load once; components read only var().
import '../src/tokens.css';
TypeScript · stories/button.stories.tsx
import type { Meta, StoryObj } from '@storybook/react-vite';
import { Button } from '../src/button';

const meta = {
  title: 'Button',
  component: Button,
} satisfies Meta<typeof Button>;

export default meta;
type Story = StoryObj<typeof meta>;

export const Primary: Story = { args: { children: 'Send reminders' } };
export const Secondary: Story = {
  args: { variant: 'secondary', children: 'Preview' },
};
export const Danger: Story = {
  args: { variant: 'danger', children: 'Delete note' },
};
export const Disabled: Story = {
  args: { disabled: true, children: 'Send reminders' },
};
export const LongLabel: Story = {
  args: { children: 'Send reminders to everyone in the group' },
};
TypeScript · stories/text-field.stories.tsx
import type { Meta, StoryObj } from '@storybook/react-vite';
import { TextField } from '../src/text-field';

const meta = { title: 'TextField', component: TextField } satisfies Meta<
  typeof TextField
>;
export default meta;
type Story = StoryObj<typeof meta>;

export const Default: Story = { args: { label: 'Invoice reference' } };
// Story id textfield--error, opened by the verify script below.
export const Error: Story = {
  args: {
    label: 'Invoice reference',
    defaultValue: 'INV-',
    error: 'Enter the full reference, for example INV-2041.',
  },
};
TypeScript · stories/dialog.stories.tsx
import type { Meta, StoryObj } from '@storybook/react-vite';
import { Dialog } from '../src/dialog';

const meta = { title: 'Dialog', component: Dialog } satisfies Meta<
  typeof Dialog
>;
export default meta;
type Story = StoryObj<typeof meta>;

// Story id dialog--default: opens as a modal as soon as it renders.
export const Default: Story = {
  args: {
    open: true,
    title: 'Delete this note?',
    children: 'The note is removed for everyone in the group.',
    onClose: () => {},
  },
};

Write stories for every state the design drew: default, each variant, disabled, an error field, and the awkward long label that shows the button grows without breaking. Name them for the state they document — the story list becomes the table of contents a reviewer walks. Then start the workshop and read the inventory back. Before you run the script, predict two of its lines from tokens.css alone: the backdrop colour behind the open dialog, and the dialog surface once the theme flips to dark.

JavaScript · scripts/verify-lesson.mjs
import { chromium } from 'playwright';
import AxeBuilder from '@axe-core/playwright';

// axe runs only rules carrying one of these tags: list every level.
const WCAG = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'];
const browser = await chromium.launch();
const context = await browser.newContext(); // AxeBuilder needs a context
const page = await context.newPage();
await page.goto('http://localhost:6006/iframe.html?id=button--primary');
const btn = page.locator('.button');
const [bg, color, radius] = await btn.evaluate((el) => {
  const s = window.getComputedStyle(el);
  return [s.backgroundColor, s.color, s.borderRadius];
});
console.log(`button:  bg=${bg} text=${color} radius=${radius}`);

const btnAxe = await new AxeBuilder({ page }).withTags(WCAG).analyze();
console.log(`button axe violations: ${btnAxe.violations.length}`);

await page.goto('http://localhost:6006/iframe.html?id=textfield--error');
const input = page.locator('.field__input');
const [labelFor, inputId, descBy, invalid] = await input.evaluate((el) => {
  const l = document.querySelector(`label[for="${el.id}"]`);
  return [
    l?.textContent?.trim(),
    el.id,
    el.getAttribute('aria-describedby'),
    el.getAttribute('aria-invalid'),
  ];
});
console.log(`field:   label "${labelFor}" for=${inputId} input=${inputId}`);
console.log(`         describedby=${descBy} invalid=${invalid}`);

const fieldAxe = await new AxeBuilder({ page }).withTags(WCAG).analyze();
console.log(`field axe violations: ${fieldAxe.violations.length}`);

await page.goto('http://localhost:6006/iframe.html?id=dialog--default');
await page.locator('dialog[open]').waitFor(); // stories render after load
const [open, focusInside, backdrop] = await page.evaluate(() => {
  const d = document.querySelector('dialog');
  const b = window.getComputedStyle(d, '::backdrop').backgroundColor;
  return [d.open, d.contains(document.activeElement), b];
});
console.log(`dialog:  open=${open} focusInside=${focusInside} backdrop=${backdrop}`);

await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark'));
const darkSurface = await page.locator('.dialog').evaluate((el) => {
  return window.getComputedStyle(el).backgroundColor;
});
console.log(`dark:    dialog surface=${darkSurface}`);

await browser.close();
Terminal
npx storybook dev -p 6006
# in a second terminal, while it runs:
node scripts/verify-lesson.mjs
Expected output · node verify-lesson.mjs
button:  bg=rgb(26, 94, 194) text=rgb(255, 255, 255) radius=8px
button axe violations: 0
field:   label "Invoice reference" for=_r_0_ input=_r_0_
         describedby=_r_0_-error invalid=true
field axe violations: 0
dialog:  open=true focusInside=true backdrop=rgba(0, 0, 0, 0.45)
dark:    dialog surface=rgb(28, 36, 46)

Each line is a claim turned into a check. The button renders rgb(26, 94, 194) — --color-primary arriving in the computed styles, with the 8px token radius. axe runs the WCAG 2.0, 2.1 and 2.2 rules for levels A and AA over two stories and finds nothing. The tag list matters: axe runs only the rules that carry one of the tags you pass, so withTags(['wcag2aa']) alone skips Level A rules such as label and button-name. Run against the field markup with its label removed, that call still reports 0 violations, while the full list reports label. The field's label points at the input, the input is described by the error, exactly as the component promises. The dialog is modal with focus inside and the scrim reading back as --color-scrim; then one data-theme write flips the surface to the dark token with no component change at all.

These checks belong in the workshop rather than a one-off script: the same assertions can run as story tests on every commit, so a dependency upgrade that quietly drops the focus ring fails a machine, not a reader. Review then walks the story list — every state visible, every claim already verified — instead of spot-checking a running app by hand.

06. Step 5: the gate that keeps tokens the only source

JavaScript · stylelint.config.mjs
/** @type {import('stylelint').Config} */
export default {
  rules: {
    'color-no-hex': true,
    'color-named': 'never',
    // One rule per way of writing a raw colour: hex, named, functional.
    'function-disallowed-list': ['rgb', 'rgba', 'hsl', 'hsla'],
  },
  overrides: [
    {
      files: ['**/tokens.css'],
      rules: {
        'color-no-hex': null,
        'function-disallowed-list': null,
      },
    },
  ],
};
CSS · src/legacy.css (un-tokenised starting point)
.card {
  border: 1px solid var(--color-border);
  background: #ffffff;
  border-radius: var(--radius-md);
  padding: var(--space-4);
  line-height: 1.5;
  color: #141a21;
}
Expected output · npx stylelint "src/**/*.css" (before the fix, stylelint 18.1.0)
src/legacy.css
  3:15  ✖  Disallowed hex color "#ffffff"  color-no-hex
  7:10  ✖  Disallowed hex color "#141a21"  color-no-hex

✖ 2 problems (2 errors, 0 warnings)
CSS · src/legacy.css, tokenised
.card {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  padding: var(--space-4);
  color: var(--color-ink);
}

Each raw colour is reported once, wherever it sits, in a longhand or inside a shorthand such as background or border: color-no-hex catches hex values, color-named catches names such as white, and function-disallowed-list catches rgb() or hsl(). The token file is exempt through overrides, because it is the one place raw values belong. A tempting alternative, declaration-property-value-allowed-list with a pattern such as /^var\(--/, fits shorthands badly: it compares the pattern with the whole value, so the kit's own border: 1px solid var(--color-border) and outline: 2px solid var(--color-focus) would fail it. After the tokenised version above, the gate reports nothing. (The positions are line:column of each hex value, and the command exits with code 2, so a CI job fails.)

Add "lint:css": "stylelint \"src/**/*.css\"" to the scripts and the token file becomes enforceable, not aspirational: a review can focus on the API while the gate catches the stray hex value that code review reads straight past. Wire it next to your other checks so it fails the same pull request as a failing test.

07. Check your understanding

Practice check · 3 questions

Why the kit is built this way

Reason from the kit you just built.

Q1. The stylelint gate flags `background: #ffffff` in a component stylesheet. What does it protect?
Q2. Why does the kit use the native `<dialog>` with `showModal()` instead of a fixed-position `div`?
Q3. The disabled Button story shows white text at half opacity on the primary colour — below 4.5:1 — yet axe reports no violation. Why is this acceptable?
Practice only: not graded, not saved, not evidence.

08. Apply it: extend the kit

  1. Add a fourth state to the Button — a loading variant with aria-busy and a spinner that is not colour-only — and give it a story plus an axe pass.
  2. Give TextField a hint prop rendered under the input, and wire it into the same aria-describedby chain as the error message.
  3. Extend the stylelint config to also pin padding and margin values to spacing tokens, and fix whatever the gate finds.
  4. Then wire the kit into the practice task: extract it to a package your app imports, and delete the last hard-coded value from the app's own stylesheets.

09. Review prompt

Without looking back: which three automated checks did the kit run, and what claim does each one prove? Why does the label live in the component rather than at the call site? What does showModal() give the dialog that a div overlay must hand-build? And what does the stylelint gate stop before it reaches a pull request?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check