Skip to content
Open
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
88 changes: 88 additions & 0 deletions packages/cli/src/commands/layout-audit.browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <body> 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"
Expand Down Expand Up @@ -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);
Expand All @@ -3072,6 +3159,7 @@
const covered = canvasCoveredIssue(root, rootRect, elements, time);
if (covered) issues.push(covered);
} finally {
hitIndex = null;
restoreHits();
}
markLostSiblingWords(matteResults);
Expand Down
100 changes: 100 additions & 0 deletions packages/cli/src/commands/layout-audit.chromium.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 style="margin:0">${body}</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) =>
`<div style="position:absolute;background:#123;${style}"></div>`;

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) +
'<div style="position:fixed;left:300px;top:250px;width:600px;height:300px;background:#123"></div>',
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(
"<div",
'<div class="host"',
),
) +
`<script>document.querySelector(".host").attachShadow({ mode: "open" }).innerHTML = '<div style="position:absolute;left:-1200px;top:-650px;width:600px;height:300px;background:#123"></div>';</script>`,
coveredFraction: 0.56,
},
{
name: "a generated box painted past its owner",
body:
"<style>.owner::after{content:'';position:absolute;left:-1200px;top:-650px;width:600px;height:300px;background:#123}</style>" +
stage(
caption +
cover("left:1500px;top:900px;width:10px;height:10px").replace(
"<div",
'<div class="owner"',
),
),
coveredFraction: 0.56,
},
])("reports text under $name", async ({ body, coveredFraction }) => {
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 = `<div class="host" style="position:absolute;left:100px;top:300px;background:#123">${heading(0, "Caption", "position:static")}</div>`;
const shadow = `<script>document.querySelector(".host").attachShadow({ mode: "open" }).innerHTML = '<slot></slot><div style="position:absolute;inset:0;background:#123"></div>';</script>`;
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 += `<span style="position:absolute;left:${col * 160}px;top:${row * 90}px;font:28px Arial">w${row}x${col}</span>`;
}
}
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 },
Expand Down