Skip to content

Write HTML. Render video. Built for agents.

fix(core): a section whose root sets pointer-events:none stays pickable (#4399)

Miguel Ángel115332f4f611
diff --git a/packages/core/src/runtime/picker.test.ts b/packages/core/src/runtime/picker.test.ts
index e454a101c6..fe49baf034 100644
--- a/packages/core/src/runtime/picker.test.ts
+++ b/packages/core/src/runtime/picker.test.ts
@@ -25,6 +25,23 @@ beforeAll(() => {
}
});
+function ancestorsOf(el: Element): Element[] {
+ const chain: Element[] = [];
+ for (let at = el.parentElement; at; at = at.parentElement) chain.push(at);
+ return chain;
+}
+
+// Like a browser: the paint stack under the point, top first, minus computed pointer-events:none.
+function emulateHitTest(painted: () => Element[]): () => void {
+ const original = document.elementsFromPoint;
+ Object.defineProperty(document, "elementsFromPoint", {
+ configurable: true,
+ value: vi.fn(() => painted().filter((el) => getComputedStyle(el).pointerEvents !== "none")),
+ });
+ return () =>
+ Object.defineProperty(document, "elementsFromPoint", { configurable: true, value: original });
+}
+
function createMockPostMessage() {
return vi.fn();
}
@@ -150,6 +167,163 @@ describe("createPickerModule", () => {
}
});
+ it("picks inside a mounted section whose root sets pointer-events:none", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ // The mount rescopes the section's own root rule onto its inner root.
+ document.head.innerHTML =
+ '<style>[data-composition-id="intro"] > [data-hf-inner-root] { pointer-events: none }' +
+ " .vignette { pointer-events: none }</style>";
+ document.body.innerHTML = `<div data-composition-id="intro" data-composition-src="intro.html">
+ <div data-hf-inner-root="true"><div class="card"><code id="code">tl.to()</code></div>
+ <div class="vignette" id="vignette"></div></div></div>`;
+ const code = document.getElementById("code")!;
+ // Paint order under the point, top first; like a browser, drop what has pointer-events:none.
+ const painted = [document.getElementById("vignette")!, code, code.parentElement!];
+ const originalElementsFromPoint = document.elementsFromPoint;
+ Object.defineProperty(document, "elementsFromPoint", {
+ configurable: true,
+ value: vi.fn(() =>
+ [...painted, ...ancestorsOf(code.parentElement!)].filter(
+ (el) => getComputedStyle(el).pointerEvents !== "none",
+ ),
+ ),
+ });
+
+ const api = (window as any).__HF_PICKER_API;
+ try {
+ expect(api.getCandidatesAtPoint(10, 10)[0]?.selector).toBe("#code");
+ expect(api.pickAtPoint(10, 10)?.selector).toBe("#code");
+ expect(document.head.querySelectorAll("style")).toHaveLength(1);
+ } finally {
+ Object.defineProperty(document, "elementsFromPoint", {
+ configurable: true,
+ value: originalElementsFromPoint,
+ });
+ }
+ });
+
+ it("picks inside a composition opened on its own whose root sets pointer-events:none", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ document.head.innerHTML = "<style>#root { pointer-events: none }</style>";
+ 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();
+ }
+ });
+
+ it("adopts the override only for the hit test, leaving the DOM and a saved outerHTML untouched", () => {
+ const adopted: CSSStyleSheet[] = [];
+ Object.defineProperty(document, "adoptedStyleSheets", {
+ configurable: true,
+ get: () => adopted.slice(),
+ set: (next: CSSStyleSheet[]) => adopted.splice(0, adopted.length, ...next),
+ });
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ document.body.innerHTML =
+ '<div data-composition-id="intro"><div data-hf-inner-root="true" style="pointer-events: none">' +
+ '<span id="t">hi</span></div></div>';
+ const during: string[][] = [];
+ const originalElementsFromPoint = document.elementsFromPoint;
+ Object.defineProperty(document, "elementsFromPoint", {
+ configurable: true,
+ value: vi.fn(() => {
+ during.push(adopted.flatMap((sheet) => [...sheet.cssRules].map((rule) => rule.cssText)));
+ return [document.getElementById("t")!];
+ }),
+ });
+ const observer = new MutationObserver(() => {});
+ observer.observe(document, { childList: true, subtree: true, attributes: true });
+ const html = document.documentElement.outerHTML;
+
+ const api = (window as any).__HF_PICKER_API;
+ try {
+ // jsdom ignores adopted sheets for style, so this checks the sheet's lifecycle, not what it picks.
+ api.getCandidatesAtPoint(10, 10);
+ api.pickAtPoint(10, 10);
+ expect(during).toHaveLength(2);
+ expect(during[0]?.join()).toContain("pointer-events: auto !important");
+ expect(adopted).toEqual([]);
+ expect(observer.takeRecords()).toEqual([]);
+ expect(document.documentElement.outerHTML).toBe(html);
+ // With no pass-through root there is nothing to override, so nothing is adopted and nothing restyles.
+ (document.querySelector("[data-hf-inner-root]") as HTMLElement).style.pointerEvents = "";
+ api.getCandidatesAtPoint(10, 10);
+ expect(during.at(-1)).toEqual([]);
+ } finally {
+ observer.disconnect();
+ Object.defineProperty(document, "elementsFromPoint", {
+ configurable: true,
+ value: originalElementsFromPoint,
+ });
+ delete (document as { adoptedStyleSheets?: unknown }).adoptedStyleSheets;
+ }
+ });
+
+ it("keeps a click-through overlay host passing through to what is under it", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ document.body.innerHTML = `<div id="root" data-composition-id="main"><video id="aroll"></video>
+ <div id="ovl" data-composition-id="intro_outro" data-composition-src="intro.html"
+ 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();
+ }
+ });
+
+ it("a section background click picks the host, and an inner root never gets a bare tag selector", () => {
+ const picker = createPickerModule({ postMessage: createMockPostMessage() });
+ picker.installPickerApi();
+ document.head.innerHTML =
+ '<style>[data-composition-id="intro"] > [data-hf-inner-root] { pointer-events: none }</style>';
+ document.body.innerHTML = `<div id="root" data-composition-id="main"><div id="host"
+ data-composition-id="intro" data-composition-src="intro.html"><div data-hf-inner-root="true">
+ </div></div><div data-composition-id="outro"><div data-hf-inner-root="true"></div></div></div>`;
+ const [intro, outro] = Array.from(document.querySelectorAll("[data-hf-inner-root]"));
+ const api = (window as any).__HF_PICKER_API;
+ let restore = emulateHitTest(() => [
+ intro!,
+ intro!.parentElement!,
+ document.getElementById("root")!,
+ ]);
+ try {
+ expect(api.getCandidatesAtPoint(10, 10).map((c: any) => c.selector)).toEqual([
+ "#host",
+ "#root",
+ ]);
+ } finally {
+ restore();
+ }
+ restore = emulateHitTest(() => [outro!, outro!.parentElement!]);
+ try {
+ expect(api.getCandidatesAtPoint(10, 10)[0]?.selector).toBe(
+ '[data-composition-id="outro"] > [data-hf-inner-root]',
+ );
+ } finally {
+ restore();
+ }
+ });
+
it("pickAtPoint returns null for invalid coords", () => {
const picker = createPickerModule({ postMessage: createMockPostMessage() });
picker.installPickerApi();
diff --git a/packages/core/src/runtime/picker.ts b/packages/core/src/runtime/picker.ts
index c995ca263e..cda4d2f472 100644
--- a/packages/core/src/runtime/picker.ts
+++ b/packages/core/src/runtime/picker.ts
@@ -20,6 +20,17 @@ const PICKER_BLOCK_SELECTOR = [
"[data-hyper-shader-loading]",
].join(",");
+// A composition root's pointer-events:none (rescoped onto its inner root at mount) is about playback, not
+// editing, yet it inherits into the whole section. Inner roots and the page's outermost composition root
+// take pointer events while the picker looks. A host keeps its own none: that is the parent author making
+// an overlay click-through.
+const PICKABLE_ROOTS = "[data-hf-inner-root],[data-composition-id]:not([data-composition-id] *)";
+const PICKABLE_ROOTS_RULE = `${PICKABLE_ROOTS}{pointer-events:auto!important}`;
+// A layered !important outranks every normal rule and every unlayered !important, whatever its specificity
+// (a mounted section's rescoped `#root { pointer-events: none !important }`). Ceiling: an author !important
+// inside the author's own layer, or inline, still wins; an adopted sheet's layer always orders last.
+const PICKABLE_ROOTS_LAYERED = `@layer hf-picker{${PICKABLE_ROOTS_RULE}}`;
+
export type PickerModule = {
enablePickMode: () => void;
disablePickMode: () => void;
@@ -32,6 +43,9 @@ export function createPickerModule(deps: PickerModuleDeps): PickerModule {
let pickModeStyleEl: HTMLStyleElement | null = null;
let pickLastHoveredInfo: RuntimePickerElementInfo | null = null;
let pickLastSelectedInfo: RuntimePickerElementInfo | null = null;
+ let pickableRootsSheetCache: CSSStyleSheet | null | undefined;
+ // Roots that were pointer-events:none before the override: their content is pickable, never they.
+ let passThroughRoots: ReadonlySet<Element> = new Set();
function emitPickerRuntimeEvent(eventName: string, detail: RuntimeJson): void {
try {
@@ -60,6 +74,58 @@ export function createPickerModule(deps: PickerModuleDeps): PickerModule {
});
}
+ // An adopted sheet is not a DOM node: no MutationObserver hears it (the runtime's timing observer would
+ // wake a paused transport on every hover) and a saved documentElement.outerHTML never contains it.
+ function withPickableCompositionRoots<T>(run: () => T): T {
+ passThroughRoots = new Set(
+ Array.from(document.querySelectorAll(PICKABLE_ROOTS)).filter(
+ (root) => getComputedStyle(root).pointerEvents === "none",
+ ),
+ );
+ // Nothing to override, so no restyle: adopting the sheet restyles the whole document twice per hover.
+ if (passThroughRoots.size === 0) return run();
+ const sheet = pickableRootsSheet();
+ const release = sheet ? adoptSheet(sheet) : appendPickableRootsStyle();
+ try {
+ return run();
+ } finally {
+ release();
+ passThroughRoots = new Set();
+ }
+ }
+
+ function pickableRootsSheet(): CSSStyleSheet | null {
+ if (pickableRootsSheetCache !== undefined) return pickableRootsSheetCache;
+ pickableRootsSheetCache = null;
+ if (!Array.isArray(document.adoptedStyleSheets) || typeof CSSStyleSheet === "undefined")
+ return null;
+ try {
+ const sheet = new CSSStyleSheet();
+ sheet.replaceSync(PICKABLE_ROOTS_LAYERED);
+ pickableRootsSheetCache = sheet;
+ } catch (err) {
+ swallow("runtime.picker.site2", err);
+ }
+ return pickableRootsSheetCache;
+ }
+
+ function adoptSheet(sheet: CSSStyleSheet): () => void {
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
+ return () => {
+ document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== sheet);
+ };
+ }
+
+ // No adoptedStyleSheets (older engines, and jsdom, whose layered !important order is reversed, so this
+ // rule stays unlayered): a style element for the hit test only. Adding it is a DOM mutation, so there a
+ // hover can wake the runtime's timing observer.
+ function appendPickableRootsStyle(): () => void {
+ const style = document.createElement("style");
+ style.textContent = PICKABLE_ROOTS_RULE;
+ (document.head ?? document.documentElement).appendChild(style);
+ return () => style.remove();
+ }
+
function isEffectivelyHidden(el: HTMLElement): boolean {
const win = el.ownerDocument.defaultView;
if (!win) return false;
@@ -85,6 +151,7 @@ export function createPickerModule(deps: PickerModuleDeps): PickerModule {
const tag = el.tagName.toLowerCase();
if (tag === "script" || tag === "style" || tag === "link" || tag === "meta") return false;
if (el.classList.contains("__hf-pick-highlight")) return false;
+ if (passThroughRoots.has(el)) return false;
if (el.closest(PICKER_IGNORE_SELECTOR)) return false;
if (isEffectivelyHidden(el as HTMLElement)) return false;
return true;
@@ -94,7 +161,16 @@ export function createPickerModule(deps: PickerModuleDeps): PickerModule {
return Boolean(el?.closest(PICKER_BLOCK_SELECTOR));
}
+ // The mount strips an inner root's id and composition id, so its own tag would match any div.
+ function innerRootSelector(el: Element): string | null {
+ const hostId = el.parentElement?.getAttribute("data-composition-id");
+ if (!el.hasAttribute("data-hf-inner-root") || !hostId) return null;
+ return `[data-composition-id="${CSS.escape(hostId)}"] > [data-hf-inner-root]`;
+ }
+
function buildElementSelector(el: Element): string {
+ const innerRoot = innerRootSelector(el);
+ if (innerRoot) return innerRoot;
const htmlEl = el as HTMLElement;
// Escape the ID so digit-leading or otherwise CSS-illegal ids (e.g. `#0`,
// `#1`) produce valid selectors — `document.querySelector("#0")` throws
@@ -183,14 +259,20 @@ export function createPickerModule(deps: PickerModuleDeps): PickerModule {
clientY: number,
limit?: number,
): RuntimePickerElementInfo[] {
- return getPickCandidatesFromPoint(clientX, clientY, limit).map(extractElementInfo);
+ return withPickableCompositionRoots(() =>
+ getPickCandidatesFromPoint(clientX, clientY, limit),
+ ).map(extractElementInfo);
}
function onPickMouseMove(event: MouseEvent): void {
if (!pickModeActive) return;
- const candidates = getPickCandidatesFromPoint(event.clientX, event.clientY, 1);
- const target = candidates[0] ?? (isElementNode(event.target) ? event.target : null);
- if (!isPickableElement(target)) return;
+ const target = withPickableCompositionRoots(() => {
+ const hit =
+ getPickCandidatesFromPoint(event.clientX, event.clientY, 1)[0] ??
+ (isElementNode(event.target) ? event.target : null);
+ return isPickableElement(hit) ? hit : null;
+ });
+ if (!target) return;
if (pickModeHighlightEl === target) return;
if (pickModeHighlightEl) {
pickModeHighlightEl.classList.remove("__hf-pick-highlight");