Skip to content

Write HTML. Render video. Built for agents.

fix(core): the picker offers what is drawn under the pointer, not see-through layers over it (#4536)

Miguel Ángel473c86248ce2
diff --git a/packages/core/src/runtime/picker.test.ts b/packages/core/src/runtime/picker.test.ts
index 1e130cbe3f..f8a74cc743 100644
--- a/packages/core/src/runtime/picker.test.ts
+++ b/packages/core/src/runtime/picker.test.ts
@@ -42,6 +42,16 @@ function emulateHitTest(painted: () => Element[]): () => void {
Object.defineProperty(document, "elementsFromPoint", { configurable: true, value: original });
}
+// The selectors getCandidatesAtPoint(10, 10) returns while the hit test yields `stack`.
+function candidatesUnder(stack: () => Element[]): string[] {
+ const restore = emulateHitTest(stack);
+ try {
+ return (window as any).__HF_PICKER_API.getCandidatesAtPoint(10, 10).map((c: any) => c.selector);
+ } finally {
+ restore();
+ }
+}
+
function createMockPostMessage() {
return vi.fn();
}
@@ -211,16 +221,10 @@ describe("createPickerModule", () => {
document.body.innerHTML = `<div id="root" data-composition-id="intro"><div id="card">
<code id="code">tl.to()</code></div></div>`;
const at = (id: string) => document.getElementById(id)!;
- const restore = emulateHitTest(() => [at("code"), at("card"), at("root")]);
- const api = (window as any).__HF_PICKER_API;
- try {
- expect(api.getCandidatesAtPoint(10, 10).map((c: any) => c.selector)).toEqual([
- "#code",
- "#card",
- ]);
- } finally {
- restore();
- }
+ expect(candidatesUnder(() => [at("code"), at("card"), at("root")])).toEqual([
+ "#code",
+ "#card",
+ ]);
});
it("adopts the override only for the hit test, leaving the DOM and a saved outerHTML untouched", () => {
@@ -280,16 +284,10 @@ describe("createPickerModule", () => {
style="pointer-events: none"><div data-hf-inner-root="true"><h1 id="t">Hi</h1></div></div></div>`;
const at = (id: string) => document.getElementById(id)!;
const inner = document.querySelector("[data-hf-inner-root]")!;
- const restore = emulateHitTest(() => [at("t"), inner, at("ovl"), at("aroll"), at("root")]);
- const api = (window as any).__HF_PICKER_API;
- try {
- expect(api.getCandidatesAtPoint(10, 10).map((c: any) => c.selector)).toEqual([
- "#aroll",
- "#root",
- ]);
- } finally {
- restore();
- }
+ expect(candidatesUnder(() => [at("t"), inner, at("ovl"), at("aroll"), at("root")])).toEqual([
+ "#aroll",
+ "#root",
+ ]);
});
it("a section background click picks the host, and an inner root never gets a bare tag selector", () => {
@@ -387,6 +385,396 @@ describe("createPickerModule", () => {
});
});
+ describe("picks what is drawn under the pointer", () => {
+ const selectorsAt = (x = 10, y = 10) =>
+ (window as any).__HF_PICKER_API.getCandidatesAtPoint(x, y).map((c: any) => c.selector);
+ const at = (id: string) => document.getElementById(id)!;
+ const BG = "background: rgb(245, 238, 220)";
+
+ it("finds a painted background under eight see-through layers", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ const layers = Array.from({ length: 8 }, (_, i) => `l${i}`);
+ const nested = layers.reduceRight((inner, id) => `<div id="${id}">${inner}</div>`, "");
+ document.body.innerHTML = `<div id="bg" style="${BG}">${nested}</div>`;
+ const restore = emulateHitTest(() => [...[...layers].reverse().map(at), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#bg"]);
+ expect((window as any).__HF_PICKER_API.pickAtPoint(10, 10)?.selector).toBe("#bg");
+ } finally {
+ restore();
+ }
+ });
+
+ it("keeps a title and every box holding it, so a same-spot click still climbs", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="card"><h1 id="title">Hi</h1></div><div id="mask"></div>`;
+ const restore = emulateHitTest(() => [at("mask"), at("title"), at("card")]);
+ try {
+ expect(selectorsAt()).toEqual(["#title", "#card"]);
+ } finally {
+ restore();
+ }
+ });
+
+ it("drops a line whose words have not faded in and the see-through layer over it", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="scene" style="${BG}"><div id="mask"><div id="line">
+ <span id="w1" style="opacity: 0">Imagine</span> <span id="w2" style="opacity: 0">you</span>
+ </div></div></div>`;
+ const restore = emulateHitTest(() => [at("w1"), at("line"), at("mask"), at("scene")]);
+ try {
+ expect(selectorsAt()).toEqual(["#scene"]);
+ } finally {
+ restore();
+ }
+ });
+
+ // jsdom lays nothing out: each named text gets the glyph box Chromium would measure.
+ function layOut(glyphs: Record<string, [number, number, number, number]>): () => void {
+ const proto = Range.prototype as any;
+ const select = proto.selectNodeContents;
+ const placed = new WeakMap<Range, Node>();
+ proto.selectNodeContents = function (this: Range, node: Node) {
+ placed.set(this, node);
+ };
+ proto.getClientRects = function (this: Range) {
+ const box = glyphs[placed.get(this)?.nodeValue?.trim() ?? ""];
+ if (!box) return [];
+ const [left, top, width, height] = box;
+ return [{ left, top, width, height, right: left + width, bottom: top + height }];
+ };
+ return () => {
+ proto.selectNodeContents = select;
+ delete proto.getClientRects;
+ };
+ }
+
+ it("counts text across its line boxes, and not the rest of its box", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"><p id="para">One line<br>Two line</p></div>`;
+ const unlay = layOut({ "One line": [100, 100, 400, 46], "Two line": [100, 220, 380, 46] });
+ const restore = emulateHitTest(() => [at("para"), at("bg")]);
+ try {
+ expect(selectorsAt(300, 120)).toEqual(["#para", "#bg"]);
+ expect(selectorsAt(300, 183)).toEqual(["#para", "#bg"]);
+ expect(selectorsAt(300, 600)).toEqual(["#bg"]);
+ } finally {
+ restore();
+ unlay();
+ }
+ });
+
+ it("does not count a layer's text that lays out no boxes (an SVG title, fallback content)", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"><h1 id="title">Hi</h1></div>
+ <div id="layer"><span>Logo</span></div>`;
+ const unlay = layOut({ Hi: [0, 0, 100, 40] });
+ const restore = emulateHitTest(() => [at("layer"), at("title"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#title", "#bg"]);
+ } finally {
+ restore();
+ unlay();
+ }
+ });
+
+ it("keeps a box holding a drawn picture, though the box draws nothing itself", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="wrap"><img id="pic"></div><div id="mask"></div>`;
+ const restore = emulateHitTest(() => [at("mask"), at("pic"), at("wrap")]);
+ try {
+ expect(selectorsAt()).toEqual(["#pic", "#wrap"]);
+ } finally {
+ restore();
+ }
+ });
+
+ it("counts an SVG's shapes, not the SVG box around them", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"><h1 id="title">Hi</h1></div>
+ <svg id="lines"><circle id="dot" r="4"></circle></svg>`;
+ const restore = emulateHitTest(() => [at("lines"), at("title"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#title", "#bg"]);
+ } finally {
+ restore();
+ }
+ const onDot = emulateHitTest(() => [at("dot"), at("lines"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#dot", "#lines", "#bg"]);
+ } finally {
+ onDot();
+ }
+ });
+
+ it("counts a border on its band, not across the box it frames", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"></div>
+ <div id="frame" style="border: 4px solid rgb(0, 200, 120)"></div>`;
+ at("frame").getBoundingClientRect = () =>
+ ({ left: 0, top: 0, right: 100, bottom: 100, width: 100, height: 100 }) as DOMRect;
+ const restore = emulateHitTest(() => [at("frame"), at("bg")]);
+ try {
+ expect(selectorsAt(50, 50)).toEqual(["#bg"]);
+ expect(selectorsAt(2, 50)).toEqual(["#frame", "#bg"]);
+ } finally {
+ restore();
+ }
+ });
+
+ it("does not count transparent text", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"></div>
+ <div id="ghost" style="color: transparent">Hidden words</div>`;
+ const restore = emulateHitTest(() => [at("ghost"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#bg"]);
+ } finally {
+ restore();
+ }
+ });
+
+ // jsdom computes neither text strokes nor pseudo-elements: lay the named properties over its style.
+ // Keys are an element id, or an id and a pseudo-element ("icon::before").
+ function styled(byKey: Record<string, Record<string, string>>): () => void {
+ const real = window.getComputedStyle.bind(window);
+ const spy = vi.spyOn(window, "getComputedStyle").mockImplementation((el, which) => {
+ const style = real(el, which);
+ const props = byKey[`${(el as Element).id}${which ?? ""}`];
+ if (!props) return style;
+ const camel = (name: string) =>
+ name.replace(/^-/, "").replace(/-(\w)/g, (_, c) => c.toUpperCase());
+ const own = Object.fromEntries(Object.entries(props).map(([k, v]) => [camel(k), v]));
+ return new Proxy(style, {
+ get: (target, key) => {
+ if (key === "getPropertyValue")
+ return (name: string) => props[name] ?? target.getPropertyValue(name);
+ if (typeof key === "string" && key in own) return own[key];
+ const value = Reflect.get(target, key);
+ return typeof value === "function" ? value.bind(target) : value;
+ },
+ });
+ });
+ return () => spy.mockRestore();
+ }
+
+ it("counts outline text and fill-coloured text though their `color` is transparent", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"></div>
+ <div id="outline" style="color: transparent">Outline</div>
+ <div id="filled" style="color: transparent">Filled</div>`;
+ const unstyle = styled({
+ outline: {
+ "-webkit-text-stroke-width": "2px",
+ "-webkit-text-stroke-color": "rgb(255, 0, 0)",
+ },
+ filled: { "-webkit-text-fill-color": "rgb(255, 0, 0)" },
+ });
+ let restore = emulateHitTest(() => [at("outline"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#outline", "#bg"]);
+ } finally {
+ restore();
+ }
+ restore = emulateHitTest(() => [at("filled"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#filled", "#bg"]);
+ } finally {
+ restore();
+ unstyle();
+ }
+ });
+
+ it("does not count a layer's out-of-flow boxes: their text is theirs, where they are", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"><h1 id="title">Hi</h1></div>
+ <div id="captions"><p style="position: absolute">Caption words</p></div>
+ <div id="banner"><p style="position: fixed">Banner words</p></div>`;
+ const restore = emulateHitTest(() => [at("captions"), at("banner"), at("title"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#title", "#bg"]);
+ } finally {
+ restore();
+ }
+ });
+
+ it("counts the gap between two words of a long split paragraph as the paragraph's", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ const words = Array.from({ length: 250 }, (_, i) => `<span>w${i}</span>`).join(" ");
+ document.body.innerHTML = `<div id="bg" style="${BG}"><p id="para">${words}</p></div>`;
+ const boxes: Record<string, [number, number, number, number]> = {};
+ for (let i = 0; i < 250; i += 1)
+ boxes[`w${i}`] = [40 + (i % 25) * 70, 100 + Math.floor(i / 25) * 60, 60, 40];
+ const unlay = layOut(boxes);
+ const restore = emulateHitTest(() => [at("para"), at("bg")]);
+ try {
+ // Between words 230 and 231, on the tenth line.
+ expect(selectorsAt(455, 660)).toEqual(["#para", "#bg"]);
+ } finally {
+ restore();
+ unlay();
+ }
+ });
+
+ it("scales a border's band with the element", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"></div>
+ <div id="wide" style="border: 4px solid rgb(0, 200, 120)"></div>
+ <div id="tall" style="border: 4px solid rgb(0, 200, 120)"></div>`;
+ // Laid out 100px square; drawn at half width, and at half height.
+ Object.defineProperty(at("wide"), "offsetWidth", { value: 100 });
+ Object.defineProperty(at("wide"), "offsetHeight", { value: 100 });
+ at("wide").getBoundingClientRect = () =>
+ ({ left: 0, top: 0, right: 50, bottom: 100, width: 50, height: 100 }) as DOMRect;
+ Object.defineProperty(at("tall"), "offsetWidth", { value: 100 });
+ Object.defineProperty(at("tall"), "offsetHeight", { value: 100 });
+ at("tall").getBoundingClientRect = () =>
+ ({ left: 0, top: 0, right: 100, bottom: 50, width: 100, height: 50 }) as DOMRect;
+ let restore = emulateHitTest(() => [at("wide"), at("bg")]);
+ try {
+ expect(selectorsAt(3, 50)).toEqual(["#bg"]);
+ expect(selectorsAt(1, 50)).toEqual(["#wide", "#bg"]);
+ expect(selectorsAt(25, 3)).toEqual(["#wide", "#bg"]);
+ } finally {
+ restore();
+ }
+ restore = emulateHitTest(() => [at("tall"), at("bg")]);
+ try {
+ expect(selectorsAt(50, 3)).toEqual(["#bg"]);
+ expect(selectorsAt(50, 1)).toEqual(["#tall", "#bg"]);
+ } finally {
+ restore();
+ }
+ });
+
+ it("counts an SVG that paints its own background", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"></div>
+ <svg id="panel" style="background-color: rgb(20, 20, 20)"></svg>`;
+ const restore = emulateHitTest(() => [at("panel"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#panel", "#bg"]);
+ } finally {
+ restore();
+ }
+ });
+
+ it("counts an SVG's text through the text element, not the SVG box", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"></div><svg id="art"><text>Label</text></svg>`;
+ const restore = emulateHitTest(() => [at("art"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#bg"]);
+ } finally {
+ restore();
+ }
+ });
+
+ // A glyph box under the pointer, in a box laid out far from it (moved by a transform): out of reach.
+ it.each([
+ ["a paragraph far below", { top: 800, bottom: 840, height: 40 }],
+ [
+ "a tall default-font box past the capped reach, about ten times its font",
+ { top: 400, bottom: 700, height: 300 },
+ ],
+ ])("does not look for a layer's text in %s", (_, box) => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"></div>
+ <div id="layer"><div id="box"><p>Box words</p></div></div>`;
+ at("box").getBoundingClientRect = () =>
+ ({ left: 0, right: 600, width: 600, ...box }) as DOMRect;
+ const unlay = layOut({ "Box words": [0, 0, 100, 40] });
+ const restore = emulateHitTest(() => [at("layer"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#bg"]);
+ } finally {
+ restore();
+ unlay();
+ }
+ });
+
+ it("reaches a line box's leading from a big line in a small-font box", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"><div id="para">
+ <div id="l1"><span>Line one</span></div><div id="l2"><span>Line two</span></div></div></div>`;
+ // Two 120px lines, 100px apart, in boxes whose own font size is the default.
+ at("l1").getBoundingClientRect = () =>
+ ({ left: 0, top: 0, right: 600, bottom: 120, width: 600, height: 120 }) as DOMRect;
+ at("l2").getBoundingClientRect = () =>
+ ({ left: 0, top: 220, right: 600, bottom: 340, width: 600, height: 120 }) as DOMRect;
+ const unlay = layOut({ "Line one": [0, 0, 600, 120], "Line two": [0, 220, 600, 120] });
+ const restore = emulateHitTest(() => [at("para"), at("bg")]);
+ try {
+ expect(selectorsAt(300, 190)).toEqual(["#para", "#bg"]);
+ } finally {
+ restore();
+ unlay();
+ }
+ });
+
+ it("counts an inset shadow, not an outer one: an outer shadow draws outside the box", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"></div>
+ <div id="glow"></div><div id="well"></div>`;
+ const unstyle = styled({
+ glow: { "box-shadow": "rgb(255, 0, 0) 0px 0px 10px 0px" },
+ well: { "box-shadow": "rgb(255, 0, 0) 0px 0px 10px 0px inset" },
+ });
+ let restore = emulateHitTest(() => [at("glow"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#bg"]);
+ } finally {
+ restore();
+ }
+ restore = emulateHitTest(() => [at("well"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#well", "#bg"]);
+ } finally {
+ restore();
+ unstyle();
+ }
+ });
+
+ it("counts pseudo content only when it is displayed and draws something", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"></div>
+ <div id="empty"></div><div id="hidden"></div><div id="icon"></div>`;
+ const unstyle = styled({
+ "empty::after": { content: '""', display: "block" },
+ "hidden::before": { content: '"*"', display: "none" },
+ "icon::before": { content: '"*"', display: "inline" },
+ });
+ try {
+ for (const [id, drawn] of [
+ ["empty", false],
+ ["hidden", false],
+ ["icon", true],
+ ] as const) {
+ const restore = emulateHitTest(() => [at(id), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(drawn ? [`#${id}`, "#bg"] : ["#bg"]);
+ } finally {
+ restore();
+ }
+ }
+ } finally {
+ unstyle();
+ }
+ });
+
+ it("picks a shown child of a hidden parent: visibility can be turned back on below", () => {
+ createPickerModule({ postMessage: createMockPostMessage() }).installPickerApi();
+ document.body.innerHTML = `<div id="bg" style="${BG}"><div id="veil" style="visibility: hidden">
+ <b id="back" style="visibility: visible">Back</b></div></div>`;
+ const restore = emulateHitTest(() => [at("back"), at("veil"), at("bg")]);
+ try {
+ expect(selectorsAt()).toEqual(["#back", "#bg"]);
+ } finally {
+ restore();
+ }
+ });
+ });
+
describe("escape key handler", () => {
it("disables pick mode and posts cancel message on Escape", () => {
const postMessage = createMockPostMessage();
diff --git a/packages/core/src/runtime/picker.ts b/packages/core/src/runtime/picker.ts
index cedaee66ee..1d198aeea0 100644
--- a/packages/core/src/runtime/picker.ts
+++ b/packages/core/src/runtime/picker.ts
@@ -2,6 +2,7 @@ import type { RuntimeJson, RuntimeOutboundMessage, RuntimePickerElementInfo } fr
import { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from "../colorGrading";
import { swallow } from "./diagnostics";
import { isElementNode } from "./domRealm";
+import { createDrawnProbe } from "./pickerDrawn";
type PickerModuleDeps = {
postMessage: (payload: RuntimeOutboundMessage) => void;
@@ -130,9 +131,10 @@ export function createPickerModule(deps: PickerModuleDeps): PickerModule {
const win = el.ownerDocument.defaultView;
if (!win) return false;
let current: HTMLElement | null = el;
+ if (win.getComputedStyle(el).visibility === "hidden") return true;
while (current && current !== document.body && current !== document.documentElement) {
const computed = win.getComputedStyle(current);
- if (computed.display === "none" || computed.visibility === "hidden") return true;
+ if (computed.display === "none") return true;
if (computed.pointerEvents === "none") return true;
const opacity = Number.parseFloat(computed.opacity);
if (
@@ -221,15 +223,20 @@ export function createPickerModule(deps: PickerModuleDeps): PickerModule {
if (blocksPickerAtPoint(raw[0] ?? null)) return [];
const dedupe: Record<string, true> = {};
const candidates: Element[] = [];
+ const drawn: Element[] = [];
+ const drawsHere = createDrawnProbe(document, clientX, clientY);
for (const [i, node] of raw.entries()) {
if (!isPickableElement(node)) continue;
const key = `${node.tagName}::${(node as HTMLElement).id || ""}::${i}`;
if (dedupe[key]) continue;
dedupe[key] = true;
candidates.push(node);
- if (candidates.length >= maxCandidates) break;
+ if (drawn.some((inner) => node.contains(inner)) || drawsHere(node)) {
+ drawn.push(node);
+ if (drawn.length >= maxCandidates) break;
+ }
}
- return candidates;
+ return drawn.length > 0 ? drawn : candidates.slice(0, maxCandidates);
}
function extractElementInfo(el: Element): RuntimePickerElementInfo {
diff --git a/packages/core/src/runtime/pickerDrawn.ts b/packages/core/src/runtime/pickerDrawn.ts
new file mode 100644
index 0000000000..97238994a6
--- /dev/null
+++ b/packages/core/src/runtime/pickerDrawn.ts
@@ -0,0 +1,190 @@
+import { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from "../colorGrading";
+
+type Rect = { left: number; right: number; top: number; bottom: number };
+
+const TRANSPARENT = /^(|transparent|rgba\(.*,\s*0\)|.*\/\s*0%?\s*\))$/;
+const PICTURES = new Set(["IMG", "VIDEO", "IFRAME", "EMBED", "OBJECT", "CANVAS"]);
+const SVG_NS = "http://www.w3.org/2000/svg";
+const SVG_BOXES = new Set(["svg", "g", "foreignObject"]);
+const SIDES = ["Top", "Right", "Bottom", "Left"] as const;
+const EVERYWHERE: Rect = { left: -Infinity, right: Infinity, top: -Infinity, bottom: Infinity };
+
+const paints = (style: CSSStyleDeclaration): boolean =>
+ (Boolean(style.backgroundImage) && style.backgroundImage !== "none") ||
+ !TRANSPARENT.test(style.backgroundColor);
+
+// Glyphs paint with the text fill colour (`color` unless set apart) or a text stroke.
+const glyphsPaint = (style: CSSStyleDeclaration): boolean => {
+ const fill = style.getPropertyValue("-webkit-text-fill-color") || style.color;
+ const stroke = Number.parseFloat(style.getPropertyValue("-webkit-text-stroke-width")) || 0;
+ const strokeColor = style.getPropertyValue("-webkit-text-stroke-color") || style.color;
+ return !TRANSPARENT.test(fill) || (stroke > 0 && !TRANSPARENT.test(strokeColor));
+};
+
+const borderWidths = (style: CSSStyleDeclaration): number[] =>
+ SIDES.map((side) =>
+ style[`border${side}Style`] !== "none" && !TRANSPARENT.test(style[`border${side}Color`])
+ ? Number.parseFloat(style[`border${side}Width`]) || 0
+ : 0,
+ );
+
+const height = (r: Rect) => r.bottom - r.top;
+const holds = (r: Rect, x: number, y: number) =>
+ x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;
+const unite = (a: Rect, b: Rect): Rect => ({
+ left: Math.min(a.left, b.left),
+ right: Math.max(a.right, b.right),
+ top: Math.min(a.top, b.top),
+ bottom: Math.max(a.bottom, b.bottom),
+});
+
+// Hidden, or its own out-of-flow box: its text is not an ancestor's to draw.
+const closesText = (el: Element, s: CSSStyleDeclaration): boolean =>
+ s.display === "none" ||
+ s.position === "absolute" ||
+ s.position === "fixed" ||
+ (Number.parseFloat(s.opacity) <= 0.01 && !el.hasAttribute(COLOR_GRADING_SOURCE_HIDDEN_ATTR));
+
+// Too far above or below the pointer's row for its lines to reach it; a box may hold lines up to
+// about ten times its own font.
+function farFromRow(r: DOMRect, s: CSSStyleDeclaration, y: number): boolean {
+ if (r.width <= 0 && r.height <= 0) return false;
+ const byFont = 3 * (Number.parseFloat(s.fontSize) || 16);
+ const reach = Math.max(byFont, Math.min(2 * r.height, (20 * byFont) / 3));
+ return y < r.top - reach || y > r.bottom + reach;
+}
+
+// On the border's band, scaled with the element on each axis; not in the box it frames.
+function onBorderBand(el: Element, s: CSSStyleDeclaration, x: number, y: number): boolean {
+ const [top, right, bottom, left] = borderWidths(s) as [number, number, number, number];
+ if (!(top || right || bottom || left)) return false;
+ const r = el.getBoundingClientRect();
+ const { offsetWidth, offsetHeight } = el as HTMLElement;
+ const kx = offsetWidth > 0 ? r.width / offsetWidth : 1;
+ const ky = offsetHeight > 0 ? r.height / offsetHeight : 1;
+ const inner = {
+ left: r.left + left * kx,
+ right: r.right - right * kx,
+ top: r.top + top * ky,
+ bottom: r.bottom - bottom * ky,
+ };
+ return !holds(inner, x, y);
+}
+
+/** Glyphs side by side on one line, no further apart than two line heights, join into one line box. */
+function lineBoxes(glyphs: readonly Rect[]): Rect[] {
+ const lines: Rect[] = [];
+ for (const g of [...glyphs].sort((a, b) => a.left - b.left)) {
+ const i = lines.findIndex(
+ (line) =>
+ g.top < line.bottom &&
+ g.bottom > line.top &&
+ g.left - line.right <= 2 * Math.max(height(line), height(g)),
+ );
+ if (i < 0) lines.push(g);
+ else lines[i] = unite(lines[i]!, g);
+ }
+ return lines;
+}
+
+/** The leading between two close lines of one block counts as the block's text too. */
+function leadings(lines: readonly Rect[]): Rect[] {
+ const sorted = [...lines].sort((a, b) => a.top - b.top);
+ return sorted.flatMap((upper, i) =>
+ sorted.slice(i + 1).flatMap((lower) => {
+ const beside = lower.left < upper.right && lower.right > upper.left;
+ const close = lower.top - upper.bottom <= 2 * Math.min(height(upper), height(lower));
+ return beside && close && lower.top > upper.bottom ? [unite(upper, lower)] : [];
+ }),
+ );
+}
+
+/**
+ * Whether an element draws pixels of its own at (x, y). One probe serves one pick, so every
+ * candidate shares its text measurements.
+ */
+export function createDrawnProbe(doc: Document, x: number, y: number): (el: Element) => boolean {
+ const view = doc.defaultView;
+ const layout = typeof doc.createRange().getClientRects === "function";
+ const range = doc.createRange();
+ const glyphsIn = new Map<Element, Rect[]>();
+ const closedBox = new Map<Element, boolean>();
+ const shownTextNode = new Map<Node, boolean>();
+
+ const closed = (el: Element): boolean => {
+ let known = closedBox.get(el);
+ if (known === undefined) {
+ const s = view!.getComputedStyle(el);
+ known = closesText(el, s) || (layout && farFromRow(el.getBoundingClientRect(), s, y));
+ closedBox.set(el, known);
+ }
+ return known;
+ };
+ const shownText = (node: Node): boolean => {
+ let known = shownTextNode.get(node);
+ if (known === undefined) {
+ const parent = node.parentElement;
+ const s = parent && node.nodeValue?.trim() ? view!.getComputedStyle(parent) : null;
+ known = Boolean(s) && s!.visibility !== "hidden" && glyphsPaint(s!);
+ shownTextNode.set(node, known);
+ }
+ return known;
+ };
+ // Only glyphs near the pointer's row can make a line or a leading that covers it.
+ const glyphsNear = (node: Node): Rect[] => {
+ // No layout to ask (a DOM without rendering): shown text counts wherever the pointer is.
+ if (!layout) return [EVERYWHERE];
+ const glyphs: Rect[] = [];
+ range.selectNodeContents(node);
+ for (const r of range.getClientRects()) {
+ const h = r.bottom - r.top;
+ if (r.width > 0 && h > 0 && y >= r.top - 2 * h && y <= r.bottom + 2 * h) glyphs.push(r);
+ }
+ return glyphs;
+ };
+ // The glyphs of the text an element lays out itself, collected once per pick for every candidate.
+ const glyphsUnder = (el: Element): Rect[] => {
+ let glyphs = glyphsIn.get(el);
+ if (glyphs) return glyphs;
+ glyphs = [];
+ for (const child of el.childNodes) {
+ if (child.nodeType === 3) {
+ if (shownText(child)) glyphs.push(...glyphsNear(child));
+ } else if (child.nodeType === 1 && child.hasChildNodes() && !closed(child as Element)) {
+ glyphs.push(...glyphsUnder(child as Element));
+ }
+ }
+ glyphsIn.set(el, glyphs);
+ return glyphs;
+ };
+
+ function textAt(el: Element): boolean {
+ const lines = lineBoxes(glyphsUnder(el));
+ return (
+ lines.some((line) => holds(line, x, y)) || leadings(lines).some((gap) => holds(gap, x, y))
+ );
+ }
+
+ function pseudoDraws(el: Element, pseudo: string): boolean {
+ const s = view!.getComputedStyle(el, pseudo);
+ if (!s.content || s.content === "none" || s.content === "normal" || s.display === "none")
+ return false;
+ return s.content !== '""' || paints(s) || borderWidths(s).some((w) => w > 0);
+ }
+
+ // An outer shadow draws outside the box, so only an inset one counts.
+ const decoratedAt = (el: Element, s: CSSStyleDeclaration): boolean =>
+ /inset/.test(s.boxShadow) ||
+ onBorderBand(el, s, x, y) ||
+ pseudoDraws(el, "::before") ||
+ pseudoDraws(el, "::after");
+
+ return (el) => {
+ if (PICTURES.has(el.tagName)) return true;
+ const box = el.namespaceURI !== SVG_NS || SVG_BOXES.has(el.localName);
+ if (!box) return true;
+ if (!view) return true;
+ const s = view.getComputedStyle(el);
+ return paints(s) || decoratedAt(el, s) || (el.namespaceURI !== SVG_NS && textAt(el));
+ };
+}