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
48 changes: 43 additions & 5 deletions src/core/effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ const CSS_IMAGE_VALUE_REGEX =
/(?:url|-webkit-image-set|image-set|cross-fade)\s*\(/i;
const HIDE_IMAGES_STYLE_ID = "arap-hide-images-style";
const HIDE_IMAGES_PSEUDO_CSS = [
"[data-arap-hide-before-bg]::before { background-image: none !important; }",
"[data-arap-hide-after-bg]::after { background-image: none !important; }",
"[data-arap-hide-before-content]::before { visibility: hidden !important; }",
"[data-arap-hide-after-content]::after { visibility: hidden !important; }",
"[data-arap-hide-before-bg]:not(#arap-s1):not(#arap-s2):not(#arap-s3)::before { background-image: none !important; }",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep the specificity hack from excluding real host IDs

When a host element with a pseudo image has the ID arap-s1, arap-s2, or arap-s3, each :not() term excludes it, so the hide rule does not match even though the plugin marked the pseudo for hiding. Use a specificity bump that cannot exclude an element with one of these IDs.

Useful? React with 👍 / 👎.

"[data-arap-hide-after-bg]:not(#arap-s1):not(#arap-s2):not(#arap-s3)::after { background-image: none !important; }",
"[data-arap-hide-before-content]:not(#arap-s1):not(#arap-s2):not(#arap-s3)::before { visibility: hidden !important; }",
"[data-arap-hide-after-content]:not(#arap-s1):not(#arap-s2):not(#arap-s3)::after { visibility: hidden !important; }",
].join("\n");
type StyleableElement = HTMLElement | SVGElement;
export const MAX_HOST_ELEMENTS = 8000;
Expand Down Expand Up @@ -2575,8 +2575,10 @@ export function useBuiltinEffects(
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
let incrementalTimer: ReturnType<typeof setTimeout> | null = null;
let mediaTimer: ReturnType<typeof setTimeout> | null = null;
let largeClassTimer: ReturnType<typeof setTimeout> | null = null;
let pendingAddedNodes: HTMLElement[] = [];
const pendingMediaNodes = new Set<StyleableElement>();
const pendingLargeClassRoots = new Set<Element>();

const flushIncremental = () => {
if (pendingAddedNodes.length === 0) return;
Expand All @@ -2594,6 +2596,30 @@ export function useBuiltinEffects(
observer.takeRecords();
};

const flushLargeClassSubtrees = () => {
if (pendingLargeClassRoots.size === 0) return;
const roots = Array.from(pendingLargeClassRoots);
pendingLargeClassRoots.clear();
const collected: StyleableElement[] = [];
for (const root of roots) {
if (!document.contains(root)) continue;
if (isStyleableElement(root) && !root.matches(EXCLUDED)) {
collected.push(root);
}
for (const desc of Array.from(root.querySelectorAll("*"))) {
if (collected.length >= MAX_HOST_ELEMENTS) break;
Comment on lines +2609 to +2610

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound descendant traversal before materializing the subtree

When a class change occurs on a subtree with more than 200 descendants, Array.from(root.querySelectorAll("*")) materializes every descendant before the loop can enforce MAX_HOST_ELEMENTS; the observer has already queried this subtree to detect that it is large. On very large dynamic pages, this adds work and memory proportional to the entire subtree and can stall the main thread despite the cap. Use a traversal that stops once the limit is reached.

Useful? React with 👍 / 👎.

if (isStyleableElement(desc) && !desc.matches(EXCLUDED)) {
collected.push(desc);
}
}
if (collected.length >= MAX_HOST_ELEMENTS) break;
}
if (collected.length > 0) {
activeSession.applyMediaIncremental?.(collected);
observer.takeRecords();
}
};

const scheduleFullRefresh = (delay = 25) => {
if (refreshTimer) clearTimeout(refreshTimer);
refreshTimer = setTimeout(() => {
Expand All @@ -2608,6 +2634,7 @@ export function useBuiltinEffects(
let hasRootAttributeChange = false;
const added: HTMLElement[] = [];
const mediaNodes: StyleableElement[] = [];
const largeClassRoots: Element[] = [];

for (const record of records) {
if (record.type === "attributes") {
Expand Down Expand Up @@ -2640,14 +2667,16 @@ export function useBuiltinEffects(
)
) {
if (attrName === "class" && values.hideImages) {
mediaNodes.push(record.target);
const descendants = record.target.querySelectorAll("*");
if (descendants.length <= 200) {
mediaNodes.push(record.target);
for (const desc of Array.from(descendants)) {
if (isStyleableElement(desc) && !desc.matches(EXCLUDED)) {
mediaNodes.push(desc);
}
}
} else {
largeClassRoots.push(record.target);
}
} else if (
record.target.matches(
Expand Down Expand Up @@ -2699,6 +2728,14 @@ export function useBuiltinEffects(
if (mediaTimer) clearTimeout(mediaTimer);
mediaTimer = setTimeout(flushMediaIncremental, 16);
}

if (largeClassRoots.length > 0) {
for (const root of largeClassRoots) {
pendingLargeClassRoots.add(root);
}
if (largeClassTimer) clearTimeout(largeClassTimer);
largeClassTimer = setTimeout(flushLargeClassSubtrees, 50);
}
});

const attributeFilter = ["class", "data-theme", "dir", "lang"];
Expand Down Expand Up @@ -2786,6 +2823,7 @@ export function useBuiltinEffects(
if (refreshTimer) clearTimeout(refreshTimer);
if (incrementalTimer) clearTimeout(incrementalTimer);
if (mediaTimer) clearTimeout(mediaTimer);
if (largeClassTimer) clearTimeout(largeClassTimer);
observer.disconnect();
for (const cleanup of fontCleanups) cleanup();
window.removeEventListener("resize", resize);
Expand Down
2 changes: 1 addition & 1 deletion src/core/profiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export function mapProfileSettingsToFeatures(
}

if (settings.hideDecorativeImages !== undefined) {
features.hideImages = settings.hideDecorativeImages;
features.hideImages = settings.hideDecorativeImages ? "decorative" : false;
}

if (settings.fontFamily !== undefined) {
Expand Down
15 changes: 15 additions & 0 deletions tests/browser/widget.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2347,6 +2347,7 @@ test("Hide Images hides HTML img/picture and CSS/pseudo/root images while Hide D
.test-sheet-bg { width: 60px; height: 30px; background-image: url("${svgUrl}"); }
.test-var-bg { width: 60px; height: 30px; background-image: var(--test-hero-bg); }
.test-pseudo-after::after { content: url("${svgUrl}"); }
#test-high-spec-pseudo::before { content: ""; display: inline-block; width: 16px; height: 16px; background-image: url("${svgUrl}") !important; }
.test-dyn-bg { width: 60px; height: 30px; background-image: url("${svgUrl}"); }
`,
});
Expand Down Expand Up @@ -2380,6 +2381,10 @@ test("Hide Images hides HTML img/picture and CSS/pseudo/root images while Hide D
pseudoAfter.className = "test-pseudo-after";
pseudoAfter.textContent = "After";

const highSpecPseudo = document.createElement("div");
highSpecPseudo.id = "test-high-spec-pseudo";
highSpecPseudo.textContent = "High specificity pseudo";

const paragraphSection = document.createElement("section");
paragraphSection.id = "test-section-paragraph";
paragraphSection.setAttribute("aria-label", "Hero banner");
Expand All @@ -2403,6 +2408,7 @@ test("Hide Images hides HTML img/picture and CSS/pseudo/root images while Hide D
sheetBg,
varBg,
pseudoAfter,
highSpecPseudo,
paragraphSection,
gradientBox,
dynTarget,
Expand Down Expand Up @@ -2477,6 +2483,11 @@ test("Hide Images hides HTML img/picture and CSS/pseudo/root images while Hide D
.evaluate((el) => getComputedStyle(el, "::after").visibility);
expect(afterVis).toBe("hidden");

const highSpecBeforeBg = await page
.locator("#test-high-spec-pseudo")
.evaluate((el) => getComputedStyle(el, "::before").backgroundImage);
expect(highSpecBeforeBg).toBe("none");

// Dynamic class + inline style mutation while active
await page.evaluate((imgSrc) => {
const dyn = document.getElementById("test-dyn-target");
Expand Down Expand Up @@ -2512,6 +2523,10 @@ test("Hide Images hides HTML img/picture and CSS/pseudo/root images while Hide D
.locator("#sample-pseudo-bg")
.evaluate((el) => getComputedStyle(el, "::before").backgroundImage);
expect(restoredBeforeBg).not.toBe("none");
const restoredHighSpecBg = await page
.locator("#test-high-spec-pseudo")
.evaluate((el) => getComputedStyle(el, "::before").backgroundImage);
expect(restoredHighSpecBg).not.toBe("none");

// Hide Decorative Images preserves informative & missing-alt images while hiding decorative & CSS images
await page
Expand Down
90 changes: 90 additions & 0 deletions tests/decorativeImages.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ import {
HideImagesController,
HideDecorativeImagesController,
HideVideosController,
PresetsController,
ResetController,
isEligibleDecorativeImage,
isFunctionalOrMeaningfulImage,
mapProfileSettingsToFeatures,
} from "../src";

const injectedStyleTags: HTMLStyleElement[] = [];
Expand Down Expand Up @@ -693,4 +695,92 @@ describe("HideImagesController (default all mode) & HideDecorativeImagesControll
expect(markedWithAltInFigure.style.visibility).toBe("");
expect(meaningfulInFigure.style.visibility).toBe("");
});

it("maps hideDecorativeImages profile preference to decorative mode and preserves decorative-only behavior across preset round-trips", () => {
expect(
mapProfileSettingsToFeatures({ hideDecorativeImages: true }),
).toEqual({ hideImages: "decorative" });
expect(
mapProfileSettingsToFeatures({ hideDecorativeImages: false }),
).toEqual({ hideImages: false });

const { host } = renderFixture(
<>
<HideDecorativeImagesController label="Hide Decorative Images" />
<PresetsController />
</>,
);

const decoToggle = screen.getByRole("button", {
name: "Hide Decorative Images",
});
fireEvent.click(decoToggle);
expect(
(host.querySelector("#deco-empty-alt") as HTMLElement).style.visibility,
).toBe("hidden");
expect(
(host.querySelector("#meaningful-alt") as HTMLElement).style.visibility,
).toBe("");

// Save custom preset while Hide Decorative Images is active
fireEvent.click(screen.getByRole("button", { name: "Presets" }));
fireEvent.change(screen.getByRole("textbox", { name: "Preset name" }), {
target: { value: "Deco Only" },
});
fireEvent.click(
screen.getByRole("button", { name: "Save current preset" }),
);

// Reset All clears image hiding
fireEvent.click(screen.getByRole("button", { name: /Reset All/i }));
expect(
(host.querySelector("#deco-empty-alt") as HTMLElement).style.visibility,
).toBe("");

// Reapplying the saved preset preserves decorative-only mode
fireEvent.click(
screen.getByRole("button", { name: "Apply preset Deco Only" }),
);
expect(
(host.querySelector("#deco-empty-alt") as HTMLElement).style.visibility,
).toBe("hidden");
expect(
(host.querySelector("#meaningful-alt") as HTMLElement).style.visibility,
).toBe("");
});

it("reprocesses descendants beyond 200 nodes on dynamic class mutations", async () => {
injectTestStyle(`
.large-wrap.show-bg .late-descendant-bg {
background-image: url("oversized-subtree.png");
}
`);

const { host } = renderFixture(<HideImagesController />);
const container = document.createElement("div");
container.className = "large-wrap";
for (let i = 0; i < 220; i++) {
const child = document.createElement("div");
if (i === 215) {
child.id = "target-215";
child.className = "late-descendant-bg";
}
container.appendChild(child);
}
host.appendChild(container);

fireEvent.click(screen.getByRole("button", { name: "Hide Images" }));
const target215 = host.querySelector("#target-215") as HTMLElement;
expect(target215.style.backgroundImage).toBe("");

// Trigger class mutation on oversized >200-node container
container.classList.add("show-bg");

await waitFor(() => {
expect(target215.style.backgroundImage).toBe("none");
});

fireEvent.click(screen.getByRole("button", { name: /Reset All/i }));
expect(target215.style.backgroundImage).toBe("");
});
});