Storybook

From j4flmao/agent-skills · View interactive version

Storybook is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks to document button variants or other components in Storybook, CSF 3 stories, args and controls, play functions, interaction or a11y tests in Storybook, Chromatic visual tests or Storybook config. Produces stories, docs and test setup for Storybook 9+. Not for general unit and

How to use this skill

Skill file

Frontend Storybook

Purpose

Create, maintain, and optimize Storybook stories using CSF 3.x format with interaction tests, accessibility checks, and addon-driven workflows. Covers setup across React/Vue/Angular/Svelte, visual testing via Chromatic, custom theming, and documentation mode.

Agent Protocol

Trigger

Exact phrases: "write stories", "storybook", "CSF", "component story", "storybook addon", "visual test", "story for", "stories for", "storybook setup", "interaction test", "chromatic", "storybook docs", "storybook theme", "storybook decorator"

Input Context

Output Artifact

No file output unless requested.

Response Format

  1. Output stories in CSF 3.x .stories.tsx/.stories.ts format (default export with meta, named exports for stories)
  2. Include import statements and meta object with component, title, tags, argTypes
  3. For interactive stories, use play function from storybook/test (@storybook/test in v8)
  4. When suggesting addon config, output the full addon registration snippet
  5. When configuring Chromatic, output the full CI workflow YAML
  6. No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.

Completion Criteria

Max Response Length

120 lines per component story set.

Storybook Architecture / Decision Trees

Story Organization Decision Tree

How many components?
  |-- 1-10 components -->
  |     Simple structure: Components/Button, Components/Card
  |     Co-locate stories with components (Button.stories.tsx next to Button.tsx)
  |
  |-- 10-50 components -->
  |     Feature-based grouping: Feature/Orders/OrderList, Feature/Orders/OrderCard
  |     Group by domain, not by type
  |
  |-- 50+ components (design system) -->
        Nested structure: DesignSystem/Buttons/Primary, DesignSystem/Buttons/Secondary
        Each variant gets its own story
        Atomic structure: Atoms, Molecules, Organisms

Story Coverage Decision Tree

What states does the component have?
  |-- Default / empty state -->
  |     STORY REQUIRED: shows component with no data
  |     Example: empty list, empty card, skeleton state
  |
  |-- Loading state -->
  |     STORY REQUIRED: skeleton or spinner
  |     Example: SkeletonList, LoadingButton
  |
  |-- Error state -->
  |     STORY REQUIRED: error message, retry action
  |     Example: ErrorCard, ErrorForm
  |
  |-- Edge cases -->
  |     STORY REQUIRED: long text, missing props, zero data, overflow
  |     Example: VeryLongText, MissingImage, SingleItem
  |
  |-- Interactive behavior -->
  |     STORY REQUIRED if component has user input
  |     Use play() function to simulate clicks, typing, hover
  |
  |-- Responsive variants -->
        STORY REQUIRED: mobile (375px), tablet (768px), desktop (1280px)
        Use parameters.viewport

Workflow

Step 1: Initialize or Verify Setup

npx storybook@latest init --type react    # or vue3, angular, nextjs, sveltekit

Check .storybook/main.ts for required addons:

| Addon | Package | Purpose |

|-------|---------|---------|

| Core (built in since Storybook 9) | storybook | Controls, Actions, Viewport, Backgrounds, interactions/play testing — addon-essentials and addon-interactions are no longer installed separately |

| Docs | @storybook/addon-docs | Autodocs and MDX |

| Vitest | @storybook/addon-vitest | Runs stories as Vitest browser tests (successor to the test-runner for Vite projects) |

| Accessibility | @storybook/addon-a11y | aXe-based accessibility audits |

| Themes | @storybook/addon-themes | Theme switching toolbar |

| Designs | @storybook/addon-designs | Figma design embeds |

Step 2: Configure Preview

// .storybook/preview.ts
const preview: Preview = {
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: { matchers: { color: /(background|color)$/i, date: /Date$/ } },
    viewport: { viewports: NEW_VIEWPORTS },
    a11y: { config: { rules: [{ id: 'color-contrast', enabled: true }] } },
  },
  decorators: [withThemeFromJSXProvider({ themes: { light, dark }, defaultTheme: 'light', Provider: ThemeProvider })],
  tags: ['autodocs'],
};

Step 3: Write Stories (CSF 3.x)

const meta = {
  title: 'Components/Button',
  component: Button,
  tags: ['autodocs'],
  argTypes: {
    variant: { control: 'select', options: ['primary', 'secondary', 'ghost'] },
    size: { control: 'select', options: ['sm', 'md', 'lg'] },
    disabled: { control: 'boolean' },
    onClick: { action: 'clicked' },
  },
} satisfies Meta<typeof Button>;

export const Primary: Story = { args: { variant: 'primary', children: 'Click Me' } };
export const Disabled: Story = { args: { ...Primary.args, disabled: true } };
export const Loading: Story = { args: { ...Primary.args, loading: true } };

Step 4: Add Interaction Tests

import { userEvent, within, expect, fn } from 'storybook/test'; // Storybook 8: '@storybook/test'

export const Interactive: Story = {
  args: { onClick: fn() },
  play: async ({ canvasElement, args }) => {
    const canvas = within(canvasElement);
    await userEvent.click(canvas.getByRole('button'));
    expect(args.onClick).toHaveBeenCalled();
  },
};

Step 5: Visual Testing with Chromatic

npm i -D chromatic
npx chromatic --project-token=<token>
# .github/workflows/chromatic.yml
- run: npx chromatic --project-token=${{ secrets.CHROMATIC_TOKEN }}

Step 6: Verify Accessibility

Run a11y plugin scan in Storybook UI or via CLI:

npx test-storybook --coverage

Fix violations: missing ARIA labels, insufficient color contrast, missing focus indicators.

Step 7: Documentation Mode

Add tags: ['autodocs'] to each meta (or to preview.ts to enable globally; the old docs.autodocs option in main.ts was removed). For custom docs:

// Button.docs.mdx
import { Meta, Story, Canvas, Controls } from '@storybook/addon-docs/blocks'; // Storybook 8: '@storybook/blocks'
<Meta of={ButtonStories} />
<Canvas><Story of={ButtonStories.Primary} /></Canvas>
<Controls of={ButtonStories.Primary} />

Step 8: MSW Integration for Data Stories

import { http, HttpResponse } from 'msw'
import { initialize, mswLoader } from 'msw-storybook-addon'

initialize()

const meta = {
  component: OrderList,
  loaders: [mswLoader],
} satisfies Meta<typeof OrderList>

export const WithOrders: Story = {
  parameters: {
    msw: {
      handlers: [
        http.get('/api/orders', () => {
          return HttpResponse.json([{ id: '1', name: 'Order 1', total: 100 }])
        }),
      ],
    },
  },
}

export const Empty: Story = {
  parameters: {
    msw: {
      handlers: [
        http.get('/api/orders', () => {
          return HttpResponse.json([])
        }),
      ],
    },
  },
}

Common Pitfalls

  1. CSF 2.x storiesOf API: Always use CSF 3.x. Never use storiesOf — removed in Storybook 8.
  2. Addon imports in story files: Configure addons via parameters/decorators in meta or .storybook/preview.ts (importing addon helpers such as withThemeFromJSXProvider in preview.ts is fine).
  3. Missing autodocs tag: Without tags: ['autodocs'] or global enable, docs tab won't generate.
  4. Real API calls in stories: Always mock data/services. Use MSW or static fixtures.
  5. any type for props: Derive from component's props type. Use StoryObj<typeof meta>.
  6. Hardcoded viewport sizes: Use parameters.viewport with named viewports from config.
  7. Skipping a11y: Run aXe on every component — catch contrast, label, and ARIA issues early.

Compared With

| Feature | Storybook | Ladle | Histoire | Catalog |

|---------|----------|-------|----------|---------|

| Framework support | React, Vue, Angular, Svelte, Web Components | React only | Vue only | Any (static) |

| CSF 3.x | Yes | Yes | No | N/A |

| Interaction testing | Built-in | Limited | Limited | No |

| A11y addon | Yes | No | No | No |

| Visual testing (Chromatic) | Built-in | Third-party | Third-party | No |

| Bundle size (SB) | Large | Small | Small | Minimal |

| MSW integration | Yes | Yes | No | No |

Theming in Storybook

// .storybook/preview.ts — theme switching
import { withThemeFromJSXProvider } from '@storybook/addon-themes';
import { ThemeProvider } from '../src/lib/ThemeProvider';
import { lightTheme, darkTheme } from '../src/lib/themes';

export const decorators = [
  withThemeFromJSXProvider({
    themes: {
      light: lightTheme,
      dark: darkTheme,
    },
    defaultTheme: 'light',
    Provider: ThemeProvider,
    GlobalStyles: () => null,
  }),
];

Story Composition and Reuse

// Composing stories from other stories
import { Primary as ButtonPrimary } from '../Button/Button.stories';

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

// Reuse Button story inside Dialog story
export const WithButton: Story = {
  args: {
    title: 'Confirm',
    children: <Button {...ButtonPrimary.args}>OK</Button>,
    onClose: fn(),
  },
};

// Args composition for complex components
export const WithForm: Story = {
  args: {
    ...Default.args,
    children: (
      <Form>
        <TextField label="Name" />
        <Button {...ButtonPrimary.args}>Submit</Button>
      </Form>
    ),
  },
};

Design System Integration

// Theming with design tokens
// .storybook/preview.ts
export const globalTypes = {
  theme: {
    name: 'Theme',
    description: 'Global theme for components',
    defaultValue: 'light',
    toolbar: {
      icon: 'circlehue',
      items: ['light', 'dark', 'high-contrast'],
      showName: true,
      dynamicTitle: true,
    },
  },
  locale: {
    name: 'Locale',
    description: 'Internationalization locale',
    defaultValue: 'en-US',
    toolbar: {
      icon: 'globe',
      items: ['en-US', 'de-DE', 'vi-VN', 'ja-JP'],
      showName: true,
    },
  },
};

// With Figma design specs
export const ButtonStory = {
  parameters: {
    design: {
      type: 'figma',
      url: 'https://www.figma.com/file/.../Button',
    },
  },
};

Visual Regression Testing with Chromatic

# .github/workflows/chromatic.yml
name: Chromatic
on: [pull_request]

jobs:
  chromatic:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Required for Chromatic to detect changed stories
      - run: npm ci
      - uses: chromaui/action@v1
        with:
          projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
          onlyChanged: true  # Only snapshot changed stories
          exitOnceUploaded: true
          buildScriptName: build-storybook
          # Auto-accept changes from dependabot
          autoAcceptChanges: 'dependabot/**'
          # Prevent false positives for specific branches
          skip: '@(renovate/**|docs/**)'
// Chromatic mode: only globally accessible styles
// Prevent Chromatic from crashing on theme provider issues
export const decorators = [
  (Story) => (
    <div style={{ padding: '1rem', fontFamily: 'sans-serif' }}>
      <Story />
    </div>
  ),
];

Storybook Test Runner

// .storybook/test-runner.ts
// Custom test runner for a11y and interaction testing
// For Vite-based projects on Storybook 9+, prefer @storybook/addon-vitest, which runs a11y checks per story
import { getStoryContext, type TestRunnerConfig } from '@storybook/test-runner';
import { checkA11y, injectAxe } from 'axe-playwright';

const config: TestRunnerConfig = {
  async preVisit(page) {
    await injectAxe(page);
  },
  async postVisit(page, context) {
    const storyContext = await getStoryContext(page, context);
    
    // Skip a11y tests for stories that opt out
    if (storyContext.parameters?.a11y?.disable) return;

    // checkA11y throws (failing the test) when violations of these impacts are found
    await checkA11y(page, '#storybook-root', {
      detailedReport: true,
      includedImpacts: ['critical', 'serious'],
    });
  },
};

export default config;

Performance Considerations

Accessibility Considerations

// Accessibility-focused stories
export const A11yViolations: Story = {
  name: 'Accessibility Check',
  parameters: {
    a11y: {
      config: { rules: [{ id: 'color-contrast', enabled: true }] },
      element: '#storybook-root',
    },
  },
  play: async ({ canvasElement }) => {
    const results = await axe(canvasElement);
    expect(results).toHaveNoViolations();
  },
};

Storybook Anti-Patterns

| Anti-Pattern | Problem | Fix |

|---|---|---|

| No stories for empty/loading states | Missing test coverage for edge cases | Add stories for every component state |

| Stories that make real API calls | Flaky, slow, require network | Use MSW to mock all API calls |

| Using storiesOf API (CSF 2.x) | Deprecated, removed in SB 8 | Use CSF 3.x const meta = { ... } |

| Hardcoded viewports in stories | Inconsistent across components | Use parameters.viewport with named viewports |

| Skipping a11y addon | Accessibility issues caught late | Add @storybook/addon-a11y to every project |

| Too many stories per component | Maintenance burden | Cover: default, loading, error, edge cases. Not every prop combination |

| Missing autodocs tag | Docs tab not generated | Add tags: ['autodocs'] to meta |

Rules

References

Handoff

No artifact produced unless requested.

Next skill: frontend-pwa (if the component needs offline support or a service worker)

Carry forward: Component prop types, existing story examples, addon list from config

Architecture Decision Trees

Documentation Strategy Decision Tree

`

Who is the primary audience?

├── Developers → Component API docs, code snippets, prop tables

├── Designers → Design system preview, design token values, variants

└── PM/QA → Interaction tests, visual regression reports, state coverage

What level of documentation is needed?

├── Basic → Props table + default story

├── Standard → All states + accessibility report + code snippet

└── Comprehensive → Design guidelines + usage rules + migration guide

`

Testing Strategy Decision Tree

`

What type of validation is needed?

├── Visual → Chromatic/Percy for screenshot comparison per PR

├── Accessibility → axe-core on every story, fail CI on violations

└── Interaction → Playwright/Cypress component tests for user flows

How often do stories change?

├── Every PR → Automate visual + a11y tests in CI pipeline

└── Infrequent → Manual review + scheduled snapshot updates

`

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.