storybook-addon-vis 0.6.2 → 0.6.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.
- package/dist/chunk-4K5KNZ64.js +268 -0
- package/dist/chunk-4K5KNZ64.js.map +1 -0
- package/dist/index.js +9 -1
- package/dist/index.js.map +1 -1
- package/dist/vitest-plugin.js +62 -1
- package/dist/vitest-plugin.js.map +1 -1
- package/dist/vitest-setup.js +38 -1
- package/dist/vitest-setup.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-B3UZM6KO.js +0 -8
- package/dist/chunk-B3UZM6KO.js.map +0 -1
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { getByAltText, getByRole, getByTestId, getByText, getByTitle, getByPlaceholderText, getByLabelText } from '@storybook/test';
|
|
2
|
+
import { join } from 'pathe';
|
|
3
|
+
import dedent from 'dedent';
|
|
4
|
+
import pixelmatch from 'pixelmatch';
|
|
5
|
+
|
|
6
|
+
// src/state.ts
|
|
7
|
+
var state = {
|
|
8
|
+
name: "",
|
|
9
|
+
testFilepath: "",
|
|
10
|
+
taskName: "",
|
|
11
|
+
snapshot: {}
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
// src/@vitest/browser/constants.ts
|
|
15
|
+
var imageSnapshotSymbol = Symbol.for("storybook-addon-vis/imageSnapshot");
|
|
16
|
+
var imageSnapshotStubSymbol = Symbol.for("storybook-addon-vis/imageSnapshotStub");
|
|
17
|
+
async function hasImageSnapshot(options) {
|
|
18
|
+
const index = state.snapshot[state.testFilepath][state.id].index;
|
|
19
|
+
const snapshotFilename = options?.customizeSnapshotId ? `${options.customizeSnapshotId(state.id, index)}.png` : `${state.id}-${index}.png`;
|
|
20
|
+
const baselinePath = join(state.baselineDir, snapshotFilename);
|
|
21
|
+
return commands.existFile(baselinePath);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/image_data.ts
|
|
25
|
+
function toImageData(base64) {
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
const img = new Image();
|
|
28
|
+
img.src = `data:image/png;base64,${base64}`;
|
|
29
|
+
img.onload = () => {
|
|
30
|
+
const canvas = document.createElement("canvas");
|
|
31
|
+
canvas.width = img.width;
|
|
32
|
+
canvas.height = img.height;
|
|
33
|
+
const ctx2 = canvas.getContext("2d");
|
|
34
|
+
ctx2.drawImage(img, 0, 0);
|
|
35
|
+
resolve(ctx2.getImageData(0, 0, canvas.width, canvas.height));
|
|
36
|
+
};
|
|
37
|
+
img.onerror = () => {
|
|
38
|
+
reject(new Error("Failed to load image"));
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
async function toDataURL(imageData) {
|
|
43
|
+
const canvas = document.createElement("canvas");
|
|
44
|
+
canvas.width = imageData.width;
|
|
45
|
+
canvas.height = imageData.height;
|
|
46
|
+
const ctx2 = canvas.getContext("2d");
|
|
47
|
+
ctx2.putImageData(imageData, 0, 0);
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
canvas.toBlob((blob) => {
|
|
50
|
+
const reader = new FileReader();
|
|
51
|
+
reader.onload = () => {
|
|
52
|
+
resolve(reader.result);
|
|
53
|
+
};
|
|
54
|
+
reader.readAsDataURL(blob);
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// src/@vitest/browser/page.image_snapshot.ts
|
|
60
|
+
async function imageSnapshot(options) {
|
|
61
|
+
const index = state.snapshot[state.testFilepath][state.id].index++;
|
|
62
|
+
const snapshotFilename = options?.customizeSnapshotId ? `${options.customizeSnapshotId(state.id, index)}.png` : `${state.id}-${index}.png`;
|
|
63
|
+
const baselinePath = join(state.baselineDir, snapshotFilename);
|
|
64
|
+
const resultPath = join(state.resultDir, snapshotFilename);
|
|
65
|
+
const diffPath = join(state.diffDir, snapshotFilename);
|
|
66
|
+
const screenshot = await this.screenshot({
|
|
67
|
+
base64: true,
|
|
68
|
+
path: resultPath,
|
|
69
|
+
element: options?.element,
|
|
70
|
+
timeout: options?.timeout ?? 3e3
|
|
71
|
+
});
|
|
72
|
+
const image = await toImageData(screenshot.base64);
|
|
73
|
+
return {
|
|
74
|
+
type: imageSnapshotSymbol,
|
|
75
|
+
snapshotFilename,
|
|
76
|
+
baselinePath,
|
|
77
|
+
resultPath,
|
|
78
|
+
diffPath,
|
|
79
|
+
base64: screenshot.base64,
|
|
80
|
+
image
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/@vitest/browser/context.ts
|
|
85
|
+
var ctx;
|
|
86
|
+
if (globalThis.__vitest_browser__) {
|
|
87
|
+
import('@vitest/browser/context').then((m) => {
|
|
88
|
+
ctx = m;
|
|
89
|
+
page.extend({ imageSnapshot, hasImageSnapshot });
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function cdp() {
|
|
93
|
+
return ctx?.cdp() ?? {};
|
|
94
|
+
}
|
|
95
|
+
var commands = new Proxy({}, {
|
|
96
|
+
get(target, prop) {
|
|
97
|
+
return target[prop] ?? (ctx?.commands)[prop];
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
var page = new Proxy(
|
|
101
|
+
{
|
|
102
|
+
getByAltText,
|
|
103
|
+
getByRole,
|
|
104
|
+
getByTestId,
|
|
105
|
+
getByText,
|
|
106
|
+
getByTitle,
|
|
107
|
+
getByPlaceholder: getByPlaceholderText,
|
|
108
|
+
getByLabelText
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
get(target, prop) {
|
|
112
|
+
return target[prop] ?? ctx?.page ? (ctx?.page)[prop] : () => {
|
|
113
|
+
if (prop === "imageSnapshot") {
|
|
114
|
+
return { type: imageSnapshotStubSymbol };
|
|
115
|
+
}
|
|
116
|
+
console.info(`\`page.${prop.toString()}\` does not exist when running in browser`);
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
);
|
|
121
|
+
var server = new Proxy({}, {
|
|
122
|
+
get(target, prop) {
|
|
123
|
+
return target[prop] ?? (ctx?.server)[prop];
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// src/@vitest/browser/image_snapshot.logic.ts
|
|
128
|
+
function isImageSnapshot(subject) {
|
|
129
|
+
return !!subject && subject.type === imageSnapshotSymbol;
|
|
130
|
+
}
|
|
131
|
+
function assertImageSnapshot(subject) {
|
|
132
|
+
if (!isImageSnapshot(subject)) {
|
|
133
|
+
throw new Error("Expected subject to be an image snapshot");
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function toSnapshotId(taskName) {
|
|
137
|
+
return `${taskName.replace(/[^a-z0-9]/gi, "-").toLowerCase()}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// src/image_resizer.ts
|
|
141
|
+
var createImageResizer = ({ width, height }) => (image) => {
|
|
142
|
+
if (image.width === width && image.height === height) {
|
|
143
|
+
return image;
|
|
144
|
+
}
|
|
145
|
+
const inArea = (x, y) => y <= image.height && x <= image.width;
|
|
146
|
+
const result = new ImageData(width, height, { colorSpace: image.colorSpace });
|
|
147
|
+
for (let y = 0; y < height; y++) {
|
|
148
|
+
for (let x = 0; x < width; x++) {
|
|
149
|
+
const idx = width * y + x << 2;
|
|
150
|
+
if (inArea(x, y)) {
|
|
151
|
+
const old = image.width * y + x << 2;
|
|
152
|
+
result.data[idx] = image.data[old];
|
|
153
|
+
result.data[idx + 1] = image.data[old + 1];
|
|
154
|
+
result.data[idx + 2] = image.data[old + 2];
|
|
155
|
+
result.data[idx + 3] = image.data[old + 3];
|
|
156
|
+
} else {
|
|
157
|
+
result.data[idx] = 0;
|
|
158
|
+
result.data[idx + 1] = 0;
|
|
159
|
+
result.data[idx + 2] = 0;
|
|
160
|
+
result.data[idx + 3] = 64;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return result;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
// src/expect.to_match_image_snapshot.ts
|
|
168
|
+
async function toMatchImageSnapshot(actual, options) {
|
|
169
|
+
const subject = await actual;
|
|
170
|
+
if (subject?.type === imageSnapshotStubSymbol) {
|
|
171
|
+
return success;
|
|
172
|
+
}
|
|
173
|
+
if (!isImageSnapshot(subject)) {
|
|
174
|
+
if (subject?.path && subject?.base64) {
|
|
175
|
+
return {
|
|
176
|
+
pass: false,
|
|
177
|
+
actual: subject,
|
|
178
|
+
message: () => "`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?"
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
if (typeof subject !== "object") {
|
|
182
|
+
return {
|
|
183
|
+
pass: false,
|
|
184
|
+
actual: subject,
|
|
185
|
+
message: () => `\`toMatchImageSnapshot()\` expects the subject to be an element, locator, or result of \`page.imageSnapshot()\`, but got: \`${subject}\``
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
assertImageSnapshot(subject);
|
|
190
|
+
const baseline = await tryReadSnapshot(subject.baselinePath);
|
|
191
|
+
if (!baseline) {
|
|
192
|
+
await commands.copyFile(subject.resultPath, subject.baselinePath);
|
|
193
|
+
return success;
|
|
194
|
+
}
|
|
195
|
+
const originalImage = await toImageData(baseline);
|
|
196
|
+
const [resultImage, baselineImage] = alignImagesToSameSize(subject.image, originalImage);
|
|
197
|
+
const { pass, diffAmount, diffImage } = compareImage(baselineImage, resultImage, options);
|
|
198
|
+
if (!pass) {
|
|
199
|
+
if (server.config.snapshotOptions.updateSnapshot === "all") {
|
|
200
|
+
await writeSnapshot(`${subject.baselinePath}`, resultImage);
|
|
201
|
+
return success;
|
|
202
|
+
}
|
|
203
|
+
await writeSnapshot(`${subject.diffPath}`, diffImage);
|
|
204
|
+
return {
|
|
205
|
+
pass: false,
|
|
206
|
+
message: () => dedent`Snapshot \`${state.taskName}\` mismatched
|
|
207
|
+
|
|
208
|
+
${options?.failureThreshold ? options?.failureThresholdType === "percent" ? `Expected image to match within ${options.failureThreshold}% but was differ by ${diffAmount}%.` : `Expected image to match within ${options.failureThreshold} pixels but was differ by ${diffAmount} pixels.` : `Expected image to match but was differ by ${options?.failureThresholdType === "percent" ? `${diffAmount}%` : `${diffAmount} pixels`}.`}
|
|
209
|
+
|
|
210
|
+
Expected: '${subject.baselinePath}'
|
|
211
|
+
Actual: '${subject.resultPath}'
|
|
212
|
+
Difference: '${subject.diffPath}'`
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
return success;
|
|
216
|
+
}
|
|
217
|
+
var success = {
|
|
218
|
+
pass: true,
|
|
219
|
+
message: () => ""
|
|
220
|
+
};
|
|
221
|
+
function tryReadSnapshot(path) {
|
|
222
|
+
return commands.readFile(path, { encoding: "base64" }).catch(() => void 0);
|
|
223
|
+
}
|
|
224
|
+
async function writeSnapshot(path, image) {
|
|
225
|
+
const content = (await toDataURL(image)).split(",")[1];
|
|
226
|
+
return commands.writeFile(path, content, "base64url");
|
|
227
|
+
}
|
|
228
|
+
function alignImagesToSameSize(image1, image2) {
|
|
229
|
+
if (isSameSize(image1, image2)) {
|
|
230
|
+
return [image1, image2];
|
|
231
|
+
}
|
|
232
|
+
const size = getMaxSize(image1, image2);
|
|
233
|
+
const resize = createImageResizer(size);
|
|
234
|
+
return [resize(image1), resize(image2)];
|
|
235
|
+
}
|
|
236
|
+
function getMaxSize(image1, image2) {
|
|
237
|
+
const width = Math.max(image1.width, image2.width);
|
|
238
|
+
const height = Math.max(image1.height, image2.height);
|
|
239
|
+
return { width, height };
|
|
240
|
+
}
|
|
241
|
+
function isSameSize(image1, image2) {
|
|
242
|
+
return image1.width === image2.width && image1.height === image2.height;
|
|
243
|
+
}
|
|
244
|
+
function compareImage(baselineImage, resultImage, { failureThreshold = 0, failureThresholdType = "pixel", diffOptions } = {}) {
|
|
245
|
+
const { width, height } = resultImage;
|
|
246
|
+
const diffImage = new ImageData(width, height);
|
|
247
|
+
const pixelDiff = pixelmatch(resultImage.data, baselineImage.data, diffImage.data, width, height, diffOptions);
|
|
248
|
+
const diffAmount = toThresholdUnit({ failureThresholdType, width, height }, pixelDiff);
|
|
249
|
+
return {
|
|
250
|
+
pass: diffAmount <= failureThreshold,
|
|
251
|
+
diffAmount,
|
|
252
|
+
diffImage
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function toThresholdUnit({ failureThresholdType, width, height }, pixelDiff) {
|
|
256
|
+
switch (failureThresholdType) {
|
|
257
|
+
case "pixel":
|
|
258
|
+
return pixelDiff;
|
|
259
|
+
case "percent":
|
|
260
|
+
return pixelDiff / (width * height) * 100;
|
|
261
|
+
default:
|
|
262
|
+
throw new Error(`Invalid failureThresholdType: ${failureThresholdType}`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export { cdp, commands, page, server, state, toMatchImageSnapshot, toSnapshotId };
|
|
267
|
+
//# sourceMappingURL=chunk-4K5KNZ64.js.map
|
|
268
|
+
//# sourceMappingURL=chunk-4K5KNZ64.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/state.ts","../src/@vitest/browser/constants.ts","../src/@vitest/browser/page.has_image_snapshot.ts","../src/image_data.ts","../src/@vitest/browser/page.image_snapshot.ts","../src/@vitest/browser/context.ts","../src/@vitest/browser/image_snapshot.logic.ts","../src/image_resizer.ts","../src/expect.to_match_image_snapshot.ts"],"names":["ctx","join"],"mappings":";;;;;;AAAO,IAAM,KAAQ,GAAA;AAAA,EACpB,IAAM,EAAA,EAAA;AAAA,EACN,YAAc,EAAA,EAAA;AAAA,EACd,QAAU,EAAA,EAAA;AAAA,EACV,UAAU;AACX;;;ACLO,IAAM,mBAAA,GAAsB,MAAO,CAAA,GAAA,CAAI,mCAAmC,CAAA;AAE1E,IAAM,uBAAA,GAA0B,MAAO,CAAA,GAAA,CAAI,uCAAuC,CAAA;ACWzF,eAAsB,iBAAoC,OAAkD,EAAA;AAC3G,EAAM,MAAA,KAAA,GAAQ,MAAM,QAAS,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,EAAM,MAAA,EAAE,KAAO,EAAA,MAAA,EAAW,GAAA,WAAA;AAC1B,EAAA,MAAM,SAAY,GAAA,IAAI,SAAU,CAAA,KAAA,EAAO,MAAM,CAAA;AAE7C,EAAM,MAAA,SAAA,GAAY,UAAW,CAAA,WAAA,CAAY,IAAM,EAAA,aAAA,CAAc,MAAM,SAAU,CAAA,IAAA,EAAM,KAAO,EAAA,MAAA,EAAQ,WAAW,CAAA;AAC7G,EAAA,MAAM,aAAa,eAAgB,CAAA,EAAE,sBAAsB,KAAO,EAAA,MAAA,IAAU,SAAS,CAAA;AAErF,EAAO,OAAA;AAAA,IACN,MAAM,UAAc,IAAA,gBAAA;AAAA,IACpB,UAAA;AAAA,IACA;AAAA,GACD;AACD;AAEA,SAAS,gBACR,EAAE,oBAAA,EAAsB,KAAO,EAAA,MAAA,IAC/B,SACS,EAAA;AACT,EAAA,QAAQ,oBAAsB;AAAA,IAC7B,KAAK,OAAA;AACJ,MAAO,OAAA,SAAA;AAAA,IACR,KAAK,SAAA;AACJ,MAAQ,OAAA,SAAA,IAAa,QAAQ,MAAW,CAAA,GAAA,GAAA;AAAA,IACzC;AACC,MAAA,MAAM,IAAI,KAAA,CAAM,CAAiC,8BAAA,EAAA,oBAAoB,CAAE,CAAA,CAAA;AAAA;AAE1E","file":"chunk-4K5KNZ64.js","sourcesContent":["export const state = {\n\tname: '',\n\ttestFilepath: '',\n\ttaskName: '',\n\tsnapshot: {},\n} as {\n\tid: string\n\tname: string\n\ttestFilepath: string\n\ttestFilename: string\n\tprojectDir: string\n\tbaselineDir: string\n\tresultDir: string\n\tdiffDir: string\n\ttaskName: string\n\tsnapshot: Record<string, Record<string, { index: number }>>\n}\n","export const imageSnapshotSymbol = Symbol.for('storybook-addon-vis/imageSnapshot')\n\nexport const imageSnapshotStubSymbol = Symbol.for('storybook-addon-vis/imageSnapshotStub')\n","import type { BrowserPage } from '@vitest/browser/context'\nimport { join } from 'pathe'\nimport { state } from '../../state'\nimport { commands } from './context'\nimport type { CustomizeSnapshotIdOptions } from './types'\n\nexport interface HasImageSnapshotAction {\n\thasImageSnapshot(this: BrowserPage, options?: CustomizeSnapshotIdOptions | undefined): Promise<boolean>\n}\n\n/**\n * Check if the snapshot image exists.\n */\nexport async function hasImageSnapshot(this: BrowserPage, options?: CustomizeSnapshotIdOptions | undefined) {\n\tconst index = state.snapshot[state.testFilepath][state.id]!.index\n\tconst snapshotFilename = options?.customizeSnapshotId\n\t\t? `${options.customizeSnapshotId(state.id, index)}.png`\n\t\t: `${state.id}-${index}.png`\n\tconst baselinePath = join(state.baselineDir, snapshotFilename)\n\treturn commands.existFile(baselinePath)\n}\n","export function toImageData(base64: string) {\n\treturn new Promise<ImageData>((resolve, reject) => {\n\t\tconst img = new Image()\n\t\timg.src = `data:image/png;base64,${base64}`\n\n\t\timg.onload = () => {\n\t\t\tconst canvas = document.createElement('canvas')\n\t\t\tcanvas.width = img.width\n\t\t\tcanvas.height = img.height\n\t\t\tconst ctx = canvas.getContext('2d')!\n\t\t\tctx.drawImage(img, 0, 0)\n\t\t\tresolve(ctx.getImageData(0, 0, canvas.width, canvas.height))\n\t\t}\n\n\t\timg.onerror = () => {\n\t\t\treject(new Error('Failed to load image'))\n\t\t}\n\t})\n}\n\nexport async function toDataURL(imageData: ImageData) {\n\tconst canvas = document.createElement('canvas')\n\tcanvas.width = imageData.width\n\tcanvas.height = imageData.height\n\tconst ctx = canvas.getContext('2d')!\n\tctx.putImageData(imageData, 0, 0)\n\treturn new Promise<string>((resolve) => {\n\t\tcanvas.toBlob((blob) => {\n\t\t\tconst reader = new FileReader()\n\t\t\treader.onload = () => {\n\t\t\t\tresolve(reader.result as string)\n\t\t\t}\n\t\t\treader.readAsDataURL(blob!)\n\t\t})\n\t})\n}\n","import type { BrowserPage } from '@vitest/browser/context'\nimport { join } from 'pathe'\nimport { toImageData } from '../../image_data.js'\nimport { state } from '../../state.js'\nimport { imageSnapshotSymbol } from './constants.js'\nimport type { ImageSnapshot, ImageSnapshotOptions } from './types.js'\n\nexport interface ImageSnapshotAction {\n\timageSnapshot(this: BrowserPage, options?: ImageSnapshotOptions | undefined): Promise<ImageSnapshot>\n}\n\nexport async function imageSnapshot(\n\tthis: BrowserPage,\n\toptions?: ImageSnapshotOptions | undefined,\n): Promise<ImageSnapshot> {\n\tconst index = state.snapshot[state.testFilepath][state.id]!.index++\n\tconst snapshotFilename = options?.customizeSnapshotId\n\t\t? `${options.customizeSnapshotId(state.id, index)}.png`\n\t\t: `${state.id}-${index}.png`\n\tconst baselinePath = join(state.baselineDir, snapshotFilename)\n\tconst resultPath = join(state.resultDir, snapshotFilename)\n\tconst diffPath = join(state.diffDir, snapshotFilename)\n\tconst screenshot = await this.screenshot({\n\t\tbase64: true,\n\t\tpath: resultPath,\n\t\telement: options?.element,\n\t\ttimeout: options?.timeout ?? 3000,\n\t})\n\tconst image = await toImageData(screenshot.base64)\n\n\treturn {\n\t\ttype: imageSnapshotSymbol,\n\t\tsnapshotFilename,\n\t\tbaselinePath,\n\t\tresultPath,\n\t\tdiffPath,\n\t\tbase64: screenshot.base64,\n\t\timage,\n\t}\n}\n","import {\n\tgetByAltText,\n\tgetByLabelText,\n\tgetByPlaceholderText,\n\tgetByRole,\n\tgetByTestId,\n\tgetByText,\n\tgetByTitle,\n} from '@storybook/test'\nimport type { BrowserCommands, BrowserPage, CDPSession, Platform } from '@vitest/browser/context'\nimport type { SerializedConfig } from 'vitest'\nimport { imageSnapshotStubSymbol } from './constants'\nimport { hasImageSnapshot } from './page.has_image_snapshot'\nimport { imageSnapshot } from './page.image_snapshot'\n\nlet ctx: Awaited<typeof import('@vitest/browser/context')>\n\nif ((globalThis as any).__vitest_browser__) {\n\timport('@vitest/browser/context').then((m) => {\n\t\tctx = m\n\t\tpage.extend({ imageSnapshot, hasImageSnapshot })\n\t})\n}\n\n// TODO: stub the functions within the `CDPSession`\n// when we better understands the use cases\nexport function cdp(): CDPSession {\n\treturn ctx?.cdp() ?? ({} as any)\n}\n\nexport const commands = new Proxy<BrowserCommands>({} as any, {\n\tget(target, prop) {\n\t\treturn (target as any)[prop] ?? (ctx?.commands as any)[prop]\n\t},\n})\n\nexport const page = new Proxy<BrowserPage>(\n\t{\n\t\tgetByAltText,\n\t\tgetByRole,\n\t\tgetByTestId,\n\t\tgetByText,\n\t\tgetByTitle,\n\t\tgetByPlaceholder: getByPlaceholderText,\n\t\tgetByLabelText,\n\t} as any,\n\t{\n\t\tget(target, prop) {\n\t\t\treturn ((target as any)[prop] ?? ctx?.page)\n\t\t\t\t? (ctx?.page as any)[prop]\n\t\t\t\t: () => {\n\t\t\t\t\t\tif (prop === 'imageSnapshot') {\n\t\t\t\t\t\t\treturn { type: imageSnapshotStubSymbol }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.info(`\\`page.${prop.toString()}\\` does not exist when running in browser`)\n\t\t\t\t\t}\n\t\t},\n\t},\n)\n\nexport const server = new Proxy<{\n\t/**\n\t * Platform the Vitest server is running on.\n\t * The same as calling `process.platform` on the server.\n\t */\n\tplatform: Platform\n\t/**\n\t * Runtime version of the Vitest server.\n\t * The same as calling `process.version` on the server.\n\t */\n\tversion: string\n\t/**\n\t * Name of the browser provider.\n\t */\n\tprovider: string\n\t/**\n\t * Name of the current browser.\n\t */\n\tbrowser: string\n\t/**\n\t * Available commands for the browser.\n\t * @see {@link https://vitest.dev/guide/browser/commands}\n\t */\n\tcommands: BrowserCommands\n\t/**\n\t * Serialized test config.\n\t */\n\tconfig: SerializedConfig\n}>({} as any, {\n\tget(target, prop) {\n\t\treturn (target as any)[prop] ?? (ctx?.server as any)[prop]\n\t},\n})\n","import { imageSnapshotSymbol } from './constants.js'\nimport type { ImageSnapshot } from './types.js'\n\nexport function isImageSnapshot(subject: any): subject is ImageSnapshot {\n\treturn !!subject && subject.type === imageSnapshotSymbol\n}\n\nexport function assertImageSnapshot(subject: any): asserts subject is ImageSnapshot {\n\tif (!isImageSnapshot(subject)) {\n\t\tthrow new Error('Expected subject to be an image snapshot')\n\t}\n}\n\nexport function toSnapshotId(taskName: string) {\n\treturn `${taskName.replace(/[^a-z0-9]/gi, '-').toLowerCase()}`\n}\n","export const createImageResizer =\n\t({ width, height }: { width: number; height: number }) =>\n\t(image: ImageData) => {\n\t\tif (image.width === width && image.height === height) {\n\t\t\treturn image\n\t\t}\n\t\tconst inArea = (x: number, y: number) => y <= image.height && x <= image.width\n\t\tconst result = new ImageData(width, height, { colorSpace: image.colorSpace })\n\n\t\tfor (let y = 0; y < height; y++) {\n\t\t\tfor (let x = 0; x < width; x++) {\n\t\t\t\tconst idx = (width * y + x) << 2\n\t\t\t\tif (inArea(x, y)) {\n\t\t\t\t\tconst old = (image.width * y + x) << 2\n\t\t\t\t\tresult.data[idx] = image.data[old]\n\t\t\t\t\tresult.data[idx + 1] = image.data[old + 1]\n\t\t\t\t\tresult.data[idx + 2] = image.data[old + 2]\n\t\t\t\t\tresult.data[idx + 3] = image.data[old + 3]\n\t\t\t\t} else {\n\t\t\t\t\tresult.data[idx] = 0\n\t\t\t\t\tresult.data[idx + 1] = 0\n\t\t\t\t\tresult.data[idx + 2] = 0\n\t\t\t\t\tresult.data[idx + 3] = 64\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n// slower\nexport const createImageResizer2 =\n\t({ width, height }: { width: number; height: number }) =>\n\t(image: ImageData) => {\n\t\tif (image.width === width && image.height === height) {\n\t\t\treturn image\n\t\t}\n\t\tconst inArea = (x: number, y: number) => y <= image.height && x <= image.width\n\t\tconst result = new ImageData(width, height, { colorSpace: image.colorSpace })\n\n\t\tconst copyBytes = image.width * 4\n\t\tfor (let y = 0; y < height; y++) {\n\t\t\tresult.data.set(image.data.slice(y * image.width, copyBytes), y * width * 4)\n\t\t\tfor (let x = image.width; x < width; x++) {\n\t\t\t\tconst idx = (width * y + x) << 2\n\t\t\t\tif (!inArea(x, y)) {\n\t\t\t\t\tresult.data[idx] = 0\n\t\t\t\t\tresult.data[idx + 1] = 0\n\t\t\t\t\tresult.data[idx + 2] = 0\n\t\t\t\t\tresult.data[idx + 3] = 64\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n","import type { AsyncExpectationResult } from '@vitest/expect'\nimport dedent from 'dedent'\nimport pixelmatch, { type PixelmatchOptions } from 'pixelmatch'\nimport { imageSnapshotStubSymbol } from './@vitest/browser/constants.js'\nimport { commands, server } from './@vitest/browser/context.js'\nimport { assertImageSnapshot, isImageSnapshot } from './@vitest/browser/image_snapshot.logic.js'\nimport { toDataURL, toImageData } from './image_data.js'\nimport { createImageResizer } from './image_resizer.js'\nimport { state } from './state.js'\n\nexport interface ImageSnapshotMatcher {\n\ttoMatchImageSnapshot(options?: MatchImageSnapshotOptions): Promise<void>\n}\n\nexport type MatchImageSnapshotOptions = {\n\t/**\n\t * Custom options passed to 'pixelmatch'\n\t */\n\tdiffOptions?: PixelmatchOptions | undefined\n\t/**\n\t * Failure threshold should measure in `pixel` or `percent`.\n\t *\n\t * Default is `pixel`.\n\t */\n\tfailureThresholdType?: 'pixel' | 'percent' | undefined\n\tfailureThreshold?: number | undefined\n}\n\nexport async function toMatchImageSnapshot(\n\tactual: any,\n\toptions?: MatchImageSnapshotOptions | undefined,\n): AsyncExpectationResult {\n\tconst subject = await actual\n\tif (subject?.type === imageSnapshotStubSymbol) {\n\t\treturn success\n\t}\n\tif (!isImageSnapshot(subject)) {\n\t\tif (subject?.path && subject?.base64) {\n\t\t\treturn {\n\t\t\t\tpass: false,\n\t\t\t\tactual: subject,\n\t\t\t\tmessage: () =>\n\t\t\t\t\t'`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?',\n\t\t\t}\n\t\t}\n\n\t\tif (typeof subject !== 'object') {\n\t\t\treturn {\n\t\t\t\tpass: false,\n\t\t\t\tactual: subject,\n\t\t\t\tmessage: () =>\n\t\t\t\t\t`\\`toMatchImageSnapshot()\\` expects the subject to be an element, locator, or result of \\`page.imageSnapshot()\\`, but got: \\`${subject}\\``,\n\t\t\t}\n\t\t}\n\t\t// subject = await page.imageSnapshot({ element: actual })\n\t}\n\tassertImageSnapshot(subject)\n\tconst baseline = await tryReadSnapshot(subject.baselinePath)\n\tif (!baseline) {\n\t\tawait commands.copyFile(subject.resultPath, subject.baselinePath)\n\t\treturn success\n\t}\n\n\tconst originalImage = await toImageData(baseline)\n\tconst [resultImage, baselineImage] = alignImagesToSameSize(subject.image, originalImage)\n\n\tconst { pass, diffAmount, diffImage } = compareImage(baselineImage, resultImage, options)\n\tif (!pass) {\n\t\tif (server.config.snapshotOptions.updateSnapshot === 'all') {\n\t\t\tawait writeSnapshot(`${subject.baselinePath}`, resultImage)\n\t\t\treturn success\n\t\t}\n\t\tawait writeSnapshot(`${subject.diffPath}`, diffImage)\n\t\treturn {\n\t\t\tpass: false,\n\t\t\tmessage: () =>\n\t\t\t\tdedent`Snapshot \\`${state.taskName}\\` mismatched\n\n\t\t\t${\n\t\t\t\toptions?.failureThreshold\n\t\t\t\t\t? options?.failureThresholdType === 'percent'\n\t\t\t\t\t\t? `Expected image to match within ${options.failureThreshold}% but was differ by ${diffAmount}%.`\n\t\t\t\t\t\t: `Expected image to match within ${options.failureThreshold} pixels but was differ by ${diffAmount} pixels.`\n\t\t\t\t\t: `Expected image to match but was differ by ${options?.failureThresholdType === 'percent' ? `${diffAmount}%` : `${diffAmount} pixels`}.`\n\t\t\t}\n\n\t\t\tExpected: '${subject.baselinePath}'\n\t\t\tActual: '${subject.resultPath}'\n\t\t\tDifference: '${subject.diffPath}'`,\n\t\t}\n\t}\n\treturn success\n}\n\nconst success = {\n\tpass: true,\n\tmessage: () => '',\n}\n\nfunction tryReadSnapshot(path: string): Promise<string | undefined> {\n\treturn commands.readFile(path, { encoding: 'base64' }).catch(() => undefined)\n}\nasync function writeSnapshot(path: string, image: ImageData) {\n\tconst content = (await toDataURL(image)).split(',')[1]!\n\treturn commands.writeFile(path, content, 'base64url')\n}\n\nfunction alignImagesToSameSize(image1: ImageData, image2: ImageData): [image1: ImageData, image2: ImageData] {\n\tif (isSameSize(image1, image2)) {\n\t\treturn [image1, image2]\n\t}\n\tconst size = getMaxSize(image1, image2)\n\tconst resize = createImageResizer(size)\n\treturn [resize(image1), resize(image2)]\n}\n\nfunction getMaxSize(image1: ImageData, image2: ImageData) {\n\tconst width = Math.max(image1.width, image2.width)\n\tconst height = Math.max(image1.height, image2.height)\n\treturn { width, height }\n}\n\nfunction isSameSize(image1: ImageData, image2: ImageData) {\n\treturn image1.width === image2.width && image1.height === image2.height\n}\n\nfunction compareImage(\n\tbaselineImage: ImageData,\n\tresultImage: ImageData,\n\t{ failureThreshold = 0, failureThresholdType = 'pixel', diffOptions }: MatchImageSnapshotOptions = {},\n) {\n\tconst { width, height } = resultImage\n\tconst diffImage = new ImageData(width, height)\n\n\tconst pixelDiff = pixelmatch(resultImage.data, baselineImage.data, diffImage.data, width, height, diffOptions)\n\tconst diffAmount = toThresholdUnit({ failureThresholdType, width, height }, pixelDiff)\n\n\treturn {\n\t\tpass: diffAmount <= failureThreshold,\n\t\tdiffAmount,\n\t\tdiffImage,\n\t}\n}\n\nfunction toThresholdUnit(\n\t{ failureThresholdType, width, height }: { failureThresholdType: 'pixel' | 'percent'; width: number; height: number },\n\tpixelDiff: number,\n): number {\n\tswitch (failureThresholdType) {\n\t\tcase 'pixel':\n\t\t\treturn pixelDiff\n\t\tcase 'percent':\n\t\t\treturn (pixelDiff / (width * height)) * 100\n\t\tdefault:\n\t\t\tthrow new Error(`Invalid failureThresholdType: ${failureThresholdType}`)\n\t}\n}\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,10 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export { cdp, commands, page, server, toMatchImageSnapshot } from './chunk-4K5KNZ64.js';
|
|
2
|
+
|
|
3
|
+
// src/param.ts
|
|
4
|
+
function defineSnapshotParam(snapshot) {
|
|
5
|
+
return { snapshot };
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export { defineSnapshotParam };
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
2
10
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/param.ts"],"names":[
|
|
1
|
+
{"version":3,"sources":["../src/param.ts"],"names":[],"mappings":";;;AAEO,SAAS,oBAAoB,QAAqC,EAAA;AACxE,EAAA,OAAO,EAAE,QAAS,EAAA;AACnB","file":"index.js","sourcesContent":["import type { MatchImageSnapshotOptions } from './expect.to_match_image_snapshot'\n\nexport function defineSnapshotParam(snapshot: MatchImageSnapshotOptions) {\n\treturn { snapshot }\n}\n"]}
|
package/dist/vitest-plugin.js
CHANGED
|
@@ -1,2 +1,63 @@
|
|
|
1
|
-
import {copyFile
|
|
1
|
+
import { copyFile as copyFile$1, stat } from 'node:fs/promises';
|
|
2
|
+
import { mkdirp } from 'mkdirp';
|
|
3
|
+
import { join, dirname } from 'pathe';
|
|
4
|
+
import ci from 'is-ci';
|
|
5
|
+
import { rimraf } from 'rimraf';
|
|
6
|
+
|
|
7
|
+
// src/vitest-plugin/commands/copy_file.ts
|
|
8
|
+
var copyFile = async ({ testPath, provider }, src, dest) => {
|
|
9
|
+
if (provider.name === "playwright") {
|
|
10
|
+
const destPath = join(dirname(testPath), dest);
|
|
11
|
+
const destDir = dirname(destPath);
|
|
12
|
+
await mkdirp(destDir);
|
|
13
|
+
return copyFile$1(join(dirname(testPath), src), destPath);
|
|
14
|
+
}
|
|
15
|
+
throw new Error(`provider ${provider.name} is not supported`);
|
|
16
|
+
};
|
|
17
|
+
var existDir = async ({ testPath, provider }, path) => {
|
|
18
|
+
if (provider.name === "playwright") {
|
|
19
|
+
return stat(join(dirname(testPath), path)).then((s) => s.isDirectory()).catch(() => false);
|
|
20
|
+
}
|
|
21
|
+
throw new Error(`provider ${provider.name} is not supported`);
|
|
22
|
+
};
|
|
23
|
+
var existFile = async ({ testPath }, path) => {
|
|
24
|
+
return stat(join(dirname(testPath), path)).then((s) => s.isFile()).catch(() => false);
|
|
25
|
+
};
|
|
26
|
+
var getSnapshotPlatform = async () => {
|
|
27
|
+
return ci ? process.platform : "local";
|
|
28
|
+
};
|
|
29
|
+
var isCI = async () => ci;
|
|
30
|
+
var rmDir = async ({ testPath, provider }, path) => {
|
|
31
|
+
if (provider.name === "playwright") {
|
|
32
|
+
return rimraf(join(dirname(testPath), path));
|
|
33
|
+
}
|
|
34
|
+
throw new Error(`provider ${provider.name} is not supported`);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/vitest-plugin.ts
|
|
38
|
+
function storybookVis() {
|
|
39
|
+
return {
|
|
40
|
+
name: "vitest:storybook-addon-vis",
|
|
41
|
+
config() {
|
|
42
|
+
return {
|
|
43
|
+
test: {
|
|
44
|
+
browser: {
|
|
45
|
+
name: "chromium",
|
|
46
|
+
commands: {
|
|
47
|
+
existDir,
|
|
48
|
+
existFile,
|
|
49
|
+
copyFile,
|
|
50
|
+
rmDir,
|
|
51
|
+
isCI,
|
|
52
|
+
getSnapshotPlatform
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export { storybookVis };
|
|
62
|
+
//# sourceMappingURL=vitest-plugin.js.map
|
|
2
63
|
//# sourceMappingURL=vitest-plugin.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/vitest-plugin/commands/copy_file.ts","../src/vitest-plugin/commands/exist_dir.ts","../src/vitest-plugin/commands/exist_file.ts","../src/vitest-plugin/commands/get_snapshot_platform.ts","../src/vitest-plugin/commands/is_ci.ts","../src/vitest-plugin/commands/rm_dir.ts","../src/vitest-plugin.ts"],"names":["
|
|
1
|
+
{"version":3,"sources":["../src/vitest-plugin/commands/copy_file.ts","../src/vitest-plugin/commands/exist_dir.ts","../src/vitest-plugin/commands/exist_file.ts","../src/vitest-plugin/comm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,CAAC,MAAM,CAAE,CAAA,MAAA,EAAQ,CACtB,CAAA,KAAA,CAAM,MAAM,KAAK,CAAA;AACpB,CAAA;ACDO,IAAM,sBAAsB,YAAY;AAC9C,EAAO,OAAA,EAAA,GAAK,QAAQ,QAAW,GAAA,OAAA;AAChC,CAAA;ACPO,IAAM,OAAO,YAAYE,EAAAA;ACEzB,IAAM,QAAwC,OAAO,EAAE,QAAU,EAAA,QAAA,IAAY,IAAS,KAAA;AAC5F,EAAI,IAAA,QAAA,CAAS,SAAS,YAAc,EAAA;AACnC,IAAA,OAAO,OAAOH,IAAKC,CAAAA,OAAAA,CAAQ,QAAQ,CAAA,EAAG,IAAI,CAAC,CAAA;AAAA;AAG5C,EAAA,MAAM,IAAI,KAAA,CAAM,CAAY,SAAA,EAAA,QAAA,CAAS,IAAI,CAAmB,iBAAA,CAAA,CAAA;AAC7D,CAAA;;;ACLO,SAAS,YAAe,GAAA;AAC9B,EAAO,OAAA;AAAA,IACN,IAAM,EAAA,4BAAA;AAAA,IACN,MAAS,GAAA;AACR,MAAO,OAAA;AAAA,QACN,IAAM,EAAA;AAAA,UACL,OAAS,EAAA;AAAA,YACR,IAAM,EAAA,UAAA;AAAA,YACN,QAAU,EAAA;AAAA,cACT,QAAA;AAAA,cACA,SAAA;AAAA,cACA,QAAA;AAAA,cACA,KAAA;AAAA,cACA,IAAA;AAAA,cACA;AAAA;AACD;AACD;AACD,OACD;AAAA;AACD,GACD;AACD","file":"vitest-plugin.js","sourcesContent":["import { copyFile as copyFileFs } from 'node:fs/promises'\nimport { mkdirp } from 'mkdirp'\nimport { dirname, join } from 'pathe'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport interface CopyFileCommand {\n\tcopyFile(src: string, dest: string): Promise<void>\n}\n\nexport const copyFile: BrowserCommand<[src: string, dest: string]> = async ({ testPath, provider }, src, dest) => {\n\tif (provider.name === 'playwright') {\n\t\tconst destPath = join(dirname(testPath), dest)\n\t\tconst destDir = dirname(destPath)\n\t\tawait mkdirp(destDir)\n\t\treturn copyFileFs(join(dirname(testPath), src), destPath)\n\t}\n\n\tthrow new Error(`provider ${provider.name} is not supported`)\n}\n","import { stat } from 'node:fs/promises'\nimport { dirname, join } from 'pathe'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport interface ExistDirCommand {\n\texistDir: (path: string) => Promise<boolean>\n}\n\nexport const existDir: BrowserCommand<[path: string]> = async ({ testPath, provider }, path) => {\n\tif (provider.name === 'playwright') {\n\t\treturn stat(join(dirname(testPath), path))\n\t\t\t.then((s) => s.isDirectory())\n\t\t\t.catch(() => false)\n\t}\n\n\tthrow new Error(`provider ${provider.name} is not supported`)\n}\n","import { stat } from 'node:fs/promises'\nimport { dirname, join } from 'pathe'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport interface ExistFileCommand {\n\texistFile: (path: string) => Promise<boolean>\n}\n\nexport const existFile: BrowserCommand<[path: string]> = async ({ testPath }, path) => {\n\treturn stat(join(dirname(testPath), path))\n\t\t.then((s) => s.isFile())\n\t\t.catch(() => false)\n}\n","import ci from 'is-ci'\n\nexport interface GetSnapshotPlatformCommand {\n\t/**\n\t * Get the platform id of the snapshot `{platform}[-ci]`.\n\t *\n\t * This is useful to control where the snapshot is stored.\n\t */\n\tgetSnapshotPlatform: () => Promise<string>\n}\n\nexport const getSnapshotPlatform = async () => {\n\treturn ci ? process.platform : 'local'\n}\n","import ci from 'is-ci'\n\nexport interface IsCICommand {\n\tisCI: () => Promise<boolean>\n}\n\nexport const isCI = async () => ci\n","import { dirname, join } from 'pathe'\nimport { rimraf } from 'rimraf'\nimport type { BrowserCommand } from 'vitest/node'\n\nexport interface RmDirCommand {\n\trmDir: (path: string) => Promise<void>\n}\n\nexport const rmDir: BrowserCommand<[path: string]> = async ({ testPath, provider }, path) => {\n\tif (provider.name === 'playwright') {\n\t\treturn rimraf(join(dirname(testPath), path))\n\t}\n\n\tthrow new Error(`provider ${provider.name} is not supported`)\n}\n","import type { Plugin } from 'vitest/config'\nimport './augment.js'\nimport { copyFile } from './vitest-plugin/commands/copy_file.js'\nimport { existDir } from './vitest-plugin/commands/exist_dir.js'\nimport { existFile } from './vitest-plugin/commands/exist_file.js'\nimport { getSnapshotPlatform } from './vitest-plugin/commands/get_snapshot_platform.js'\nimport { isCI } from './vitest-plugin/commands/is_ci.js'\nimport { rmDir } from './vitest-plugin/commands/rm_dir.js'\n\nexport function storybookVis() {\n\treturn {\n\t\tname: 'vitest:storybook-addon-vis',\n\t\tconfig() {\n\t\t\treturn {\n\t\t\t\ttest: {\n\t\t\t\t\tbrowser: {\n\t\t\t\t\t\tname: 'chromium',\n\t\t\t\t\t\tcommands: {\n\t\t\t\t\t\t\texistDir,\n\t\t\t\t\t\t\texistFile,\n\t\t\t\t\t\t\tcopyFile,\n\t\t\t\t\t\t\trmDir,\n\t\t\t\t\t\t\tisCI,\n\t\t\t\t\t\t\tgetSnapshotPlatform,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t} satisfies Plugin\n}\n"]}
|
package/dist/vitest-setup.js
CHANGED
|
@@ -1,2 +1,39 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { state, commands, toSnapshotId } from './chunk-4K5KNZ64.js';
|
|
2
|
+
export { cdp, commands, page, server, toMatchImageSnapshot } from './chunk-4K5KNZ64.js';
|
|
3
|
+
import { basename, join, dirname, relative } from 'pathe';
|
|
4
|
+
|
|
5
|
+
// src/tags.ts
|
|
6
|
+
function shouldTakeSnapshot(ctx) {
|
|
7
|
+
if (!ctx.story?.tags) return false;
|
|
8
|
+
return ctx.story.tags.lastIndexOf("!snapshot") < ctx.story.tags.lastIndexOf("snapshot");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// src/vitest-setup.ts
|
|
12
|
+
async function configureSnapshotBeforeAll(suite, options) {
|
|
13
|
+
state.name = suite.name;
|
|
14
|
+
state.testFilepath = suite.file.filepath;
|
|
15
|
+
state.testFilename = basename(state.testFilepath);
|
|
16
|
+
state.projectDir = state.testFilepath.slice(0, -state.name.length);
|
|
17
|
+
const snapshotPath = join(
|
|
18
|
+
state.projectDir,
|
|
19
|
+
options?.snapshotPath ?? `__snapshots__/${await commands.getSnapshotPlatform()}`
|
|
20
|
+
);
|
|
21
|
+
const currentDir = dirname(state.testFilepath);
|
|
22
|
+
state.baselineDir = relative(currentDir, join(snapshotPath, state.testFilename));
|
|
23
|
+
state.resultDir = relative(currentDir, join(snapshotPath, "__results__", state.testFilename));
|
|
24
|
+
state.diffDir = relative(currentDir, join(snapshotPath, "__diff_output__", state.testFilename));
|
|
25
|
+
if (!state.snapshot[state.testFilepath]) {
|
|
26
|
+
state.snapshot[state.testFilepath] = {};
|
|
27
|
+
await commands.rmDir(state.resultDir);
|
|
28
|
+
await commands.rmDir(state.diffDir);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function configureSnapshotBeforeEach(ctx) {
|
|
32
|
+
state.taskName = ctx.task.name;
|
|
33
|
+
const id = state.id = toSnapshotId(state.taskName);
|
|
34
|
+
state.snapshot[state.testFilepath][id] = state.snapshot[state.testFilepath][id] ?? { index: 1 };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export { configureSnapshotBeforeAll, configureSnapshotBeforeEach, shouldTakeSnapshot };
|
|
38
|
+
//# sourceMappingURL=vitest-setup.js.map
|
|
2
39
|
//# sourceMappingURL=vitest-setup.js.map
|
package/dist/vitest-setup.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tags.ts","../src/vitest-setup.ts"],"names":[
|
|
1
|
+
{"version":3,"sources":["../src/tags.ts","../src/vitest-setup.ts"],"names":[],"mappings":";;;;;AAOO,SAAS,mBAAmB,GAAqC,EAAA;AACvE,EAAA,IAAI,CAAC,GAAA,CAAI,KAAO,EAAA,IAAA,EAAa,OAAA,KAAA;AAC7B,EAAO,OAAA,GAAA,CAAI,KAAM,CAAA,IAAA,CAAK,WAAY,CAAA,WAAW,IAA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AAM,OAAO,CAAA;AAAA;AAEpC;AAEO,SAAS,4BAA4B,GAOzC,EAAA;AACF,EAAM,KAAA,CAAA,QAAA,GAAW,IAAI,IAAK,CAAA,IAAA;AAC1B,EAAA,MAAM,EAAM,GAAA,KAAA,CAAM,EAAK,GAAA,YAAA,CAAa,MAAM,QAAQ,CAAA;AAClD,EAAA,KAAA,CAAM,QAAS,CAAA,KAAA,CAAM,YAAY,CAAA,CAAE,EAAE,CAAI,GAAA,KAAA,CAAM,QAAS,CAAA,KAAA,CAAM,YAAY,CAAE,CAAA,EAAE,CAAK,IAAA,EAAE,OAAO,CAAE,EAAA;AAC/F","file":"vitest-setup.js","sourcesContent":["/**\n * Determine should snapshot be taken.\n *\n * not story: false\n * no `snapshot` tag: false\n * disabled by `!snapshot` tag: false\n */\nexport function shouldTakeSnapshot(ctx: { story?: { tags: string[] } }) {\n\tif (!ctx.story?.tags) return false\n\treturn ctx.story.tags.lastIndexOf('!snapshot') < ctx.story.tags.lastIndexOf('snapshot')\n}\n","import { basename, dirname, join, relative } from 'pathe'\nimport './augment.js'\nimport { commands } from './@vitest/browser/context.js'\nimport { toSnapshotId } from './@vitest/browser/image_snapshot.logic.js'\nimport { state } from './state.js'\n\nexport * from './@vitest/browser/context.js'\nexport * from './expect.to_match_image_snapshot.js'\nexport * from './tags.js'\n\n/**\n * The project parameters for the snapshot.\n *\n * These parameters are set per project in the `.storybook/preview.ts` file.\n */\nexport type VisOptions = {\n\t/**\n\t * The snapshot folder relative to the root of the project.\n\t */\n\tsnapshotPath: string\n}\n\nexport async function configureSnapshotBeforeAll(\n\tsuite: { file: { filepath: string }; name: string },\n\toptions?: VisOptions,\n) {\n\tstate.name = suite.name\n\tstate.testFilepath = suite.file.filepath\n\tstate.testFilename = basename(state.testFilepath)\n\tstate.projectDir = state.testFilepath.slice(0, -state.name.length)\n\tconst snapshotPath = join(\n\t\tstate.projectDir,\n\t\toptions?.snapshotPath ?? `__snapshots__/${await commands.getSnapshotPlatform()}`,\n\t)\n\tconst currentDir = dirname(state.testFilepath)\n\tstate.baselineDir = relative(currentDir, join(snapshotPath, state.testFilename))\n\tstate.resultDir = relative(currentDir, join(snapshotPath, '__results__', state.testFilename))\n\tstate.diffDir = relative(currentDir, join(snapshotPath, '__diff_output__', state.testFilename))\n\n\tif (!state.snapshot[state.testFilepath]) {\n\t\tstate.snapshot[state.testFilepath] = {}\n\t\tawait commands.rmDir(state.resultDir)\n\t\tawait commands.rmDir(state.diffDir)\n\t}\n}\n\nexport function configureSnapshotBeforeEach(ctx: {\n\ttask: {\n\t\tname: string\n\t\tfile: {\n\t\t\tfilepath: string\n\t\t}\n\t}\n}) {\n\tstate.taskName = ctx.task.name\n\tconst id = (state.id = toSnapshotId(state.taskName))\n\tstate.snapshot[state.testFilepath][id] = state.snapshot[state.testFilepath][id] ?? { index: 1 }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "storybook-addon-vis",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.3",
|
|
4
4
|
"description": "Storybook Vitest Image Snapshot addon",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"image-snapshot",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"tsup": "^8.2.4",
|
|
72
72
|
"typescript": "^5.5.4",
|
|
73
73
|
"vite": "^5.3.5",
|
|
74
|
-
"zx": "^
|
|
74
|
+
"zx": "^8.0.0"
|
|
75
75
|
},
|
|
76
76
|
"peerDependencies": {
|
|
77
77
|
"@types/pixelmatch": "^5.2.6",
|
package/dist/chunk-B3UZM6KO.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import {getByAltText,getByRole,getByTestId,getByText,getByTitle,getByPlaceholderText,getByLabelText}from'@storybook/test';import {join}from'pathe';import E from'dedent';import M from'pixelmatch';var r={name:"",testFilepath:"",taskName:"",snapshot:{}};var g=Symbol.for("storybook-addon-vis/imageSnapshot"),u=Symbol.for("storybook-addon-vis/imageSnapshotStub");async function y(t){let e=r.snapshot[r.testFilepath][r.id].index,a=t?.customizeSnapshotId?`${t.customizeSnapshotId(r.id,e)}.png`:`${r.id}-${e}.png`,o=join(r.baselineDir,a);return h.existFile(o)}function f(t){return new Promise((e,a)=>{let o=new Image;o.src=`data:image/png;base64,${t}`,o.onload=()=>{let n=document.createElement("canvas");n.width=o.width,n.height=o.height;let s=n.getContext("2d");s.drawImage(o,0,0),e(s.getImageData(0,0,n.width,n.height));},o.onerror=()=>{a(new Error("Failed to load image"));};})}async function x(t){let e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d").putImageData(t,0,0),new Promise(o=>{e.toBlob(n=>{let s=new FileReader;s.onload=()=>{o(s.result);},s.readAsDataURL(n);});})}async function I(t){let e=r.snapshot[r.testFilepath][r.id].index++,a=t?.customizeSnapshotId?`${t.customizeSnapshotId(r.id,e)}.png`:`${r.id}-${e}.png`,o=join(r.baselineDir,a),n=join(r.resultDir,a),s=join(r.diffDir,a),i=await this.screenshot({base64:!0,path:n,element:t?.element,timeout:t?.timeout??3e3}),m=await f(i.base64);return {type:g,snapshotFilename:a,baselinePath:o,resultPath:n,diffPath:s,base64:i.base64,image:m}}var c;globalThis.__vitest_browser__&&import('@vitest/browser/context').then(t=>{c=t,A.extend({imageSnapshot:I,hasImageSnapshot:y});});function st(){return c?.cdp()??{}}var h=new Proxy({},{get(t,e){return t[e]??(c?.commands)[e]}}),A=new Proxy({getByAltText:getByAltText,getByRole:getByRole,getByTestId:getByTestId,getByText:getByText,getByTitle:getByTitle,getByPlaceholder:getByPlaceholderText,getByLabelText:getByLabelText},{get(t,e){return t[e]??c?.page?(c?.page)[e]:()=>{if(e==="imageSnapshot")return {type:u};console.info(`\`page.${e.toString()}\` does not exist when running in browser`);}}}),w=new Proxy({},{get(t,e){return t[e]??(c?.server)[e]}});function b(t){return !!t&&t.type===g}function P(t){if(!b(t))throw new Error("Expected subject to be an image snapshot")}function mt(t){return `${t.replace(/[^a-z0-9]/gi,"-").toLowerCase()}`}var D=({width:t,height:e})=>a=>{if(a.width===t&&a.height===e)return a;let o=(s,i)=>i<=a.height&&s<=a.width,n=new ImageData(t,e,{colorSpace:a.colorSpace});for(let s=0;s<e;s++)for(let i=0;i<t;i++){let m=t*s+i<<2;if(o(i,s)){let p=a.width*s+i<<2;n.data[m]=a.data[p],n.data[m+1]=a.data[p+1],n.data[m+2]=a.data[p+2],n.data[m+3]=a.data[p+3];}else n.data[m]=0,n.data[m+1]=0,n.data[m+2]=0,n.data[m+3]=64;}return n};async function yt(t,e){let a=await t;if(a?.type===u)return l;if(!b(a)){if(a?.path&&a?.base64)return {pass:!1,actual:a,message:()=>"`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?"};if(typeof a!="object")return {pass:!1,actual:a,message:()=>`\`toMatchImageSnapshot()\` expects the subject to be an element, locator, or result of \`page.imageSnapshot()\`, but got: \`${a}\``}}P(a);let o=await j(a.baselinePath);if(!o)return await h.copyFile(a.resultPath,a.baselinePath),l;let n=await f(o),[s,i]=k(a.image,n),{pass:m,diffAmount:p,diffImage:d}=U(i,s,e);return m?l:w.config.snapshotOptions.updateSnapshot==="all"?(await $(`${a.baselinePath}`,s),l):(await $(`${a.diffPath}`,d),{pass:!1,message:()=>E`Snapshot \`${r.taskName}\` mismatched
|
|
2
|
-
|
|
3
|
-
${e?.failureThreshold?e?.failureThresholdType==="percent"?`Expected image to match within ${e.failureThreshold}% but was differ by ${p}%.`:`Expected image to match within ${e.failureThreshold} pixels but was differ by ${p} pixels.`:`Expected image to match but was differ by ${e?.failureThresholdType==="percent"?`${p}%`:`${p} pixels`}.`}
|
|
4
|
-
|
|
5
|
-
Expected: '${a.baselinePath}'
|
|
6
|
-
Actual: '${a.resultPath}'
|
|
7
|
-
Difference: '${a.diffPath}'`})}var l={pass:!0,message:()=>""};function j(t){return h.readFile(t,{encoding:"base64"}).catch(()=>{})}async function $(t,e){let a=(await x(e)).split(",")[1];return h.writeFile(t,a,"base64url")}function k(t,e){if(_(t,e))return [t,e];let a=L(t,e),o=D(a);return [o(t),o(e)]}function L(t,e){let a=Math.max(t.width,e.width),o=Math.max(t.height,e.height);return {width:a,height:o}}function _(t,e){return t.width===e.width&&t.height===e.height}function U(t,e,{failureThreshold:a=0,failureThresholdType:o="pixel",diffOptions:n}={}){let{width:s,height:i}=e,m=new ImageData(s,i),p=M(e.data,t.data,m.data,s,i,n),d=N({failureThresholdType:o,width:s,height:i},p);return {pass:d<=a,diffAmount:d,diffImage:m}}function N({failureThresholdType:t,width:e,height:a},o){switch(t){case"pixel":return o;case"percent":return o/(e*a)*100;default:throw new Error(`Invalid failureThresholdType: ${t}`)}}export{r as a,st as b,h as c,A as d,w as e,mt as f,yt as g};//# sourceMappingURL=chunk-B3UZM6KO.js.map
|
|
8
|
-
//# sourceMappingURL=chunk-B3UZM6KO.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/state.ts","../src/@vitest/browser/constants.ts","../src/@vitest/browser/page.has_image_snapshot.ts","../src/image_data.ts","../src/@vitest/browser/page.image_snapshot.ts","../src/@vitest/browser/context.ts","../src/@vitest/browser/image_snapshot.logic.ts","../src/image_resizer.ts","../src/expect.to_match_image_snapshot.ts"],"names":["state","imageSnapshotSymbol","imageSnapshotStubSymbol","hasImageSnapshot","options","index","snapshotFilename","baselinePath","join","commands","toImageData","base64","resolve","reject","img","canvas","ctx","toDataURL","imageData","blob","reader","imageSnapshot","resultPath","diffPath","screenshot","image","m","page","cdp","target","prop","getByAltText","getByRole","getByTestId","getByText","getByTitle","getByPlaceholderText","getByLabelText","server","isImageSnapshot","subject","assertImageSnapshot","toSnapshotId","taskName","createImageResizer","width","height","inArea","x","y","result","idx","old","toMatchImageSnapshot","actual","success","baseline","tryReadSnapshot","originalImage","resultImage","baselineImage","alignImagesToSameSize","pass","diffAmount","diffImage","compareImage","writeSnapshot","dedent","path","content","image1","image2","isSameSize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EACvGf,CAAakB,CAAAA,CAAAA,CAAgB,CAAE,oBAAA,CAAAJ,CAAsB,CAAA,KAAA,CAAAhC,CAAO,CAAA,MAAA,CAAAC,CAAO,CAAA,CAAGiC,CAAS,CAAA,CAErF,OAAO,CACN,KAAMhB,CAAca,EAAAA,CAAAA,CACpB,UAAAb,CAAAA,CAAAA,CACA,SAAAC,CAAAA,CACD,CACD,CAEA,SAASiB,CAAAA,CACR,CAAE,oBAAA,CAAAJ,CAAsB,CAAA,KAAA,CAAAhC,EAAO,MAAAC,CAAAA,CAAO,CACtCiC,CAAAA,CAAAA,CACS,CACT,OAAQF,CAAsB,EAC7B,IAAK,OAAA,CACJ,OAAOE,CAAAA,CACR,IAAK,SAAA,CACJ,OAAQA,CAAalC,EAAAA,CAAAA,CAAQC,CAAW,CAAA,CAAA,GAAA,CACzC,QACC,MAAM,IAAI,KAAA,CAAM,CAAiC+B,8BAAAA,EAAAA,CAAoB,CAAE,CAAA,CACzE,CACD","file":"chunk-B3UZM6KO.js","sourcesContent":["export const state = {\n\tname: '',\n\ttestFilepath: '',\n\ttaskName: '',\n\tsnapshot: {},\n} as {\n\tid: string\n\tname: string\n\ttestFilepath: string\n\ttestFilename: string\n\tprojectDir: string\n\tbaselineDir: string\n\tresultDir: string\n\tdiffDir: string\n\ttaskName: string\n\tsnapshot: Record<string, Record<string, { index: number }>>\n}\n","export const imageSnapshotSymbol = Symbol.for('storybook-addon-vis/imageSnapshot')\n\nexport const imageSnapshotStubSymbol = Symbol.for('storybook-addon-vis/imageSnapshotStub')\n","import type { BrowserPage } from '@vitest/browser/context'\nimport { join } from 'pathe'\nimport { state } from '../../state'\nimport { commands } from './context'\nimport type { CustomizeSnapshotIdOptions } from './types'\n\nexport interface HasImageSnapshotAction {\n\thasImageSnapshot(this: BrowserPage, options?: CustomizeSnapshotIdOptions | undefined): Promise<boolean>\n}\n\n/**\n * Check if the snapshot image exists.\n */\nexport async function hasImageSnapshot(this: BrowserPage, options?: CustomizeSnapshotIdOptions | undefined) {\n\tconst index = state.snapshot[state.testFilepath][state.id]!.index\n\tconst snapshotFilename = options?.customizeSnapshotId\n\t\t? `${options.customizeSnapshotId(state.id, index)}.png`\n\t\t: `${state.id}-${index}.png`\n\tconst baselinePath = join(state.baselineDir, snapshotFilename)\n\treturn commands.existFile(baselinePath)\n}\n","export function toImageData(base64: string) {\n\treturn new Promise<ImageData>((resolve, reject) => {\n\t\tconst img = new Image()\n\t\timg.src = `data:image/png;base64,${base64}`\n\n\t\timg.onload = () => {\n\t\t\tconst canvas = document.createElement('canvas')\n\t\t\tcanvas.width = img.width\n\t\t\tcanvas.height = img.height\n\t\t\tconst ctx = canvas.getContext('2d')!\n\t\t\tctx.drawImage(img, 0, 0)\n\t\t\tresolve(ctx.getImageData(0, 0, canvas.width, canvas.height))\n\t\t}\n\n\t\timg.onerror = () => {\n\t\t\treject(new Error('Failed to load image'))\n\t\t}\n\t})\n}\n\nexport async function toDataURL(imageData: ImageData) {\n\tconst canvas = document.createElement('canvas')\n\tcanvas.width = imageData.width\n\tcanvas.height = imageData.height\n\tconst ctx = canvas.getContext('2d')!\n\tctx.putImageData(imageData, 0, 0)\n\treturn new Promise<string>((resolve) => {\n\t\tcanvas.toBlob((blob) => {\n\t\t\tconst reader = new FileReader()\n\t\t\treader.onload = () => {\n\t\t\t\tresolve(reader.result as string)\n\t\t\t}\n\t\t\treader.readAsDataURL(blob!)\n\t\t})\n\t})\n}\n","import type { BrowserPage } from '@vitest/browser/context'\nimport { join } from 'pathe'\nimport { toImageData } from '../../image_data.js'\nimport { state } from '../../state.js'\nimport { imageSnapshotSymbol } from './constants.js'\nimport type { ImageSnapshot, ImageSnapshotOptions } from './types.js'\n\nexport interface ImageSnapshotAction {\n\timageSnapshot(this: BrowserPage, options?: ImageSnapshotOptions | undefined): Promise<ImageSnapshot>\n}\n\nexport async function imageSnapshot(\n\tthis: BrowserPage,\n\toptions?: ImageSnapshotOptions | undefined,\n): Promise<ImageSnapshot> {\n\tconst index = state.snapshot[state.testFilepath][state.id]!.index++\n\tconst snapshotFilename = options?.customizeSnapshotId\n\t\t? `${options.customizeSnapshotId(state.id, index)}.png`\n\t\t: `${state.id}-${index}.png`\n\tconst baselinePath = join(state.baselineDir, snapshotFilename)\n\tconst resultPath = join(state.resultDir, snapshotFilename)\n\tconst diffPath = join(state.diffDir, snapshotFilename)\n\tconst screenshot = await this.screenshot({\n\t\tbase64: true,\n\t\tpath: resultPath,\n\t\telement: options?.element,\n\t\ttimeout: options?.timeout ?? 3000,\n\t})\n\tconst image = await toImageData(screenshot.base64)\n\n\treturn {\n\t\ttype: imageSnapshotSymbol,\n\t\tsnapshotFilename,\n\t\tbaselinePath,\n\t\tresultPath,\n\t\tdiffPath,\n\t\tbase64: screenshot.base64,\n\t\timage,\n\t}\n}\n","import {\n\tgetByAltText,\n\tgetByLabelText,\n\tgetByPlaceholderText,\n\tgetByRole,\n\tgetByTestId,\n\tgetByText,\n\tgetByTitle,\n} from '@storybook/test'\nimport type { BrowserCommands, BrowserPage, CDPSession, Platform } from '@vitest/browser/context'\nimport type { SerializedConfig } from 'vitest'\nimport { imageSnapshotStubSymbol } from './constants'\nimport { hasImageSnapshot } from './page.has_image_snapshot'\nimport { imageSnapshot } from './page.image_snapshot'\n\nlet ctx: Awaited<typeof import('@vitest/browser/context')>\n\nif ((globalThis as any).__vitest_browser__) {\n\timport('@vitest/browser/context').then((m) => {\n\t\tctx = m\n\t\tpage.extend({ imageSnapshot, hasImageSnapshot })\n\t})\n}\n\n// TODO: stub the functions within the `CDPSession`\n// when we better understands the use cases\nexport function cdp(): CDPSession {\n\treturn ctx?.cdp() ?? ({} as any)\n}\n\nexport const commands = new Proxy<BrowserCommands>({} as any, {\n\tget(target, prop) {\n\t\treturn (target as any)[prop] ?? (ctx?.commands as any)[prop]\n\t},\n})\n\nexport const page = new Proxy<BrowserPage>(\n\t{\n\t\tgetByAltText,\n\t\tgetByRole,\n\t\tgetByTestId,\n\t\tgetByText,\n\t\tgetByTitle,\n\t\tgetByPlaceholder: getByPlaceholderText,\n\t\tgetByLabelText,\n\t} as any,\n\t{\n\t\tget(target, prop) {\n\t\t\treturn ((target as any)[prop] ?? ctx?.page)\n\t\t\t\t? (ctx?.page as any)[prop]\n\t\t\t\t: () => {\n\t\t\t\t\t\tif (prop === 'imageSnapshot') {\n\t\t\t\t\t\t\treturn { type: imageSnapshotStubSymbol }\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconsole.info(`\\`page.${prop.toString()}\\` does not exist when running in browser`)\n\t\t\t\t\t}\n\t\t},\n\t},\n)\n\nexport const server = new Proxy<{\n\t/**\n\t * Platform the Vitest server is running on.\n\t * The same as calling `process.platform` on the server.\n\t */\n\tplatform: Platform\n\t/**\n\t * Runtime version of the Vitest server.\n\t * The same as calling `process.version` on the server.\n\t */\n\tversion: string\n\t/**\n\t * Name of the browser provider.\n\t */\n\tprovider: string\n\t/**\n\t * Name of the current browser.\n\t */\n\tbrowser: string\n\t/**\n\t * Available commands for the browser.\n\t * @see {@link https://vitest.dev/guide/browser/commands}\n\t */\n\tcommands: BrowserCommands\n\t/**\n\t * Serialized test config.\n\t */\n\tconfig: SerializedConfig\n}>({} as any, {\n\tget(target, prop) {\n\t\treturn (target as any)[prop] ?? (ctx?.server as any)[prop]\n\t},\n})\n","import { imageSnapshotSymbol } from './constants.js'\nimport type { ImageSnapshot } from './types.js'\n\nexport function isImageSnapshot(subject: any): subject is ImageSnapshot {\n\treturn !!subject && subject.type === imageSnapshotSymbol\n}\n\nexport function assertImageSnapshot(subject: any): asserts subject is ImageSnapshot {\n\tif (!isImageSnapshot(subject)) {\n\t\tthrow new Error('Expected subject to be an image snapshot')\n\t}\n}\n\nexport function toSnapshotId(taskName: string) {\n\treturn `${taskName.replace(/[^a-z0-9]/gi, '-').toLowerCase()}`\n}\n","export const createImageResizer =\n\t({ width, height }: { width: number; height: number }) =>\n\t(image: ImageData) => {\n\t\tif (image.width === width && image.height === height) {\n\t\t\treturn image\n\t\t}\n\t\tconst inArea = (x: number, y: number) => y <= image.height && x <= image.width\n\t\tconst result = new ImageData(width, height, { colorSpace: image.colorSpace })\n\n\t\tfor (let y = 0; y < height; y++) {\n\t\t\tfor (let x = 0; x < width; x++) {\n\t\t\t\tconst idx = (width * y + x) << 2\n\t\t\t\tif (inArea(x, y)) {\n\t\t\t\t\tconst old = (image.width * y + x) << 2\n\t\t\t\t\tresult.data[idx] = image.data[old]\n\t\t\t\t\tresult.data[idx + 1] = image.data[old + 1]\n\t\t\t\t\tresult.data[idx + 2] = image.data[old + 2]\n\t\t\t\t\tresult.data[idx + 3] = image.data[old + 3]\n\t\t\t\t} else {\n\t\t\t\t\tresult.data[idx] = 0\n\t\t\t\t\tresult.data[idx + 1] = 0\n\t\t\t\t\tresult.data[idx + 2] = 0\n\t\t\t\t\tresult.data[idx + 3] = 64\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result\n\t}\n\n// slower\nexport const createImageResizer2 =\n\t({ width, height }: { width: number; height: number }) =>\n\t(image: ImageData) => {\n\t\tif (image.width === width && image.height === height) {\n\t\t\treturn image\n\t\t}\n\t\tconst inArea = (x: number, y: number) => y <= image.height && x <= image.width\n\t\tconst result = new ImageData(width, height, { colorSpace: image.colorSpace })\n\n\t\tconst copyBytes = image.width * 4\n\t\tfor (let y = 0; y < height; y++) {\n\t\t\tresult.data.set(image.data.slice(y * image.width, copyBytes), y * width * 4)\n\t\t\tfor (let x = image.width; x < width; x++) {\n\t\t\t\tconst idx = (width * y + x) << 2\n\t\t\t\tif (!inArea(x, y)) {\n\t\t\t\t\tresult.data[idx] = 0\n\t\t\t\t\tresult.data[idx + 1] = 0\n\t\t\t\t\tresult.data[idx + 2] = 0\n\t\t\t\t\tresult.data[idx + 3] = 64\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n","import type { AsyncExpectationResult } from '@vitest/expect'\nimport dedent from 'dedent'\nimport pixelmatch, { type PixelmatchOptions } from 'pixelmatch'\nimport { imageSnapshotStubSymbol } from './@vitest/browser/constants.js'\nimport { commands, server } from './@vitest/browser/context.js'\nimport { assertImageSnapshot, isImageSnapshot } from './@vitest/browser/image_snapshot.logic.js'\nimport { toDataURL, toImageData } from './image_data.js'\nimport { createImageResizer } from './image_resizer.js'\nimport { state } from './state.js'\n\nexport interface ImageSnapshotMatcher {\n\ttoMatchImageSnapshot(options?: MatchImageSnapshotOptions): Promise<void>\n}\n\nexport type MatchImageSnapshotOptions = {\n\t/**\n\t * Custom options passed to 'pixelmatch'\n\t */\n\tdiffOptions?: PixelmatchOptions | undefined\n\t/**\n\t * Failure threshold should measure in `pixel` or `percent`.\n\t *\n\t * Default is `pixel`.\n\t */\n\tfailureThresholdType?: 'pixel' | 'percent' | undefined\n\tfailureThreshold?: number | undefined\n}\n\nexport async function toMatchImageSnapshot(\n\tactual: any,\n\toptions?: MatchImageSnapshotOptions | undefined,\n): AsyncExpectationResult {\n\tconst subject = await actual\n\tif (subject?.type === imageSnapshotStubSymbol) {\n\t\treturn success\n\t}\n\tif (!isImageSnapshot(subject)) {\n\t\tif (subject?.path && subject?.base64) {\n\t\t\treturn {\n\t\t\t\tpass: false,\n\t\t\t\tactual: subject,\n\t\t\t\tmessage: () =>\n\t\t\t\t\t'`toMatchImageSnapshot()` expects the subject to be the result of `page.imageSnapshot()`, but seems like you are using `page.screenshot()`?',\n\t\t\t}\n\t\t}\n\n\t\tif (typeof subject !== 'object') {\n\t\t\treturn {\n\t\t\t\tpass: false,\n\t\t\t\tactual: subject,\n\t\t\t\tmessage: () =>\n\t\t\t\t\t`\\`toMatchImageSnapshot()\\` expects the subject to be an element, locator, or result of \\`page.imageSnapshot()\\`, but got: \\`${subject}\\``,\n\t\t\t}\n\t\t}\n\t\t// subject = await page.imageSnapshot({ element: actual })\n\t}\n\tassertImageSnapshot(subject)\n\tconst baseline = await tryReadSnapshot(subject.baselinePath)\n\tif (!baseline) {\n\t\tawait commands.copyFile(subject.resultPath, subject.baselinePath)\n\t\treturn success\n\t}\n\n\tconst originalImage = await toImageData(baseline)\n\tconst [resultImage, baselineImage] = alignImagesToSameSize(subject.image, originalImage)\n\n\tconst { pass, diffAmount, diffImage } = compareImage(baselineImage, resultImage, options)\n\tif (!pass) {\n\t\tif (server.config.snapshotOptions.updateSnapshot === 'all') {\n\t\t\tawait writeSnapshot(`${subject.baselinePath}`, resultImage)\n\t\t\treturn success\n\t\t}\n\t\tawait writeSnapshot(`${subject.diffPath}`, diffImage)\n\t\treturn {\n\t\t\tpass: false,\n\t\t\tmessage: () =>\n\t\t\t\tdedent`Snapshot \\`${state.taskName}\\` mismatched\n\n\t\t\t${\n\t\t\t\toptions?.failureThreshold\n\t\t\t\t\t? options?.failureThresholdType === 'percent'\n\t\t\t\t\t\t? `Expected image to match within ${options.failureThreshold}% but was differ by ${diffAmount}%.`\n\t\t\t\t\t\t: `Expected image to match within ${options.failureThreshold} pixels but was differ by ${diffAmount} pixels.`\n\t\t\t\t\t: `Expected image to match but was differ by ${options?.failureThresholdType === 'percent' ? `${diffAmount}%` : `${diffAmount} pixels`}.`\n\t\t\t}\n\n\t\t\tExpected: '${subject.baselinePath}'\n\t\t\tActual: '${subject.resultPath}'\n\t\t\tDifference: '${subject.diffPath}'`,\n\t\t}\n\t}\n\treturn success\n}\n\nconst success = {\n\tpass: true,\n\tmessage: () => '',\n}\n\nfunction tryReadSnapshot(path: string): Promise<string | undefined> {\n\treturn commands.readFile(path, { encoding: 'base64' }).catch(() => undefined)\n}\nasync function writeSnapshot(path: string, image: ImageData) {\n\tconst content = (await toDataURL(image)).split(',')[1]!\n\treturn commands.writeFile(path, content, 'base64url')\n}\n\nfunction alignImagesToSameSize(image1: ImageData, image2: ImageData): [image1: ImageData, image2: ImageData] {\n\tif (isSameSize(image1, image2)) {\n\t\treturn [image1, image2]\n\t}\n\tconst size = getMaxSize(image1, image2)\n\tconst resize = createImageResizer(size)\n\treturn [resize(image1), resize(image2)]\n}\n\nfunction getMaxSize(image1: ImageData, image2: ImageData) {\n\tconst width = Math.max(image1.width, image2.width)\n\tconst height = Math.max(image1.height, image2.height)\n\treturn { width, height }\n}\n\nfunction isSameSize(image1: ImageData, image2: ImageData) {\n\treturn image1.width === image2.width && image1.height === image2.height\n}\n\nfunction compareImage(\n\tbaselineImage: ImageData,\n\tresultImage: ImageData,\n\t{ failureThreshold = 0, failureThresholdType = 'pixel', diffOptions }: MatchImageSnapshotOptions = {},\n) {\n\tconst { width, height } = resultImage\n\tconst diffImage = new ImageData(width, height)\n\n\tconst pixelDiff = pixelmatch(resultImage.data, baselineImage.data, diffImage.data, width, height, diffOptions)\n\tconst diffAmount = toThresholdUnit({ failureThresholdType, width, height }, pixelDiff)\n\n\treturn {\n\t\tpass: diffAmount <= failureThreshold,\n\t\tdiffAmount,\n\t\tdiffImage,\n\t}\n}\n\nfunction toThresholdUnit(\n\t{ failureThresholdType, width, height }: { failureThresholdType: 'pixel' | 'percent'; width: number; height: number },\n\tpixelDiff: number,\n): number {\n\tswitch (failureThresholdType) {\n\t\tcase 'pixel':\n\t\t\treturn pixelDiff\n\t\tcase 'percent':\n\t\t\treturn (pixelDiff / (width * height)) * 100\n\t\tdefault:\n\t\t\tthrow new Error(`Invalid failureThresholdType: ${failureThresholdType}`)\n\t}\n}\n"]}
|