@cappa/plugin-storybook 0.8.11 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,131 @@
1
- # Storybook Plugin for Cappa
1
+ # Cappa — Storybook plugin
2
2
 
3
- This plugin allows to take screenshots of Storybook stories with Cappa.
3
+ Visual regression testing for Storybook, powered by [Cappa](https://github.com/tim-richter/cappa)
4
+ and Playwright.
4
5
 
5
- For documentation, see the [Storybook Plugin documentation](https://tim-richter.github.io/cappa/storybook).
6
+ The plugin fetches every story from a running Storybook, opens it in Playwright, and captures a
7
+ screenshot. Cappa then diffs each capture against an approved baseline and gives you a local review
8
+ UI to approve or reject the changes. No SaaS account, no upload — everything stays on your machine
9
+ and in your repo.
10
+
11
+ - **Story-aware** — reads the Storybook index, so new stories are picked up automatically
12
+ - **Per-story configuration** via `parameters.cappa` (delay, masks, viewport, full page, diff
13
+ thresholds)
14
+ - **Variants** — capture the same story multiple times with different viewports or args
15
+ - **Play functions** — waits for `play` to finish before capturing, so you can screenshot
16
+ interactive states
17
+ - **Pixel and perceptual (GMSD) diffing**, configurable globally or per story
18
+ - **Local review UI** — `cappa review` to inspect diffs, `cappa approve` to update baselines
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install -D @cappa/cli @cappa/plugin-storybook
24
+ ```
25
+
26
+ ## Setup
27
+
28
+ ### 1. Register the plugin in `cappa.config.ts`
29
+
30
+ ```ts
31
+ import { defineConfig } from '@cappa/core';
32
+ import { cappaPluginStorybook } from '@cappa/plugin-storybook';
33
+
34
+ export default defineConfig({
35
+ outputDir: 'screenshots',
36
+ plugins: [
37
+ cappaPluginStorybook({
38
+ storybookUrl: 'http://localhost:6006',
39
+ }),
40
+ ],
41
+ });
42
+ ```
43
+
44
+ ### 2. Register the addon in `.storybook/main.ts`
45
+
46
+ The addon exposes each story's `parameters.cappa` to the capture pipeline.
47
+
48
+ ```ts
49
+ import type { StorybookConfig } from '@storybook/react-vite';
50
+
51
+ const config: StorybookConfig = {
52
+ addons: ['@cappa/plugin-storybook'],
53
+ };
54
+
55
+ export default config;
56
+ ```
57
+
58
+ ### 3. Capture
59
+
60
+ Start Storybook, then run the capture in a second terminal:
61
+
62
+ ```bash
63
+ # Terminal 1
64
+ npm run storybook
65
+
66
+ # Terminal 2
67
+ npx cappa capture
68
+ ```
69
+
70
+ Then `npx cappa review` to inspect the diffs and `npx cappa approve` to promote the new screenshots
71
+ to baselines.
72
+
73
+ > For faster and more stable runs, build Storybook first and serve the static output instead of using
74
+ > the dev server.
75
+
76
+ ## Plugin options
77
+
78
+ | Option | Description |
79
+ | --- | --- |
80
+ | `storybookUrl` | URL of the running Storybook instance (required) |
81
+ | `includeStories` | Predicate `(story) => boolean`; only matching stories are captured |
82
+ | `excludeStories` | Predicate `(story) => boolean`; applied after `includeStories` |
83
+ | `defaultViewport` | Fallback viewport when a story does not define its own |
84
+ | `waitForSelector` | Wait for a selector to appear before capturing |
85
+ | `waitForTimeout` | Extra wait (ms) before capturing |
86
+
87
+ ## Per-story options
88
+
89
+ ```ts
90
+ export const Primary = {
91
+ parameters: {
92
+ cappa: {
93
+ delay: 250,
94
+ mask: ['.tooltip'],
95
+ variants: [
96
+ {
97
+ id: 'mobile',
98
+ label: 'Mobile',
99
+ options: { viewport: { width: 375, height: 812 } },
100
+ },
101
+ ],
102
+ },
103
+ },
104
+ };
105
+ ```
106
+
107
+ Supported keys: `skip`, `delay`, `fullPage`, `mask`, `omitBackground`, `viewport`, `variants` and
108
+ `diff`.
109
+
110
+ To detect a Cappa run from inside the browser (to disable animations, seed mock data, …):
111
+
112
+ ```ts
113
+ import { isCappa } from '@cappa/plugin-storybook/browser';
114
+
115
+ if (isCappa()) {
116
+ // ...
117
+ }
118
+ ```
119
+
120
+ ## Compatibility
121
+
122
+ Storybook `^9 || ^10`, any renderer that runs in a browser (React, Vue, Angular, Svelte, Preact,
123
+ Web Components, Ember, HTML). React Native is not supported.
124
+
125
+ ## Documentation
126
+
127
+ Full documentation: <https://tim-richter.github.io/cappa/storybook>
128
+
129
+ ## License
130
+
131
+ MIT © Tim Richter
@@ -2,6 +2,5 @@
2
2
  /**
3
3
  * Checks if the current window is a cappa window
4
4
  */
5
- declare const isCappa: () => boolean;
6
- //#endregion
7
- export { isCappa };
5
+ export declare const isCappa: () => boolean;
6
+ //#endregion
@@ -2,6 +2,5 @@
2
2
  /**
3
3
  * Checks if the current window is a cappa window
4
4
  */
5
- declare const isCappa: () => boolean;
6
- //#endregion
7
- export { isCappa };
5
+ export declare const isCappa: () => boolean;
6
+ //#endregion
@@ -100,6 +100,51 @@ const buildFilename = (story) => {
100
100
  return `${story.title.replace(/[^a-zA-Z0-9/]/g, "").toLowerCase()}/${story.name.replace(/[^a-zA-Z0-9]/g, "").toLowerCase()}.png`;
101
101
  };
102
102
  //#endregion
103
+ //#region src/cappa/watch.ts
104
+ /**
105
+ * Globs whose changes this plugin can map precisely.
106
+ *
107
+ * These mirror Storybook's own default `stories` patterns rather than being
108
+ * read from the project's config: the plugin talks to a *running* Storybook
109
+ * over HTTP and never sees its config file. They only widen what a watch
110
+ * session watches — resolution itself is driven by the story index, which is
111
+ * the authority on which files produce which stories.
112
+ */
113
+ const DEFAULT_STORY_WATCH_PATHS = ["**/*.stories.@(js|jsx|mjs|cjs|ts|tsx|mts|cts)", "**/*.story.@(js|jsx|mjs|cjs|ts|tsx|mts|cts)"];
114
+ /** Compare paths written by different tools: `./src/a.tsx`, `src\\a.tsx`, `/abs/src/a.tsx`. */
115
+ const normalizeWatchPath = (file) => file.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
116
+ /**
117
+ * Whether a changed file and a story index `importPath` name the same file.
118
+ *
119
+ * Suffix matching in both directions, because the two are relative to roots
120
+ * nobody here knows: `importPath` is relative to the Storybook project, and the
121
+ * changed file is relative to wherever `cappa` was started — which in a
122
+ * monorepo is routinely a directory above it. Over-matching costs a few extra
123
+ * screenshots; under-matching silently misses the regression being hunted.
124
+ */
125
+ const isSameFile = (file, importPath) => {
126
+ const changed = normalizeWatchPath(file);
127
+ const imported = normalizeWatchPath(importPath);
128
+ return changed === imported || changed.endsWith(`/${imported}`) || imported.endsWith(`/${changed}`);
129
+ };
130
+ /**
131
+ * Map a changed file onto the story ids it produces.
132
+ *
133
+ * `null` — "cannot tell, re-run everything" — for any file the index does not
134
+ * attribute a story to. That covers the component a story renders, which is the
135
+ * common case and genuinely unmappable from the index; it also covers a story
136
+ * file the index has never seen, which is what a freshly created story looks
137
+ * like until discovery runs again. Returning "nothing to do" for that second
138
+ * case would mean saving a new story and watching nothing happen.
139
+ */
140
+ const resolveStoryTasks = (file, tasks) => {
141
+ const affected = tasks.filter((task) => {
142
+ const importPath = task.data?.story?.importPath;
143
+ return typeof importPath === "string" && isSameFile(file, importPath);
144
+ }).map((task) => task.id);
145
+ return affected.length > 0 ? affected : null;
146
+ };
147
+ //#endregion
103
148
  //#region src/cappa/plugin.ts
104
149
  /**
105
150
  * Wait for the play function to complete by checking the playAfterEach flag
@@ -191,6 +236,17 @@ const cappaPluginStorybook = (options) => {
191
236
  data: { story }
192
237
  }));
193
238
  },
239
+ /**
240
+ * Precise watch resolution, which is what makes watch mode worth running:
241
+ * the story index already knows which file produced which story, so a saved
242
+ * story file re-captures only its own stories. Everything else — the
243
+ * components those stories render — resolves to `null` and re-runs the
244
+ * plugin, because the index cannot say more than that.
245
+ */
246
+ watch: {
247
+ paths: options?.watchPaths ?? DEFAULT_STORY_WATCH_PATHS,
248
+ resolve: resolveStoryTasks
249
+ },
194
250
  initPage: async (page, screenshotTool) => {
195
251
  const logger = (0, _cappa_logger.getLogger)();
196
252
  const { logConsoleEvents = true } = screenshotTool;
@@ -69,15 +69,23 @@ interface StorybookPluginOptions {
69
69
  waitForSelector?: string;
70
70
  waitForTimeout?: number;
71
71
  storybook?: StorybookRenderOptions;
72
+ /**
73
+ * Globs, relative to the working directory, that watch mode should watch on
74
+ * top of the project sources it watches anyway.
75
+ *
76
+ * Defaults to Storybook's own default story patterns. Set this when the
77
+ * project's `stories` globs point somewhere those do not reach.
78
+ */
79
+ watchPaths?: string[];
72
80
  }
73
81
  /**
74
82
  * Storybook Plugin for Cappa
75
83
  * Fetches stories from a running Storybook server and takes screenshots of each story.
76
84
  * Supports includeStories and excludeStories predicate functions for filtering.
77
85
  */
78
- declare const cappaPluginStorybook: Plugin<StorybookPluginOptions>;
86
+ export declare const cappaPluginStorybook: Plugin<StorybookPluginOptions>;
79
87
  //#endregion
80
88
  //#region src/index.cjs.d.ts
81
- declare const previewAnnotations: string[];
89
+ export declare const previewAnnotations: string[];
82
90
  //#endregion
83
- export { type ScreenshotOptionsStorybook as CappaStorybookOptions, type StoryFilterContext, type StorybookPluginOptions, cappaPluginStorybook, previewAnnotations };
91
+ export type { ScreenshotOptionsStorybook as CappaStorybookOptions, StoryFilterContext, StorybookPluginOptions };
@@ -69,15 +69,23 @@ interface StorybookPluginOptions {
69
69
  waitForSelector?: string;
70
70
  waitForTimeout?: number;
71
71
  storybook?: StorybookRenderOptions;
72
+ /**
73
+ * Globs, relative to the working directory, that watch mode should watch on
74
+ * top of the project sources it watches anyway.
75
+ *
76
+ * Defaults to Storybook's own default story patterns. Set this when the
77
+ * project's `stories` globs point somewhere those do not reach.
78
+ */
79
+ watchPaths?: string[];
72
80
  }
73
81
  /**
74
82
  * Storybook Plugin for Cappa
75
83
  * Fetches stories from a running Storybook server and takes screenshots of each story.
76
84
  * Supports includeStories and excludeStories predicate functions for filtering.
77
85
  */
78
- declare const cappaPluginStorybook: Plugin<StorybookPluginOptions>;
86
+ export declare const cappaPluginStorybook: Plugin<StorybookPluginOptions>;
79
87
  //#endregion
80
88
  //#region src/index.esm.d.ts
81
- declare const previewAnnotations: string[];
89
+ export declare const previewAnnotations: string[];
82
90
  //#endregion
83
- export { type ScreenshotOptionsStorybook as CappaStorybookOptions, type StoryFilterContext, type StorybookPluginOptions, cappaPluginStorybook, previewAnnotations };
91
+ export type { ScreenshotOptionsStorybook as CappaStorybookOptions, StoryFilterContext, StorybookPluginOptions };
@@ -100,6 +100,51 @@ const buildFilename = (story) => {
100
100
  return `${story.title.replace(/[^a-zA-Z0-9/]/g, "").toLowerCase()}/${story.name.replace(/[^a-zA-Z0-9]/g, "").toLowerCase()}.png`;
101
101
  };
102
102
  //#endregion
103
+ //#region src/cappa/watch.ts
104
+ /**
105
+ * Globs whose changes this plugin can map precisely.
106
+ *
107
+ * These mirror Storybook's own default `stories` patterns rather than being
108
+ * read from the project's config: the plugin talks to a *running* Storybook
109
+ * over HTTP and never sees its config file. They only widen what a watch
110
+ * session watches — resolution itself is driven by the story index, which is
111
+ * the authority on which files produce which stories.
112
+ */
113
+ const DEFAULT_STORY_WATCH_PATHS = ["**/*.stories.@(js|jsx|mjs|cjs|ts|tsx|mts|cts)", "**/*.story.@(js|jsx|mjs|cjs|ts|tsx|mts|cts)"];
114
+ /** Compare paths written by different tools: `./src/a.tsx`, `src\\a.tsx`, `/abs/src/a.tsx`. */
115
+ const normalizeWatchPath = (file) => file.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "");
116
+ /**
117
+ * Whether a changed file and a story index `importPath` name the same file.
118
+ *
119
+ * Suffix matching in both directions, because the two are relative to roots
120
+ * nobody here knows: `importPath` is relative to the Storybook project, and the
121
+ * changed file is relative to wherever `cappa` was started — which in a
122
+ * monorepo is routinely a directory above it. Over-matching costs a few extra
123
+ * screenshots; under-matching silently misses the regression being hunted.
124
+ */
125
+ const isSameFile = (file, importPath) => {
126
+ const changed = normalizeWatchPath(file);
127
+ const imported = normalizeWatchPath(importPath);
128
+ return changed === imported || changed.endsWith(`/${imported}`) || imported.endsWith(`/${changed}`);
129
+ };
130
+ /**
131
+ * Map a changed file onto the story ids it produces.
132
+ *
133
+ * `null` — "cannot tell, re-run everything" — for any file the index does not
134
+ * attribute a story to. That covers the component a story renders, which is the
135
+ * common case and genuinely unmappable from the index; it also covers a story
136
+ * file the index has never seen, which is what a freshly created story looks
137
+ * like until discovery runs again. Returning "nothing to do" for that second
138
+ * case would mean saving a new story and watching nothing happen.
139
+ */
140
+ const resolveStoryTasks = (file, tasks) => {
141
+ const affected = tasks.filter((task) => {
142
+ const importPath = task.data?.story?.importPath;
143
+ return typeof importPath === "string" && isSameFile(file, importPath);
144
+ }).map((task) => task.id);
145
+ return affected.length > 0 ? affected : null;
146
+ };
147
+ //#endregion
103
148
  //#region src/cappa/plugin.ts
104
149
  /**
105
150
  * Wait for the play function to complete by checking the playAfterEach flag
@@ -191,6 +236,17 @@ const cappaPluginStorybook = (options) => {
191
236
  data: { story }
192
237
  }));
193
238
  },
239
+ /**
240
+ * Precise watch resolution, which is what makes watch mode worth running:
241
+ * the story index already knows which file produced which story, so a saved
242
+ * story file re-captures only its own stories. Everything else — the
243
+ * components those stories render — resolves to `null` and re-runs the
244
+ * plugin, because the index cannot say more than that.
245
+ */
246
+ watch: {
247
+ paths: options?.watchPaths ?? DEFAULT_STORY_WATCH_PATHS,
248
+ resolve: resolveStoryTasks
249
+ },
194
250
  initPage: async (page, screenshotTool) => {
195
251
  const logger = getLogger();
196
252
  const { logConsoleEvents = true } = screenshotTool;
@@ -1,6 +1,5 @@
1
1
  //#region src/storybook/addon/preview.d.ts
2
- declare const decorators: ((...args: any) => any)[];
3
- declare const parameters: {};
4
- declare const afterEach: () => void;
5
- //#endregion
6
- export { afterEach, decorators, parameters };
2
+ export declare const decorators: ((...args: any) => any)[];
3
+ export declare const parameters: {};
4
+ export declare const afterEach: () => void;
5
+ //#endregion
@@ -1,6 +1,5 @@
1
1
  //#region src/storybook/addon/preview.d.ts
2
- declare const decorators: ((...args: any) => any)[];
3
- declare const parameters: {};
4
- declare const afterEach: () => void;
5
- //#endregion
6
- export { afterEach, decorators, parameters };
2
+ export declare const decorators: ((...args: any) => any)[];
3
+ export declare const parameters: {};
4
+ export declare const afterEach: () => void;
5
+ //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cappa/plugin-storybook",
3
- "version": "0.8.11",
3
+ "version": "0.9.0",
4
4
  "description": "Storybook plugin for Cappa - takes screenshots of Storybook stories",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -43,14 +43,29 @@
43
43
  },
44
44
  "keywords": [
45
45
  "storybook-addon",
46
+ "test",
46
47
  "screenshot",
47
48
  "plugin",
48
49
  "storybook",
49
- "visual-testing"
50
+ "visual-testing",
51
+ "visual regression",
52
+ "vrt",
53
+ "playwright",
54
+ "cappa"
50
55
  ],
51
56
  "storybook": {
52
57
  "displayName": "Cappa",
53
- "unsupportedFrameworks": []
58
+ "icon": "https://raw.githubusercontent.com/tim-richter/cappa/main/packages/plugins/plugin-storybook/assets/cappa-icon.png",
59
+ "supportedFrameworks": [
60
+ "react",
61
+ "vue",
62
+ "angular",
63
+ "web-components",
64
+ "ember",
65
+ "html",
66
+ "svelte",
67
+ "preact"
68
+ ]
54
69
  },
55
70
  "peerDependencies": {
56
71
  "storybook": "^9 || ^10"
@@ -61,24 +76,25 @@
61
76
  }
62
77
  },
63
78
  "dependencies": {
64
- "@swc/core": "^1.15.43",
65
- "chalk": "^5.6.2",
66
- "@cappa/core": "0.12.3",
67
- "@cappa/logger": "0.0.11"
79
+ "@cappa/core": "0.13.0",
80
+ "@cappa/logger": "0.0.12",
81
+ "@swc/core": "^1.16.2",
82
+ "chalk": "^6.0.0"
68
83
  },
69
84
  "devDependencies": {
70
85
  "@arethetypeswrong/cli": "0.18.5",
71
86
  "@types/node": "25.9.3",
72
- "@vitest/coverage-v8": "4.1.10",
73
- "@vitest/ui": "4.1.10",
74
- "playwright-core": "^1.61.1",
75
- "storybook": "^10.5.0",
76
- "tsdown": "0.22.8",
77
- "typescript": "6.0.3",
78
- "vitest": "4.1.10"
87
+ "@vitest/coverage-v8": "5.0.0",
88
+ "@vitest/ui": "5.0.0",
89
+ "playwright-core": "^1.63.0",
90
+ "storybook": "^10.6.0",
91
+ "tsdown": "0.23.0",
92
+ "typescript": "7.0.2",
93
+ "vitest": "5.0.0"
79
94
  },
80
95
  "scripts": {
81
96
  "test": "vitest",
97
+ "test:run": "vitest --run",
82
98
  "build": "tsdown",
83
99
  "tsc": "tsc",
84
100
  "attw": "attw --pack --profile node16 ."