@cappa/plugin-storybook 0.8.0 → 0.8.1

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.
@@ -0,0 +1,321 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { getLogger } from "@cappa/logger";
3
+ //#region src/cappa/storybook-url.ts
4
+ function encodePairs(obj) {
5
+ if (!obj || !Object.keys(obj).length) return "";
6
+ return Object.entries(obj).filter(([, v]) => v !== void 0).map(([k, v]) => {
7
+ const val = typeof v === "string" ? encodeURIComponent(v) : typeof v === "number" || typeof v === "boolean" ? String(v) : encodeURIComponent(JSON.stringify(v));
8
+ return `${encodeURIComponent(k)}:${val}`;
9
+ }).join(";");
10
+ }
11
+ function buildStorybookIframeUrl({ baseUrl, storyId, viewMode = "story", args, globals, query, fullscreen = true, singleStory = true }) {
12
+ const u = new URL("/iframe.html", baseUrl);
13
+ u.searchParams.set("id", storyId);
14
+ u.searchParams.set("viewMode", viewMode);
15
+ const argPairs = encodePairs(args);
16
+ if (argPairs) u.searchParams.set("args", argPairs);
17
+ const globalPairs = encodePairs(globals);
18
+ if (globalPairs) u.searchParams.set("globals", globalPairs);
19
+ if (fullscreen) u.searchParams.set("full", "1");
20
+ if (singleStory) u.searchParams.set("singleStory", "true");
21
+ if (query) for (const [k, v] of Object.entries(query)) {
22
+ if (v === void 0) continue;
23
+ u.searchParams.set(k, String(v));
24
+ }
25
+ return u.toString();
26
+ }
27
+ //#endregion
28
+ //#region src/cappa/util.ts
29
+ /**
30
+ * Disable CSS transitions, animations, and scrollbars
31
+ * @param page - The page to disable CSS transitions, animations, and scrollbars
32
+ */
33
+ const freezeUI = async (page) => {
34
+ await page.addStyleTag({ content: `
35
+ *, *::before, *::after {
36
+ -moz-animation: none !important;
37
+ -moz-transition: none !important;
38
+ transition: none !important;
39
+ animation: none !important;
40
+ }
41
+ *, input, textarea { caret-color: transparent !important }
42
+ *:focus { outline: none !important }
43
+ *:focus-visible { outline: none !important }
44
+ *:focus-within { outline: none !important }
45
+ * { text-rendering: optimizeLegibility !important }
46
+ ::-webkit-scrollbar { display: none !important }
47
+ html { scroll-behavior: auto !important }
48
+ svg, svg * {
49
+ shape-rendering: crispEdges !important;
50
+ text-rendering: geometricPrecision !important;
51
+ vector-effect: non-scaling-stroke !important;
52
+ }
53
+ img { image-rendering: crisp-edges !important }
54
+ ` });
55
+ };
56
+ /**
57
+ * Wait for general visual stability on the page
58
+ * @param page - The page to wait for
59
+ */
60
+ const waitForVisualIdle = async (page) => {
61
+ await page.waitForLoadState("load");
62
+ await page.evaluate(async () => {
63
+ await document.fonts?.ready?.catch(() => {});
64
+ const imgs = Array.from(document.images).filter((i) => !i.complete);
65
+ await Promise.all(imgs.map((i) => new Promise((res) => {
66
+ i.onload = i.onerror = () => res(null);
67
+ })));
68
+ });
69
+ await page.evaluate(({ minIdleMs }) => new Promise((resolve) => {
70
+ let timer = null;
71
+ let last = performance.now();
72
+ const done = () => {
73
+ if (timer) cancelAnimationFrame(timer);
74
+ resolve();
75
+ };
76
+ const mo = new MutationObserver(() => {
77
+ last = performance.now();
78
+ });
79
+ mo.observe(document, {
80
+ attributes: true,
81
+ childList: true,
82
+ subtree: true,
83
+ characterData: true
84
+ });
85
+ const tick = () => {
86
+ if (performance.now() - last >= minIdleMs) {
87
+ mo.disconnect();
88
+ done();
89
+ } else timer = requestAnimationFrame(tick);
90
+ };
91
+ requestAnimationFrame(() => requestAnimationFrame(tick));
92
+ }), { minIdleMs: 100 });
93
+ };
94
+ /**
95
+ * Build a filename for a story.
96
+ * @param story - The story to build a filename for
97
+ * @returns The filename for the story. Slashes represent folders that should be handled by seperate file system calls.
98
+ */
99
+ const buildFilename = (story) => {
100
+ return `${story.title.replace(/[^a-zA-Z0-9/]/g, "")}/${story.name.replace(/[^a-zA-Z0-9]/g, "")}.png`;
101
+ };
102
+ //#endregion
103
+ //#region src/cappa/plugin.ts
104
+ /**
105
+ * Wait for the play function to complete by checking the playAfterEach flag
106
+ * Only waits if the story actually has a play function
107
+ */
108
+ async function waitForPlayFunctionCompletion(page, storyName) {
109
+ const logger = getLogger();
110
+ try {
111
+ if (!await page.evaluate(() => window.__cappa_has_play_function === true)) return;
112
+ logger.debug(`Waiting for play function to complete for story: ${storyName}`);
113
+ await page.waitForFunction(() => window.playAfterEach === true, { timeout: 1e4 });
114
+ logger.debug(`Play function completed for story: ${storyName}`);
115
+ await page.evaluate(() => {
116
+ window.playAfterEach = false;
117
+ window.__cappa_has_play_function = false;
118
+ });
119
+ } catch {
120
+ await page.evaluate(() => {
121
+ window.playAfterEach = false;
122
+ window.__cappa_has_play_function = false;
123
+ });
124
+ }
125
+ }
126
+ function toFilterContext(story) {
127
+ return {
128
+ id: story.id,
129
+ title: story.title,
130
+ name: story.name,
131
+ filePath: `${story.title}/${story.name}`
132
+ };
133
+ }
134
+ /**
135
+ * Create a latch for a Promise. A latch is a Promise that can be resolved from outside.
136
+ * @param T - The type of the Promise
137
+ * @returns A latch for a Promise
138
+ */
139
+ function createLatch() {
140
+ let resolve;
141
+ return {
142
+ p: new Promise((r) => {
143
+ resolve = r;
144
+ }),
145
+ resolve
146
+ };
147
+ }
148
+ /**
149
+ * Storybook Plugin for Cappa
150
+ * Fetches stories from a running Storybook server and takes screenshots of each story.
151
+ * Supports includeStories and excludeStories predicate functions for filtering.
152
+ */
153
+ const cappaPluginStorybook = (options) => {
154
+ return {
155
+ name: "StorybookPlugin",
156
+ description: "Takes screenshots of Storybook stories with configurable options",
157
+ discover: async (screenshotTool) => {
158
+ if (!options) throw new Error("Storybook plugin options are required");
159
+ if (!options.storybookUrl) throw new Error("storybookUrl is required");
160
+ const logger = getLogger();
161
+ const { storybookUrl, includeStories, excludeStories, storybook: defaultStorybookOptions } = options;
162
+ const storiesUrl = `${storybookUrl}/index.json`;
163
+ logger.debug(`Fetching stories from: ${storiesUrl}`);
164
+ const timeout = screenshotTool.connectionTimeout;
165
+ let response;
166
+ try {
167
+ response = await fetch(storiesUrl, { signal: AbortSignal.timeout(timeout) });
168
+ } catch (error) {
169
+ if (error instanceof DOMException && error.name === "TimeoutError") throw new Error(`Connection to Storybook at ${storybookUrl} timed out after ${timeout}ms. Make sure Storybook is running and accessible.`);
170
+ throw new Error(`Failed to connect to Storybook at ${storybookUrl}. Make sure Storybook is running and accessible. Error: ${error.message}`);
171
+ }
172
+ if (!response.ok) throw new Error(`Failed to fetch stories: ${response.status} ${response.statusText}`);
173
+ const data = await response.json();
174
+ let filteredStories = Object.values(data.entries);
175
+ if (includeStories) filteredStories = filteredStories.filter((story) => includeStories(toFilterContext(story)));
176
+ if (excludeStories) filteredStories = filteredStories.filter((story) => !excludeStories(toFilterContext(story)));
177
+ filteredStories = filteredStories.filter((story) => story.type === "story");
178
+ logger.start(`Found ${filteredStories.length} stories to screenshot...`);
179
+ return filteredStories.map((story) => ({
180
+ id: story.id,
181
+ url: buildStorybookIframeUrl({
182
+ baseUrl: storybookUrl,
183
+ storyId: story.id,
184
+ viewMode: defaultStorybookOptions?.viewMode,
185
+ args: defaultStorybookOptions?.args,
186
+ globals: defaultStorybookOptions?.globals,
187
+ query: defaultStorybookOptions?.query,
188
+ fullscreen: defaultStorybookOptions?.fullscreen,
189
+ singleStory: defaultStorybookOptions?.singleStory
190
+ }),
191
+ data: { story }
192
+ }));
193
+ },
194
+ initPage: async (page, screenshotTool) => {
195
+ const logger = getLogger();
196
+ const { logConsoleEvents = true } = screenshotTool;
197
+ const latchMap = /* @__PURE__ */ new Map();
198
+ await page.exposeFunction("__cappa_parameters", async (id, payload) => {
199
+ latchMap.get(id)?.resolve?.(payload);
200
+ });
201
+ if (logConsoleEvents) page.on("console", (message) => {
202
+ logger.debug("console", message.text());
203
+ });
204
+ page.on("pageerror", (error) => {
205
+ logger.debug("pageerror", error);
206
+ });
207
+ return { latchMap };
208
+ },
209
+ execute: async (task, page, screenshotTool, context) => {
210
+ const { url, data } = task;
211
+ const { story } = data;
212
+ const logger = getLogger();
213
+ const { storybook: defaultStorybookOptions } = options || {};
214
+ try {
215
+ const currentLatch = createLatch();
216
+ context.latchMap.set(story.id, currentLatch);
217
+ const captureStart = performance.now();
218
+ await page.goto(url, { timeout: screenshotTool.connectionTimeout });
219
+ const storyParameters = await context.latchMap.get(story.id)?.p;
220
+ context.latchMap.delete(story.id);
221
+ const variantParameters = storyParameters?.variants ?? [];
222
+ if (storyParameters?.skip) {
223
+ logger.warn(`Skipping story ${story.title} - ${story.name}`);
224
+ return {
225
+ storyId: story.id,
226
+ storyName: `${story.title} - ${story.name}`,
227
+ skipped: true
228
+ };
229
+ }
230
+ if (storyParameters && Object.keys(storyParameters).length > 0) logger.debug("Taking screenshot with options", storyParameters);
231
+ const resolvedViewport = storyParameters?.viewport ?? screenshotTool.viewport;
232
+ await page.setViewportSize(resolvedViewport);
233
+ await freezeUI(page);
234
+ await waitForVisualIdle(page);
235
+ await waitForPlayFunctionCompletion(page, `${story.title} - ${story.name}`);
236
+ const toLocatorMask = (mask) => mask?.map((selector) => page.locator(selector));
237
+ const filename = buildFilename(story);
238
+ const variantsWithUrls = [];
239
+ const variantExtrasEntries = [];
240
+ for (const variant of variantParameters) {
241
+ const variantFilename = variant.filename || screenshotTool.getVariantFilename(filename, {
242
+ id: variant.id,
243
+ label: variant.label,
244
+ filename: variant.filename
245
+ });
246
+ const mergedArgs = {
247
+ ...defaultStorybookOptions?.args,
248
+ ...variant.options?.args
249
+ };
250
+ variantsWithUrls.push({
251
+ id: variant.id,
252
+ label: variant.label,
253
+ filename: variantFilename,
254
+ url: buildStorybookIframeUrl({
255
+ baseUrl: options?.storybookUrl || "",
256
+ storyId: story.id,
257
+ viewMode: defaultStorybookOptions?.viewMode,
258
+ args: mergedArgs,
259
+ globals: defaultStorybookOptions?.globals,
260
+ query: defaultStorybookOptions?.query,
261
+ fullscreen: defaultStorybookOptions?.fullscreen,
262
+ singleStory: defaultStorybookOptions?.singleStory
263
+ }),
264
+ options: variant.options ? {
265
+ ...variant.options,
266
+ mask: toLocatorMask(variant.options.mask)
267
+ } : void 0
268
+ });
269
+ variantExtrasEntries.push([variant.id, {
270
+ saveDiffImage: true,
271
+ diffImageFilename: variantFilename,
272
+ diff: variant.options?.diff
273
+ }]);
274
+ }
275
+ const baseOptions = {
276
+ fullPage: storyParameters?.fullPage,
277
+ delay: storyParameters?.delay,
278
+ omitBackground: storyParameters?.omitBackground,
279
+ skip: storyParameters?.skip,
280
+ viewport: storyParameters?.viewport ?? screenshotTool.viewport,
281
+ mask: toLocatorMask(storyParameters?.mask)
282
+ };
283
+ const variantFilenameMap = /* @__PURE__ */ new Map();
284
+ for (const variant of variantsWithUrls) {
285
+ const variantFilename = variant.filename;
286
+ if (!variantFilename) continue;
287
+ variantFilenameMap.set(variant.id, variantFilename);
288
+ }
289
+ const captureExtras = {
290
+ saveDiffImage: true,
291
+ diffImageFilename: filename,
292
+ diff: storyParameters?.diff,
293
+ variants: variantExtrasEntries.length ? Object.fromEntries(variantExtrasEntries) : void 0,
294
+ skipBaseNavigation: true,
295
+ waitForStability: waitForVisualIdle,
296
+ captureStart
297
+ };
298
+ const captureResult = await screenshotTool.captureWithVariants(page, filename, url, baseOptions, variantsWithUrls, captureExtras);
299
+ return {
300
+ storyId: story.id,
301
+ storyName: `${story.title} - ${story.name}`,
302
+ filepath: captureResult.base.filepath,
303
+ success: captureResult.base.skipped ? void 0 : captureResult.base.comparisonResult ? captureResult.base.comparisonResult.passed : Boolean(captureResult.base.filepath),
304
+ skipped: captureResult.base.skipped
305
+ };
306
+ } catch (error) {
307
+ logger.error(`Error taking screenshot of story ${story.title} - ${story.name}:`, error.message);
308
+ return {
309
+ storyId: story.id,
310
+ storyName: `${story.title} - ${story.name}`,
311
+ error: error?.message ?? "Unknown error"
312
+ };
313
+ }
314
+ }
315
+ };
316
+ };
317
+ //#endregion
318
+ //#region src/index.esm.ts
319
+ const previewAnnotations = [fileURLToPath(new URL("./preview.js", import.meta.url))];
320
+ //#endregion
321
+ export { cappaPluginStorybook, previewAnnotations };
@@ -0,0 +1,6 @@
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 };
@@ -0,0 +1,58 @@
1
+ import { makeDecorator } from "storybook/preview-api";
2
+ //#region src/storybook/util.ts
3
+ /**
4
+ * Wait for a function to be exposed on the window object
5
+ * @param name - The name of the function to wait for
6
+ * @param timeoutMs - The timeout in milliseconds
7
+ * @returns The function or rejects if the function is not exposed within the timeout
8
+ */
9
+ const waitForExposed = (name, timeoutMs = 5e3) => {
10
+ return new Promise((resolve, reject) => {
11
+ const start = performance.now();
12
+ const t = setInterval(() => {
13
+ const fn = window[name];
14
+ if (typeof fn === "function") {
15
+ clearInterval(t);
16
+ resolve(fn);
17
+ } else if (performance.now() - start > timeoutMs) {
18
+ clearInterval(t);
19
+ reject(/* @__PURE__ */ new Error(`Timed out waiting for ${name}`));
20
+ }
21
+ }, 16);
22
+ });
23
+ };
24
+ //#endregion
25
+ //#region src/storybook/addon/browser.ts
26
+ /**
27
+ * Checks if the current window is a cappa window
28
+ */
29
+ const isCappa = () => {
30
+ return navigator.userAgent.includes("CappaStorybook");
31
+ };
32
+ //#endregion
33
+ //#region src/storybook/addon/preview.ts
34
+ const decorators = [makeDecorator({
35
+ name: "withCappa",
36
+ parameterName: "cappa",
37
+ skipIfNoParametersOrOptions: false,
38
+ wrapper: (getStory, context, { parameters }) => {
39
+ if (isCappa()) {
40
+ window.__cappa_screenshot = true;
41
+ if (context.playFunction != null) window.__cappa_has_play_function = true;
42
+ queueMicrotask(async () => {
43
+ try {
44
+ (await waitForExposed("__cappa_parameters"))(context.id, parameters ?? {});
45
+ } catch (error) {
46
+ console.error("Cappa decorator error:", error);
47
+ }
48
+ });
49
+ }
50
+ return getStory(context);
51
+ }
52
+ })];
53
+ const parameters = {};
54
+ const afterEach = () => {
55
+ window.playAfterEach = true;
56
+ };
57
+ //#endregion
58
+ export { afterEach, decorators, parameters };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cappa/plugin-storybook",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "Storybook plugin for Cappa - takes screenshots of Storybook stories",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -15,24 +15,24 @@
15
15
  "license": "MIT",
16
16
  "author": "Tim Richter",
17
17
  "type": "module",
18
- "main": "./dist/index.cjs",
19
- "module": "./dist/index.js",
20
- "types": "./dist/index.esm.d.ts",
18
+ "main": "./dist/index.cjs.cjs",
19
+ "module": "./dist/index.esm.mjs",
20
+ "types": "./dist/index.esm.d.mts",
21
21
  "exports": {
22
22
  ".": {
23
23
  "import": {
24
- "types": "./dist/index.esm.d.ts",
25
- "default": "./dist/index.js"
24
+ "types": "./dist/index.esm.d.mts",
25
+ "default": "./dist/index.esm.mjs"
26
26
  },
27
27
  "require": {
28
28
  "types": "./dist/index.cjs.d.cts",
29
- "default": "./dist/index.cjs"
29
+ "default": "./dist/index.cjs.cjs"
30
30
  }
31
31
  },
32
32
  "./browser": {
33
33
  "import": {
34
- "types": "./dist/browser.d.ts",
35
- "default": "./dist/browser.js"
34
+ "types": "./dist/browser.d.mts",
35
+ "default": "./dist/browser.mjs"
36
36
  },
37
37
  "require": {
38
38
  "types": "./dist/browser.d.cts",
@@ -63,23 +63,23 @@
63
63
  "dependencies": {
64
64
  "@swc/core": "^1.15.18",
65
65
  "chalk": "^5.6.2",
66
- "@cappa/core": "0.8.0",
67
- "@cappa/logger": "0.0.10"
66
+ "@cappa/logger": "0.0.11",
67
+ "@cappa/core": "0.8.1"
68
68
  },
69
69
  "devDependencies": {
70
70
  "@arethetypeswrong/cli": "0.18.2",
71
- "@types/node": "25.5.0",
72
- "@vitest/coverage-v8": "4.1.2",
73
- "@vitest/ui": "4.1.2",
71
+ "@types/node": "25.5.2",
72
+ "@vitest/coverage-v8": "4.1.3",
73
+ "@vitest/ui": "4.1.3",
74
74
  "playwright-core": "^1.58.2",
75
75
  "storybook": "^10.3.1",
76
- "tsup": "8.5.1",
77
- "typescript": "5.9.3",
78
- "vitest": "4.1.2"
76
+ "tsdown": "0.21.7",
77
+ "typescript": "6.0.2",
78
+ "vitest": "4.1.3"
79
79
  },
80
80
  "scripts": {
81
81
  "test": "vitest",
82
- "build": "tsup",
82
+ "build": "tsdown",
83
83
  "tsc": "tsc",
84
84
  "attw": "attw --pack --profile node16 ."
85
85
  }
package/dist/browser.js DELETED
@@ -1,7 +0,0 @@
1
- // src/storybook/addon/browser.ts
2
- var isCappa = () => {
3
- return navigator.userAgent.includes("CappaStorybook");
4
- };
5
- export {
6
- isCappa
7
- };