Swatchbook

Storybook addon for DTCG design tokens — toolbar, panel, and useToken hook.

View on GithubNew to Storybook?Get started

swatchbook-addon

Storybook 10 addon for documenting DTCG design tokens.

Loads your token files, resolves the alias graph, and adds a toolbar that flips the active theme tuple (e.g. mode × brand × contrast, or whatever axes your resolver declares). Every story and MDX doc block re-renders against the new tuple without per-story wiring, so component stories and the token reference share one source of truth.

Bundles MDX doc blocks (<TokenTable />, <ColorPalette />, <TokenDetail />, …), a standalone <ThemeSwitcher> for non-Storybook surfaces, and a typed useToken() hook for stories that need a resolved value at runtime. Re-exports @unpunnyfuns/swatchbook-blocks and @unpunnyfuns/swatchbook-switcher, so a single install covers the whole React surface.

Install

npm install -D @unpunnyfuns/swatchbook-addon

Peer requirements: storybook@^10.1, @storybook/react-vite@^10.1, react / react-dom 18+, vite@>=5.

Usage

The Quickstart walks through .storybook/main.ts + .storybook/preview.ts setup end to end. The short version:

addons: [
  {
    name: '@unpunnyfuns/swatchbook-addon',
    options: {
      config: {
        resolver: 'tokens/resolver.json',
        cssVarPrefix: 'sb',
      },
    },
  },
],
import { definePreview } from '@storybook/react-vite';
import swatchbookAddon from '@unpunnyfuns/swatchbook-addon';
export default definePreview({ addons: [swatchbookAddon()] });

useToken

import { useToken } from '@unpunnyfuns/swatchbook-addon';

function Card() {
  const bg = useToken('color.surface.default');
  return <div style={{ background: bg.cssVar }}>{bg.description}</div>;
}

Returns { value, cssVar, type?, description? }. cssVar is stable across themes; value flips with the active tuple. Paths autocomplete from the generated .swatchbook/tokens.d.ts.

Testing

Author axis coverage for tests with withAxes from the testing subpath.

Credits

Token parsing and resolver evaluation come from Terrazzo by the Terrazzo team via @unpunnyfuns/swatchbook-core.

Documentation

unpunnyfuns.github.io/swatchbook: concepts, guides, and full API reference.