Skip to content

Write HTML. Render video. Built for agents.

fix(studio): make canvas selection hit intended elements (#1907)

Miguel Ángel02e9d6142d8e
diff --git a/packages/studio/src/components/editor/DomEditOverlay.test.ts b/packages/studio/src/components/editor/DomEditOverlay.test.ts
index 468bebfdfe..db1f2291bc 100644
--- a/packages/studio/src/components/editor/DomEditOverlay.test.ts
+++ b/packages/studio/src/components/editor/DomEditOverlay.test.ts
@@ -345,6 +345,101 @@ describe("DomEditOverlay", () => {
Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
host.remove();
});
+
+ it("passes the tracked hover selection when clicking the existing selection box", async () => {
+ const originalGetBoundingClientRect = Element.prototype.getBoundingClientRect;
+ Element.prototype.getBoundingClientRect = function (): DOMRect {
+ return {
+ left: 0,
+ top: 0,
+ right: 800,
+ bottom: 450,
+ width: 800,
+ height: 450,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ };
+ };
+
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ const selection: DomEditSelection = {
+ element: document.createElement("div"),
+ id: "hero-title",
+ selector: ".hero-title",
+ selectorIndex: 0,
+ sourceFile: "index.html",
+ tagName: "div",
+ label: "Hero Title",
+ textContent: "Hello",
+ textFields: [],
+ capabilities: {
+ canEditText: true,
+ canEditLayout: true,
+ canMove: false,
+ canApplyManualOffset: false,
+ canApplyManualSize: false,
+ canApplyManualRotation: false,
+ canAdjustOpacity: true,
+ canAdjustFill: true,
+ canAdjustBorderRadius: true,
+ canAdjustStroke: true,
+ canAdjustShadow: true,
+ canAdjustZIndex: true,
+ },
+ computedStyle: {
+ display: "block",
+ position: "absolute",
+ },
+ };
+ const hoverSelection: DomEditSelection = { ...selection, id: "hovered-sibling" };
+ const onCanvasMouseDown = vi.fn();
+ const iframeRef = { current: document.createElement("iframe") as HTMLIFrameElement | null };
+
+ function Harness() {
+ return React.createElement(DomEditOverlay, {
+ ...createOverlayProps({
+ iframeRef,
+ selection,
+ hoverSelection,
+ onSelectionChange: () => {},
+ }),
+ onCanvasMouseDown,
+ });
+ }
+
+ act(() => {
+ root.render(React.createElement(Harness));
+ });
+
+ await act(async () => {
+ await new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+ });
+ });
+
+ const selectionBox = host.querySelector(
+ '[data-dom-edit-selection-box="true"]',
+ ) as HTMLDivElement;
+ expect(selectionBox).toBeTruthy();
+
+ act(() => {
+ selectionBox.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+
+ expect(onCanvasMouseDown).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ hoverSelection }),
+ );
+
+ act(() => {
+ root.unmount();
+ });
+ Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
+ host.remove();
+ });
});
describe("resolveDomEditCoordinateScale", () => {
diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsx
index f0861be649..48e563a203 100644
--- a/packages/studio/src/components/editor/DomEditOverlay.tsx
+++ b/packages/studio/src/components/editor/DomEditOverlay.tsx
@@ -1,6 +1,7 @@
import { memo, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import { useMountEffect } from "../../hooks/useMountEffect";
import { type DomEditSelection } from "./domEditing";
+import type { PreviewMouseDownOptions } from "../../hooks/usePreviewInteraction";
import { useMarqueeGestures } from "./marqueeCommit";
import { MarqueeOverlay } from "./MarqueeOverlay";
import { groupAwareOverlayRect, resolveDomEditGroupOverlayRect } from "./domEditOverlayGeometry";
@@ -44,7 +45,7 @@ interface DomEditOverlayProps {
allowCanvasMovement?: boolean;
onCanvasMouseDown: (
event: React.MouseEvent<HTMLDivElement>,
- options?: { preferClipAncestor?: boolean },
+ options?: PreviewMouseDownOptions,
) => void;
onCanvasPointerMove: (
event: React.PointerEvent<HTMLDivElement>,
@@ -277,6 +278,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
iframeRef,
boxRef,
selectionRef,
+ hoverSelectionRef,
overlayRectRef,
groupOverlayItemsRef,
gestureRef,
@@ -336,7 +338,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
// Allow clicks anywhere on the overlay — GSAP-translated elements can
// extend beyond the composition rect into the gray zone, and users need
// to select/deselect them by clicking there.
- onCanvasMouseDown(event, { preferClipAncestor: false });
+ onCanvasMouseDown(event, { hoverSelection: hoverSelectionRef.current });
if (event.shiftKey) {
suppressNextBoxMouseDownRef.current = true;
suppressNextBoxClickRef.current = true;
@@ -401,7 +403,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
event.stopPropagation();
return;
}
- onCanvasMouseDown(event, { preferClipAncestor: false });
+ onCanvasMouseDown(event, { hoverSelection: hoverSelectionRef.current });
};
const suppressBoxMouseDown = (e: React.MouseEvent) => {
diff --git a/packages/studio/src/components/editor/domEditOverlayGestures.ts b/packages/studio/src/components/editor/domEditOverlayGestures.ts
index d693e974a9..7f3c63c805 100644
--- a/packages/studio/src/components/editor/domEditOverlayGestures.ts
+++ b/packages/studio/src/components/editor/domEditOverlayGestures.ts
@@ -9,6 +9,7 @@ import type { ManualOffsetDragMember } from "./manualOffsetDrag";
import type { GroupOverlayItem, OverlayRect } from "./domEditOverlayGeometry";
import type { SnapContext } from "./snapTargetCollection";
import type { SnapGuidesState } from "./SnapGuideOverlay";
+import type { PreviewMouseDownOptions } from "../../hooks/usePreviewInteraction";
export type GestureKind = "drag" | "resize" | "rotate";
@@ -161,6 +162,7 @@ export type UseDomEditOverlayGesturesOptions = {
iframeRef: RefObject<HTMLIFrameElement | null>;
boxRef: RefObject<HTMLDivElement | null>;
selectionRef: RefObject<DomEditSelection | null>;
+ hoverSelectionRef: RefObject<DomEditSelection | null>;
overlayRectRef: RefObject<OverlayRect | null>;
groupOverlayItemsRef: RefObject<GroupOverlayItem[]>;
gestureRef: RefObject<GestureState | null>;
@@ -194,9 +196,6 @@ export type UseDomEditOverlayGesturesOptions = {
o?: { preferClipAncestor?: boolean },
) => Promise<DomEditSelection | null>
>;
- onCanvasMouseDown: (
- e: React.MouseEvent<HTMLDivElement>,
- o?: { preferClipAncestor?: boolean },
- ) => void;
+ onCanvasMouseDown: (e: React.MouseEvent<HTMLDivElement>, o?: PreviewMouseDownOptions) => void;
snapGuidesRef: RefObject<SnapGuidesState | null>;
};
diff --git a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts
index 002e9cb8b9..a67653bda7 100644
--- a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts
+++ b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts
@@ -369,6 +369,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
opts.suppressNextBoxClickRef.current = true;
opts.onCanvasMouseDown(e as unknown as React.MouseEvent<HTMLDivElement>, {
preferClipAncestor: false,
+ hoverSelection: opts.hoverSelectionRef.current,
});
return;
}
diff --git a/packages/studio/src/hooks/domSelectionTestHarness.ts b/packages/studio/src/hooks/domSelectionTestHarness.ts
new file mode 100644
index 0000000000..527c8c0e7c
--- /dev/null
+++ b/packages/studio/src/hooks/domSelectionTestHarness.ts
@@ -0,0 +1,40 @@
+// Shared harness helpers for selection hook tests (useDomSelection,
+// usePreviewInteraction). Test-only module.
+import type { DomEditSelection } from "../components/editor/domEditing";
+
+export function installReactActEnvironment(): void {
+ Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
+ value: true,
+ configurable: true,
+ });
+}
+
+export function makeSelection(label: string, element: HTMLElement): DomEditSelection {
+ return {
+ element,
+ id: element.id || undefined,
+ selector: `#${element.id || label}`,
+ selectorIndex: 0,
+ sourceFile: "index.html",
+ compositionPath: "index.html",
+ label,
+ tagName: element.tagName.toLowerCase(),
+ isCompositionHost: false,
+ isInsideLockedComposition: false,
+ boundingBox: { x: 0, y: 0, width: 100, height: 40 },
+ textContent: element.textContent,
+ dataAttributes: {},
+ inlineStyles: {},
+ computedStyles: {},
+ textFields: [],
+ capabilities: {
+ canSelect: true,
+ canEditStyles: true,
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: true,
+ canApplyManualSize: true,
+ canApplyManualRotation: false,
+ },
+ };
+}
diff --git a/packages/studio/src/hooks/useDomSelection.test.ts b/packages/studio/src/hooks/useDomSelection.test.ts
new file mode 100644
index 0000000000..53f4524644
--- /dev/null
+++ b/packages/studio/src/hooks/useDomSelection.test.ts
@@ -0,0 +1,134 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vitest";
+import { installReactActEnvironment, makeSelection } from "./domSelectionTestHarness";
+import { useDomSelection } from "./useDomSelection";
+
+installReactActEnvironment();
+
+interface HarnessProps {
+ activeCompPath: string | null;
+ projectId: string | null;
+ refreshKey: number;
+}
+
+function renderHarness(initialProps: HarnessProps): {
+ current: () => ReturnType<typeof useDomSelection>;
+ rerender: (props: HarnessProps) => void;
+ cleanup: () => void;
+} {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+ let currentHook: ReturnType<typeof useDomSelection> | null = null;
+
+ function Harness(props: HarnessProps) {
+ currentHook = useDomSelection({
+ projectId: props.projectId,
+ activeCompPath: props.activeCompPath,
+ isMasterView: false,
+ compIdToSrc: new Map(),
+ captionEditMode: false,
+ previewIframeRef: { current: null },
+ timelineElements: [],
+ setSelectedTimelineElementId: vi.fn(),
+ setRightCollapsed: vi.fn(),
+ setRightPanelTab: vi.fn(),
+ previewIframe: null,
+ refreshKey: props.refreshKey,
+ rightPanelTab: "design",
+ });
+ return null;
+ }
+
+ const rerender = (props: HarnessProps) => {
+ act(() => {
+ root.render(React.createElement(Harness, props));
+ });
+ };
+
+ rerender(initialProps);
+
+ return {
+ current: () => {
+ if (!currentHook) throw new Error("Expected hook result");
+ return currentHook;
+ },
+ rerender,
+ cleanup: () => {
+ act(() => root.unmount());
+ host.remove();
+ },
+ };
+}
+
+function setupSelectedHarness() {
+ const element = document.createElement("div");
+ element.id = "headline";
+ const selection = makeSelection("Headline", element);
+ const harness = renderHarness({
+ activeCompPath: "intro.html",
+ projectId: "project-1",
+ refreshKey: 0,
+ });
+ act(() => harness.current().applyDomSelection(selection));
+ return { selection, harness };
+}
+
+describe("useDomSelection", () => {
+ it("clears a committed selection when the active composition path changes", () => {
+ const { selection, harness } = setupSelectedHarness();
+ expect(harness.current().domEditSelection).toBe(selection);
+
+ harness.rerender({
+ activeCompPath: "outro.html",
+ projectId: "project-1",
+ refreshKey: 0,
+ });
+
+ expect(harness.current().domEditSelection).toBe(null);
+ harness.cleanup();
+ });
+
+ it("preserves a committed selection when composition identity is unchanged", () => {
+ const { selection, harness } = setupSelectedHarness();
+ harness.rerender({
+ activeCompPath: "intro.html",
+ projectId: "project-1",
+ refreshKey: 1,
+ });
+
+ expect(harness.current().domEditSelection).toBe(selection);
+ harness.cleanup();
+ });
+
+ it("preserves selection when clearing an already inactive group scope", () => {
+ const { selection, harness } = setupSelectedHarness();
+ act(() => harness.current().setActiveGroupElement(null));
+
+ expect(harness.current().domEditSelection).toBe(selection);
+ harness.cleanup();
+ });
+
+ it("preserves selection when entering the already active group scope", () => {
+ const group = document.createElement("div");
+ const child = document.createElement("span");
+ child.id = "headline";
+ group.append(child);
+ const selection = makeSelection("Headline", child);
+ const harness = renderHarness({
+ activeCompPath: "intro.html",
+ projectId: "project-1",
+ refreshKey: 0,
+ });
+
+ act(() => harness.current().setActiveGroupElement(group));
+ act(() => harness.current().applyDomSelection(selection));
+ act(() => harness.current().setActiveGroupElement(group));
+
+ expect(harness.current().domEditSelection).toBe(selection);
+ harness.cleanup();
+ });
+});
diff --git a/packages/studio/src/hooks/useDomSelection.ts b/packages/studio/src/hooks/useDomSelection.ts
index d7a7af35e4..72892dd744 100644
--- a/packages/studio/src/hooks/useDomSelection.ts
+++ b/packages/studio/src/hooks/useDomSelection.ts
@@ -27,6 +27,18 @@ import { reapplyPositionEditsAfterSeek } from "../components/editor/manualEdits"
// ── Types ──
+export interface ApplyDomSelectionOptions {
+ revealPanel?: boolean;
+ additive?: boolean;
+ preserveGroup?: boolean;
+}
+
+export interface ResolveDomSelectionOptions {
+ preferClipAncestor?: boolean;
+ skipSourceProbe?: boolean;
+ activeGroupElement?: HTMLElement | null;
+}
+
export interface UseDomSelectionParams {
projectId: string | null;
activeCompPath: string | null;
@@ -61,29 +73,17 @@ export interface UseDomSelectionReturn {
// Callbacks
applyDomSelection: (
selection: DomEditSelection | null,
- options?: {
- revealPanel?: boolean;
- additive?: boolean;
- preserveGroup?: boolean;
- },
+ options?: ApplyDomSelectionOptions,
) => void;
clearDomSelection: () => void;
buildDomSelectionFromTarget: (
target: HTMLElement,
- options?: {
- preferClipAncestor?: boolean;
- skipSourceProbe?: boolean;
- activeGroupElement?: HTMLElement | null;
- },
+ options?: ResolveDomSelectionOptions,
) => Promise<DomEditSelection | null>;
resolveDomSelectionFromPreviewPoint: (
clientX: number,
clientY: number,
- options?: {
- preferClipAncestor?: boolean;
- skipSourceProbe?: boolean;
- activeGroupElement?: HTMLElement | null;
- },
+ options?: ResolveDomSelectionOptions,
) => Promise<DomEditSelection | null>;
resolveAllDomSelectionsFromPreviewPoint: (
clientX: number,
@@ -130,6 +130,7 @@ export function useDomSelection({
const domEditGroupSelectionsRef = useRef<DomEditSelection[]>(domEditGroupSelections);
const domEditHoverSelectionRef = useRef<DomEditSelection | null>(domEditHoverSelection);
const activeGroupElementRef = useRef<HTMLElement | null>(activeGroupElement);
+ const compositionIdentityRef = useRef({ activeCompPath, projectId });
// Keep refs in sync with state
domEditSelectionRef.current = domEditSelection;
@@ -230,6 +231,8 @@ export function useDomSelection({
// the user isn't left with an out-of-scope element selected.
const setActiveGroupElement = useCallback(
(el: HTMLElement | null) => {
+ if (activeGroupElementRef.current === el) return;
+ activeGroupElementRef.current = el;
setActiveGroupElementState(el);
applyDomSelection(null, { revealPanel: false });
},
@@ -454,6 +457,17 @@ export function useDomSelection({
updateDomEditHoverSelection(null);
}, [activeCompPath, projectId, previewIframe, refreshKey, updateDomEditHoverSelection]);
+ // Clear committed selection only when the composition identity actually changes.
+ // eslint-disable-next-line no-restricted-syntax
+ useEffect(() => {
+ const previous = compositionIdentityRef.current;
+ if (previous.activeCompPath === activeCompPath && previous.projectId === projectId) return;
+ compositionIdentityRef.current = { activeCompPath, projectId };
+ activeGroupElementRef.current = null;
+ setActiveGroupElementState(null);
+ applyDomSelection(null, { revealPanel: false });
+ }, [activeCompPath, projectId, applyDomSelection]);
+
// Clear hover conditionally (caption mode, matches selection, disconnected element)
// eslint-disable-next-line no-restricted-syntax
useEffect(() => {
diff --git a/packages/studio/src/hooks/usePreviewInteraction.test.ts b/packages/studio/src/hooks/usePreviewInteraction.test.ts
new file mode 100644
index 0000000000..6a5aa19739
--- /dev/null
+++ b/packages/studio/src/hooks/usePreviewInteraction.test.ts
@@ -0,0 +1,260 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { DomEditSelection } from "../components/editor/domEditing";
+import { usePlayerStore } from "../player";
+import { installReactActEnvironment, makeSelection } from "./domSelectionTestHarness";
+import { usePreviewInteraction } from "./usePreviewInteraction";
+
+installReactActEnvironment();
+
+function createPreviewIframe(playerPause?: () => void): HTMLIFrameElement {
+ const iframe = document.createElement("iframe");
+ if (playerPause) {
+ Object.defineProperty(iframe, "contentWindow", {
+ configurable: true,
+ value: {
+ __player: {
+ getTime: () => 3.25,
+ pause: playerPause,
+ },
+ },
+ });
+ }
+ return iframe;
+}
+
+interface HarnessArgs {
+ previewIframe: HTMLIFrameElement | null;
+ resolveDomSelectionFromPreviewPoint: (
+ clientX: number,
+ clientY: number,
+ options?: { activeGroupElement?: HTMLElement | null },
+ ) => Promise<DomEditSelection | null>;
+ resolveAllDomSelectionsFromPreviewPoint?: (
+ clientX: number,
+ clientY: number,
+ ) => Promise<DomEditSelection[]>;
+ applyDomSelection: (
+ selection: DomEditSelection | null,
+ options?: { revealPanel?: boolean; additive?: boolean; preserveGroup?: boolean },
+ ) => void;
+ setActiveGroupElement?: (el: HTMLElement | null) => void;
+ mouseDownOptions?: {
+ preferClipAncestor?: boolean;
+ hoverSelection?: DomEditSelection | null;
+ };
+}
+
+function renderHarness(args: HarnessArgs): {
+ canvas: HTMLDivElement;
+ cleanup: () => void;
+} {
+ const host = document.createElement("div");
+ document.body.append(host);
+ const root = createRoot(host);
+
+ function Harness() {
+ const interaction = usePreviewInteraction({
+ captionEditMode: false,
+ compositionLoading: false,
+ previewIframeRef: { current: args.previewIframe },
+ showToast: vi.fn(),
+ applyDomSelection: args.applyDomSelection,
+ resolveDomSelectionFromPreviewPoint: args.resolveDomSelectionFromPreviewPoint,
+ resolveAllDomSelectionsFromPreviewPoint:
+ args.resolveAllDomSelectionsFromPreviewPoint ?? vi.fn(async () => []),
+ updateDomEditHoverSelection: vi.fn(),
+ setActiveGroupElement: args.setActiveGroupElement ?? vi.fn(),
+ });
+
+ return React.createElement("div", {
+ id: "canvas",
+ onMouseDown: (event: React.MouseEvent<HTMLDivElement>) => {
+ void interaction.handlePreviewCanvasMouseDown(event, args.mouseDownOptions);
+ },
+ });
+ }
+
+ act(() => {
+ root.render(React.createElement(Harness));
+ });
+
+ const canvas = host.querySelector("#canvas");
+ if (!(canvas instanceof HTMLDivElement)) throw new Error("Expected canvas div");
+
+ return {
+ canvas,
+ cleanup: () => {
+ act(() => root.unmount());
+ host.remove();
+ },
+ };
+}
+
+async function dispatchMouseDown(canvas: HTMLDivElement, init: MouseEventInit): Promise<void> {
+ await act(async () => {
+ canvas.dispatchEvent(
+ new MouseEvent("mousedown", {
+ bubbles: true,
+ cancelable: true,
+ clientX: 50,
+ clientY: 60,
+ ...init,
+ }),
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+describe("usePreviewInteraction", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("pauses playback before resolving a click and falls back to the tracked hover selection", async () => {
+ const order: string[] = [];
+ const playerPause = vi.fn(() => {
+ order.push("pause");
+ });
+ const element = document.createElement("div");
+ element.id = "headline";
+ const hoverSelection = makeSelection("Headline", element);
+ const applyDomSelection = vi.fn();
+ const resolveDomSelectionFromPreviewPoint = vi.fn(async () => {
+ order.push("resolve");
+ return null;
+ });
+ const { canvas, cleanup } = renderHarness({
+ previewIframe: createPreviewIframe(playerPause),
+ resolveDomSelectionFromPreviewPoint,
+ applyDomSelection,
+ mouseDownOptions: { preferClipAncestor: false, hoverSelection },
+ });
+
+ await dispatchMouseDown(canvas, {});
+
+ expect(order[0]).toBe("pause");
+ expect(applyDomSelection).toHaveBeenCalledWith(hoverSelection);
+ cleanup();
+ });
+
+ it("treats a double-click on a regular element as a plain selection", async () => {
+ const element = document.createElement("div");
+ element.id = "headline";
+ const selection = makeSelection("Headline", element);
+ const applyDomSelection = vi.fn();
+ let resolveCount = 0;
+ const resolveDomSelectionFromPreviewPoint = vi.fn(async () => {
+ resolveCount += 1;
+ return resolveCount === 1 ? selection : null;
+ });
+ const { canvas, cleanup } = renderHarness({
+ previewIframe: null,
+ resolveDomSelectionFromPreviewPoint,
+ applyDomSelection,
+ });
+
+ await dispatchMouseDown(canvas, { detail: 2 });
+
+ expect(applyDomSelection).toHaveBeenCalledWith(selection);
+ expect(applyDomSelection).not.toHaveBeenCalledWith(null, { revealPanel: false });
+ cleanup();
+ });
+
+ it("preserves group drill-in on double-click", async () => {
+ const group = document.createElement("div");
+ group.setAttribute("data-hf-group", "hero");
+ const child = document.createElement("span");
+ child.id = "headline";
+ group.append(child);
+ const groupSelection = makeSelection("Hero Group", group);
+ const childSelection = makeSelection("Headline", child);
+ const applyDomSelection = vi.fn();
+ const setActiveGroupElement = vi.fn();
+ const resolveDomSelectionFromPreviewPoint = vi.fn(
+ async (
+ _clientX: number,
+ _clientY: number,
+ options?: { activeGroupElement?: HTMLElement | null },
+ ) => (options?.activeGroupElement === group ? childSelection : groupSelection),
+ );
+ const { canvas, cleanup } = renderHarness({
+ previewIframe: null,
+ resolveDomSelectionFromPreviewPoint,
+ applyDomSelection,
+ setActiveGroupElement,
+ });
+
+ await dispatchMouseDown(canvas, { detail: 2 });
+
+ expect(setActiveGroupElement).toHaveBeenCalledWith(group);
+ expect(applyDomSelection).toHaveBeenCalledWith(childSelection);
+ cleanup();
+ });
+
+ it("cycles stacked candidates on a rapid second click at the same spot", async () => {
+ const topElement = document.createElement("div");
+ topElement.id = "top";
+ const bottomElement = document.createElement("div");
+ bottomElement.id = "bottom";
+ const topSelection = makeSelection("Top", topElement);
+ const bottomSelection = makeSelection("Bottom", bottomElement);
+ const applyDomSelection = vi.fn();
+ const resolveDomSelectionFromPreviewPoint = vi.fn(async () => topSelection);
+ const resolveAllDomSelectionsFromPreviewPoint = vi.fn(async () => [
+ topSelection,
+ bottomSelection,
+ ]);
+ const { canvas, cleanup } = renderHarness({
+ previewIframe: null,
+ resolveDomSelectionFromPreviewPoint,
+ resolveAllDomSelectionsFromPreviewPoint,
+ applyDomSelection,
+ });
+
+ await dispatchMouseDown(canvas, { detail: 1 });
+ await dispatchMouseDown(canvas, { detail: 2 });
+
+ expect(applyDomSelection).toHaveBeenNthCalledWith(1, topSelection);
+ expect(applyDomSelection).toHaveBeenNthCalledWith(2, bottomSelection);
+ cleanup();
+ });
+
+ it("resumes playback when a click resolves to nothing (dead-zone / deselect)", async () => {
+ usePlayerStore.setState({ isPlaying: true });
+ const applyDomSelection = vi.fn();
+ const resolveDomSelectionFromPreviewPoint = vi.fn(async () => null);
+ const { canvas, cleanup } = renderHarness({
+ previewIframe: createPreviewIframe(vi.fn()),
+ resolveDomSelectionFromPreviewPoint,
+ applyDomSelection,
+ });
+
+ await dispatchMouseDown(canvas, {});
+
+ expect(applyDomSelection).toHaveBeenCalledWith(null, { revealPanel: false });
+ expect(usePlayerStore.getState().isPlaying).toBe(true);
+ cleanup();
+ });
+
+ it("does not resume playback on deselect when it was already paused", async () => {
+ usePlayerStore.setState({ isPlaying: false });
+ const applyDomSelection = vi.fn();
+ const resolveDomSelectionFromPreviewPoint = vi.fn(async () => null);
+ const { canvas, cleanup } = renderHarness({
+ previewIframe: createPreviewIframe(vi.fn()),
+ resolveDomSelectionFromPreviewPoint,
+ applyDomSelection,
+ });
+
+ await dispatchMouseDown(canvas, {});
+
+ expect(applyDomSelection).toHaveBeenCalledWith(null, { revealPanel: false });
+ expect(usePlayerStore.getState().isPlaying).toBe(false);
+ cleanup();
+ });
+});
diff --git a/packages/studio/src/hooks/usePreviewInteraction.ts b/packages/studio/src/hooks/usePreviewInteraction.ts
index b11b6b80a8..e73d3fa07b 100644
--- a/packages/studio/src/hooks/usePreviewInteraction.ts
+++ b/packages/studio/src/hooks/usePreviewInteraction.ts
@@ -3,6 +3,7 @@ import { liveTime, usePlayerStore } from "../player";
import { pauseStudioPreviewPlayback } from "../utils/studioPreviewHelpers";
import { STUDIO_PREVIEW_SELECTION_ENABLED } from "../components/editor/manualEditingAvailability";
import { type DomEditSelection } from "../components/editor/domEditing";
+import type { ApplyDomSelectionOptions, ResolveDomSelectionOptions } from "./useDomSelection";
import { trackStudioEvent } from "../utils/studioTelemetry";
// ── Types ──
@@ -16,16 +17,12 @@ export interface UsePreviewInteractionParams {
// From useDomSelection
applyDomSelection: (
selection: DomEditSelection | null,
- options?: { revealPanel?: boolean; additive?: boolean; preserveGroup?: boolean },
+ options?: ApplyDomSelectionOptions,
) => void;
resolveDomSelectionFromPreviewPoint: (
clientX: number,
clientY: number,
- options?: {
- preferClipAncestor?: boolean;
- skipSourceProbe?: boolean;
- activeGroupElement?: HTMLElement | null;
- },
+ options?: ResolveDomSelectionOptions,
) => Promise<DomEditSelection | null>;
resolveAllDomSelectionsFromPreviewPoint: (
clientX: number,
@@ -46,6 +43,11 @@ interface ClickCycleState {
at: number;
}
+export interface PreviewMouseDownOptions {
+ preferClipAncestor?: boolean;
+ hoverSelection?: DomEditSelection | null;
+}
+
const CYCLE_RADIUS_PX = 6;
const CYCLE_WINDOW_MS = 600;
// Manual double-click window. `e.detail` can't be trusted here: the first click
@@ -72,9 +74,19 @@ export function usePreviewInteraction({
const cycleRef = useRef<ClickCycleState | null>(null);
const lastDownRef = useRef<{ t: number; x: number; y: number } | null>(null);
+ const pausePreviewPlayback = useCallback(() => {
+ const pausedTime = pauseStudioPreviewPlayback(previewIframeRef.current);
+ const playerStore = usePlayerStore.getState();
+ playerStore.setIsPlaying(false);
+ if (pausedTime != null) {
+ playerStore.setCurrentTime(pausedTime);
+ liveTime.notify(pausedTime);
+ }
+ }, [previewIframeRef]);
+
const handlePreviewCanvasMouseDown = useCallback(
// fallow-ignore-next-line complexity
- async (e: React.MouseEvent<HTMLDivElement>, options?: { preferClipAncestor?: boolean }) => {
+ async (e: React.MouseEvent<HTMLDivElement>, options?: PreviewMouseDownOptions) => {
if (!STUDIO_PREVIEW_SELECTION_ENABLED || captionEditMode || compositionLoading) return;
// Manual double-click detection (see DOUBLE_CLICK_MS): the first click
@@ -87,12 +99,26 @@ export function usePreviewInteraction({
downTs - lastDown.t < DOUBLE_CLICK_MS &&
Math.hypot(e.clientX - lastDown.x, e.clientY - lastDown.y) < DOUBLE_CLICK_RADIUS_PX);
lastDownRef.current = { t: downTs, x: e.clientX, y: e.clientY };
+ const wasPlaying = usePlayerStore.getState().isPlaying;
+ pausePreviewPlayback();
+ // A click that resolves to nothing (dead-zone / deselect) shouldn't leave
+ // playback paused — pausing before sampling only exists to keep the hit
+ // target stable while resolving; resume if nothing was selected.
+ const resumeIfNothingSelected = () => {
+ if (wasPlaying) usePlayerStore.getState().setIsPlaying(true);
+ };
// Double-click a group → drill into it and select the child under the
// pointer (resolve with the group as the explicit drill-in scope, since the
// activeGroupElement state hasn't re-rendered yet within this handler).
if (isDoubleClick && !e.shiftKey) {
const hit = await resolveDomSelectionFromPreviewPoint(e.clientX, e.clientY);
+ const cycle = cycleRef.current;
+ const hasStackCycleAtSpot =
+ cycle !== null &&
+ cycle.candidates.length > 1 &&
+ Math.hypot(e.clientX - cycle.x, e.clientY - cycle.y) < CYCLE_RADIUS_PX &&
+ downTs - cycle.at < CYCLE_WINDOW_MS;
if (hit?.element.hasAttribute("data-hf-group")) {
e.preventDefault();
e.stopPropagation();
@@ -105,6 +131,18 @@ export function usePreviewInteraction({
applyDomSelection(child ?? hit);
return;
}
+ if (
+ hit &&
+ !hasStackCycleAtSpot &&
+ !hit.element.hasAttribute("data-composition-src") &&
+ !hit.element.hasAttribute("data-composition-file")
+ ) {
+ e.preventDefault();
+ e.stopPropagation();
+ cycleRef.current = null;
+ applyDomSelection(hit);
+ return;
+ }
}
const now = Date.now();
@@ -119,10 +157,16 @@ export function usePreviewInteraction({
if (e.shiftKey) {
// Additive selection — no cycling
cycleRef.current = null;
- const nextSelection = await resolveDomSelectionFromPreviewPoint(e.clientX, e.clientY, {
- preferClipAncestor: options?.preferClipAncestor ?? false,
- });
- if (!nextSelection) return;
+ const nextSelection =
+ (await resolveDomSelectionFromPreviewPoint(e.clientX, e.clientY, {
+ preferClipAncestor: options?.preferClipAncestor ?? false,
+ })) ??
+ options?.hoverSelection ??
+ null;
+ if (!nextSelection) {
+ resumeIfNothingSelected();
+ return;
+ }
e.preventDefault();
e.stopPropagation();
applyDomSelection(nextSelection, { additive: true });
@@ -156,9 +200,11 @@ export function usePreviewInteraction({
activeGroupElement: null,
});
}
+ nextSelection = nextSelection ?? options?.hoverSelection ?? null;
if (!nextSelection) {
cycleRef.current = null;
applyDomSelection(null, { revealPanel: false });
+ resumeIfNothingSelected();
return;
}
e.preventDefault();
@@ -180,6 +226,7 @@ export function usePreviewInteraction({
captionEditMode,
compositionLoading,
onClickToSource,
+ pausePreviewPlayback,
resolveAllDomSelectionsFromPreviewPoint,
resolveDomSelectionFromPreviewPoint,
setActiveGroupElement,
@@ -225,14 +272,8 @@ export function usePreviewInteraction({
);
const handleDomManualDragStart = useCallback(() => {
- const pausedTime = pauseStudioPreviewPlayback(previewIframeRef.current);
- const playerStore = usePlayerStore.getState();
- playerStore.setIsPlaying(false);
- if (pausedTime != null) {
- playerStore.setCurrentTime(pausedTime);
- liveTime.notify(pausedTime);
- }
- }, [previewIframeRef]);
+ pausePreviewPlayback();
+ }, [pausePreviewPlayback]);
return {
handlePreviewCanvasMouseDown,
diff --git a/packages/studio/src/utils/studioPreviewHelpers.test.ts b/packages/studio/src/utils/studioPreviewHelpers.test.ts
index c673142e6a..4114a03a58 100644
--- a/packages/studio/src/utils/studioPreviewHelpers.test.ts
+++ b/packages/studio/src/utils/studioPreviewHelpers.test.ts
@@ -1,5 +1,29 @@
+// @vitest-environment happy-dom
+
import { describe, expect, it, vi } from "vitest";
-import { coversComposition, pauseStudioPreviewPlayback } from "./studioPreviewHelpers";
+import {
+ coversComposition,
+ getPreviewTargetFromPointer,
+ pauseStudioPreviewPlayback,
+} from "./studioPreviewHelpers";
+
+function domRect(left: number, top: number, width: number, height: number): DOMRect {
+ return {
+ x: left,
+ y: top,
+ left,
+ top,
+ width,
+ height,
+ right: left + width,
+ bottom: top + height,
+ toJSON: () => ({}),
+ };
+}
+
+function stubRect(el: Element, rect: DOMRect): void {
+ el.getBoundingClientRect = () => rect;
+}
describe("coversComposition (full-bleed canvas-pick exclusion)", () => {
const viewport = { width: 1920, height: 1080 };
@@ -79,3 +103,73 @@ describe("pauseStudioPreviewPlayback", () => {
expect(siblingPause).toHaveBeenCalledTimes(1);
});
});
+
+describe("getPreviewTargetFromPointer", () => {
+ it("skips candidates hidden from author hit-testing by inherited pointer-events:none", () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument;
+ if (!doc) throw new Error("Expected iframe document");
+
+ doc.body.innerHTML = `
+ <main id="scene" data-composition-id="scene">
+ <h1 id="headline">Launch title</h1>
+ <div id="overlay-parent" style="pointer-events: none;">
+ <div id="overlay" style="position: absolute; background: rgba(0, 0, 0, 0.1);"></div>
+ </div>
+ </main>
+ `;
+
+ const scene = doc.getElementById("scene");
+ const headline = doc.getElementById("headline");
+ const overlayParent = doc.getElementById("overlay-parent");
+ const overlay = doc.getElementById("overlay");
+ if (!scene || !headline || !overlayParent || !overlay) {
+ throw new Error("Expected preview fixture elements");
+ }
+
+ stubRect(iframe, domRect(0, 0, 400, 300));
+ stubRect(scene, domRect(0, 0, 400, 300));
+ stubRect(headline, domRect(40, 40, 160, 48));
+ stubRect(overlayParent, domRect(0, 0, 360, 260));
+ stubRect(overlay, domRect(0, 0, 360, 260));
+ doc.elementsFromPoint = () => [overlay, overlayParent, headline, scene];
+
+ expect(getPreviewTargetFromPointer(iframe, 80, 64, "index.html")).toBe(headline);
+
+ iframe.remove();
+ });
+
+ it("honors a CSS-class pointer-events:auto opt-in under a pointer-events:none ancestor", () => {
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const doc = iframe.contentDocument;
+ if (!doc) throw new Error("Expected iframe document");
+
+ doc.head.innerHTML = `<style>.clickable { pointer-events: auto; }</style>`;
+ doc.body.innerHTML = `
+ <main id="scene" data-composition-id="scene">
+ <div id="overlay-parent" style="pointer-events: none;">
+ <button id="clickable-child" class="clickable">Play</button>
+ </div>
+ </main>
+ `;
+
+ const scene = doc.getElementById("scene");
+ const overlayParent = doc.getElementById("overlay-parent");
+ const clickableChild = doc.getElementById("clickable-child");
+ if (!scene || !overlayParent || !clickableChild) {
+ throw new Error("Expected preview fixture elements");
+ }
+
+ stubRect(iframe, domRect(0, 0, 400, 300));
+ stubRect(scene, domRect(0, 0, 400, 300));
+ stubRect(overlayParent, domRect(0, 0, 360, 260));
+ stubRect(clickableChild, domRect(40, 40, 80, 24));
+ doc.elementsFromPoint = () => [clickableChild, overlayParent, scene];
+
+ expect(getPreviewTargetFromPointer(iframe, 60, 50, "index.html")).toBe(clickableChild);
+
+ iframe.remove();
+ });
+});
diff --git a/packages/studio/src/utils/studioPreviewHelpers.ts b/packages/studio/src/utils/studioPreviewHelpers.ts
index 455844b8bc..9f76b59cb5 100644
--- a/packages/studio/src/utils/studioPreviewHelpers.ts
+++ b/packages/studio/src/utils/studioPreviewHelpers.ts
@@ -4,6 +4,7 @@ import {
isElementComputedVisible,
resolveAllVisualDomEditTargets,
} from "../components/editor/domEditingElement";
+import { isHtmlElement } from "../components/editor/domEditingDom";
import { getEventTargetElement } from "./studioHelpers";
interface PreviewLocalPointer {
@@ -81,11 +82,90 @@ function removePointerEventsOverride(style: HTMLStyleElement | null): void {
}
}
+const pointerEventsInheritanceFallbackByDocument = new WeakMap<Document, boolean>();
+
+function needsPointerEventsInheritanceFallback(doc: Document, win: Window): boolean {
+ const cached = pointerEventsInheritanceFallbackByDocument.get(doc);
+ if (cached !== undefined) return cached;
+
+ const parent = doc.createElement("div");
+ const child = doc.createElement("div");
+ parent.style.pointerEvents = "none";
+ parent.appendChild(child);
+ const host = doc.body ?? doc.documentElement;
+ if (!host) return false;
+
+ host.appendChild(parent);
+ const needsFallback = win.getComputedStyle(child).pointerEvents !== "none";
+ parent.remove();
+ pointerEventsInheritanceFallbackByDocument.set(doc, needsFallback);
+ return needsFallback;
+}
+
+// Own declared pointer-events value, via computed style rather than inline
+// style, so a CSS-class opt-in/opt-out (not just an inline style attribute)
+// is honored when walking back down from a pointer-events:none ancestor.
+function hasOwnPointerEventsOverride(el: HTMLElement, win: Window): boolean {
+ const value = win.getComputedStyle(el).pointerEvents;
+ return value !== "" && value !== "inherit" && value !== "unset";
+}
+
+function inheritsPointerEventsNoneFromAncestor(el: HTMLElement, win: Window): boolean {
+ let current = el.parentElement;
+ while (current) {
+ if (win.getComputedStyle(current).pointerEvents === "none") {
+ let descendant: HTMLElement | null = el;
+ while (descendant && descendant !== current) {
+ if (hasOwnPointerEventsOverride(descendant, win)) {
+ return win.getComputedStyle(descendant).pointerEvents === "none";
+ }
+ descendant = descendant.parentElement;
+ }
+ return true;
+ }
+ current = current.parentElement;
+ }
+ return false;
+}
+
+function hasAuthorPointerEventsNone(el: HTMLElement): boolean {
+ const win = el.ownerDocument.defaultView;
+ if (!win) return false;
+ if (win.getComputedStyle(el).pointerEvents === "none") return true;
+ if (!needsPointerEventsInheritanceFallback(el.ownerDocument, win)) return false;
+ return inheritsPointerEventsNoneFromAncestor(el, win);
+}
+
+function collectPointerEventsNoneTargets(
+ elements: Iterable<Element | null | undefined>,
+): WeakSet<HTMLElement> {
+ const disabled = new WeakSet<HTMLElement>();
+ for (const entry of elements) {
+ if (isHtmlElement(entry) && hasAuthorPointerEventsNone(entry)) {
+ disabled.add(entry);
+ }
+ }
+ return disabled;
+}
+
+// Shared tail of both pointer resolvers: hit-test candidates minus elements the
+// author hid from hit-testing via pointer-events:none.
+function filterAuthorInteractiveTargets(
+ elements: Element[],
+ activeCompositionPath: string | null,
+): HTMLElement[] {
+ const pointerEventsNoneTargets = collectPointerEventsNoneTargets(elements);
+ return resolveAllVisualDomEditTargets(elements, { activeCompositionPath }).filter(
+ (el) => !pointerEventsNoneTargets.has(el),
+ );
+}
+
// Animated group members can move outside their wrapper's static layout box, so
// the empty space inside a group's *visual* bounds (the member-union the overlay
// draws) doesn't hit-test to the group via elementsFromPoint. Recover it: if the
// point falls within a group's live member-union rect, return that wrapper.
// Innermost (smallest-area) group wins for nested groups.
+// fallow-ignore-next-line complexity
function findGroupAtPoint(doc: Document, x: number, y: number): HTMLElement | null {
let best: HTMLElement | null = null;
let bestArea = Infinity;
@@ -132,26 +212,39 @@ export function getPreviewTargetFromPointer(
const localPointer = resolvePreviewLocalPointer(iframe, doc, win, clientX, clientY);
if (!localPointer) return null;
- const overrideStyle = forcePointerEventsAuto(doc);
+ let overrideStyle = forcePointerEventsAuto(doc);
try {
if (typeof doc.elementsFromPoint === "function") {
- const candidates = resolveAllVisualDomEditTargets(
- doc.elementsFromPoint(localPointer.x, localPointer.y),
- { activeCompositionPath },
- );
+ const elements = doc.elementsFromPoint(localPointer.x, localPointer.y);
+ removePointerEventsOverride(overrideStyle);
+ overrideStyle = null;
+ const candidates = filterAuthorInteractiveTargets(elements, activeCompositionPath);
const visualTarget =
candidates.find((el) => !isFullBleedTarget(el, localPointer.viewport)) ?? null;
if (visualTarget) return visualTarget;
}
+ // Belt-and-suspenders: elementsFromPoint is universally supported in the
+ // browsers this ships in, so the override is already removed by this
+ // point in practice — but guard the environment without it too, so
+ // hasAuthorPointerEventsNone below never reads a forced-auto value.
+ removePointerEventsOverride(overrideStyle);
+ overrideStyle = null;
+
// No element hit (e.g. empty space inside an animated group's overlay) — fall
// back to the group whose member-union contains the point, so the whole group
// area is hoverable/selectable, not just where a member currently sits.
const groupHit = findGroupAtPoint(doc, localPointer.x, localPointer.y);
- if (groupHit && getDomLayerPatchTarget(groupHit, activeCompositionPath)) return groupHit;
+ if (
+ groupHit &&
+ !hasAuthorPointerEventsNone(groupHit) &&
+ getDomLayerPatchTarget(groupHit, activeCompositionPath)
+ )
+ return groupHit;
const fallback = getEventTargetElement(doc.elementFromPoint(localPointer.x, localPointer.y));
if (!fallback || !getDomLayerPatchTarget(fallback, activeCompositionPath)) return null;
+ if (hasAuthorPointerEventsNone(fallback)) return null;
if (!isElementComputedVisible(fallback)) return null;
if (isFullBleedTarget(fallback, localPointer.viewport)) return null;
return fallback;
@@ -180,15 +273,21 @@ export function getAllPreviewTargetsFromPointer(
const localPointer = resolvePreviewLocalPointer(iframe, doc, win, clientX, clientY);
if (!localPointer) return [];
- const overrideStyle = forcePointerEventsAuto(doc);
+ let overrideStyle = forcePointerEventsAuto(doc);
try {
if (typeof doc.elementsFromPoint === "function") {
- return resolveAllVisualDomEditTargets(doc.elementsFromPoint(localPointer.x, localPointer.y), {
- activeCompositionPath,
- }).filter((el) => !isFullBleedTarget(el, localPointer.viewport));
+ const elements = doc.elementsFromPoint(localPointer.x, localPointer.y);
+ removePointerEventsOverride(overrideStyle);
+ overrideStyle = null;
+ return filterAuthorInteractiveTargets(elements, activeCompositionPath).filter(
+ (el) => !isFullBleedTarget(el, localPointer.viewport),
+ );
}
const fallback = getEventTargetElement(doc.elementFromPoint(localPointer.x, localPointer.y));
if (!fallback || !getDomLayerPatchTarget(fallback, activeCompositionPath)) return [];
+ removePointerEventsOverride(overrideStyle);
+ overrideStyle = null;
+ if (hasAuthorPointerEventsNone(fallback)) return [];
if (!isElementComputedVisible(fallback)) return [];
if (isFullBleedTarget(fallback, localPointer.viewport)) return [];
return [fallback];