> [Agent navigation index](/llms.txt)

# Author and test Storybook stories

Initialize managed Preact Storybook, author colocated stories and interactions, and enforce accessible, translated, themed previews.

> Managed Brix Storybook is Preact-only. Managed React applications and separately integrated external React hosts use their own React testing and catalog tooling.

First choose the owner in [catalog ownership](/docs/storybook-catalogs.md). By the end of this guide,
`brix storybook dev` should render one stable state and `brix storybook test` should execute one
interaction with the generated accessibility policy.

## Initialize a catalog

Preview, then initialize from the catalog owner:

```sh
brix storybook init --dry-run
brix storybook init
brix storybook dev

```

Initialization accepts a Brix application, library, or workspace root. It refuses to overwrite existing Storybook files, installs exact compatible packages, records `brix.integrations.storybook`, adds the `storybook`, `build:storybook`, and `test:storybook` scripts and the `.storybook` TypeScript include, ignores `storybook-static/`, and writes:

- `.storybook/main.ts`
- `.storybook/catalog.ts`
- `.storybook/vite.config.ts`
- `.storybook/preview.ts`
- `.storybook/vitest.config.ts`
- `.storybook/env.d.ts`

In a library that still has the `brix create ui-library` starter `src/Button.tsx` and no
`src/Button.stories.tsx`, it also writes that starter story.

Storybook itself uses React internally, so those exact React, ReactDOM, and type packages are development-only tooling dependencies. Your Brix application and stories continue to use Preact. Running `init` again on an integrated project only reports that Storybook is already integrated. Run `brix doctor` when configuration, dependencies, or scripts drift.

## Write a colocated story

Place stories beside components as `src/**/*.stories.tsx`. Import supported story types, spies, interactions, assertions, and queries through `brix/storybook/test`:

```tsx
import { expect, fn, type Meta, type StoryObj, userEvent, within } from "brix/storybook/test";
import { Button } from "./Button.tsx";

const meta: Meta<typeof Button> = {
  title: "Checkout/Button",
  component: Button,
  args: { label: "Continue", onClick: fn() },
};

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

export const Default: Story = {};

export const Clicked: Story = {
  play: async ({ canvasElement, args }) => {
    const canvas = within(canvasElement);
    await userEvent.click(canvas.getByRole("button", { name: "Continue" }));
    await expect(args.onClick).toHaveBeenCalledOnce();
  },
};

```

In Preact applications and libraries, `brix doctor` and `brix check` reject direct or namespace imports of the APIs this entry point re-exports (`expect`, `fn`, `userEvent`, and `within` from `storybook/test`; `Meta`, `Preview`, and `StoryObj` from `@storybook/preact-vite`) in `src/` files. Import other Storybook APIs, such as `waitFor` or `Decorator`, by name from the installed Storybook packages. React applications are not checked because they keep their own Storybook tooling.

Use ordinary stories for stable visual states and `play` for user flows. Prefer role and accessible-name queries over CSS selectors. `brix create ui-library` supplies a component and library test that check without Storybook installed; running `brix storybook init` in that library adds the colocated starter story with an interaction.

## Test a built package in a consumer

The generated library story imports `./Button.tsx` for authoring. To test what an application
consumes, add a separate story to that application's `src/`, importing the built public package.
The example assumes `foundation` exports the generated UI-library `Button` and declares its
`brand` token. Link/build the library first and initialize Storybook in the consuming application.
Keep its catalog at `projects: []` so it does not also select the library's authoring stories.

Configure the consumer's root Panda config without scanning producer source:

`panda.config.ts`

```ts
import { definePandaConfig } from "brix/panda";

export default definePandaConfig({
  designSystem: "foundation",
  include: ["src/**/*.{js,jsx,ts,tsx}"],
  theme: { extend: { tokens: { colors: { brand: { value: "#8d2386" } } } } },
});

```

`src/components/Button.stories.tsx`

```tsx
import { expect, fn, type Meta, type StoryObj, userEvent, within } from "brix/storybook/test";
import { Button } from "foundation";

const meta: Meta<typeof Button> = {
  title: "Consumption/Button",
  component: Button,
  args: { label: "Continue", onClick: fn() },
};
export default meta;
type Story = StoryObj<typeof meta>;

export const Branded: Story = {
  play: async ({ canvasElement, args }) => {
    const button = within(canvasElement).getByRole("button", { name: "Continue" });
    await expect(getComputedStyle(button).backgroundColor).toBe("rgb(141, 35, 134)");
    await userEvent.click(button);
    await expect(args.onClick).toHaveBeenCalledOnce();
  },
};

```

Run `brix storybook test` and `brix storybook build` from the consumer, then inspect the built story.
Add assertions for the library's supported variants and responsive states. A local package import
tests built output; repeat with only publishable files installed in a disposable consumer to verify
the publication allowlist too. Do not replace this import with a source alias or add producer source
to Panda `include`: that tests recompilation under the consumer theme, not packaged rendering.
See [catalog ownership](/docs/storybook-catalogs.md#separate-authoring-from-package-consumption).

## Enforce accessibility

The generated preview treats accessibility violations as test errors. This means `brix storybook test` checks the rendered story after its interaction alongside its assertions.

Keep the strict global policy. If a known component state requires an exception, make it explicit and reviewed at story level rather than downgrading all stories. An exception documents debt; it is not a replacement for semantic elements, labels, keyboard interaction, focus behavior, or contrast.

`brix doctor`, `brix check`, and `brix verify` reject a statically resolved literal global
`parameters.a11y.test` other than `"error"` in `.storybook/preview.ts`, including `"off"` and
`"todo"`. This check inspects the exported inline preview object (directly exported or a `const`
immediately before its default export); it does not evaluate arbitrary TypeScript, imported values,
or spreads that could override the policy. An unresolved policy is not proof of strict accessibility:
keep the explicit `test: "error"` setting and review composed configuration yourself. Per-story
exceptions are unaffected. Storybook `dev`, `test`, and `build` do not themselves run doctor;
include `brix check` or `brix verify` in your gate.

## Preview translations

Compose static dictionaries into `.storybook/preview.ts`:

```ts
import "virtual:brix/storybook-styles";
import { createBrixTranslationPreview, type Preview } from "brix/storybook/test";
import { dictionaries } from "../src/translations.storybook.ts";

const preview = {
  ...createBrixTranslationPreview({
    locales: ["sv", "en-GB"] as const,
    defaultLocale: "sv",
    dictionaries,
  }),
  parameters: { a11y: { test: "error" } },
} satisfies Preview;

export default preview;

```

Every listed locale needs a dictionary. The locale toolbar uses the same Preact provider semantics as islands, but Storybook does not run a server loader or require CMS credentials. Generate CMS snapshots in a separate explicit workflow and check in or supply stable preview data.

Keep the generated stylesheet import when replacing the preview object; otherwise the stories may
render without Panda styles. Preserve any existing decorators and parameters as well—spreading the
translation preview does not automatically merge a second `parameters` object or decorator array.

## Exercise Contentful loading states

For loader-backed Contentful adapters, wrap a story in `ContentfulRenderingProvider` with an
explicit `clientLoading` resource from `createContentfulLoadingResource`. Give it a story-local
scope, a `contentfulEntryKey(entry)` to fixture-token mapping, and a `transport` returning
`{ loaded: { status: "ok", data: wireFixture }, permissions: {} }` or a typed error envelope.
A deferred transport exercises `loaded.status === "pending"` in the adapter's single `component`.
Keep hooks unconditional and shared controls mounted across pending/success/error branches.
Reset or recreate the resource
between stories so success/error state does not leak. Never omit the transport in these stories:
the default transport calls the real endpoint. Keep production credentials out of the catalog;
`preview.data` remains deterministic fixture data, not a pending/error fallback.

Storybook renders without a server hydration payload, so each fixture provider is independent and
its explicit `loadedData` is used as supplied. When a story also passes `clientLoading`, that
resource owns its seed and reset data: `loadedData` applies only until the resource loads or resets
and is never a fallback for stale state. Use the explicit resource for isolated loading-state
stories rather than mixing competing fixture sources. The server-rendering error
`Conflicting Contentful hydration results` (two uses of one entry producing different results)
does not arise in Storybook.

## Apply the application theme

The generated integration discovers the application's Panda sources and includes managed styles. Author theme tokens and recipes through Brix and import generated utilities through `#brix/panda/*`; do not add a second Panda or PostCSS setup.

Keep global Storybook decorators and parameters in `.storybook/preview.ts`. Preserve the generated `virtual:brix/storybook-styles` import and the `a11y` parameter (plus the translation decorator, when used) while adding deliberate backgrounds, layout, or theme controls. Keep `withBrixStorybook` in `.storybook/main.ts`. See the [styling guide](/docs/styling.md).

Continue with [own and operate storybook catalogs](/docs/storybook-catalogs.md).
