@cappa/plugin-storybook 0.0.27 → 0.1.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.
@@ -1,20 +1,20 @@
1
1
 
2
2
 
3
- > @cappa/plugin-storybook@0.0.26 build /home/tim/code/work/cappa/packages/plugins/plugin-storybook
3
+ > @cappa/plugin-storybook@0.1.0 build /home/tim/cappa/packages/plugins/plugin-storybook
4
4
  > tsup
5
5
 
6
6
  CLI Building entry: src/index.ts
7
7
  CLI Using tsconfig: ../../../tsconfig.json
8
8
  CLI tsup v8.5.0
9
- CLI Using tsup config: /home/tim/code/work/cappa/packages/plugins/plugin-storybook/tsup.config.ts
9
+ CLI Using tsup config: /home/tim/cappa/packages/plugins/plugin-storybook/tsup.config.ts
10
10
  CLI Building entry: src/storybook/addon/preview.ts
11
11
  CLI Using tsconfig: ../../../tsconfig.json
12
12
  CLI tsup v8.5.0
13
- CLI Using tsup config: /home/tim/code/work/cappa/packages/plugins/plugin-storybook/tsup.config.ts
13
+ CLI Using tsup config: /home/tim/cappa/packages/plugins/plugin-storybook/tsup.config.ts
14
14
  CLI Building entry: src/storybook/addon/browser.ts
15
15
  CLI Using tsconfig: ../../../tsconfig.json
16
16
  CLI tsup v8.5.0
17
- CLI Using tsup config: /home/tim/code/work/cappa/packages/plugins/plugin-storybook/tsup.config.ts
17
+ CLI Using tsup config: /home/tim/cappa/packages/plugins/plugin-storybook/tsup.config.ts
18
18
  CLI Target: esnext
19
19
  CLI Target: node16
20
20
  CLI Target: es2015
@@ -26,14 +26,14 @@
26
26
  CLI Cleaning output folder
27
27
  ESM Build start
28
28
  ESM dist/browser.mjs 138.00 B
29
- ESM ⚡️ Build success in 8ms
30
- ESM dist/preview.mjs 1.34 KB
31
- ESM ⚡️ Build success in 8ms
32
- ESM dist/index.mjs 7.61 KB
33
29
  ESM ⚡️ Build success in 11ms
34
- CJS dist/index.js 8.96 KB
35
- CJS ⚡️ Build success in 11ms
30
+ ESM dist/preview.mjs 1.34 KB
31
+ ESM ⚡️ Build success in 12ms
32
+ CJS dist/index.js 11.02 KB
33
+ CJS ⚡️ Build success in 18ms
34
+ ESM dist/index.mjs 9.65 KB
35
+ ESM ⚡️ Build success in 18ms
36
36
  DTS Build start
37
- DTS ⚡️ Build success in 848ms
37
+ DTS ⚡️ Build success in 1222ms
38
38
  DTS dist/index.d.ts 593.00 B
39
39
  DTS dist/index.d.mts 593.00 B
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @cappa/plugin-storybook
2
2
 
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - d640855: Fix server public folder publish
8
+ - Updated dependencies [d640855]
9
+ - @cappa/core@0.1.1
10
+
11
+ ## 0.1.0
12
+
13
+ ### Minor Changes
14
+
15
+ - 78c1423: Add review functionality
16
+
17
+ ### Patch Changes
18
+
19
+ - Updated dependencies [78c1423]
20
+ - @cappa/core@0.1.0
21
+
3
22
  ## 0.0.27
4
23
 
5
24
  ### Patch Changes
package/README.md CHANGED
@@ -51,6 +51,7 @@ Cappa uses a storybook addon that allows you to pass options from storybook into
51
51
  | delay | The delay to wait before taking the screenshot | null (no delay) |
52
52
  | fullPage | Whether to take a full page screenshot | true |
53
53
  | mask | An array of selectors to mask in the screenshot | [] |
54
+ | omitBackground | Whether to omit the background in the screenshot | false |
54
55
 
55
56
  #### Example
56
57
 
@@ -67,34 +68,28 @@ export const Primary: Story = {
67
68
  };
68
69
  ```
69
70
 
70
- ### Play function
71
-
72
- cappa automatically waits for the play function to finish, before taking screenshots. This allows you to define 'actions' that are executed before the screenshot is taken e.g. clicking on a button.
73
-
74
- > `delay` is added "on top" of the play function execution.
75
-
76
- #### Example
77
-
78
- ```ts
79
- export const Primary: Story = {
80
- play: async ({ canvasElement }) => {
81
- const canvas = within(canvasElement);
82
- await userEvent.click(canvas.getByRole("button"));
83
- },
84
- };
85
- ```
86
-
87
71
  ## Flakiness
88
72
 
89
73
  To avoid flakiness, cappa disables css animations and transitions by default. For additional use cases or animation libraries, you can use the `isCappa` function to check if the current window is a cappa window. You can use it inside of your storybook preview file (`.storybook/preview.ts`):
90
74
 
91
75
  ```ts
76
+ import { isCappa } from '@cappa/plugin-storybook/browser';
77
+
92
78
  if (isCappa()) {
93
79
  import("disable-animations.css");
94
80
  MotionGlobalConfig.disableAnimations = true;
95
81
  }
96
82
  ```
97
83
 
98
- ## How it works
84
+ ### DOM Mutations
85
+
86
+ Cappa waits for DOM mutations to be idle before taking the screenshot. It does so by querying the DOM for mutations and waiting for a certain amount of time to pass, until the page is considered idle.
87
+
88
+ ### Fonts & Images
89
+
90
+ Cappa waits for fonts and images to be loaded before taking the screenshot.
91
+
92
+ ### SVG's
99
93
 
100
- cappa uses a 'one way binding' to pass options from storybook into cappa. That means that the storybook addon is responsible for passing options into cappa and 'communicating' the correct timing to take the screenshot.
94
+ Cappa sets global css styles to render svg images more consistently. You might experience
95
+ differences between actual browsers and cappa screenshots, but that is expected and wanted behavior, since browsers tend to render svg images differently.
package/dist/index.js CHANGED
@@ -35,6 +35,9 @@ __export(index_exports, {
35
35
  });
36
36
  module.exports = __toCommonJS(index_exports);
37
37
 
38
+ // src/cappa/plugin.ts
39
+ var import_chalk = __toESM(require("chalk"));
40
+
38
41
  // src/cappa/util.ts
39
42
  var freezeUI = async (page) => {
40
43
  await page.addStyleTag({
@@ -67,38 +70,49 @@ var waitForVisualIdle = async (page) => {
67
70
  await document.fonts?.ready?.catch(() => {
68
71
  });
69
72
  const imgs = Array.from(document.images).filter((i) => !i.complete);
70
- await Promise.all(imgs.map((i) => new Promise((res) => {
71
- i.onload = i.onerror = () => res(null);
72
- })));
73
+ await Promise.all(
74
+ imgs.map(
75
+ (i) => new Promise((res) => {
76
+ i.onload = i.onerror = () => res(null);
77
+ })
78
+ )
79
+ );
73
80
  });
74
- await page.evaluate(({ minIdleMs }) => new Promise((resolve) => {
75
- let timer = null;
76
- let last = performance.now();
77
- const done = () => {
78
- if (timer) cancelAnimationFrame(timer);
79
- resolve();
80
- };
81
- const mo = new MutationObserver(() => {
82
- last = performance.now();
83
- });
84
- mo.observe(document, { attributes: true, childList: true, subtree: true, characterData: true });
85
- const tick = () => {
86
- if (performance.now() - last >= minIdleMs) {
87
- mo.disconnect();
88
- done();
89
- } else {
90
- timer = requestAnimationFrame(tick);
91
- }
92
- };
93
- requestAnimationFrame(() => requestAnimationFrame(tick));
94
- }), { minIdleMs: 100 });
81
+ await page.evaluate(
82
+ ({ minIdleMs }) => new Promise((resolve) => {
83
+ let timer = null;
84
+ let last = performance.now();
85
+ const done = () => {
86
+ if (timer) cancelAnimationFrame(timer);
87
+ resolve();
88
+ };
89
+ const mo = new MutationObserver(() => {
90
+ last = performance.now();
91
+ });
92
+ mo.observe(document, {
93
+ attributes: true,
94
+ childList: true,
95
+ subtree: true,
96
+ characterData: true
97
+ });
98
+ const tick = () => {
99
+ if (performance.now() - last >= minIdleMs) {
100
+ mo.disconnect();
101
+ done();
102
+ } else {
103
+ timer = requestAnimationFrame(tick);
104
+ }
105
+ };
106
+ requestAnimationFrame(() => requestAnimationFrame(tick));
107
+ }),
108
+ { minIdleMs: 100 }
109
+ );
95
110
  };
96
111
  var buildFilename = (story) => {
97
112
  return `${story.title.replace(/[^a-zA-Z0-9/]/g, "")}/${story.name.replace(/[^a-zA-Z0-9]/g, "")}.png`;
98
113
  };
99
114
 
100
115
  // src/cappa/plugin.ts
101
- var import_chalk = __toESM(require("chalk"));
102
116
  function createLatch() {
103
117
  let resolve;
104
118
  const p = new Promise((r) => resolve = r);
@@ -176,7 +190,6 @@ var cappaPluginStorybook = (options) => {
176
190
  await page.goto(storyUrl);
177
191
  const options2 = await currentLatch.p;
178
192
  currentLatch = createLatch();
179
- logger.debug("options", options2);
180
193
  if (options2.skip) {
181
194
  logger.log(`Skipping story ${story.title} - ${story.name}`);
182
195
  results.push({
@@ -186,27 +199,67 @@ var cappaPluginStorybook = (options) => {
186
199
  });
187
200
  continue;
188
201
  }
202
+ if (options2 && Object.keys(options2).length > 0) {
203
+ logger.debug("Taking screenshot with options", options2);
204
+ }
189
205
  await freezeUI(page);
190
206
  await waitForVisualIdle(page);
191
207
  if (options2.delay) {
192
208
  await page.waitForTimeout(options2.delay);
193
209
  }
194
210
  const filename = buildFilename(story);
195
- const actualFilepath = await screenshotTool.takeScreenshot(
196
- page,
197
- filename,
198
- {
199
- fullPage: options2.fullPage,
200
- mask: options2.mask?.map((selector) => page.locator(selector)),
201
- omitBackground: options2.omitBackground
211
+ const expectedExists = screenshotTool.hasExpectedImage(filename);
212
+ let actualFilepath;
213
+ if (expectedExists) {
214
+ const { screenshotPath, comparisonResult } = await screenshotTool.takeScreenshotWithComparison(
215
+ page,
216
+ filename,
217
+ screenshotTool.getExpectedImageBuffer(filename),
218
+ {
219
+ fullPage: options2.fullPage,
220
+ mask: options2.mask?.map(
221
+ (selector) => page.locator(selector)
222
+ ),
223
+ omitBackground: options2.omitBackground,
224
+ saveDiffImage: true
225
+ }
226
+ );
227
+ actualFilepath = screenshotPath;
228
+ if (comparisonResult.passed) {
229
+ logger.log(
230
+ `Story ${story.title} - ${story.name} passed visual comparison`
231
+ );
232
+ } else {
233
+ logger.log(
234
+ `Story ${story.title} - ${story.name} failed visual comparison`
235
+ );
202
236
  }
203
- );
204
- results.push({
205
- storyId: story.id,
206
- storyName: `${story.title} - ${story.name}`,
207
- filepath: actualFilepath,
208
- success: true
209
- });
237
+ results.push({
238
+ storyId: story.id,
239
+ storyName: `${story.title} - ${story.name}`,
240
+ filepath: actualFilepath,
241
+ success: comparisonResult.passed
242
+ });
243
+ } else {
244
+ logger.info(
245
+ `Expected image not found for story ${story.title} - ${story.name}, taking screenshot`
246
+ );
247
+ actualFilepath = await screenshotTool.takeScreenshot(
248
+ page,
249
+ filename,
250
+ {
251
+ fullPage: options2.fullPage,
252
+ mask: options2.mask?.map((selector) => page.locator(selector)),
253
+ omitBackground: options2.omitBackground
254
+ }
255
+ );
256
+ results.push({
257
+ storyId: story.id,
258
+ storyName: `${story.title} - ${story.name}`,
259
+ filepath: actualFilepath,
260
+ success: true
261
+ });
262
+ }
210
263
  } catch (error) {
211
264
  console.error(
212
265
  `Error taking screenshot of story ${story.title} - ${story.name}:`,
@@ -231,11 +284,20 @@ ${results.filter((r) => r.error).map((r) => `${r.storyName}: ${r.error}`).join("
231
284
  ${results.filter((r) => r.skipped).map((r) => `${r.storyName}`).join("\n")}`
232
285
  );
233
286
  }
287
+ const skipped = results.filter((r) => r.skipped);
288
+ const failed = results.filter(
289
+ (r) => r.error || !r.skipped && !r.success
290
+ );
291
+ const successful = results.filter((r) => r.success);
292
+ const output = [
293
+ `${import_chalk.default.yellow("Skipped stories:")} ${skipped.length}`,
294
+ `${import_chalk.default.red("Failed stories:")} ${failed.length}`,
295
+ `${import_chalk.default.green("Successful stories:")} ${successful.length}`,
296
+ `${import_chalk.default.blue("Total stories:")} ${results.length}`
297
+ ];
234
298
  logger.box({
235
299
  title: "Storybook Report",
236
- message: `${import_chalk.default.yellow("Skipped stories:")} ${results.filter((r) => r.skipped).length}
237
- ${import_chalk.default.red("Failed stories:")} ${results.filter((r) => r.error).length}
238
- ${import_chalk.default.green("Successful screenshots:")} ${results.length}`
300
+ message: output.join("\n")
239
301
  });
240
302
  return results;
241
303
  } catch (error) {
package/dist/index.mjs CHANGED
@@ -5,6 +5,9 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
5
5
  throw Error('Dynamic require of "' + x + '" is not supported');
6
6
  });
7
7
 
8
+ // src/cappa/plugin.ts
9
+ import chalk from "chalk";
10
+
8
11
  // src/cappa/util.ts
9
12
  var freezeUI = async (page) => {
10
13
  await page.addStyleTag({
@@ -37,38 +40,49 @@ var waitForVisualIdle = async (page) => {
37
40
  await document.fonts?.ready?.catch(() => {
38
41
  });
39
42
  const imgs = Array.from(document.images).filter((i) => !i.complete);
40
- await Promise.all(imgs.map((i) => new Promise((res) => {
41
- i.onload = i.onerror = () => res(null);
42
- })));
43
+ await Promise.all(
44
+ imgs.map(
45
+ (i) => new Promise((res) => {
46
+ i.onload = i.onerror = () => res(null);
47
+ })
48
+ )
49
+ );
43
50
  });
44
- await page.evaluate(({ minIdleMs }) => new Promise((resolve) => {
45
- let timer = null;
46
- let last = performance.now();
47
- const done = () => {
48
- if (timer) cancelAnimationFrame(timer);
49
- resolve();
50
- };
51
- const mo = new MutationObserver(() => {
52
- last = performance.now();
53
- });
54
- mo.observe(document, { attributes: true, childList: true, subtree: true, characterData: true });
55
- const tick = () => {
56
- if (performance.now() - last >= minIdleMs) {
57
- mo.disconnect();
58
- done();
59
- } else {
60
- timer = requestAnimationFrame(tick);
61
- }
62
- };
63
- requestAnimationFrame(() => requestAnimationFrame(tick));
64
- }), { minIdleMs: 100 });
51
+ await page.evaluate(
52
+ ({ minIdleMs }) => new Promise((resolve) => {
53
+ let timer = null;
54
+ let last = performance.now();
55
+ const done = () => {
56
+ if (timer) cancelAnimationFrame(timer);
57
+ resolve();
58
+ };
59
+ const mo = new MutationObserver(() => {
60
+ last = performance.now();
61
+ });
62
+ mo.observe(document, {
63
+ attributes: true,
64
+ childList: true,
65
+ subtree: true,
66
+ characterData: true
67
+ });
68
+ const tick = () => {
69
+ if (performance.now() - last >= minIdleMs) {
70
+ mo.disconnect();
71
+ done();
72
+ } else {
73
+ timer = requestAnimationFrame(tick);
74
+ }
75
+ };
76
+ requestAnimationFrame(() => requestAnimationFrame(tick));
77
+ }),
78
+ { minIdleMs: 100 }
79
+ );
65
80
  };
66
81
  var buildFilename = (story) => {
67
82
  return `${story.title.replace(/[^a-zA-Z0-9/]/g, "")}/${story.name.replace(/[^a-zA-Z0-9]/g, "")}.png`;
68
83
  };
69
84
 
70
85
  // src/cappa/plugin.ts
71
- import chalk from "chalk";
72
86
  function createLatch() {
73
87
  let resolve;
74
88
  const p = new Promise((r) => resolve = r);
@@ -146,7 +160,6 @@ var cappaPluginStorybook = (options) => {
146
160
  await page.goto(storyUrl);
147
161
  const options2 = await currentLatch.p;
148
162
  currentLatch = createLatch();
149
- logger.debug("options", options2);
150
163
  if (options2.skip) {
151
164
  logger.log(`Skipping story ${story.title} - ${story.name}`);
152
165
  results.push({
@@ -156,27 +169,67 @@ var cappaPluginStorybook = (options) => {
156
169
  });
157
170
  continue;
158
171
  }
172
+ if (options2 && Object.keys(options2).length > 0) {
173
+ logger.debug("Taking screenshot with options", options2);
174
+ }
159
175
  await freezeUI(page);
160
176
  await waitForVisualIdle(page);
161
177
  if (options2.delay) {
162
178
  await page.waitForTimeout(options2.delay);
163
179
  }
164
180
  const filename = buildFilename(story);
165
- const actualFilepath = await screenshotTool.takeScreenshot(
166
- page,
167
- filename,
168
- {
169
- fullPage: options2.fullPage,
170
- mask: options2.mask?.map((selector) => page.locator(selector)),
171
- omitBackground: options2.omitBackground
181
+ const expectedExists = screenshotTool.hasExpectedImage(filename);
182
+ let actualFilepath;
183
+ if (expectedExists) {
184
+ const { screenshotPath, comparisonResult } = await screenshotTool.takeScreenshotWithComparison(
185
+ page,
186
+ filename,
187
+ screenshotTool.getExpectedImageBuffer(filename),
188
+ {
189
+ fullPage: options2.fullPage,
190
+ mask: options2.mask?.map(
191
+ (selector) => page.locator(selector)
192
+ ),
193
+ omitBackground: options2.omitBackground,
194
+ saveDiffImage: true
195
+ }
196
+ );
197
+ actualFilepath = screenshotPath;
198
+ if (comparisonResult.passed) {
199
+ logger.log(
200
+ `Story ${story.title} - ${story.name} passed visual comparison`
201
+ );
202
+ } else {
203
+ logger.log(
204
+ `Story ${story.title} - ${story.name} failed visual comparison`
205
+ );
172
206
  }
173
- );
174
- results.push({
175
- storyId: story.id,
176
- storyName: `${story.title} - ${story.name}`,
177
- filepath: actualFilepath,
178
- success: true
179
- });
207
+ results.push({
208
+ storyId: story.id,
209
+ storyName: `${story.title} - ${story.name}`,
210
+ filepath: actualFilepath,
211
+ success: comparisonResult.passed
212
+ });
213
+ } else {
214
+ logger.info(
215
+ `Expected image not found for story ${story.title} - ${story.name}, taking screenshot`
216
+ );
217
+ actualFilepath = await screenshotTool.takeScreenshot(
218
+ page,
219
+ filename,
220
+ {
221
+ fullPage: options2.fullPage,
222
+ mask: options2.mask?.map((selector) => page.locator(selector)),
223
+ omitBackground: options2.omitBackground
224
+ }
225
+ );
226
+ results.push({
227
+ storyId: story.id,
228
+ storyName: `${story.title} - ${story.name}`,
229
+ filepath: actualFilepath,
230
+ success: true
231
+ });
232
+ }
180
233
  } catch (error) {
181
234
  console.error(
182
235
  `Error taking screenshot of story ${story.title} - ${story.name}:`,
@@ -201,11 +254,20 @@ ${results.filter((r) => r.error).map((r) => `${r.storyName}: ${r.error}`).join("
201
254
  ${results.filter((r) => r.skipped).map((r) => `${r.storyName}`).join("\n")}`
202
255
  );
203
256
  }
257
+ const skipped = results.filter((r) => r.skipped);
258
+ const failed = results.filter(
259
+ (r) => r.error || !r.skipped && !r.success
260
+ );
261
+ const successful = results.filter((r) => r.success);
262
+ const output = [
263
+ `${chalk.yellow("Skipped stories:")} ${skipped.length}`,
264
+ `${chalk.red("Failed stories:")} ${failed.length}`,
265
+ `${chalk.green("Successful stories:")} ${successful.length}`,
266
+ `${chalk.blue("Total stories:")} ${results.length}`
267
+ ];
204
268
  logger.box({
205
269
  title: "Storybook Report",
206
- message: `${chalk.yellow("Skipped stories:")} ${results.filter((r) => r.skipped).length}
207
- ${chalk.red("Failed stories:")} ${results.filter((r) => r.error).length}
208
- ${chalk.green("Successful screenshots:")} ${results.length}`
270
+ message: output.join("\n")
209
271
  });
210
272
  return results;
211
273
  } catch (error) {
package/dist/preview.mjs CHANGED
@@ -25,7 +25,7 @@ var withCappaDecorator = makeDecorator({
25
25
  skipIfNoParametersOrOptions: false,
26
26
  wrapper: (getStory, context, { parameters: parameters2 }) => {
27
27
  window.__cappa_screenshot = true;
28
- const hasPlayFunction = context.playFunction != null;
28
+ const _hasPlayFunction = context.playFunction != null;
29
29
  queueMicrotask(async () => {
30
30
  try {
31
31
  const cappaParameters = await waitForExposed("__cappa_parameters");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cappa/plugin-storybook",
3
- "version": "0.0.27",
3
+ "version": "0.1.1",
4
4
  "description": "Storybook plugin for Cappa - takes screenshots of Storybook stories",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -31,7 +31,7 @@
31
31
  "@swc/core": "^1.13.5",
32
32
  "chalk": "^5.6.2",
33
33
  "storybook": "^9.1.5",
34
- "@cappa/core": "0.0.27"
34
+ "@cappa/core": "0.1.1"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@vitest/coverage-v8": "3.2.4",
@@ -1,6 +1,6 @@
1
1
  import type { Plugin, ScreenshotOptions } from "@cappa/core";
2
- import { buildFilename, freezeUI, waitForVisualIdle } from "./util";
3
2
  import chalk from "chalk";
3
+ import { buildFilename, freezeUI, waitForVisualIdle } from "./util";
4
4
 
5
5
  export interface StorybookStory {
6
6
  id: string;
@@ -148,8 +148,6 @@ export const cappaPluginStorybook: Plugin<StorybookPluginOptions> = (
148
148
  const options = await currentLatch.p;
149
149
  currentLatch = createLatch<ScreenshotOptions>();
150
150
 
151
- logger.debug("options", options);
152
-
153
151
  if (options.skip) {
154
152
  logger.log(`Skipping story ${story.title} - ${story.name}`);
155
153
  results.push({
@@ -160,6 +158,10 @@ export const cappaPluginStorybook: Plugin<StorybookPluginOptions> = (
160
158
  continue;
161
159
  }
162
160
 
161
+ if (options && Object.keys(options).length > 0) {
162
+ logger.debug("Taking screenshot with options", options);
163
+ }
164
+
163
165
  await freezeUI(page);
164
166
  await waitForVisualIdle(page);
165
167
 
@@ -169,24 +171,63 @@ export const cappaPluginStorybook: Plugin<StorybookPluginOptions> = (
169
171
 
170
172
  // Take screenshot with story-specific filename
171
173
  const filename = buildFilename(story);
174
+ const expectedExists = screenshotTool.hasExpectedImage(filename);
175
+
176
+ let actualFilepath: string | undefined;
177
+ if (expectedExists) {
178
+ const { screenshotPath, comparisonResult } =
179
+ await screenshotTool.takeScreenshotWithComparison(
180
+ page,
181
+ filename,
182
+ screenshotTool.getExpectedImageBuffer(filename),
183
+ {
184
+ fullPage: options.fullPage,
185
+ mask: options.mask?.map((selector) =>
186
+ page.locator(selector),
187
+ ),
188
+ omitBackground: options.omitBackground,
189
+ saveDiffImage: true,
190
+ },
191
+ );
192
+
193
+ actualFilepath = screenshotPath;
194
+ if (comparisonResult.passed) {
195
+ logger.log(
196
+ `Story ${story.title} - ${story.name} passed visual comparison`,
197
+ );
198
+ } else {
199
+ logger.log(
200
+ `Story ${story.title} - ${story.name} failed visual comparison`,
201
+ );
202
+ }
172
203
 
173
- // Actually take the screenshot
174
- const actualFilepath = await screenshotTool.takeScreenshot(
175
- page,
176
- filename,
177
- {
178
- fullPage: options.fullPage,
179
- mask: options.mask?.map((selector) => page.locator(selector)),
180
- omitBackground: options.omitBackground,
181
- },
182
- );
204
+ results.push({
205
+ storyId: story.id,
206
+ storyName: `${story.title} - ${story.name}`,
207
+ filepath: actualFilepath,
208
+ success: comparisonResult.passed,
209
+ });
210
+ } else {
211
+ logger.info(
212
+ `Expected image not found for story ${story.title} - ${story.name}, taking screenshot`,
213
+ );
214
+ actualFilepath = await screenshotTool.takeScreenshot(
215
+ page,
216
+ filename,
217
+ {
218
+ fullPage: options.fullPage,
219
+ mask: options.mask?.map((selector) => page.locator(selector)),
220
+ omitBackground: options.omitBackground,
221
+ },
222
+ );
183
223
 
184
- results.push({
185
- storyId: story.id,
186
- storyName: `${story.title} - ${story.name}`,
187
- filepath: actualFilepath,
188
- success: true,
189
- });
224
+ results.push({
225
+ storyId: story.id,
226
+ storyName: `${story.title} - ${story.name}`,
227
+ filepath: actualFilepath,
228
+ success: true,
229
+ });
230
+ }
190
231
  } catch (error) {
191
232
  console.error(
192
233
  `Error taking screenshot of story ${story.title} - ${story.name}:`,
@@ -220,9 +261,22 @@ export const cappaPluginStorybook: Plugin<StorybookPluginOptions> = (
220
261
  );
221
262
  }
222
263
 
264
+ const skipped = results.filter((r) => r.skipped);
265
+ const failed = results.filter(
266
+ (r) => r.error || (!r.skipped && !r.success),
267
+ );
268
+ const successful = results.filter((r) => r.success);
269
+
270
+ const output = [
271
+ `${chalk.yellow("Skipped stories:")} ${skipped.length}`,
272
+ `${chalk.red("Failed stories:")} ${failed.length}`,
273
+ `${chalk.green("Successful stories:")} ${successful.length}`,
274
+ `${chalk.blue("Total stories:")} ${results.length}`,
275
+ ];
276
+
223
277
  logger.box({
224
278
  title: "Storybook Report",
225
- message: `${chalk.yellow("Skipped stories:")} ${results.filter((r) => r.skipped).length}\n${chalk.red("Failed stories:")} ${results.filter((r) => r.error).length}\n${chalk.green("Successful screenshots:")} ${results.length}`,
279
+ message: output.join("\n"),
226
280
  });
227
281
 
228
282
  return results;
package/src/cappa/util.ts CHANGED
@@ -40,36 +40,54 @@ export const waitForVisualIdle = async (page: Page) => {
40
40
  await page.waitForLoadState("networkidle");
41
41
 
42
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(imgs.map(i => new Promise(res => { i.onload = i.onerror = () => res(null) })))
47
- })
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
+ });
48
55
 
49
56
  // 2 animation frames + idle period with no DOM mutations
50
- await page.evaluate(({ minIdleMs }) => new Promise<void>(resolve => {
51
- let timer: number | null = null
52
- let last = performance.now()
57
+ await page.evaluate(
58
+ ({ minIdleMs }) =>
59
+ new Promise<void>((resolve) => {
60
+ let timer: number | null = null;
61
+ let last = performance.now();
53
62
 
54
- const done = () => {
55
- if (timer) cancelAnimationFrame(timer)
56
- resolve()
57
- }
63
+ const done = () => {
64
+ if (timer) cancelAnimationFrame(timer);
65
+ resolve();
66
+ };
58
67
 
59
- const mo = new MutationObserver(() => { last = performance.now() })
60
- mo.observe(document, { attributes: true, childList: true, subtree: true, characterData: true })
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
+ });
61
77
 
62
- const tick = () => {
63
- if (performance.now() - last >= minIdleMs) {
64
- mo.disconnect()
65
- done()
66
- } else {
67
- timer = requestAnimationFrame(tick)
68
- }
69
- }
78
+ const tick = () => {
79
+ if (performance.now() - last >= minIdleMs) {
80
+ mo.disconnect();
81
+ done();
82
+ } else {
83
+ timer = requestAnimationFrame(tick);
84
+ }
85
+ };
70
86
 
71
- requestAnimationFrame(() => requestAnimationFrame(tick))
72
- }), { minIdleMs: 100 })
87
+ requestAnimationFrame(() => requestAnimationFrame(tick));
88
+ }),
89
+ { minIdleMs: 100 },
90
+ );
73
91
  };
74
92
 
75
93
  /**
@@ -8,7 +8,7 @@ export const withCappaDecorator = makeDecorator({
8
8
  wrapper: (getStory, context, { parameters }) => {
9
9
  (window as any).__cappa_screenshot = true;
10
10
 
11
- const hasPlayFunction = context.playFunction != null;
11
+ const _hasPlayFunction = context.playFunction != null;
12
12
 
13
13
  queueMicrotask(async () => {
14
14
  try {
@@ -1,5 +0,0 @@
1
-
2
-
3
- > @cappa/plugin-storybook@0.0.14 tsc /home/tim/code/work/cappa/packages/plugins/plugin-storybook
4
- > tsc
5
-