Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 65 additions & 12 deletions packages/browser/src/global/stabilization/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,34 @@ export interface Plugin {
* Name of the plugin.
*/
name: string;
/**
* When `true`, the plugin is disabled unless explicitly enabled through the
* options (e.g. `{ [name]: true }`). Use it for plugins that are too
* expensive to run by default.
*/
optIn?: boolean;
/**
* Run before taking all screenshots.
*/
beforeAll?: (context: RuntimeContext) => Cleanup | undefined;
beforeAll?: (
context: RuntimeContext,
options?: unknown,
) => Cleanup | undefined;
/**
* Run before taking each screenshot (between viewport changes).
*/
beforeEach?: (context: RuntimeContext) => Cleanup | undefined;
beforeEach?: (
context: RuntimeContext,
options?: unknown,
) => Cleanup | undefined;
/**
* Wait for a condition to be met before taking a screenshot.
*/
wait?: {
/**
* Function to check if the condition is met.
*/
for: (context: RuntimeContext) => boolean;
for: (context: RuntimeContext, options?: unknown) => boolean;
/**
* Error message to display if the condition is not met.
*/
Expand All @@ -48,8 +60,28 @@ export interface RuntimeContext {
argosCSS?: string;
}

/**
* Options for the `waitForBackgroundImages` plugin.
*/
export interface WaitForBackgroundImagesOptions {
/**
* CSS selector scoping which elements are scanned for background images.
* Scoping avoids a full-document `getComputedStyle` sweep on large pages.
* @default "*"
*/
selector?: string;
}

export type PluginOptions = {
[key in PluginName]?: boolean;
[key in Exclude<PluginName, "waitForBackgroundImages">]?: boolean;
} & {
/**
* Wait for CSS background images to be loaded.
* Disabled by default. Enable with `true` to scan the whole document, or
* pass an object to scope it to a selector.
* @default false
*/
waitForBackgroundImages?: boolean | WaitForBackgroundImagesOptions;
};

export interface Context extends RuntimeContext {
Expand All @@ -59,6 +91,16 @@ export interface Context extends RuntimeContext {
const beforeAllCleanups = new Set<Cleanup>();
const beforeEachCleanups = new Set<Cleanup>();

/**
* Get the option value passed for a specific plugin.
*/
function getPluginOptions(context: Context, name: string): unknown {
if (typeof context.options === "object" && context.options) {
return (context.options as Record<string, unknown>)[name];
}
return undefined;
}

/**
* Get the list of plugins to run based on the options.
*/
Expand All @@ -67,11 +109,13 @@ function getPlugins(context: Context): Plugin[] {
if (context.options === false) {
return false;
}
if (typeof context.options === "object") {
const pluginEnabled = context.options[plugin.name];
if (pluginEnabled === false) {
return false;
}
const pluginOptions = getPluginOptions(context, plugin.name);
if ((plugin as Plugin).optIn) {
// Opt-in plugins stay disabled unless explicitly enabled.
return Boolean(pluginOptions);
}
if (pluginOptions === false) {
return false;
}
return true;
});
Expand All @@ -93,7 +137,10 @@ function getPluginByName(name: string): Plugin {
export function beforeAll(context: Context = {}) {
getPlugins(context).forEach((plugin) => {
if (plugin.beforeAll) {
const cleanup = plugin.beforeAll(context);
const cleanup = plugin.beforeAll(
context,
getPluginOptions(context, plugin.name),
);
if (cleanup) {
beforeAllCleanups.add(cleanup);
}
Expand All @@ -117,7 +164,10 @@ export function afterAll() {
export function beforeEach(context: Context = {}) {
getPlugins(context).forEach((plugin) => {
if (plugin.beforeEach) {
const cleanup = plugin.beforeEach(context);
const cleanup = plugin.beforeEach(
context,
getPluginOptions(context, plugin.name),
);
if (cleanup) {
beforeEachCleanups.add(cleanup);
}
Expand All @@ -143,7 +193,10 @@ function getStabilityState(context: Context) {

getPlugins(context).forEach((plugin) => {
if (plugin.wait) {
stabilityState[plugin.name] = plugin.wait.for(context);
stabilityState[plugin.name] = plugin.wait.for(
context,
getPluginOptions(context, plugin.name),
);
}
});

Expand Down
2 changes: 2 additions & 0 deletions packages/browser/src/global/stabilization/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { plugin as loadImageSrcset } from "./loadImageSrcset";
import { plugin as roundImageSize } from "./roundImageSize";
import { plugin as stabilizeSticky } from "./stabilizeSticky";
import { plugin as waitForAriaBusy } from "./waitForAriaBusy";
import { plugin as waitForBackgroundImages } from "./waitForBackgroundImages";
import { plugin as waitForFonts } from "./waitForFonts";
import { plugin as waitForImages } from "./waitForImages";

Expand All @@ -24,6 +25,7 @@ export const plugins = [
roundImageSize,
stabilizeSticky,
waitForAriaBusy,
waitForBackgroundImages,
waitForFonts,
waitForImages,
] satisfies Plugin[];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import type { Plugin, WaitForBackgroundImagesOptions } from "..";

/**
* Images preloaded for the current screenshot cycle.
* Populated by a single DOM scan in `beforeEach` and polled cheaply in
* `wait.for` (we only read `img.complete`, never re-scan the DOM).
*/
const preloadedImages = new Set<HTMLImageElement>();

const URL_REGEX = /url\((['"]?)([^'")]+)\1\)/g;

/**
* Extract non-data background-image URLs from a computed `background-image`
* value (which may contain several layered backgrounds and gradients).
*/
function collectUrls(
value: string | null | undefined,
urls: Set<string>,
): void {
if (!value || value === "none") {
return;
}
URL_REGEX.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = URL_REGEX.exec(value)) !== null) {
const url = match[2];
// `getComputedStyle` resolves background URLs to absolute URLs, so they can
// be assigned directly to `Image.src`. Skip inlined data URIs.
if (url && !url.startsWith("data:")) {
urls.add(url);
}
}
}

/**
* Resolve the selector scoping the scan, defaulting to the whole document.
*/
function resolveSelector(options: unknown): string {
if (options && typeof options === "object") {
const { selector } = options as WaitForBackgroundImagesOptions;
if (typeof selector === "string" && selector.trim() !== "") {
return selector;
}
}
return "*";
}

/**
* Wait for CSS background images to be loaded.
*
* There is no native load event for CSS background images, so URLs are
* discovered with `getComputedStyle` and preloaded through `Image` objects.
*
* This plugin is opt-in because the scan is resource-intensive. Enable it with
* `stabilize: { waitForBackgroundImages: true }` to scan the whole document, or
* scope it on large pages with
* `stabilize: { waitForBackgroundImages: { selector: ".hero, [data-bg]" } }`.
*
* The expensive scan runs only once per viewport in `beforeEach`; `wait.for`
* just polls the preloaded images.
*/
export const plugin = {
name: "waitForBackgroundImages" as const,
optIn: true,
beforeEach(_context, options) {
const selector = resolveSelector(options);
const urls = new Set<string>();

document.querySelectorAll(selector).forEach((element) => {
collectUrls(window.getComputedStyle(element).backgroundImage, urls);
// Pseudo-elements are a common home for decorative background images.
collectUrls(
window.getComputedStyle(element, "::before").backgroundImage,
urls,
);
collectUrls(
window.getComputedStyle(element, "::after").backgroundImage,
urls,
);
});

urls.forEach((url) => {
const img = new Image();
img.decoding = "sync";
img.src = url;
preloadedImages.add(img);
});

return () => {
preloadedImages.clear();
};
},
wait: {
for: () => {
// Intentionally only check `complete` (which is also `true` on error), so
// a failing background image (e.g. 404) does not block stabilization.
return Array.from(preloadedImages).every((img) => img.complete);
},
failureExplanation: "Some background images are still loading",
},
} satisfies Plugin;
1 change: 1 addition & 0 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export * from "./script";
export type {
PluginOptions as StabilizationPluginOptions,
Context as StabilizationContext,
WaitForBackgroundImagesOptions,
} from "./global/stabilization";
90 changes: 90 additions & 0 deletions packages/playwright/e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,96 @@ test.describe("#argosScreenshot", () => {
});
});

test.describe("with `waitForBackgroundImages`", () => {
// A 1x1 transparent PNG, served by the route below.
const PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64",
);

test("waits for background images to load before screenshotting", async ({
page,
context,
}) => {
// Gate the background image request so we control exactly when it loads.
let releaseImage = () => {};
const imageGate = new Promise<void>((resolve) => {
releaseImage = resolve;
});
let imageRequested = () => {};
const imageRequestedPromise = new Promise<void>((resolve) => {
imageRequested = resolve;
});

await context.route(/slow-background\.png/, async (route) => {
imageRequested();
await imageGate;
await route.fulfill({
status: 200,
contentType: "image/png",
body: PNG,
});
});

// `domcontentloaded` so navigation doesn't wait for the gated image.
await page.goto(url, { waitUntil: "domcontentloaded" });

let resolved = false;
const screenshotPromise = argosScreenshot(page, "background-images", {
fullPage: false,
stabilize: { waitForBackgroundImages: true },
})
.then(() => {
resolved = true;
})
.catch(() => {
// Swallow so a failure surfaces through the assertions below.
});

// The plugin must have triggered the background image request…
await imageRequestedPromise;
// …and stabilization must still be blocked on it (well past the other
// stabilizers: the 1000ms loader and the 500ms delayed fonts).
await page.waitForTimeout(2000);
expect(resolved).toBe(false);

// Once the image loads, stabilization completes.
releaseImage();
await screenshotPromise;
expect(resolved).toBe(true);
});

test("does not wait for background images by default", async ({
page,
context,
}) => {
// Gate the image and never release it: default stabilization must still
// complete, proving it does not block on background images.
let releaseImage = () => {};
const imageGate = new Promise<void>((resolve) => {
releaseImage = resolve;
});
await context.route(/slow-background\.png/, async (route) => {
await imageGate;
await route.fulfill({
status: 200,
contentType: "image/png",
body: PNG,
});
});

await page.goto(url, { waitUntil: "domcontentloaded" });

// The plugin is opt-in, so this resolves even though the image is stuck.
await argosScreenshot(page, "background-images-disabled", {
fullPage: false,
});

// Release the still-pending request to avoid leaking it.
releaseImage();
});
});

test.describe("with argosCSS", () => {
test("evaluate custom CSS", async ({ page }) => {
await argosScreenshot(page, "custom-css", {
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright/fixtures/dummy.html
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@
background-color: green;
}
}
#background-image {
width: 200px;
height: 100px;
background-image: url("slow-background.png");
background-size: cover;
}
</style>
</head>
<body>
Expand Down Expand Up @@ -127,6 +133,10 @@ <h3>Image</h3>
style="width: 100%; height: auto"
/>

<h3>Background image</h3>
<div class="hint">Hint: the background image should be loaded.</div>
<div id="background-image"></div>

<h3>Input</h3>
<div class="hint">Hint: spellcheck should be disabled</div>
<input value="an orrange carrot" autofocus />
Expand Down
Loading