From 02f228dba708a2357ca9e530c2eaaccd709bafce Mon Sep 17 00:00:00 2001 From: Manas Ganesh Dasari Date: Thu, 3 Dec 2026 00:59:39 +0530 Subject: [PATCH] perf(cli): skip occlusion hit tests where nothing could cover the text Each layout audit now indexes the elements that could occlude text (raster tags and opaque backgrounds) into a 64px grid. occluderAt skips elementsFromPoint for a probe when no element unrelated to the text could be hit there. Elements whose hit area can reach past their box (shadow hosts, custom elements, ::before/::after, list items, SVG under an overflow:visible root) count as covering the whole page for the text they are foreign to, so those cases fall back to the full hit test. Refs #9213 --- .../cli/src/commands/layout-audit.browser.js | 88 +++++++++++++++ .../commands/layout-audit.chromium.test.ts | 100 ++++++++++++++++++ 2 files changed, 188 insertions(+) diff --git a/packages/cli/src/commands/layout-audit.browser.js b/packages/cli/src/commands/layout-audit.browser.js index 5145a3422c9..75f7045c81b 100644 --- a/packages/cli/src/commands/layout-audit.browser.js +++ b/packages/cli/src/commands/layout-audit.browser.js @@ -1659,11 +1659,97 @@ return !!allowed && !allowed.contains(element); } + // A hit test costs time in proportion to what is on screen, and most probes land where nothing + // could cover the text. Each audit files the elements `isOpaqueOccluder` could accept under the + // viewport cells their hittable box touches, so `occluderAt` skips the hit test everywhere else. + const HIT_CELL = 64; + let hitIndex = null; + const EMPTY_BOX = { left: 0, top: 0, right: -1, bottom: -1 }; + + // Null when the box can be hit outside its rect in ways not cheap to bound: shadow content, + // generated boxes and list markers, and SVG strokes past an overflow:visible root. + function hitBounds(element, range) { + const style = getComputedStyle(element); + if (element.getClientRects().length === 0 && style.display !== "contents") return EMPTY_BOX; + if (!RASTER_TAGS.has(element.tagName) && !hasOpaqueBackground(style)) return EMPTY_BOX; + if (element.shadowRoot || element.localName.includes("-") || style.display === "list-item") + return null; + if (["::before", "::after"].some((p) => getComputedStyle(element, p).content !== "none")) + return null; + if (element instanceof SVGElement) { + let svg = element; + while (svg.ownerSVGElement) svg = svg.ownerSVGElement; + return getComputedStyle(svg).overflow === "visible" + ? null + : toRect(svg.getBoundingClientRect()); + } + const box = toRect(element.getBoundingClientRect()); + for (const node of directTextNodes(element)) { + range.selectNodeContents(node); + const text = range.getBoundingClientRect(); + if (text.width === 0 && text.height === 0) continue; + box.left = Math.min(box.left, text.left); + box.top = Math.min(box.top, text.top); + box.right = Math.max(box.right, text.right); + box.bottom = Math.max(box.bottom, text.bottom); + } + return box; + } + // Every element in the document, not just the composition root: overlays on occlude too. + function buildHitIndex() { + const cols = Math.ceil(window.innerWidth / HIT_CELL); + const rows = Math.ceil(window.innerHeight / HIT_CELL); + const cells = Array.from({ length: cols * rows }, () => []); + const unbounded = []; + const range = document.createRange(); + for (const element of document.querySelectorAll("*")) { + const box = hitBounds(element, range); + if (!box) { + unbounded.push(element); + continue; + } + // One pixel of slack for subpixel edges. + const entry = { + element, + left: box.left - 1, + top: box.top - 1, + right: box.right + 1, + bottom: box.bottom + 1, + }; + const lastCol = Math.min(cols - 1, Math.floor(entry.right / HIT_CELL)); + const lastRow = Math.min(rows - 1, Math.floor(entry.bottom / HIT_CELL)); + for (let row = Math.max(0, Math.floor(entry.top / HIT_CELL)); row <= lastRow; row++) { + for (let col = Math.max(0, Math.floor(entry.left / HIT_CELL)); col <= lastCol; col++) { + cells[row * cols + col].push(entry); + } + } + } + return { cols, rows, cells, unbounded }; + } + + function mayHitForeign(element, x, y) { + if (!hitIndex) return true; + const { cols, rows, cells, unbounded } = hitIndex; + const col = Math.floor(x / HIT_CELL); + const row = Math.floor(y / HIT_CELL); + if (col < 0 || row < 0 || col >= cols || row >= rows) return true; + if (unbounded.some((other) => isForeignElement(element, other))) return true; + return cells[row * cols + col].some( + (entry) => + x >= entry.left && + x <= entry.right && + y >= entry.top && + y <= entry.bottom && + isForeignElement(element, entry.element), + ); + } + // The opaque element painted over (x, y), or null when the topmost element // there is related to the text, non-opaque, sharing a 3D context with it, or // part of a transient crossfade overlap. // fallow-ignore-next-line complexity function occluderAt(element, x, y, seenMattes) { + if (!mayHitForeign(element, x, y)) return null; // Walk the paint-ordered stack: a transparent layer on top must not mask an opaque one below it. const stack = typeof document.elementsFromPoint === "function" @@ -3054,6 +3140,7 @@ const restoreHits = restoreHitTesting(root); try { + hitIndex = buildHitIndex(); for (const element of elements) { if (!hasOwnTextCandidate(element)) continue; const clipped = clippedTextIssue(element, time, tolerance); @@ -3072,6 +3159,7 @@ const covered = canvasCoveredIssue(root, rootRect, elements, time); if (covered) issues.push(covered); } finally { + hitIndex = null; restoreHits(); } markLostSiblingWords(matteResults); diff --git a/packages/cli/src/commands/layout-audit.chromium.test.ts b/packages/cli/src/commands/layout-audit.chromium.test.ts index 39eb99e198d..facf3654199 100644 --- a/packages/cli/src/commands/layout-audit.chromium.test.ts +++ b/packages/cli/src/commands/layout-audit.chromium.test.ts @@ -662,6 +662,106 @@ describe.runIf(executablePath)("layout audit in Chromium", () => { expect((await auditCodes(stage(text + cover))).includes("text_occluded")).toBe(occluded); }); + describe("occlusion probes skipped where nothing could cover the text", () => { + async function occlusions(body: string) { + const page = await browser.newPage(); + try { + await page.setViewport({ width: 1920, height: 1080 }); + await page.setContent(`${body}`); + await page.addScriptTag({ content: script }); + return await page.evaluate(() => { + const hitTest = document.elementsFromPoint.bind(document); + let hitTests = 0; + document.elementsFromPoint = (x, y) => { + hitTests += 1; + return hitTest(x, y); + }; + const found = window + .__hyperframesLayoutAudit({ time: 1, tolerance: 2 }) + .flatMap((issue) => + issue.code === "text_occluded" && "text" in issue && "coveredFraction" in issue + ? [{ text: issue.text, coveredFraction: issue.coveredFraction }] + : [], + ); + return { found, hitTests }; + }); + } finally { + await page.close(); + } + } + + const caption = heading(300, "Caption"); + const cover = (style: string) => + `
`; + + it.each([ + { + name: "an opaque sibling", + body: stage(caption + cover("left:300px;top:250px;width:600px;height:300px")), + coveredFraction: 0.56, + }, + { + name: "a sibling moved over it by a transform", + body: stage( + caption + + cover("left:1300px;top:250px;width:600px;height:300px;transform:translateX(-1000px)"), + ), + coveredFraction: 0.56, + }, + { + name: "an overlay outside the composition root", + body: + stage(caption) + + '
', + coveredFraction: 0.56, + }, + { + name: "a shadow host whose shadow content reaches past its box", + body: + stage( + caption + + cover("left:1500px;top:900px;width:10px;height:10px").replace( + "document.querySelector(".host").attachShadow({ mode: "open" }).innerHTML = '
';`, + coveredFraction: 0.56, + }, + { + name: "a generated box painted past its owner", + body: + "" + + stage( + caption + + cover("left:1500px;top:900px;width:10px;height:10px").replace( + " { + expect((await occlusions(body)).found).toEqual([{ text: "Caption", coveredFraction }]); + }); + + it("does not report text slotted inside a shadow host that paints over it", async () => { + const host = `
${heading(0, "Caption", "position:static")}
`; + const shadow = ``; + expect((await occlusions(stage(host) + shadow)).found).toEqual([]); + }); + + it("hit-tests nothing on a page of labels that do not touch", async () => { + let labels = ""; + for (let row = 0; row < 12; row++) { + for (let col = 0; col < 12; col++) { + labels += `w${row}x${col}`; + } + } + expect(await occlusions(stage(labels))).toEqual({ found: [], hitTests: 0 }); + }); + }); + it.each([ { name: "below", color: "oklch(1 0 0 / .34)", overlap: false }, { name: "at", color: "color(display-p3 1 1 1 / .35)", overlap: true },