@cappa/plugin-storybook 0.4.2 → 0.4.3

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.
@@ -1,438 +0,0 @@
1
- import type {
2
- Plugin,
3
- ScreenshotCaptureExtras,
4
- ScreenshotVariantWithUrl,
5
- } from "@cappa/core";
6
- import { getLogger } from "@cappa/logger";
7
- import { minimatch } from "minimatch";
8
- import type { Page } from "playwright-core";
9
- import type {
10
- ScreenshotOptionsStorybook,
11
- ScreenshotVariantOptionsStorybook,
12
- StorybookRenderOptions,
13
- } from "../types";
14
- import { buildStorybookIframeUrl } from "./storybook-url";
15
- import { buildFilename, freezeUI, waitForVisualIdle } from "./util";
16
-
17
- /**
18
- * Wait for the play function to complete by checking the playAfterEach flag
19
- * Only waits if the story actually has a play function
20
- */
21
- async function waitForPlayFunctionCompletion(page: Page, storyName: string) {
22
- const logger = getLogger();
23
-
24
- try {
25
- // First check if this story has a play function
26
- const hasPlayFunction = await page.evaluate(
27
- () => (window as any).__cappa_has_play_function === true,
28
- );
29
-
30
- if (!hasPlayFunction) {
31
- return;
32
- }
33
-
34
- logger.debug(
35
- `Waiting for play function to complete for story: ${storyName}`,
36
- );
37
-
38
- await page.waitForFunction(() => (window as any).playAfterEach === true, {
39
- timeout: 10000,
40
- });
41
-
42
- logger.debug(`Play function completed for story: ${storyName}`);
43
-
44
- // Reset the flags for the next story
45
- await page.evaluate(() => {
46
- (window as any).playAfterEach = false;
47
- (window as any).__cappa_has_play_function = false;
48
- });
49
- } catch {
50
- // Reset flags even on timeout
51
- await page.evaluate(() => {
52
- (window as any).playAfterEach = false;
53
- (window as any).__cappa_has_play_function = false;
54
- });
55
- }
56
- }
57
-
58
- export interface StorybookStory {
59
- id: string;
60
- name: string;
61
- title: string;
62
- kind: string;
63
- story: string;
64
- type: "story" | "docs";
65
- }
66
-
67
- /**
68
- * Matches a story against glob patterns
69
- * @param story - The story to match
70
- * @param patterns - Array of glob patterns to match against
71
- * @returns true if the story matches any of the patterns
72
- */
73
- function matchesGlobPatterns(
74
- story: StorybookStory,
75
- patterns: string[],
76
- ): boolean {
77
- return patterns.some((pattern) => {
78
- // Match against story id (e.g., "button--primary")
79
- if (minimatch(story.id, pattern)) {
80
- return true;
81
- }
82
-
83
- // Match against story title (e.g., "Button")
84
- if (minimatch(story.title, pattern)) {
85
- return true;
86
- }
87
-
88
- // Match against story name (e.g., "Primary")
89
- if (minimatch(story.name, pattern)) {
90
- return true;
91
- }
92
-
93
- // Match against full story path (e.g., "Button/Primary")
94
- const fullPath = `${story.title}/${story.name}`;
95
- if (minimatch(fullPath, pattern)) {
96
- return true;
97
- }
98
-
99
- return false;
100
- });
101
- }
102
-
103
- interface StorybookStoriesResponse {
104
- entries: Record<string, StorybookStory>;
105
- }
106
-
107
- export interface StorybookPluginOptions {
108
- storybookUrl: string;
109
- /**
110
- * Array of glob patterns to include stories. Stories matching any of these patterns will be included.
111
- * Patterns can match against:
112
- * - Story ID (e.g., "button--primary")
113
- * - Story title (e.g., "Button")
114
- * - Story name (e.g., "Primary")
115
- * - Full story path (e.g., "Button/Primary")
116
- *
117
- * Examples:
118
- * - ["button--*"] - Include all button stories
119
- * - ["*--primary"] - Include all primary stories
120
- * - ["Button/*"] - Include all stories under Button title
121
- * - ["*--*"] - Include all stories
122
- */
123
- includeStories?: string[];
124
- /**
125
- * Array of glob patterns to exclude stories. Stories matching any of these patterns will be excluded.
126
- * Patterns can match against:
127
- * - Story ID (e.g., "button--primary")
128
- * - Story title (e.g., "Button")
129
- * - Story name (e.g., "Primary")
130
- * - Full story path (e.g., "Button/Primary")
131
- *
132
- * Examples:
133
- * - ["button--*"] - Exclude all button stories
134
- * - ["*--secondary"] - Exclude all secondary stories
135
- * - ["Input/*"] - Exclude all stories under Input title
136
- */
137
- excludeStories?: string[];
138
- defaultViewport?: { width: number; height: number };
139
- waitForSelector?: string;
140
- waitForTimeout?: number;
141
- storybook?: StorybookRenderOptions;
142
- }
143
-
144
- /**
145
- * Create a latch for a Promise. A latch is a Promise that can be resolved from outside.
146
- * @param T - The type of the Promise
147
- * @returns A latch for a Promise
148
- */
149
- function createLatch<T>() {
150
- let resolve!: (v: T) => void;
151
- // biome-ignore lint/suspicious/noAssignInExpressions: explicitly setting resolve
152
- const p = new Promise<T>((r) => (resolve = r));
153
- return { p, resolve };
154
- }
155
-
156
- /**
157
- * Storybook Plugin for Cappa
158
- * Fetches stories from a running Storybook server and takes screenshots of each story.
159
- * Supports glob pattern matching for includeStories and excludeStories options.
160
- */
161
- export const cappaPluginStorybook: Plugin<StorybookPluginOptions> = (
162
- options,
163
- ) => {
164
- return {
165
- name: "StorybookPlugin",
166
- description:
167
- "Takes screenshots of Storybook stories with configurable options",
168
-
169
- discover: async () => {
170
- if (!options) {
171
- throw new Error("Storybook plugin options are required");
172
- }
173
- if (!options.storybookUrl) {
174
- throw new Error("storybookUrl is required");
175
- }
176
-
177
- const logger = getLogger();
178
-
179
- const {
180
- storybookUrl,
181
- includeStories = [],
182
- excludeStories = [],
183
- storybook: defaultStorybookOptions,
184
- } = options;
185
-
186
- const storiesUrl = `${storybookUrl}/index.json`;
187
- logger.debug(`Fetching stories from: ${storiesUrl}`);
188
-
189
- const response = await fetch(storiesUrl);
190
- if (!response.ok) {
191
- throw new Error(
192
- `Failed to fetch stories: ${response.status} ${response.statusText}`,
193
- );
194
- }
195
-
196
- const data = (await response.json()) as StorybookStoriesResponse;
197
- const stories = Object.values(data.entries);
198
-
199
- // Filter stories based on include/exclude glob patterns
200
- let filteredStories = stories;
201
-
202
- if (includeStories.length > 0) {
203
- filteredStories = filteredStories.filter((story) =>
204
- matchesGlobPatterns(story, includeStories),
205
- );
206
- }
207
-
208
- if (excludeStories.length > 0) {
209
- filteredStories = filteredStories.filter(
210
- (story) => !matchesGlobPatterns(story, excludeStories),
211
- );
212
- }
213
-
214
- filteredStories = filteredStories.filter(
215
- (story) => story.type === "story",
216
- );
217
-
218
- logger.start(`Found ${filteredStories.length} stories to screenshot...`);
219
-
220
- // Return tasks
221
- return filteredStories.map((story) => ({
222
- id: story.id,
223
- url: buildStorybookIframeUrl({
224
- baseUrl: storybookUrl,
225
- storyId: story.id,
226
- viewMode: defaultStorybookOptions?.viewMode,
227
- args: defaultStorybookOptions?.args,
228
- globals: defaultStorybookOptions?.globals,
229
- query: defaultStorybookOptions?.query,
230
- fullscreen: defaultStorybookOptions?.fullscreen,
231
- singleStory: defaultStorybookOptions?.singleStory,
232
- }),
233
- data: {
234
- story,
235
- },
236
- }));
237
- },
238
-
239
- initPage: async () => {
240
- return {
241
- latchMap: new Map<
242
- string,
243
- {
244
- p: Promise<ScreenshotOptionsStorybook>;
245
- resolve: (v: ScreenshotOptionsStorybook) => void;
246
- }
247
- >(),
248
- };
249
- },
250
-
251
- // Phase 2: Execute single story
252
- execute: async (task, page, screenshotTool, context) => {
253
- const { url, data } = task;
254
- const { story } = data;
255
- const logger = getLogger();
256
- const { storybook: defaultStorybookOptions } = options || {};
257
- const { logConsoleEvents = true } = screenshotTool;
258
-
259
- try {
260
- // Setup exposed function for this page
261
- const currentLatch = createLatch<ScreenshotOptionsStorybook>();
262
- context.latchMap.set(story.id, currentLatch);
263
-
264
- if (
265
- await page.evaluate(() => {
266
- return (window as any).__cappa_parameters === undefined;
267
- })
268
- ) {
269
- await page.exposeFunction(
270
- "__cappa_parameters",
271
- async (id: string, payload: ScreenshotOptionsStorybook) => {
272
- context.latchMap.get(id)?.resolve?.(payload);
273
- },
274
- );
275
- }
276
-
277
- if (logConsoleEvents) {
278
- page.on("console", (message) => {
279
- logger.debug("console", message.text());
280
- });
281
- }
282
- page.on("pageerror", (error) => {
283
- logger.debug("pageerror", error);
284
- });
285
-
286
- // Navigate to story
287
- await page.goto(url);
288
-
289
- // Get story parameters
290
- const storyParameters = await context.latchMap.get(story.id)?.p;
291
- context.latchMap.delete(story.id);
292
-
293
- const variantParameters = storyParameters?.variants ?? [];
294
-
295
- if (storyParameters?.skip) {
296
- logger.warn(`Skipping story ${story.title} - ${story.name}`);
297
- return {
298
- storyId: story.id,
299
- storyName: `${story.title} - ${story.name}`,
300
- skipped: true,
301
- };
302
- }
303
-
304
- if (storyParameters && Object.keys(storyParameters).length > 0) {
305
- logger.debug("Taking screenshot with options", storyParameters);
306
- }
307
-
308
- const resolvedViewport =
309
- storyParameters?.viewport ?? screenshotTool.viewport;
310
-
311
- await page.setViewportSize(resolvedViewport);
312
-
313
- await freezeUI(page);
314
- await waitForVisualIdle(page);
315
-
316
- // Wait for play function to complete if it exists
317
- await waitForPlayFunctionCompletion(
318
- page,
319
- `${story.title} - ${story.name}`,
320
- );
321
-
322
- const toLocatorMask = (mask?: string[]) =>
323
- mask?.map((selector) => page.locator(selector));
324
-
325
- const filename = buildFilename(story);
326
-
327
- // Convert variants to the new format with URLs
328
- const variantsWithUrls: ScreenshotVariantWithUrl[] =
329
- variantParameters.map(
330
- (variant: ScreenshotVariantOptionsStorybook) => {
331
- const variantFilename =
332
- variant.filename ||
333
- screenshotTool.getVariantFilename(filename, {
334
- id: variant.id,
335
- label: variant.label,
336
- filename: variant.filename,
337
- });
338
-
339
- // Merge variant args with default storybook options
340
- const mergedArgs = {
341
- ...defaultStorybookOptions?.args,
342
- ...variant.options?.args,
343
- };
344
-
345
- return {
346
- id: variant.id,
347
- label: variant.label,
348
- filename: variantFilename,
349
- url: buildStorybookIframeUrl({
350
- baseUrl: options?.storybookUrl || "",
351
- storyId: story.id,
352
- viewMode: defaultStorybookOptions?.viewMode,
353
- args: mergedArgs,
354
- globals: defaultStorybookOptions?.globals,
355
- query: defaultStorybookOptions?.query,
356
- fullscreen: defaultStorybookOptions?.fullscreen,
357
- singleStory: defaultStorybookOptions?.singleStory,
358
- }),
359
- options: variant.options
360
- ? {
361
- ...variant.options,
362
- mask: toLocatorMask(variant.options.mask),
363
- }
364
- : undefined,
365
- };
366
- },
367
- );
368
-
369
- const baseOptions = {
370
- fullPage: storyParameters?.fullPage,
371
- delay: storyParameters?.delay,
372
- omitBackground: storyParameters?.omitBackground,
373
- skip: storyParameters?.skip,
374
- viewport: storyParameters?.viewport ?? screenshotTool.viewport,
375
- mask: toLocatorMask(storyParameters?.mask),
376
- };
377
-
378
- const variantFilenameMap = new Map<string, string>();
379
- for (const variant of variantsWithUrls) {
380
- const variantFilename = variant.filename;
381
- if (!variantFilename) continue; // Skip if no filename
382
-
383
- variantFilenameMap.set(variant.id, variantFilename);
384
- }
385
-
386
- const variantExtrasEntries = variantsWithUrls.map(
387
- (variant) =>
388
- [
389
- variant.id,
390
- {
391
- saveDiffImage: true,
392
- diffImageFilename: variant.filename,
393
- },
394
- ] as const,
395
- );
396
-
397
- const captureExtras: ScreenshotCaptureExtras = {
398
- saveDiffImage: true,
399
- diffImageFilename: filename,
400
- variants: variantExtrasEntries.length
401
- ? Object.fromEntries(variantExtrasEntries)
402
- : undefined,
403
- };
404
-
405
- const captureResult = await screenshotTool.captureWithVariants(
406
- page,
407
- filename,
408
- url,
409
- baseOptions,
410
- variantsWithUrls,
411
- captureExtras,
412
- );
413
-
414
- return {
415
- storyId: story.id,
416
- storyName: `${story.title} - ${story.name}`,
417
- filepath: captureResult.base.filepath,
418
- success: captureResult.base.skipped
419
- ? undefined
420
- : captureResult.base.comparisonResult
421
- ? captureResult.base.comparisonResult.passed
422
- : Boolean(captureResult.base.filepath),
423
- skipped: captureResult.base.skipped,
424
- };
425
- } catch (error) {
426
- logger.error(
427
- `Error taking screenshot of story ${story.title} - ${story.name}:`,
428
- (error as Error).message,
429
- );
430
- return {
431
- storyId: story.id,
432
- storyName: `${story.title} - ${story.name}`,
433
- error: (error as Error)?.message ?? "Unknown error",
434
- };
435
- }
436
- },
437
- };
438
- };
@@ -1,43 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
-
3
- import { buildStorybookIframeUrl } from "./storybook-url";
4
-
5
- describe("buildStorybookIframeUrl", () => {
6
- it("builds a default url", () => {
7
- expect(
8
- buildStorybookIframeUrl({
9
- baseUrl: "https://storybook.example.com",
10
- storyId: "button--primary",
11
- }),
12
- ).toBe(
13
- "https://storybook.example.com/iframe.html?id=button--primary&viewMode=story&full=1&singleStory=true",
14
- );
15
- });
16
-
17
- it("includes args, globals and query parameters", () => {
18
- expect(
19
- buildStorybookIframeUrl({
20
- baseUrl: "https://storybook.example.com",
21
- storyId: "button--primary",
22
- args: { label: "Click Me", count: 2 },
23
- globals: { locale: "en", darkMode: true },
24
- query: { nav: false },
25
- }),
26
- ).toBe(
27
- "https://storybook.example.com/iframe.html?id=button--primary&viewMode=story&args=label%3AClick%2520Me%3Bcount%3A2&globals=locale%3Aen%3BdarkMode%3Atrue&full=1&singleStory=true&nav=false",
28
- );
29
- });
30
-
31
- it("omits fullscreen and single story flags when disabled", () => {
32
- expect(
33
- buildStorybookIframeUrl({
34
- baseUrl: "https://storybook.example.com",
35
- storyId: "button--primary",
36
- fullscreen: false,
37
- singleStory: false,
38
- }),
39
- ).toBe(
40
- "https://storybook.example.com/iframe.html?id=button--primary&viewMode=story",
41
- );
42
- });
43
- });
@@ -1,55 +0,0 @@
1
- import type { StorybookRenderOptions } from "../types";
2
-
3
- type SBUrlOptions = StorybookRenderOptions & {
4
- baseUrl: string;
5
- storyId: string;
6
- };
7
-
8
- function encodePairs(obj: Record<string, unknown> | undefined) {
9
- if (!obj || !Object.keys(obj).length) return "";
10
- return Object.entries(obj)
11
- .filter(([, v]) => v !== undefined)
12
- .map(([k, v]) => {
13
- const val =
14
- typeof v === "string"
15
- ? encodeURIComponent(v)
16
- : typeof v === "number" || typeof v === "boolean"
17
- ? String(v)
18
- : encodeURIComponent(JSON.stringify(v));
19
- return `${encodeURIComponent(k)}:${val}`;
20
- })
21
- .join(";");
22
- }
23
-
24
- export function buildStorybookIframeUrl({
25
- baseUrl,
26
- storyId,
27
- viewMode = "story",
28
- args,
29
- globals,
30
- query,
31
- fullscreen = true,
32
- singleStory = true,
33
- }: SBUrlOptions) {
34
- const u = new URL("/iframe.html", baseUrl);
35
- u.searchParams.set("id", storyId);
36
- u.searchParams.set("viewMode", viewMode);
37
-
38
- const argPairs = encodePairs(args);
39
- if (argPairs) u.searchParams.set("args", argPairs);
40
-
41
- const globalPairs = encodePairs(globals);
42
- if (globalPairs) u.searchParams.set("globals", globalPairs);
43
-
44
- if (fullscreen) u.searchParams.set("full", "1");
45
- if (singleStory) u.searchParams.set("singleStory", "true");
46
-
47
- if (query) {
48
- for (const [k, v] of Object.entries(query)) {
49
- if (v === undefined) continue;
50
- u.searchParams.set(k, String(v));
51
- }
52
- }
53
-
54
- return u.toString();
55
- }
@@ -1,47 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import type { StorybookStory } from "./plugin";
3
- import { buildFilename } from "./util";
4
-
5
- describe("buildFilename", () => {
6
- it("should build a filename for a story", () => {
7
- const story: StorybookStory = {
8
- id: "1",
9
- name: "Primary",
10
- title: "Story",
11
- kind: "Kind",
12
- story: "Story",
13
- type: "story",
14
- };
15
-
16
- const filename = buildFilename(story);
17
- expect(filename).toBe("Story/Primary.png");
18
- });
19
-
20
- it("should build a filename for a story with a folder", () => {
21
- const story: StorybookStory = {
22
- id: "1",
23
- name: "Primary",
24
- title: "Folder/Story",
25
- kind: "Kind",
26
- story: "Story",
27
- type: "story",
28
- };
29
-
30
- const filename = buildFilename(story);
31
- expect(filename).toBe("Folder/Story/Primary.png");
32
- });
33
-
34
- it("should build a filename for a story with special characters", () => {
35
- const story: StorybookStory = {
36
- id: "1",
37
- name: "Primary123!@#$%^&*()",
38
- title: "Story123!@#$%^&*()",
39
- kind: "Kind",
40
- story: "Story",
41
- type: "story",
42
- };
43
-
44
- const filename = buildFilename(story);
45
- expect(filename).toBe("Story123/Primary123.png");
46
- });
47
- });
package/src/cappa/util.ts DELETED
@@ -1,100 +0,0 @@
1
- import type { Page } from "playwright-core";
2
- import type { StorybookStory } from "./plugin";
3
-
4
- /**
5
- * Disable CSS transitions, animations, and scrollbars
6
- * @param page - The page to disable CSS transitions, animations, and scrollbars
7
- */
8
- export const freezeUI = async (page: Page) => {
9
- await page.addStyleTag({
10
- content: `
11
- *, *::before, *::after {
12
- -moz-animation: none !important;
13
- -moz-transition: none !important;
14
- transition: none !important;
15
- animation: none !important;
16
- }
17
- *, input, textarea { caret-color: transparent !important }
18
- *:focus { outline: none !important }
19
- *:focus-visible { outline: none !important }
20
- *:focus-within { outline: none !important }
21
- * { text-rendering: optimizeLegibility !important }
22
- ::-webkit-scrollbar { display: none !important }
23
- html { scroll-behavior: auto !important }
24
- svg, svg * {
25
- shape-rendering: crispEdges !important;
26
- text-rendering: geometricPrecision !important;
27
- vector-effect: non-scaling-stroke !important;
28
- }
29
- img { image-rendering: crisp-edges !important }
30
- `,
31
- });
32
- };
33
-
34
- /**
35
- * Wait for general visual stability on the page
36
- * @param page - The page to wait for
37
- */
38
- export const waitForVisualIdle = async (page: Page) => {
39
- // Wait for the page to be fully loaded
40
- await page.waitForLoadState("networkidle");
41
-
42
- // fonts + images
43
- await page.evaluate(async () => {
44
- await (document as any).fonts?.ready?.catch(() => {});
45
- const imgs = Array.from(document.images).filter((i) => !i.complete);
46
- await Promise.all(
47
- imgs.map(
48
- (i) =>
49
- new Promise((res) => {
50
- i.onload = i.onerror = () => res(null);
51
- }),
52
- ),
53
- );
54
- });
55
-
56
- // 2 animation frames + idle period with no DOM mutations
57
- await page.evaluate(
58
- ({ minIdleMs }) =>
59
- new Promise<void>((resolve) => {
60
- let timer: number | null = null;
61
- let last = performance.now();
62
-
63
- const done = () => {
64
- if (timer) cancelAnimationFrame(timer);
65
- resolve();
66
- };
67
-
68
- const mo = new MutationObserver(() => {
69
- last = performance.now();
70
- });
71
- mo.observe(document, {
72
- attributes: true,
73
- childList: true,
74
- subtree: true,
75
- characterData: true,
76
- });
77
-
78
- const tick = () => {
79
- if (performance.now() - last >= minIdleMs) {
80
- mo.disconnect();
81
- done();
82
- } else {
83
- timer = requestAnimationFrame(tick);
84
- }
85
- };
86
-
87
- requestAnimationFrame(() => requestAnimationFrame(tick));
88
- }),
89
- { minIdleMs: 100 },
90
- );
91
- };
92
-
93
- /**
94
- * Build a filename for a story.
95
- * @param story - The story to build a filename for
96
- * @returns The filename for the story. Slashes represent folders that should be handled by seperate file system calls.
97
- */
98
- export const buildFilename = (story: StorybookStory) => {
99
- return `${story.title.replace(/[^a-zA-Z0-9/]/g, "")}/${story.name.replace(/[^a-zA-Z0-9]/g, "")}.png`;
100
- };
package/src/index.cjs.ts DELETED
@@ -1,5 +0,0 @@
1
- export const previewAnnotations = [require.resolve("./preview.js")];
2
-
3
- export type { StorybookPluginOptions } from "./cappa/plugin";
4
- export { cappaPluginStorybook } from "./cappa/plugin";
5
- export type { ScreenshotOptionsStorybook as CappaStorybookOptions } from "./types";
package/src/index.esm.ts DELETED
@@ -1,9 +0,0 @@
1
- import { fileURLToPath } from "node:url";
2
-
3
- export const previewAnnotations = [
4
- fileURLToPath(new URL("./preview.js", import.meta.url)),
5
- ];
6
-
7
- export type { StorybookPluginOptions } from "./cappa/plugin";
8
- export { cappaPluginStorybook } from "./cappa/plugin";
9
- export type { ScreenshotOptionsStorybook as CappaStorybookOptions } from "./types";