Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): the motion path draws on every load, not only when the layer's node is the frame's own (#4957)
Miguel Ángelb45818f69d55
diff --git a/packages/studio/package.json b/packages/studio/package.jsonindex c7d2caeb05..7eb98a8681 100644--- a/packages/studio/package.json+++ b/packages/studio/package.json@@ -83,6 +83,7 @@"test:timeline-virtualization": "TIMELINE_ROW_VIRTUALIZATION=on TIMELINE_ELEMENT_COUNT=50000 node tests/e2e/timeline-virtualization.mjs","test:watch": "vitest","test:colors:browser": "node tests/e2e/native-css-colors.mjs",+ "test:motion-path-home:browser": "node tests/e2e/motion-path-home.mjs","report:sdk-cutover": "bun src/utils/sdkCutoverPolicy.report.ts","test:timeline-default": "bun run test:timeline-virtualization"},diff --git a/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsx b/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsxindex 1cb88bffbd..3b439b651b 100644--- a/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsx+++ b/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsx@@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client";import { describe, expect, it, vi } from "vitest";import type { DomEditSelection } from "./domEditing";import { DomEditGroupChrome, DomEditSelectionChrome } from "./DomEditSelectionChrome";+import { SELECTION_CHROME } from "./motionPathLayerNode";(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -127,6 +128,10 @@ describe("DomEditSelectionChrome crop composition", () => {}expect(rotations).toHaveLength(1);expect(Number.parseFloat(rotations[0]!.slice("rotate(".length))).toBeCloseTo(30, 5);+ // A motion-path node over any of these hands its press to it.+ const controls = [...host.querySelectorAll(".pointer-events-auto, button")];+ expect(controls.length).toBeGreaterThan(8);+ for (const control of controls) expect(control.closest(SELECTION_CHROME)).not.toBeNull();act(() => root.unmount());});});diff --git a/packages/studio/src/components/editor/DomEditSelectionChrome.tsx b/packages/studio/src/components/editor/DomEditSelectionChrome.tsxindex e07c010755..18c05730e0 100644--- a/packages/studio/src/components/editor/DomEditSelectionChrome.tsx+++ b/packages/studio/src/components/editor/DomEditSelectionChrome.tsx@@ -169,6 +169,7 @@ export function DomEditSelectionChrome({return (<><div+ data-dom-edit-chrome="true"className="pointer-events-none absolute inset-0"style={{transformOrigin: `${overlayRect.left + overlayRect.width / 2}px ${overlayRect.top + overlayRect.height / 2}px`,diff --git a/packages/studio/src/components/editor/MotionPathNode.tsx b/packages/studio/src/components/editor/MotionPathNode.tsxindex 26f1c71030..625258e63d 100644--- a/packages/studio/src/components/editor/MotionPathNode.tsx+++ b/packages/studio/src/components/editor/MotionPathNode.tsx@@ -98,3 +98,59 @@ export function MotionPathNode(props: {</g>);}++type Point = { x: number; y: number };++/** The drawn path from GSAP's start (a passive mark) through the nodes, and the add-on-line ghost. */+export function MotionPathLine(props: {+ points: string;+ start?: Point;+ ghost: Point | null;+ r: number;+}) {+ const { points, start, ghost, r: nodeR } = props;+ return (+ <>+ <polyline+ points={start ? `${start.x},${start.y} ${points}` : points}+ fill="none"+ style={{ stroke: ACCENT }}+ strokeWidth={1.5}+ strokeDasharray="5 5"+ strokeLinejoin="round"+ strokeLinecap="round"+ vectorEffect="non-scaling-stroke"+ opacity={0.85}+ />+ {start && (+ <circle+ data-motion-path-start+ cx={start.x}+ cy={start.y}+ r={nodeR * 0.6}+ fill="none"+ strokeWidth={1.5}+ vectorEffect="non-scaling-stroke"+ className="pointer-events-none"+ style={{ stroke: ACCENT }}+ />+ )}+ {ghost && (+ <rect+ x={ghost.x - nodeR * 0.707}+ y={ghost.y - nodeR * 0.707}+ width={nodeR * 1.414}+ height={nodeR * 1.414}+ rx={nodeR * 0.24}+ transform={`rotate(45 ${ghost.x} ${ghost.y})`}+ fill="none"+ strokeWidth={1.5}+ strokeDasharray="2 2"+ vectorEffect="non-scaling-stroke"+ className="pointer-events-none"+ style={{ stroke: ACCENT }}+ />+ )}+ </>+ );+}diff --git a/packages/studio/src/components/editor/MotionPathOverlay.layerPress.test.tsx b/packages/studio/src/components/editor/MotionPathOverlay.layerPress.test.tsxindex 2aef7068a0..c841405cad 100644--- a/packages/studio/src/components/editor/MotionPathOverlay.layerPress.test.tsx+++ b/packages/studio/src/components/editor/MotionPathOverlay.layerPress.test.tsx@@ -1,15 +1,18 @@// @vitest-environment happy-domimport { act } from "react";import { createRoot } from "react-dom/client";-import { expect, it, vi } from "vitest";+import { afterEach, expect, it, vi } from "vitest";import { usePlayerStore } from "../../player/store/playerStore";import { MotionPathOverlay } from "./MotionPathOverlay";import type { DomEditSelection } from "./domEditing";Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);+const { commitMutation } = vi.hoisted(() => ({+ commitMutation: vi.fn(async (..._args: unknown[]) => {}),+}));vi.mock("../../contexts/DomEditContext", () => ({- useDomEditContext: () => ({ selectedGsapAnimations: [], commitMutation: vi.fn() }),+ useDomEditContext: () => ({ selectedGsapAnimations: [], commitMutation }),}));vi.mock("./motionPathSelection", () => ({selectorFor: () => "#box",@@ -28,72 +31,161 @@ vi.mock("./useMotionPathData", async (importOriginal) => ({points: "60,30 120,30",nodes: [{ x: 60, y: 30, ref: { type: "keyframe", pct: 66.667 } },- { x: 120, y: 30, ref: { type: "keyframe", pct: 100 } },+ // 140 wide there against 100 now: drawn 20 px right, where the layer's centre will be.+ { x: 120, y: 30, w: 140, ref: { type: "keyframe", pct: 100 } },],+ start: { x: 40, y: 30, w: 120 },},geometryResolved: true,visibleInPreview: true,- home: { x: 0, y: 0 },+ home: { x: 0, y: 0, w: 100, h: 50, ax: 0.5, ay: 0.5 },pScale: 1,}),}));-it("the layer's node and another node's ring inside the layer's box press the layer; a dot keeps its node", () => {+const cleanups: Array<() => void> = [];+afterEach(() => {+ while (cleanups.length) cleanups.pop()!();+ commitMutation.mockClear();+});++/** What lies under the pointer below the path: the layer's box, a handle over it, a marker, or nothing. */+type Under = boolean | "handle" | "marker";++/** The overlay over a selected layer's box and a crop handle, scale 1: client px are composition px. */+function mount() {+ const overlay = document.createElement("div");+ const chrome = overlay.appendChild(document.createElement("div"));+ chrome.setAttribute("data-dom-edit-chrome", "true");const box = document.createElement("div");box.setAttribute("data-dom-edit-selection-box", "true");+ box.style.cursor = "move";+ const handle = document.createElement("button");+ handle.style.cursor = "ew-resize";+ chrome.append(box, handle);+ // Another layer's off-canvas marker: no handler of its own, so a press on it reaches the overlay's marquee.+ const marker = overlay.appendChild(document.createElement("div"));+ overlay.addEventListener("pointerdown", (e) => {+ if (!(e.target as Element).closest("[data-dom-edit-chrome]")) e.preventDefault();+ });const host = document.createElement("div");- document.body.append(box, host);+ document.body.append(overlay, host);+ const handlePresses: number[] = [];+ handle.addEventListener("pointerdown", (e) => {+ handlePresses.push((e as PointerEvent).clientX);+ e.preventDefault();+ });const boxPresses: number[] = [];- let boxStarts = true;+ const state = { boxStarts: true };box.addEventListener("pointerdown", (e) => {boxPresses.push((e as PointerEvent).clientX);- if (boxStarts) e.preventDefault();+ if (state.boxStarts) e.preventDefault();});const captured = vi.spyOn(Element.prototype, "setPointerCapture").mockImplementation(() => {});const root = createRoot(host);const selection = { element: document.createElement("div") } as unknown as DomEditSelection;- // Scale 1: client px are composition px. `inBox`: the layer's box is under the press.- const press = (node: number, x: number, inBox: boolean) => {+ act(() =>+ root.render(+ <MotionPathOverlay+ iframeRef={{ current: null }}+ selection={selection}+ compositionSize={{ width: 1920, height: 1080 }}+ isPlaying={false}+ />,+ ),+ );+ cleanups.push(() => {+ captured.mockRestore();+ act(() => root.unmount());+ overlay.remove();+ host.remove();+ });+ /** Fires `type` at `target`; `under`: the layer's box, a handle over the box, or only the canvas. */+ const fire = (target: Element, type: string, x: number, under: Under) => {+ const stack = { handle: [handle, box], marker: [marker], true: [box], false: [] }[+ String(under)+ ]!;+ document.elementsFromPoint = () => [target, ...stack, overlay];+ const init = { bubbles: true, cancelable: true, button: 0, clientX: x, clientY: 30 };+ act(() => void target.dispatchEvent(new PointerEvent(type, init)));+ };+ return { host, boxPresses, handlePresses, state, captured, fire };+}++it("the layer's node, and any node inside the layer's box, press the layer; outside it a node keeps the press", () => {+ const { host, boxPresses, state, captured, fire } = mount();+ const press = (node: number, x: number, inBox: Under) => {const hit = [...host.querySelectorAll("circle.pointer-events-auto")].find((c) => c.getAttribute("cx") === String(node),)!;- document.elementsFromPoint = () => (inBox ? [hit, box] : [hit]);- const down = { bubbles: true, cancelable: true, button: 0, clientX: x, clientY: 30 };- act(() => void hit.dispatchEvent(new PointerEvent("pointerdown", down)));+ fire(hit, "pointerdown", x, inBox);};- try {- act(() =>- root.render(- <MotionPathOverlay- iframeRef={{ current: null }}- selection={selection}- compositionSize={{ width: 1920, height: 1080 }}- isPlaying={false}- />,- ),- );- press(60, 63, false);- press(120, 110, true);- expect(boxPresses).toEqual([63, 110]);- press(120, 118, true);- press(120, 110, false);- expect(boxPresses).toEqual([63, 110]);- // A selected node draws its dot 1.5x as large, and the larger dot is the node's.- act(() => usePlayerStore.setState({ activeKeyframePct: 100 }));- press(120, 112, true);- expect(boxPresses).toEqual([63, 110]);- act(() => usePlayerStore.setState({ activeKeyframePct: null }));- press(120, 112, true);- expect(boxPresses).toEqual([63, 110, 112]);- // A box that starts no gesture leaves the press to the node.- boxStarts = false;- captured.mockClear();- press(60, 63, false);- expect(captured).toHaveBeenCalledTimes(1);- } finally {- captured.mockRestore();- act(() => root.unmount());- box.remove();- host.remove();- }+ press(60, 63, false);+ press(140, 130, true);+ // On the dot itself: a drag from the layer's middle moves the layer (the edit bench's keys case).+ press(140, 140, true);+ expect(boxPresses).toEqual([63, 130, 140]);+ act(() => usePlayerStore.setState({ activeKeyframePct: 100 }));+ press(140, 140, true);+ act(() => usePlayerStore.setState({ activeKeyframePct: null }));+ expect(boxPresses).toEqual([63, 130, 140, 140]);+ press(140, 138, false);+ expect(boxPresses).toEqual([63, 130, 140, 140]);+ // Over another layer's off-canvas marker the node keeps its press; the canvas starts no marquee.+ captured.mockClear();+ press(140, 138, "marker");+ expect(captured).toHaveBeenCalledTimes(1);+ expect(boxPresses).toEqual([63, 130, 140, 140]);+ // A box that starts no gesture leaves the press to the node.+ state.boxStarts = false;+ captured.mockClear();+ press(60, 63, false);+ expect(captured).toHaveBeenCalledTimes(1);+});++it("the path's line inside the layer's box moves the layer and offers no add; outside it adds a keyframe", async () => {+ const { host, boxPresses, fire } = mount();+ const line = host.querySelector("polyline.pointer-events-auto") as SVGElement;+ const ghost = () => host.querySelector("rect.pointer-events-none");++ fire(line, "pointermove", 90, true);+ expect(line.style.cursor).toBe("move");+ expect(ghost()).toBeNull();+ fire(line, "pointerdown", 90, true);+ expect(boxPresses).toEqual([90]);+ expect(commitMutation).not.toHaveBeenCalled();++ fire(line, "pointermove", 90, false);+ expect(line.style.cursor).toBe("copy");+ expect(ghost()).not.toBeNull();+ // Halfway along the drawn segment 60 to 140: halfway between the stored offsets 60 and 120.+ fire(line, "pointerdown", 100, false);+ expect(boxPresses).toEqual([90]);+ await vi.waitFor(() => expect(commitMutation).toHaveBeenCalledTimes(1));+ expect(commitMutation.mock.calls[0]![0]).toMatchObject({ properties: { x: 90, y: 30 } });+});++it("a crop or resize handle over a node or the line takes the press, not the node or the layer", () => {+ const { host, boxPresses, handlePresses, captured, fire } = mount();+ const node = host.querySelector('circle.pointer-events-auto[cx="140"]')!;+ const line = host.querySelector("polyline.pointer-events-auto") as SVGElement;+ captured.mockClear();+ fire(node, "pointerdown", 142, "handle");+ fire(line, "pointermove", 100, "handle");+ expect(line.style.cursor).toBe("ew-resize");+ fire(line, "pointerdown", 100, "handle");+ expect(handlePresses).toEqual([142, 100]);+ expect(boxPresses).toEqual([]);+ expect(captured).not.toHaveBeenCalled();+ expect(commitMutation).not.toHaveBeenCalled();+});++it("draws where GSAP started the tween before the first keyframe, as a mark that takes no press", () => {+ const { host } = mount();+ const start = host.querySelector("circle[data-motion-path-start]")!;+ // 120 wide at the start against 100 now: drawn 10 px right.+ expect([start.getAttribute("cx"), start.getAttribute("cy")]).toEqual(["50", "30"]);+ expect(start.classList.contains("pointer-events-none")).toBe(true);+ const drawn = host.querySelector("polyline:not(.pointer-events-auto)")!;+ expect(drawn.getAttribute("points")).toBe("50,30 60,30 140,30");});diff --git a/packages/studio/src/components/editor/MotionPathOverlay.test.tsx b/packages/studio/src/components/editor/MotionPathOverlay.test.tsxindex 9996a98877..b28080e642 100644--- a/packages/studio/src/components/editor/MotionPathOverlay.test.tsx+++ b/packages/studio/src/components/editor/MotionPathOverlay.test.tsx@@ -6,12 +6,17 @@ import { MotionPathOverlay } from "./MotionPathOverlay";import { usePlayerStore } from "../../player/store/playerStore";import { usePreviewIframeStore } from "../../player/store/previewIframeStore";import type { DomEditSelection } from "./domEditing";+import { commitCreatePath } from "./motionPathCommit";Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);vi.mock("../../contexts/DomEditContext", () => ({useDomEditContext: () => ({ selectedGsapAnimations: [] }),}));+vi.mock("./motionPathCommit", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./motionPathCommit")>()),+ commitCreatePath: vi.fn(),+}));vi.mock("./motionPathSelection", () => ({selectorFor: () => "#box",editableAnimationId: () => null,@@ -63,3 +68,43 @@ it("re-evaluates set-destination availability when a reload swaps the live iframafter.remove();}});++it("sets a destination on a layer whichever window built its node", () => {+ const host = document.createElement("div");+ const surface = document.createElement("div");+ surface.setAttribute("data-preview-pan-surface", "");+ const frame = document.createElement("iframe");+ document.body.append(host, surface, frame);+ Reflect.set(frame.contentWindow as object, "MotionPathPlugin", {});+ frame.getBoundingClientRect = () => new DOMRect(0, 0, 1920, 1080);+ // As on the loads that hid the path, the layer's node carries the editor window's prototypes.+ const box = document.createElement("div");+ box.id = "box";+ frame.contentDocument!.body.append(box);+ const root = createRoot(host);+ const selection = { element: box } as unknown as DomEditSelection;+ try {+ act(() => usePreviewIframeStore.getState().setIframe(frame));+ act(() =>+ root.render(+ <MotionPathOverlay+ iframeRef={{ current: frame }}+ selection={selection}+ compositionSize={{ width: 1920, height: 1080 }}+ isPlaying={false}+ />,+ ),+ );+ act(() => usePlayerStore.getState().setMotionPathArmed(true));+ const press = { bubbles: true, button: 0, clientX: 100, clientY: 100 };+ act(() => void surface.dispatchEvent(new PointerEvent("pointerdown", press)));+ expect(commitCreatePath).toHaveBeenCalledTimes(1);+ } finally {+ act(() => usePlayerStore.getState().setMotionPathArmed(false));+ act(() => root.unmount());+ usePreviewIframeStore.setState({ iframe: null });+ host.remove();+ surface.remove();+ frame.remove();+ }+});diff --git a/packages/studio/src/components/editor/MotionPathOverlay.tsx b/packages/studio/src/components/editor/MotionPathOverlay.tsxindex 64030d137d..46caab6a47 100644--- a/packages/studio/src/components/editor/MotionPathOverlay.tsx+++ b/packages/studio/src/components/editor/MotionPathOverlay.tsx@@ -8,11 +8,12 @@ import { usePlayerStore } from "../../player/store/playerStore";import { useLivePreviewIframe } from "../../player/store/previewIframeStore";import { parkPlayheadOnKeyframe } from "../../hooks/gsapDragCommit";import { commitWholePropertyOffset } from "../../hooks/gsapWholePropertyOffsetCommit";-import { nearestPointOnPath, type MotionNodeRef } from "./motionPathGeometry";+import { nearestPointOnPath, nodeCentre, type MotionNodeRef } from "./motionPathGeometry";import { editableAnimationId, selectorFor } from "./motionPathSelection";-import { dotRadius, pressBelongsToLayer, pressSelectedLayer } from "./motionPathLayerNode";+import { controlForNode, controlUnder, pressControl } from "./motionPathLayerNode";import { readGsapPositionFromIframe } from "../../hooks/gsapPositionDetection";-import { ACCENT, MotionPathNode } from "./MotionPathNode";+import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";+import { ACCENT, MotionPathLine, MotionPathNode } from "./MotionPathNode";import {KeyframeDiamondContextMenu,type KeyframeDiamondContextMenuState,@@ -25,13 +26,8 @@ import {commitNode,commitRemoveWaypoint,} from "./motionPathCommit";-import {- elementHome,- hasMotionPathPlugin,- isPreviewHtmlElement,- transformWDivisor,- useMotionPathData,-} from "./useMotionPathData";+import { elementHome } from "./motionPathHome";+import { hasMotionPathPlugin, transformWDivisor, useMotionPathData } from "./useMotionPathData";interface MotionPathOverlayProps {iframeRef: RefObject<HTMLIFrameElement | null>;@@ -101,6 +97,7 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({);const [draft, setDraft] = useState<Draft | null>(null);const [ghost, setGhost] = useState<{ x: number; y: number; segIndex: number } | null>(null);+ const [lineCursor, setLineCursor] = useState("copy");const [hoverNode, setHoverNode] = useState<number | null>(null);// Right-click context menu on a path node — same delete actions as the// timeline keyframe diamond. The node it was opened on rides along, because@@ -194,7 +191,7 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({// Resolve the element LIVE from the current iframe document — the selected// node may be detached after a soft-reload, which would skew home.const live = frame.contentDocument?.querySelector(createSelector);- if (!isPreviewHtmlElement(live, frame)) return;+ if (!isHtmlElement(live)) return;e.stopPropagation();e.preventDefault();const sc = r.width / compW;@@ -284,12 +281,12 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({// pivot (transform-origin), so it stays put; only the offsets foreshorten. 2D// elements have pScale = 1 (no change). Inverse (de-magnify) applied wherever a// pointer position is mapped back to a stored offset (create + node drag).- const abs = nodes.map((n) => ({- ...n,- ax: home.x + n.x * pScale,- ay: home.y + n.y * pScale,- }));+ const abs = nodes.map((n) => {+ const c = nodeCentre(n, home, pScale);+ return { ...n, ax: c.x, ay: c.y };+ });const points = abs.map((p) => `${p.ax},${p.ay}`).join(" ");+ const startAt = geometry.start && nodeCentre(geometry.start, home, pScale);// Map a VIEWPORT pointer to composition space. Use the iframe's LIVE viewport// rect, not `rect` — `rect.left/top` are stored pan-surface-relative (for the// absolute-positioned SVG), so subtracting them from a viewport clientX/Y would@@ -313,9 +310,7 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({if (e.button !== 0) return;e.stopPropagation();const live = readGsapPositionFromIframe(iframeRef.current, selectorFor(selection) ?? "");- const dotR = dotRadius(nodeR, ref.type === "keyframe" && ref.pct === activeKeyframePct);- if (pressBelongsToLayer(e, clientToComp(e), abs[index]!, dotR, live) && pressSelectedLayer(e))- return;+ if (pressControl(e, controlForNode(e, abs[index]!, live))) return;(e.target as Element).setPointerCapture(e.pointerId);dragRef.current = {index,@@ -378,10 +373,7 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({// high zoom) would commit an identical value — a no-op undo entry. Skip the// commit, but don't treat it as a click either (the user did drag).if (x === Math.round(d.initX) && y === Math.round(d.initY)) return;- // With auto-keyframe off (#1808), dragging a keyframe's node on the motion- // path (the common way to nudge a KEYFRAMED element's position on canvas,- // since the element renders exactly at its current keyframe) shifts the- // whole path instead of moving just that one keyframe.+ // Auto-keyframe off (#1808): dragging a keyframe's node shifts the whole path.const anim =d.ref.type === "keyframe" ? selectedGsapAnimations?.find((a) => a.id === animId) : undefined;if (@@ -405,9 +397,7 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({} else {void commitNode(d.ref, x, y, animId, commitMutation);}- // Park the playhead on the edited keyframe's time so the element previews AT- // that keyframe. Without it, a playhead sitting before the tween renders the- // element's base pose — the edit (correct on the path) looks like it vanished.+ // Park on the edited keyframe, or a playhead before the tween hides the edit.if (d.ref.type === "keyframe" && anim) {parkPlayheadOnKeyframe(anim, d.ref.pct);}@@ -415,15 +405,21 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({// Ghost "add" affordance: project the cursor onto the path; click inserts.const onPathHover = (e: React.PointerEvent) => {+ const control = controlUnder(e);+ setLineCursor(control ? getComputedStyle(control).cursor : "copy");const c = clientToComp(e);const np = nearestPointOnPath(c.x,c.y,abs.map((p) => ({ x: p.ax, y: p.ay })),);- setGhost(np ? { x: np.x, y: np.y, segIndex: np.segIndex } : null);+ setGhost(np && !control ? { x: np.x, y: np.y, segIndex: np.segIndex } : null);};const onPathDown = (e: React.PointerEvent) => {+ if (pressControl(e, controlUnder(e))) {+ e.stopPropagation();+ return;+ }if (!animId) return;// Compute the insertion point from the event directly so a click works// without (or faster than) a preceding hover.@@ -434,8 +430,9 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({abs.map((p) => ({ x: p.ax, y: p.ay })),);if (!np) return;- const x = Math.round(np.x - home.x);- const y = Math.round(np.y - home.y);+ const [a, b] = [abs[np.segIndex]!, abs[np.segIndex + 1]!];+ const x = Math.round(a.x + np.t * (b.x - a.x));+ const y = Math.round(a.y + np.t * (b.y - a.y));if (geometry.kind === "arc") {e.stopPropagation();void commitAddWaypoint(animId, np.segIndex + 1, x, y, commitMutation);@@ -458,10 +455,8 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({};const elementId = selection?.id ?? null;- // Right-click any path node → the timeline's keyframe context menu (delete this- // one / delete all), so path nodes are removable in place. Waypoints open it- // too: returning early for them let the browser's own context menu open over- // the editor overlay, which is never what a right-click on a node should do.+ // Right-click any path node → the timeline's keyframe menu. Waypoints too, or the+ // browser's own context menu opens over the editor.const onNodeContextMenu = (e: React.MouseEvent, ref: MotionNodeRef) => {if (!animId || !elementId || !timelineElement) return;e.preventDefault();@@ -525,39 +520,13 @@ export const MotionPathOverlay = memo(function MotionPathOverlay({stroke="transparent"strokeWidth={14 / scale}className="pointer-events-auto"- style={{ cursor: "copy" }}+ style={{ cursor: lineCursor }}onPointerMove={onPathHover}onPointerLeave={() => setGhost(null)}onPointerDown={onPathDown}/>)}- <polyline- points={points}- fill="none"- style={{ stroke: ACCENT }}- strokeWidth={1.5}- strokeDasharray="5 5"- strokeLinejoin="round"- strokeLinecap="round"- vectorEffect="non-scaling-stroke"- opacity={0.85}- />- {ghost && (- <rect- x={ghost.x - nodeR * 0.707}- y={ghost.y - nodeR * 0.707}- width={nodeR * 1.414}- height={nodeR * 1.414}- rx={nodeR * 0.24}- transform={`rotate(45 ${ghost.x} ${ghost.y})`}- fill="none"- strokeWidth={1.5}- strokeDasharray="2 2"- vectorEffect="non-scaling-stroke"- className="pointer-events-none"- style={{ stroke: ACCENT }}- />- )}+ <MotionPathLine points={points} start={startAt} ghost={ghost} r={nodeR} />{abs.map((p, i) => (<MotionPathNodekey={i}diff --git a/packages/studio/src/components/editor/canvasContextMenuZOrder.ts b/packages/studio/src/components/editor/canvasContextMenuZOrder.tsindex 47b69c1483..a1c753a0d9 100644--- a/packages/studio/src/components/editor/canvasContextMenuZOrder.ts+++ b/packages/studio/src/components/editor/canvasContextMenuZOrder.ts@@ -124,17 +124,8 @@ export function readEffectiveZIndex(el: HTMLElement): number {return 0;}-/**- * Realm-safe HTMLElement check. The target lives in the preview IFRAME's- * document, but this module runs in the top window, so `child instanceof- * HTMLElement` (top-window constructor) is ALWAYS false for iframe elements —- * which silently emptied the sibling list and left every z-order action- * permanently disabled. Compare against the element's own realm instead, with- * a nodeType fallback for detached / cross-realm edge cases.- */+/** Any element, asked structurally: the preview's nodes are not this window's. */function isElementNode(node: Node): node is HTMLElement {- const view = node.ownerDocument?.defaultView;- if (view && node instanceof view.HTMLElement) return true;return node.nodeType === 1;}diff --git a/packages/studio/src/components/editor/manualEditsSeekReapply.ts b/packages/studio/src/components/editor/manualEditsSeekReapply.tsindex 6782e7c2e3..b22837061b 100644--- a/packages/studio/src/components/editor/manualEditsSeekReapply.ts+++ b/packages/studio/src/components/editor/manualEditsSeekReapply.ts@@ -1,4 +1,5 @@// Puts Studio's committed edits back after a timeline seek has rendered over them.+import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";import {STUDIO_BOX_SIZE_ATTR,STUDIO_HEIGHT_PROP,@@ -15,15 +16,11 @@ import { STUDIO_MOTION_ATTR, STUDIO_MOTION_TIMELINE_ID } from "./studioMotionTypimport { gsapWritesChannels } from "../../hooks/gsapRuntimeKeyframes";function queryStudioElements(doc: Document, attr: string): HTMLElement[] {- const ctor = doc.defaultView?.HTMLElement;- if (!ctor) return [];- const elements = Array.from(doc.querySelectorAll(`[${attr}="true"]`)).filter(- (el): el is HTMLElement => el instanceof ctor,- );+ const elements = Array.from(doc.querySelectorAll(`[${attr}="true"]`)).filter(isHtmlElement);// Handle legacy HTML files where attributes were persisted with a double data- prefixconst legacyAttr = `data-${attr}`;for (const el of doc.querySelectorAll(`[${legacyAttr}="true"]`)) {- if (el instanceof ctor && !el.hasAttribute(attr)) {+ if (isHtmlElement(el) && !el.hasAttribute(attr)) {el.setAttribute(attr, "true");el.removeAttribute(legacyAttr);elements.push(el);diff --git a/packages/studio/src/components/editor/manualOffsetDrag.ts b/packages/studio/src/components/editor/manualOffsetDrag.tsindex 5fc332bb4f..9db1f5c296 100644--- a/packages/studio/src/components/editor/manualOffsetDrag.ts+++ b/packages/studio/src/components/editor/manualOffsetDrag.ts@@ -1,3 +1,4 @@+import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";import type { DomEditSelection } from "./domEditing";import {applyStudioPathOffset,@@ -131,9 +132,7 @@ function getFrameElement(win: Window): HTMLElement | null {try {const frameElement = win.frameElement;if (!frameElement) return null;- const ownerWin = frameElement.ownerDocument.defaultView;- const htmlElement = ownerWin?.HTMLElement;- return htmlElement && frameElement instanceof htmlElement ? frameElement : null;+ return isHtmlElement(frameElement) ? frameElement : null;} catch {return null;}diff --git a/packages/studio/src/components/editor/motionPathGeometry.test.ts b/packages/studio/src/components/editor/motionPathGeometry.test.tsindex be5f3840a6..da65dab330 100644--- a/packages/studio/src/components/editor/motionPathGeometry.test.ts+++ b/packages/studio/src/components/editor/motionPathGeometry.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { buildMotionPathGeometry, nearestPointOnPath } from "./motionPathGeometry";+import { buildMotionPathGeometry, nearestPointOnPath, nodeCentre } from "./motionPathGeometry";import type { ReadTween } from "../../hooks/gsapRuntimeKeyframes";const kf = (percentage: number, x: number, y: number) => ({ percentage, properties: { x, y } });@@ -135,3 +135,50 @@ describe("nearestPointOnPath", () => {expect(nearestPointOnPath(0, 0, [{ x: 0, y: 0 }])).toBeNull();});});++describe("nodeCentre", () => {+ // The edit bench's `keys` layer at 1 s: left 560, 260 wide now, GSAP x 50; it reaches x 60 and+ // width 280 at 2 s, x 120 and width 320 at 3 s, so its centre is then at 760 and 840.+ const home = { x: 690, y: 380, w: 260, h: 160, ax: 0.5, ay: 0.5 };+ const read: ReadTween = {+ keyframes: [+ { percentage: 66.667, properties: { x: 60, width: 280 } },+ { percentage: 100, properties: { x: 120, width: 320 } },+ ],+ };++ it("draws a keyframe that also sets the size where the layer's centre is at that keyframe", () => {+ const geo = buildMotionPathGeometry(read, { x: 50, y: 30 })!;+ expect(geo.nodes.map((n) => nodeCentre(n, home, 1))).toEqual([+ { x: 760, y: 410 },+ { x: 840, y: 410 },+ ]);+ });++ it("keeps a layer centred by xPercent/yPercent -50 on its centre as a keyframe resizes it", () => {+ const geo = buildMotionPathGeometry(read, { x: 50, y: 30 })!;+ const centred = { ...home, ax: 0, ay: 0 };+ expect(geo.nodes.map((n) => nodeCentre(n, centred, 1).x)).toEqual([750, 810]);+ });++ it("keeps a keyframe that sets no size at home plus its offset", () => {+ const geo = buildMotionPathGeometry({ keyframes: [kf(0, 10, 20), kf(100, 200, 80)] })!;+ expect(nodeCentre(geo.nodes[1]!, home, 1)).toEqual({ x: 890, y: 460 });+ });+});++describe("start", () => {+ it("keeps where GSAP started a tween whose first keyframe comes later, with the size it had", () => {+ const read: ReadTween = {+ keyframes: [kf(66.667, 60, 30), kf(100, 120, 30)],+ start: { x: 40, y: 30, width: 260 },+ };+ expect(buildMotionPathGeometry(read)?.start).toEqual({ x: 40, y: 30, w: 260 });+ });++ it("draws no start when GSAP has not read one", () => {+ expect(buildMotionPathGeometry({ keyframes: [kf(50, 60, 30), kf(100, 120, 30)] })?.start).toBe(+ undefined,+ );+ });+});diff --git a/packages/studio/src/components/editor/motionPathGeometry.ts b/packages/studio/src/components/editor/motionPathGeometry.tsindex 6cbda07ca2..6676ca33eb 100644--- a/packages/studio/src/components/editor/motionPathGeometry.ts+++ b/packages/studio/src/components/editor/motionPathGeometry.ts@@ -11,18 +11,40 @@ export type MotionNodeRef =| { type: "keyframe"; pct: number } // x/y position keyframe at this tween-relative %| { type: "waypoint"; index: number }; // motionPath waypoint (anchor) at this index-export interface MotionPathNode {+/** An offset on the path and the layout width/height set there, when one is. */+export interface MotionPathPoint {x: number;y: number;+ w?: number;+ h?: number;+}++export interface MotionPathNode extends MotionPathPoint {ref: MotionNodeRef;}+/** The live layer's centre without its x/y offset, its layout size now, and the share of a size+ * change that moves the centre (0.5 from the left edge; 0 when xPercent -50 centres it). */+export type MotionPathHome = { x: number; y: number; w: number; h: number; ax: number; ay: number };++/** Where the layer's centre is at a node, with the size that keyframe sets. */+export function nodeCentre(n: MotionPathPoint, home: MotionPathHome, pScale: number) {+ const grow = (to: number | undefined, now: number, share: number) =>+ to === undefined ? 0 : (to - now) * share;+ return {+ x: home.x + (n.x + grow(n.w, home.w, home.ax)) * pScale,+ y: home.y + (n.y + grow(n.h, home.h, home.ay)) * pScale,+ };+}+export interface MotionPathGeometry {/** "linear" = x/y keyframes; "arc" = motionPath tween. */kind: "linear" | "arc";/** SVG polyline points: "x,y x,y ...". */points: string;nodes: MotionPathNode[];+ /** Where GSAP started the tween, when its first keyframe comes later: drawn, not draggable. */+ start?: MotionPathPoint;}/**@@ -78,6 +100,16 @@ export function nearestPointOnPath(return best;}+const finiteNumber = (v: unknown): v is number => typeof v === "number" && isFinite(v);++/** The layout width/height a keyframe sets, when it sets one. */+function sizeAt(p: Record<string, unknown>): { w?: number; h?: number } {+ return {+ ...(finiteNumber(p.width) && { w: p.width }),+ ...(finiteNumber(p.height) && { h: p.height }),+ };+}+export function buildMotionPathGeometry(read: ReadTween | null,base: { x: number; y: number } = { x: 0, y: 0 },@@ -94,26 +126,32 @@ export function buildMotionPathGeometry(// translate it folded in, else 0), so we default it and still draw a path. But if the tween// DOES animate an axis and a given keyframe omits it, that value is interpolated// (not 0) and can't be placed here → skip that node (the prior behavior).- const finite = (v: unknown): v is number => typeof v === "number" && isFinite(v);- const tweenHasX = read.keyframes.some((kf) => finite(kf.properties.x));- const tweenHasY = read.keyframes.some((kf) => finite(kf.properties.y));+ const tweenHasX = read.keyframes.some((kf) => finiteNumber(kf.properties.x));+ const tweenHasY = read.keyframes.some((kf) => finiteNumber(kf.properties.y));if (!tweenHasX && !tweenHasY) return null; // no positional motion (opacity/scale only)+ const pointAt = (p: Record<string, unknown>): MotionPathPoint | null => {+ if ((tweenHasX && !finiteNumber(p.x)) || (tweenHasY && !finiteNumber(p.y))) return null;+ const x = tweenHasX ? (p.x as number) : base.x;+ const y = tweenHasY ? (p.y as number) : base.y;+ return { x, y, ...sizeAt(p) };+ };read.keyframes.forEach((kf, i) => {- if (tweenHasX && !finite(kf.properties.x)) return;- if (tweenHasY && !finite(kf.properties.y)) return;+ const at = pointAt(kf.properties);+ if (!at) return;nodes.push({- x: tweenHasX ? (kf.properties.x as number) : base.x,- y: tweenHasY ? (kf.properties.y as number) : base.y,+ ...at,ref: isArc ? { type: "waypoint", index: i } : { type: "keyframe", pct: kf.percentage },});});if (nodes.length < 2) return null;+ const start = !isArc && read.start ? pointAt(read.start) : null;return {kind: isArc ? "arc" : "linear",points: nodes.map((n) => `${n.x},${n.y}`).join(" "),nodes,+ ...(start && { start }),};}diff --git a/packages/studio/src/components/editor/motionPathHome.ts b/packages/studio/src/components/editor/motionPathHome.tsnew file mode 100644index 0000000000..556e252578--- /dev/null+++ b/packages/studio/src/components/editor/motionPathHome.ts@@ -0,0 +1,75 @@+import type { MotionPathHome } from "./motionPathGeometry";++// An element's computed transform translate: a group wrapper GSAP moved carries its offset here.+function transformTranslate(el: HTMLElement): { x: number; y: number } {+ const t = el.ownerDocument?.defaultView?.getComputedStyle(el).transform;+ if (!t || t === "none") return { x: 0, y: 0 };+ const m3 = t.match(/matrix3d\(([^)]+)\)/);+ if (m3) {+ const v = m3[1].split(",").map(Number);+ return { x: v[12] || 0, y: v[13] || 0 };+ }+ const m = t.match(/matrix\(([^)]+)\)/);+ if (m) {+ const v = m[1].split(",").map(Number);+ return { x: v[4] || 0, y: v[5] || 0 };+ }+ return { x: 0, y: 0 };+}++function cssTranslate(el: HTMLElement): [number, number] {+ const raw = el.ownerDocument?.defaultView?.getComputedStyle(el).translate ?? "none";+ const [x = "0", y = "0"] = raw === "none" ? [] : raw.split(" ");+ const px = (v: string, size: number) =>+ v.endsWith("%") ? (Number.parseFloat(v) / 100) * size : Number.parseFloat(v) || 0;+ return [px(x, el.offsetWidth), px(y, el.offsetHeight)];+}++/** Centre shift per px grown: 0.5 from a set left/top, -0.5 from a set right/bottom, plus the percent.+ * ponytail: in-flow layers get 0 (layout may centre them); read their anchor if one draws off. */+function growShares(el: HTMLElement, px: number, py: number): { ax: number; ay: number } {+ const style = el.ownerDocument?.defaultView?.getComputedStyle(el);+ if (!style || !/^(absolute|fixed)$/.test(style.position)) return { ax: 0, ay: 0 };+ const map = el.computedStyleMap?.();+ const auto = (side: string) => String(map?.get(side) ?? "") === "auto";+ const share = (start: string, end: string) => (auto(start) && !auto(end) ? -0.5 : 0.5);+ return { ax: share("left", "right") + px, ay: share("top", "bottom") + py };+}++export function elementHome(el: HTMLElement): MotionPathHome {+ let left = 0;+ let top = 0;+ let node: HTMLElement | null = el;+ while (node) {+ left += node.offsetLeft;+ top += node.offsetTop;+ // Ancestor transforms (a group wrapper GSAP moved) shift where the layer renders; its own+ // transform is the animated offset the path itself draws, so it is left out.+ if (node !== el) {+ const t = transformTranslate(node);+ left += t.x;+ top += t.y;+ }+ const parent = node.offsetParent as HTMLElement | null;+ if (!parent || parent.hasAttribute("data-composition-id")) break;+ node = parent;+ }+ // A translate composes once GSAP has parsed the layer; before, its parse sums translate and transform,+ // makes minus half the size xPercent -50 and folds the rest into x, which a path sets (_parseTransform).+ const cache = (+ el as { _gsap?: { x?: unknown; uncache?: unknown; xPercent?: unknown; yPercent?: unknown } }+ )._gsap;+ const parsed = cache !== undefined && "x" in cache && !cache.uncache;+ const [tx, ty] = cssTranslate(el);+ const share = (cached: unknown, t: number, size: number) =>+ parsed ? (Number(cached) || 0) / 100 : t && Math.round(size / 2) === Math.round(-t) ? -0.5 : 0;+ const own = parsed ? { x: 0, y: 0 } : transformTranslate(el);+ const [px, py] = [+ share(cache?.xPercent, tx + own.x, el.offsetWidth),+ share(cache?.yPercent, ty + own.y, el.offsetHeight),+ ];+ const x = left + el.offsetWidth * (0.5 + px) + (parsed ? tx : 0);+ const y = top + el.offsetHeight * (0.5 + py) + (parsed ? ty : 0);+ const { ax, ay } = growShares(el, px, py);+ return { x, y, w: el.offsetWidth, h: el.offsetHeight, ax, ay };+}diff --git a/packages/studio/src/components/editor/motionPathLayerNode.test.ts b/packages/studio/src/components/editor/motionPathLayerNode.test.tsindex 2d7b11e41f..5a50a9a591 100644--- a/packages/studio/src/components/editor/motionPathLayerNode.test.ts+++ b/packages/studio/src/components/editor/motionPathLayerNode.test.ts@@ -1,54 +1,64 @@// @vitest-environment happy-domimport { expect, it } from "vitest";-import { pressBelongsToLayer, pressSelectedLayer } from "./motionPathLayerNode";+import { controlForNode, controlUnder, pressControl } from "./motionPathLayerNode";-// Keyframe nodes at x 60 and 120 (y 30), drawn from home (500, 400); dots of radius 6.-const atLayer = { x: 60, y: 30, ax: 560, ay: 430 };-const other = { x: 120, y: 30, ax: 620, ay: 430 };+// Keyframe nodes at x 60 and 120 (y 30); GSAP renders the layer at the first.+const atLayer = { x: 60, y: 30 };+const other = { x: 120, y: 30 };const live = { x: 60, y: 30 };+// The editor overlay: the selection's chrome (box and a handle) and another layer's off-canvas marker.+const overlay = document.createElement("div");+const chrome = document.createElement("div");+chrome.setAttribute("data-dom-edit-chrome", "true");const box = document.createElement("div");box.setAttribute("data-dom-edit-selection-box", "true");+const handle = document.createElement("button");+const marker = document.createElement("div");+chrome.append(box, handle);+overlay.append(chrome, marker);+const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");-document.body.append(box, circle);+const line = document.createElementNS("http://www.w3.org/2000/svg", "polyline");+svg.append(line, circle);+document.body.append(overlay, svg);-/** A press on `circle` at (x, y), with `under` what the document hit-tests there. */-function press(x: number, y: number, under: Element[]) {- document.elementsFromPoint = () => [circle, ...under];- return { currentTarget: circle, clientX: x, clientY: y } as unknown as React.PointerEvent;+/** A press on `circle`, with `under` what the document hit-tests below it. */+function press(under: Element[]) {+ document.elementsFromPoint = () => [circle, line, ...under];+ return { currentTarget: circle, clientX: 0, clientY: 0 } as unknown as React.PointerEvent;}it("the node GSAP renders the layer at is the layer, inside the box or out", () => {- expect(pressBelongsToLayer(press(562, 431, [box]), { x: 562, y: 431 }, atLayer, 6, live)).toBe(- true,- );- expect(pressBelongsToLayer(press(570, 440, []), { x: 570, y: 440 }, atLayer, 6, live)).toBe(true);+ expect(controlForNode(press([box, overlay]), atLayer, live)).toBe(box);+ expect(controlForNode(press([overlay]), atLayer, live)).toBe(box);});-it("inside the layer's box another node's grab ring is the layer's; its dot stays the node's", () => {- expect(pressBelongsToLayer(press(610, 430, [box]), { x: 610, y: 430 }, other, 6, live)).toBe(- true,- );- expect(pressBelongsToLayer(press(617, 430, [box]), { x: 617, y: 430 }, other, 6, live)).toBe(- false,- );+it("inside the layer's box any other node is the layer's, so a drag from its middle moves it", () => {+ expect(controlForNode(press([box, overlay]), other, live)).toBe(box);+ expect(controlForNode(press([box, overlay]), other, null)).toBe(box);});-it("outside the layer's box a node's whole grab ring is the node's", () => {- expect(pressBelongsToLayer(press(610, 430, []), { x: 610, y: 430 }, other, 6, live)).toBe(false);- expect(pressBelongsToLayer(press(610, 430, [box]), { x: 610, y: 430 }, other, 6, null)).toBe(- true,- );+it("a handle above the box under a node takes the press, not the box or the node", () => {+ expect(controlForNode(press([handle, box, overlay]), other, live)).toBe(handle);+ expect(controlForNode(press([handle, box, overlay]), atLayer, live)).toBe(handle);+ expect(controlUnder(press([handle, overlay]))).toBe(handle);});-it("hands a press to the selected layer's box with its pointer and position", () => {+it("outside the layer's box and its handles a node is the node's", () => {+ expect(controlForNode(press([overlay]), other, live)).toBeNull();+ expect(controlForNode(press([marker, overlay]), other, live)).toBeNull();+ expect(controlForNode(press([document.body]), other, live)).toBeNull();+});++it("hands a press to the control with its pointer and position", () => {const got: number[][] = [];const listen = (e: Event) => {const p = e as PointerEvent;got.push([p.pointerId, p.clientX, p.clientY, p.button]);e.preventDefault();};- box.addEventListener("pointerdown", listen);+ handle.addEventListener("pointerdown", listen);const nativeEvent = new PointerEvent("pointerdown", {pointerId: 7,clientX: 12,@@ -58,24 +68,22 @@ it("hands a press to the selected layer's box with its pointer and position", ()cancelable: true,});const down = { currentTarget: circle, nativeEvent } as unknown as React.PointerEvent;- expect(pressSelectedLayer(down)).toBe(true);+ expect(pressControl(down, handle)).toBe(true);expect(got).toEqual([[7, 12, 34, 0]]);- box.removeEventListener("pointerdown", listen);- box.remove();- expect(pressSelectedLayer(down)).toBe(false);- document.body.append(box);+ expect(pressControl(down, null)).toBe(false);+ handle.removeEventListener("pointerdown", listen);});-it("keeps the press when the box does not start a gesture with it, or takes no pointer", () => {+it("keeps the press when the control does not start a gesture with it, or takes no pointer", () => {let got = 0;const listen = () => void got++;box.addEventListener("pointerdown", listen);const nativeEvent = new PointerEvent("pointerdown", { bubbles: true, cancelable: true });const down = { currentTarget: circle, nativeEvent } as unknown as React.PointerEvent;- expect(pressSelectedLayer(down)).toBe(false);+ expect(pressControl(down, box)).toBe(false);expect(got).toBe(1);box.style.pointerEvents = "none";- expect(pressSelectedLayer(down)).toBe(false);+ expect(pressControl(down, box)).toBe(false);expect(got).toBe(1);box.style.pointerEvents = "";box.removeEventListener("pointerdown", listen);diff --git a/packages/studio/src/components/editor/motionPathLayerNode.ts b/packages/studio/src/components/editor/motionPathLayerNode.tsindex dd49d4712a..c245f85246 100644--- a/packages/studio/src/components/editor/motionPathLayerNode.ts+++ b/packages/studio/src/components/editor/motionPathLayerNode.ts@@ -1,28 +1,32 @@type Point = { x: number; y: number };-type DrawnNode = Point & { ax: number; ay: number };const LAYER_BOX = '[data-dom-edit-selection-box="true"]';+export const SELECTION_CHROME = `${LAYER_BOX}, [data-dom-edit-chrome="true"], [data-dom-edit-crop-frame="true"]`;/** How far a node's dot reaches; a selected node draws it larger. */export const dotRadius = (r: number, selected: boolean) => (selected ? r * 1.5 : r);-/** A press on the layer's own node, or in its box but off a node's dot, belongs to the layer. */-export function pressBelongsToLayer(+export function controlUnder(e: React.PointerEvent): Element | null {+ const path = e.currentTarget.closest("svg");+ const hits = e.currentTarget.ownerDocument.elementsFromPoint(e.clientX, e.clientY);+ const hit = hits.find((el) => !path?.contains(el));+ return hit?.closest(SELECTION_CHROME) ? hit : null;+}++/** The handle or box above a node, else the box if the layer sits at the node; null: the node. */+export function controlForNode(e: React.PointerEvent,- point: Point,- pressed: DrawnNode,- dotR: number,+ pressed: Point,live: Point | null,-): boolean {- if (live && Math.abs(pressed.x - live.x) < 0.5 && Math.abs(pressed.y - live.y) < 0.5) return true;- const hits = e.currentTarget.ownerDocument.elementsFromPoint(e.clientX, e.clientY);- const inBox = hits.some((el) => el.closest(LAYER_BOX));- return inBox && Math.hypot(point.x - pressed.ax, point.y - pressed.ay) > dotR;+): Element | null {+ const atLayer = live && Math.abs(pressed.x - live.x) < 0.5 && Math.abs(pressed.y - live.y) < 0.5;+ return (+ controlUnder(e) ?? (atLayer ? e.currentTarget.ownerDocument.querySelector(LAYER_BOX) : null)+ );}-/** Hands a press to the selected layer's box; true when the box started a gesture with it. */-export function pressSelectedLayer(e: React.PointerEvent): boolean {- const box = e.currentTarget.ownerDocument.querySelector(LAYER_BOX);- if (!box || getComputedStyle(box).pointerEvents === "none") return false;- return !box.dispatchEvent(new PointerEvent("pointerdown", e.nativeEvent));+/** Hands a press to `control`; true when it started a gesture with it. */+export function pressControl(e: React.PointerEvent, control: Element | null): boolean {+ if (!control || getComputedStyle(control).pointerEvents === "none") return false;+ return !control.dispatchEvent(new PointerEvent("pointerdown", e.nativeEvent));}diff --git a/packages/studio/src/components/editor/reapplyPositionEditsAfterSeek.test.ts b/packages/studio/src/components/editor/reapplyPositionEditsAfterSeek.test.tsindex b40b9bb810..558435ec7f 100644--- a/packages/studio/src/components/editor/reapplyPositionEditsAfterSeek.test.ts+++ b/packages/studio/src/components/editor/reapplyPositionEditsAfterSeek.test.ts@@ -130,6 +130,26 @@ describe("reapplyPositionEditsAfterSeek", () => {delete win.__timelines;});+ it("reapplies and migrates marks in the preview, whichever window built its node", () => {+ const frame = document.body.appendChild(document.createElement("iframe"));+ const doc = frame.contentDocument!;+ // The frame builds one node; the editor builds the other, as on loads where they differ.+ const nodes = [doc.createElement("div"), document.createElement("div")];+ for (const el of nodes) {+ el.setAttribute(`data-${STUDIO_PATH_OFFSET_ATTR}`, "true");+ el.setAttribute(STUDIO_ROTATION_ATTR, "true");+ el.style.setProperty(STUDIO_ROTATION_PROP, "8deg");+ doc.body.append(el);+ }++ reapplyPositionEditsAfterSeek(doc);++ for (const el of nodes) {+ expect(el.getAttribute(STUDIO_PATH_OFFSET_ATTR)).toBe("true");+ expect(el.style.getPropertyValue("rotate")).toContain(STUDIO_ROTATION_PROP);+ }+ });+it("still migrates a legacy double-prefixed edit mark", () => {document.body.innerHTML = `<div id="a" data-${STUDIO_PATH_OFFSET_ATTR}="true"></div>`;diff --git a/packages/studio/src/components/editor/studioMotion.ts b/packages/studio/src/components/editor/studioMotion.tsindex 19e494910d..a90dcd898f 100644--- a/packages/studio/src/components/editor/studioMotion.ts+++ b/packages/studio/src/components/editor/studioMotion.ts@@ -35,6 +35,7 @@ export {clearStudioMotionFromElement,} from "./studioMotionOps";+import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";import { readStudioMotionFromElement as readMotionAttr } from "./studioMotionOps";import {STUDIO_MOTION_ATTR,@@ -71,21 +72,17 @@ function elementMatchesSourceFile(}function querySelectorCandidates(document: Document, selector: string): HTMLElement[] {- const isCandidate = (element: Element): element is HTMLElement => {- const HTMLElementCtor = element.ownerDocument.defaultView?.HTMLElement;- return Boolean(HTMLElementCtor && element instanceof HTMLElementCtor);- };const className = selector.match(/^\.([A-Za-z0-9_-]+)$/)?.[1];if (className) {return Array.from(document.getElementsByTagName("*")).filter((element): element is HTMLElement =>- isCandidate(element) && element.classList.contains(className),+ isHtmlElement(element) && element.classList.contains(className),);}if (/^[A-Za-z][A-Za-z0-9-]*$/.test(selector)) {- return Array.from(document.getElementsByTagName(selector)).filter(isCandidate);+ return Array.from(document.getElementsByTagName(selector)).filter(isHtmlElement);}- return Array.from(document.querySelectorAll(selector)).filter(isCandidate);+ return Array.from(document.querySelectorAll(selector)).filter(isHtmlElement);}function resolveTarget(@@ -93,12 +90,10 @@ function resolveTarget(target: StudioMotionTarget,activeCompositionPath: string | null,): HTMLElement | null {- const HTMLElementCtor = document.defaultView?.HTMLElement;if (target.id) {const byId = document.getElementById(target.id);if (- HTMLElementCtor &&- byId instanceof HTMLElementCtor &&+ isHtmlElement(byId) &&elementMatchesSourceFile(byId, target.sourceFile, activeCompositionPath)) {return byId;@@ -135,10 +130,8 @@ function restoreStudioMotionElement(element: HTMLElement, gsap: StudioMotionWind}function restoreStudioMotionElements(document: Document, gsap: StudioMotionWindow["gsap"]): void {- const HTMLElementCtor = document.defaultView?.HTMLElement;- if (!HTMLElementCtor) return;for (const element of Array.from(document.querySelectorAll(`[${STUDIO_MOTION_ATTR}]`))) {- if (element instanceof HTMLElementCtor) restoreStudioMotionElement(element, gsap);+ if (isHtmlElement(element)) restoreStudioMotionElement(element, gsap);}}@@ -238,11 +231,6 @@ export function applyStudioMotionFromDom(document: Document, currentTime?: numbewin.__timelines[STUDIO_MOTION_TIMELINE_ID]?.kill?.();delete win.__timelines[STUDIO_MOTION_TIMELINE_ID];- // Restore elements that had GSAP motion applied previously but whose attribute- // is now just the legacy marker "true" (i.e. they were restored/cleared).- const HTMLElementCtor = document.defaultView?.HTMLElement;- if (!HTMLElementCtor) return 0;-// Collect elements that have JSON motion data in their attributeconst motionElements: Array<{element: HTMLElement;@@ -257,7 +245,7 @@ export function applyStudioMotionFromDom(document: Document, currentTime?: numbe}> = [];for (const el of Array.from(document.querySelectorAll(`[${STUDIO_MOTION_ATTR}]`))) {- if (!(el instanceof HTMLElementCtor)) continue;+ if (!isHtmlElement(el)) continue;const motionData = readMotionAttr(el);if (motionData) {motionElements.push({ element: el, motion: motionData });diff --git a/packages/studio/src/components/editor/useMotionPathData.test.tsx b/packages/studio/src/components/editor/useMotionPathData.test.tsxindex e0869604ba..108a0a51bf 100644--- a/packages/studio/src/components/editor/useMotionPathData.test.tsx+++ b/packages/studio/src/components/editor/useMotionPathData.test.tsx@@ -1,7 +1,9 @@// @vitest-environment happy-dom+import { gsap } from "gsap";import { act, useRef } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { elementHome } from "./motionPathHome";import { useMotionPathData } from "./useMotionPathData";import { resetOverlayFrameLoopForTests } from "./overlayFrameLoop";import { usePlayerStore } from "../../player/store/playerStore";@@ -92,3 +94,237 @@ it("reads no layout per frame until there is a path or a create ring to draw", (act(() => root.unmount());}});++it("finds the layer whichever window built its node, so the path draws on every load", () => {+ runtime.read = {+ keyframes: [+ { percentage: 0, properties: { x: 0, y: 0 } },+ { percentage: 100, properties: { x: 100, y: 0 } },+ ],+ };+ const iframe = document.createElement("iframe");+ document.body.append(iframe);+ const box = iframe.contentDocument!.createElement("div");+ box.id = "box";+ iframe.contentDocument!.body.append(box);+ // happy-dom shares one realm, so the frame's own constructor stands in for another window's.+ Object.defineProperty(iframe.contentWindow!, "HTMLElement", { value: class {} });+ let home: unknown = null;+ function Probe() {+ const ref = useRef(iframe);+ home = useMotionPathData(ref, "#box").home;+ return null;+ }+ const root = createRoot(document.body.appendChild(document.createElement("div")));+ try {+ act(() => root.render(<Probe />));+ runFrames(3);+ expect(home).not.toBeNull();+ } finally {+ act(() => root.unmount());+ }+});++it("redraws a node whose keyframe changes only its size", () => {+ const read = (width: number) => ({+ keyframes: [+ { percentage: 66.667, properties: { x: 60, width } },+ { percentage: 100, properties: { x: 120, width: 320 } },+ ],+ });+ runtime.read = read(280);+ runtime.gsapPosition = { x: 50, y: 30 };+ let w: number | undefined;+ function Probe() {+ const ref = useRef(document.createElement("iframe"));+ w = useMotionPathData(ref, "#box").geometry?.nodes[0]?.w;+ return null;+ }+ const root = createRoot(document.body.appendChild(document.createElement("div")));+ try {+ act(() => root.render(<Probe />));+ expect(w).toBe(280);+ runtime.read = read(300);+ act(() => vi.advanceTimersByTime(250));+ expect(w).toBe(300);+ } finally {+ act(() => root.unmount());+ }+});++/** A layer laid out at (960, 540), 240 x 160, with `css` inline and `cache` as GSAP's `_gsap`. */+function layer(css: Partial<CSSStyleDeclaration>, cache?: Record<string, number>) {+ const el = document.body.appendChild(document.createElement("div"));+ Object.assign(el.style, css);+ const box = {+ offsetLeft: 960,+ offsetTop: 540,+ offsetWidth: 240,+ offsetHeight: 160,+ offsetParent: null,+ };+ for (const [key, value] of Object.entries(box)) Object.defineProperty(el, key, { value });+ return cache ? Object.assign(el, { _gsap: cache }) : el;+}++it("anchors a layer GSAP centres with xPercent/yPercent -50 on its centre", () => {+ const el = layer(+ { position: "absolute", left: "50%", top: "50%" },+ { x: 0, y: 0, xPercent: -50, yPercent: -50 },+ );+ expect(elementHome(el)).toEqual({ x: 960, y: 540, w: 240, h: 160, ax: 0, ay: 0 });+});++it("moves a resized layer's centre by half the change from a set left, against it from a set right, and not in flow", () => {+ const fromLeft = layer({ position: "absolute", left: "10px", top: "10px" });+ expect(elementHome(fromLeft)).toMatchObject({ x: 1080, y: 620, ax: 0.5, ay: 0.5 });+ const fromRight = layer({ position: "absolute", right: "10px", bottom: "10px" });+ const auto = new Set(["left", "top"]);+ fromRight.computedStyleMap = () =>+ ({+ get: (side: string) => (auto.has(side) ? "auto" : "10px"),+ }) as unknown as StylePropertyMapReadOnly;+ expect(elementHome(fromRight)).toMatchObject({ ax: -0.5, ay: -0.5 });+ expect(elementHome(layer({}))).toMatchObject({ x: 1080, ax: 0, ay: 0 });+});++const resolved = (style: CSSStyleDeclaration) =>+ (style.translate ?? "").replace(/var\((--[\w-]+)\)/g, (_, name) =>+ style.getPropertyValue(name),+ ) || "none";++/** Computes `translate` and `transform` as Chromium does (happy-dom does not), so GSAP's parse would fold them. */+function computeTranslate() {+ const real = window.getComputedStyle.bind(window);+ const computed = (node: Element, pseudo?: string | null) =>+ new Proxy(real(node, pseudo), {+ get(style, key) {+ if (key === "translate") return resolved((node as HTMLElement).style);+ if (key === "transform") return (node as HTMLElement).style.transform || "none";+ if (key === "scale" || key === "rotate") return "none";+ const value = Reflect.get(style, key);+ return typeof value === "function" ? value.bind(style) : value;+ },+ });+ vi.stubGlobal("getComputedStyle", computed);+ vi.spyOn(window, "getComputedStyle").mockImplementation(+ computed as typeof window.getComputedStyle,+ );+}++it("leaves a layer's CSS translate alone and anchors where GSAP's parse will put it (real GSAP)", () => {+ vi.stubGlobal("gsap", gsap);+ computeTranslate();+ try {+ const offset = "var(--hf-studio-offset-x) var(--hf-studio-offset-y)";+ const cases: [string, number, number][] = [+ // GSAP folds these into x, which a created path sets.+ ["40px 30px", 1080, 620],+ [offset, 1080, 620],+ // Minus half the size becomes xPercent/yPercent -50.+ ["-50% -50%", 960, 540],+ ["-120px -80px", 960, 540],+ ];+ // GSAP sums the layer's own transform with its translate: Chromium's matrix for translate(-50%, -50%).+ const centred = layer({ position: "absolute", transform: "matrix(1, 0, 0, 1, -120, -80)" });+ expect(elementHome(centred)).toMatchObject({ x: 960, y: 540 });+ for (const [translate, x, y] of cases) {+ const el = layer({ position: "absolute", left: "10px", top: "10px", translate });+ el.style.setProperty("--hf-studio-offset-x", "40px");+ el.style.setProperty("--hf-studio-offset-y", "30px");+ expect(elementHome(el), translate).toMatchObject({ x, y });+ expect([el.style.translate, el.style.transform]).toEqual([translate, ""]);+ }+ // A drag's offset on a layer GSAP already parsed composes with its transform.+ const dragged = layer({ position: "absolute", left: "10px", top: "10px" });+ gsap.set(dragged, { x: 20 });+ dragged.style.setProperty("--hf-studio-offset-x", "40px");+ dragged.style.setProperty("--hf-studio-offset-y", "30px");+ dragged.style.translate = offset;+ expect(elementHome(dragged)).toMatchObject({ x: 1120, y: 650 });+ // After clearProps GSAP marks its cache uncache and its next parse folds the translate again.+ const css = { position: "absolute", left: "10px", top: "10px", translate: "40px 30px" };+ expect(elementHome(layer(css, { x: 0, y: 0, uncache: 1 }))).toMatchObject({ x: 1080, y: 620 });+ // A fade gives GSAP a cache with no transform in it yet, so its next parse still folds.+ expect(elementHome(layer(css, { opacity: 1 }))).toMatchObject({ x: 1080, y: 620 });+ const owned = layer({ position: "absolute", left: "50%", top: "50%" });+ gsap.set(owned, { xPercent: -50, yPercent: -50 });+ expect(elementHome(owned)).toMatchObject({ x: 960, y: 540, ax: 0, ay: 0 });+ } finally {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ }+});++it("redraws the start ring when only GSAP's start changes", () => {+ const read = (start?: Record<string, number>) => ({+ keyframes: [+ { percentage: 50, properties: { x: 60 } },+ { percentage: 100, properties: { x: 120 } },+ ],+ ...(start && { start }),+ });+ runtime.read = read();+ runtime.gsapPosition = { x: 50, y: 30 };+ let start: unknown;+ function Probe() {+ const ref = useRef(document.createElement("iframe"));+ start = useMotionPathData(ref, "#box").geometry?.start;+ return null;+ }+ const root = createRoot(document.body.appendChild(document.createElement("div")));+ try {+ act(() => root.render(<Probe />));+ expect(start).toBeUndefined();+ runtime.read = read({ x: 40 });+ act(() => vi.advanceTimersByTime(250));+ expect(start).toEqual({ x: 40, y: 30 });+ } finally {+ act(() => root.unmount());+ }+});++it("updates the home when the layer's size or anchoring changes but its centre does not", () => {+ runtime.read = {+ keyframes: [+ { percentage: 0, properties: { x: 0, width: 200 } },+ { percentage: 100, properties: { x: 100, width: 240 } },+ ],+ };+ const iframe = document.body.appendChild(document.createElement("iframe"));+ const layout = { offsetLeft: 100, offsetWidth: 200 };+ const box = iframe.contentDocument!.body.appendChild(+ iframe.contentDocument!.createElement("div"),+ );+ box.id = "box";+ for (const key of ["offsetLeft", "offsetWidth"] as const)+ Object.defineProperty(box, key, { get: () => layout[key] });+ let w: number | undefined;+ let ax: number | undefined;+ function Probe() {+ const ref = useRef(iframe);+ ({ w, ax } = useMotionPathData(ref, "#box").home ?? {});+ return null;+ }+ const root = createRoot(document.body.appendChild(document.createElement("div")));+ try {+ act(() => root.render(<Probe />));+ runFrames(2);+ expect(w).toBe(200);+ Object.assign(layout, { offsetLeft: 80, offsetWidth: 240 });+ runFrames(2);+ expect(w).toBe(240);+ // Re-anchored from the left to the right edge without moving: the share a size change moves changes.+ Object.assign(box.style, { position: "absolute", left: "10px" });+ runFrames(2);+ expect(ax).toBe(0.5);+ box.computedStyleMap = () =>+ ({+ get: (side: string) => (side === "left" ? "auto" : "0px"),+ }) as unknown as StylePropertyMapReadOnly;+ runFrames(2);+ expect(ax).toBe(-0.5);+ } finally {+ act(() => root.unmount());+ }+});diff --git a/packages/studio/src/components/editor/useMotionPathData.ts b/packages/studio/src/components/editor/useMotionPathData.tsindex db1b1a595f..ef20286986 100644--- a/packages/studio/src/components/editor/useMotionPathData.ts+++ b/packages/studio/src/components/editor/useMotionPathData.ts@@ -1,31 +1,19 @@import { useEffect, useRef, useState, type RefObject } from "react";+import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";import { readRuntimeKeyframes } from "../../hooks/gsapRuntimeKeyframes";import { readGsapPositionFromIframe } from "../../hooks/gsapPositionDetection";import { isElementVisibleForOverlay } from "./domEditOverlayGeometry";-import { buildMotionPathGeometry, type MotionPathGeometry } from "./motionPathGeometry";+import {+ buildMotionPathGeometry,+ type MotionPathGeometry,+ type MotionPathHome,+} from "./motionPathGeometry";+import { elementHome } from "./motionPathHome";import { subscribeOverlayFrame } from "./overlayFrameLoop";import { usePlayerStore } from "../../player/store/playerStore";type Rect = { left: number; top: number; width: number; height: number };-// The translate (e/f) components of an element's computed transform, in comp px.-// A group wrapper dragged via GSAP carries its offset here, not in offsetLeft/Top.-function transformTranslate(el: HTMLElement): { x: number; y: number } {- const t = el.ownerDocument?.defaultView?.getComputedStyle(el).transform;- if (!t || t === "none") return { x: 0, y: 0 };- const m3 = t.match(/matrix3d\(([^)]+)\)/);- if (m3) {- const v = m3[1].split(",").map(Number);- return { x: v[12] || 0, y: v[13] || 0 };- }- const m = t.match(/matrix\(([^)]+)\)/);- if (m) {- const v = m[1].split(",").map(Number);- return { x: v[4] || 0, y: v[5] || 0 };- }- return { x: 0, y: 0 };-}-// Perspective foreshortening of the element's OWN transform (matrix3d m44). A// depth element (translateZ toward the viewer) renders 1/m44× larger, so its// animated x/y offsets travel 1/m44× further on screen than the flat preview@@ -40,43 +28,6 @@ export function transformWDivisor(el: HTMLElement): number {return Number.isFinite(w) && w > 0 ? w : 1;}-export function elementHome(el: HTMLElement): { x: number; y: number } {- let left = 0;- let top = 0;- let node: HTMLElement | null = el;- while (node) {- left += node.offsetLeft;- top += node.offsetTop;- // Ancestor transforms (e.g. a group wrapper moved via GSAP) shift where the- // element actually renders, so the path must anchor on top of them. The element's- // OWN transform is excluded — that's the animated offset the path itself draws.- if (node !== el) {- const t = transformTranslate(node);- left += t.x;- top += t.y;- }- const parent = node.offsetParent as HTMLElement | null;- if (!parent || parent.hasAttribute("data-composition-id")) break;- node = parent;- }- let x = left + el.offsetWidth / 2;- let y = top + el.offsetHeight / 2;- if ((el.style.translate ?? "").includes("var(")) {- x += Number.parseFloat(el.style.getPropertyValue("--hf-studio-offset-x")) || 0;- y += Number.parseFloat(el.style.getPropertyValue("--hf-studio-offset-y")) || 0;- }- return { x, y };-}--export function isPreviewHtmlElement(- node: Element | null | undefined,- iframe: HTMLIFrameElement | null,-): node is HTMLElement {- const Ctor = (iframe?.contentWindow as unknown as { HTMLElement?: typeof HTMLElement } | null)- ?.HTMLElement;- return Boolean(node && Ctor && node instanceof Ctor);-}-function rectsClose(a: Rect, b: Rect): boolean {return (Math.abs(a.left - b.left) < 0.5 &&@@ -104,7 +55,7 @@ export function useMotionPathData(geometry: MotionPathGeometry | null;geometryResolved: boolean;visibleInPreview: boolean;- home: { x: number; y: number } | null;+ home: MotionPathHome | null;pScale: number;} {const [rect, setRect] = useState<Rect | null>(null);@@ -112,7 +63,7 @@ export function useMotionPathData(const resolvedForRef = useRef<string | null>(null);const geometryResolved = resolvedForRef.current === selector;const [visibleInPreview, setVisibleInPreview] = useState(true);- const [home, setHome] = useState<{ x: number; y: number } | null>(null);+ const [home, setHome] = useState<MotionPathHome | null>(null);// Perspective magnification (1/m44) of the selected element — applied to the// path's offset points so depth (translateZ) elements' paths track on screen.const [pScale, setPScale] = useState(1);@@ -146,13 +97,21 @@ export function useMotionPathData(} catch {/* cross-origin guard */}- const live = isPreviewHtmlElement(target, el) ? target : null;+ const live = isHtmlElement(target) ? target : null;const vis = live ? isElementVisibleForOverlay(live) : true;setVisibleInPreview((prev) => (prev === vis ? prev : vis));if (live) {const h = elementHome(live);setHome((prev) =>- prev && Math.abs(prev.x - h.x) < 0.5 && Math.abs(prev.y - h.y) < 0.5 ? prev : h,+ prev &&+ Math.abs(prev.x - h.x) < 0.5 &&+ Math.abs(prev.y - h.y) < 0.5 &&+ prev.w === h.w &&+ prev.h === h.h &&+ prev.ax === h.ax &&+ prev.ay === h.ay+ ? prev+ : h,);const ps = 1 / transformWDivisor(live);setPScale((p) => (Math.abs(p - ps) < 0.001 ? p : ps));@@ -173,7 +132,10 @@ export function useMotionPathData(const base = read ? readGsapPositionFromIframe(iframeRef.current, selector) : null;const next = buildMotionPathGeometry(read, base ?? undefined);setGeometry((prev) =>- prev?.points === next?.points && prev?.kind === next?.kind ? prev : next,+ prev?.kind === next?.kind &&+ JSON.stringify([prev?.nodes, prev?.start]) === JSON.stringify([next?.nodes, next?.start])+ ? prev+ : next,);resolvedForRef.current = selector;};diff --git a/packages/studio/src/hooks/gsapParsedTween.ts b/packages/studio/src/hooks/gsapParsedTween.tsindex 90a8e80060..168f26a8bb 100644--- a/packages/studio/src/hooks/gsapParsedTween.ts+++ b/packages/studio/src/hooks/gsapParsedTween.ts@@ -2,6 +2,7 @@ import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import { elementTargets } from "../utils/elementGsap";import { resolveTweenStart } from "../utils/globalTimeCompiler";import type { ImplicitEndValue } from "./gsapValueAtPlayhead";+import type { ReadTween } from "./gsapRuntimeKeyframes";// GSAP 3 internals: a property tween in a tween's `_pt` chain; CSSPlugin keeps its own under `d._pt`.interface PropTween {@@ -57,6 +58,21 @@ function endsIn(tween: ParsedTween, prop: string): [number, number] | null {return tween._from ? [pair[1], pair[0]] : pair;}+/** `read` plus GSAP's start for a step list or a first key past 0%, read per channel. */+export function withParsedStart(read: ReadTween, live: unknown): ReadTween {+ const tween = live as ParsedTween;+ const first = read.keyframes[0];+ if (!Array.isArray(tween.vars?.keyframes) && !((first?.percentage ?? 0) > 0)) return read;+ const children = tween.timeline?.getChildren?.() ?? [tween];+ const start: Record<string, number> = {};+ for (const prop of ["x", "y", "width", "height"]) {+ const ends = children.map((child) => endsIn(child, prop)).find(Boolean);+ if (ends) start[prop] = ends[0];+ }+ const moved = Object.entries(start).some(([prop, value]) => value !== first?.properties[prop]);+ return moved ? { ...read, start } : read;+}+/** The live tween GSAP built from `anim`: same element, start and channels, parsed. */// fallow-ignore-next-line complexityexport function findParsedTween(diff --git a/packages/studio/src/hooks/gsapRuntimeKeyframes.realGsap.test.ts b/packages/studio/src/hooks/gsapRuntimeKeyframes.realGsap.test.tsnew file mode 100644index 0000000000..f11ec70a34--- /dev/null+++ b/packages/studio/src/hooks/gsapRuntimeKeyframes.realGsap.test.ts@@ -0,0 +1,48 @@+// @vitest-environment happy-dom+import { gsap } from "gsap";+import { expect, it } from "vitest";+import { readRuntimeKeyframes } from "./gsapRuntimeKeyframes";++/** The edit bench's `keys` layer: GSAP starts it at x 40, 260 wide, and plays it to 1 s. */+function read(keyframes: string) {+ const box = Object.assign(document.body.appendChild(document.createElement("div")), { id: "x" });+ box.style.width = "260px";+ gsap.set(box, { x: 40 });+ const win = { __timelines: {} as Record<string, gsap.core.Timeline> };+ new Function(+ "gsap",+ "window",+ `var tl = gsap.timeline({ paused: true });+tl.to("#x", { keyframes: ${keyframes} }, 0);+window.__timelines["t"] = tl;`,+ )(gsap, win);+ const timeline = win.__timelines.t!;+ timeline.progress(0.0001, true).seek(1);+ const iframe = { contentWindow: { ...win, gsap }, contentDocument: document };+ const got = readRuntimeKeyframes(iframe as unknown as HTMLIFrameElement, "#x");+ timeline.kill();+ box.remove();+ return got;+}++it("reads where GSAP started a step list whose first keyframe comes later", () => {+ const got = read(+ `[{ x: 60, width: 280, duration: 2, ease: "none" }, { x: 120, width: 320, duration: 1, ease: "none" }]`,+ );+ expect(got?.start).toEqual({ x: 40, width: 260 });+});++it.each([+ [`{ "50%": { x: 60, y: 20 }, "100%": { x: 120, y: 40 } }, duration: 2`, { x: 40, y: 0 }],+ [+ `{ "50%": { x: 60, width: 280 }, "100%": { x: 120, width: 320 } }, duration: 2`,+ { x: 40, width: 260 },+ ],+])("reads every channel's start for a percentage list past 0%: %s", (keyframes, start) => {+ expect(read(keyframes)?.start).toEqual(start);+});++it("reads no start for keyframes that begin at 0%, or a step list that begins where GSAP started", () => {+ expect(read(`{ "0%": { x: 10 }, "100%": { x: 120 } }, duration: 3`)?.start).toBeUndefined();+ expect(read(`[{ x: 40, duration: 0 }, { x: 120, duration: 1 }]`)?.start).toBeUndefined();+});diff --git a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts b/packages/studio/src/hooks/gsapRuntimeKeyframes.tsindex 28daf75ee0..691025489c 100644--- a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts+++ b/packages/studio/src/hooks/gsapRuntimeKeyframes.ts@@ -11,6 +11,7 @@import { buildArcPath, type ArcPathConfig } from "@hyperframes/core/gsap-parser-acorn";import { parsePercentageKeyframes, toAbsoluteTime } from "./gsapShared";import { roundTo3 } from "../utils/rounding";+import { withParsedStart } from "./gsapParsedTween";import { BOX_SIZE_STYLE_PROPS } from "../components/editor/manualEditsDomPatches";import { gsapRendersTransform } from "../components/editor/gsapAnimatesProperty";@@ -43,7 +44,13 @@ export interface RuntimeTimeline {}type Pct = { percentage: number; properties: Record<string, number | string> };-export type ReadTween = { keyframes: Pct[]; easeEach?: string; arcPath?: ArcPathConfig };+export type ReadTween = {+ keyframes: Pct[];+ easeEach?: string;+ arcPath?: ArcPathConfig;+ /** GSAP's start values when the first keyframe is after 0%. */+ start?: Record<string, number>;+};export interface RuntimeKeyframeEntry {keyframes: Pct[];@@ -365,11 +372,11 @@ export function readRuntimeKeyframes(const read = readTween(tween.vars);if (!read) continue;if (requireChannels && !readCarriesChannel(read, requireChannels)) continue;- if (firstRead === null) firstRead = read;+ if (firstRead === null) firstRead = withParsedStart(read, tween);// Prefer the tween whose [start, start+dur] contains the playhead.if (now != null) {const start = typeof tween.startTime === "function" ? tween.startTime() : 0;- if (now >= start - 1e-3 && now <= start + dur + 1e-3) return read;+ if (now >= start - 1e-3 && now <= start + dur + 1e-3) return withParsedStart(read, tween);}}}diff --git a/packages/studio/src/hooks/gsapShared.ts b/packages/studio/src/hooks/gsapShared.tsindex e8c7d56702..92a7569880 100644--- a/packages/studio/src/hooks/gsapShared.ts+++ b/packages/studio/src/hooks/gsapShared.ts@@ -3,6 +3,7 @@* Centralises duplicated interfaces, constants, and small utilities* to reduce drift risk.*/+import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditingTypes";import {@@ -223,7 +224,7 @@ function structuralSelector(element: Element): string | null {const parts: string[] = [];for (let node: Element | null = element; node; node = node.parentElement) {if (node !== element) {- const id = node instanceof HTMLElement ? node.id : "";+ const id = isHtmlElement(node) ? node.id : "";const hfId = node.getAttribute("data-hf-id");if (id) {parts.unshift(idSelector(id));diff --git a/packages/studio/src/hooks/gsapShared.writeTarget.test.ts b/packages/studio/src/hooks/gsapShared.writeTarget.test.tsindex d274097856..bd20b775b6 100644--- a/packages/studio/src/hooks/gsapShared.writeTarget.test.ts+++ b/packages/studio/src/hooks/gsapShared.writeTarget.test.ts@@ -110,6 +110,16 @@ describe("writeTargetSelector", () => {expect(writeTargetSelector(selection)).toBe("#scene > div:nth-child(2)");});+ it("anchors on an ancestor's id in the preview, whichever window built its nodes", () => {+ const frame = document.body.appendChild(document.createElement("iframe"));+ const doc = frame.contentDocument!;+ doc.body.innerHTML = `<div id="scene"><div></div><div></div></div>`;+ const el = doc.querySelectorAll<HTMLElement>("#scene > div")[1]!;+ const selection = { ...stableSelectionFor(el), selector: "div[unclosed" } as DomEditSelection;++ expect(writeTargetSelector(selection)).toBe("#scene > div:nth-child(2)");+ });+it("returns null when a live DOM is present and no rung addresses one element", () => {document.body.innerHTML = `<div id="scene"><div class="group"></div><div class="group"></div></div>`;const el = document.querySelectorAll<HTMLElement>(".group")[1]!;diff --git a/packages/studio/src/hooks/timelineEditingHelpers.ts b/packages/studio/src/hooks/timelineEditingHelpers.tsindex f88ff38f0c..a315ea316a 100644--- a/packages/studio/src/hooks/timelineEditingHelpers.ts+++ b/packages/studio/src/hooks/timelineEditingHelpers.ts@@ -1,3 +1,4 @@+import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";import { type TimelineElement, usePlayerStore } from "../player/store/playerStore";import { toAuthoredStart } from "../player/store/timelineElement";import {@@ -35,14 +36,6 @@ import {} from "../components/editor/domEditingElement";export { deleteSelectedKeyframes } from "./deleteSelectedKeyframes";export { readFileContent };-function isHTMLElement(element: Element | null): element is HTMLElement {- if (!element) return false;- // Use the element's OWN realm's HTMLElement: timeline clips live in the preview- // iframe, and cross-realm `element instanceof HTMLElement` (main window) is- // always false — which silently dropped every timeline z-index commit.- const Ctor = element.ownerDocument?.defaultView?.HTMLElement ?? globalThis.HTMLElement;- return element instanceof Ctor;-}/*** Resolve a timeline vertical move to a z-index stacking reorder and commit it* through the shared layers-panel reorder path. Reads live sibling z-index from@@ -96,7 +89,7 @@ export function applyTimelineStackingReorder(input: {input.activeCompPath,): null;- if (!isHTMLElement(element)) return Promise.resolve();+ if (!isHtmlElement(element)) return Promise.resolve();if (getElementZIndex(element) === change.zIndex) continue;commitEntries.push({element,diff --git a/packages/studio/src/noWindowBoundDomChecks.test.ts b/packages/studio/src/noWindowBoundDomChecks.test.tsnew file mode 100644index 0000000000..eccfe3de7d--- /dev/null+++ b/packages/studio/src/noWindowBoundDomChecks.test.ts@@ -0,0 +1,31 @@+import { readdirSync, readFileSync } from "node:fs";+import { dirname, join, relative } from "node:path";+import { fileURLToPath } from "node:url";+import { expect, it } from "vitest";++const SRC = dirname(fileURLToPath(import.meta.url));+const DOM_CTOR = String.raw`(?:HTML\w*Element|SVG\w*Element|Element|Node|Text|ShadowRoot|DocumentFragment)\b`;+// A DOM constructor read off any object, a window most of all, asks which window built a node.+const WINDOW_BOUND = [+ new RegExp(String.raw`[\w$)\]!?]\??\.\s*${DOM_CTOR}`),+ new RegExp(String.raw`^\s*\??\.\s*${DOM_CTOR}`),+ new RegExp(String.raw`\[\s*["'](?:HTML|SVG)\w*Element["']`),+];++function sources(dir: string): string[] {+ return readdirSync(dir, { withFileTypes: true, recursive: true })+ .filter((e) => e.isFile() && /\.tsx?$/.test(e.name) && !/\.test(-helpers)?\.tsx?$/.test(e.name))+ .map((e) => join(e.parentPath, e.name));+}++it("no studio source checks a DOM node against a window's own constructor", () => {+ const hits = sources(SRC).flatMap((file) =>+ readFileSync(file, "utf8")+ .split("\n")+ .map((line, i) => ({ line, at: `${relative(SRC, file)}:${i + 1}` }))+ .filter(({ line }) => !/^\s*(\/\/|\*|\/\*)/.test(line))+ .filter(({ line }) => WINDOW_BOUND.some((re) => re.test(line)))+ .map(({ at, line }) => `${at} ${line.trim()}`),+ );+ expect(hits, "use @hyperframes/core/runtime/dom-realm instead").toEqual([]);+});diff --git a/packages/studio/src/player/lib/timelineGroupInfo.realm.test.ts b/packages/studio/src/player/lib/timelineGroupInfo.realm.test.tsnew file mode 100644index 0000000000..c899d7aa52--- /dev/null+++ b/packages/studio/src/player/lib/timelineGroupInfo.realm.test.ts@@ -0,0 +1,20 @@+// @vitest-environment jsdom+import { expect, it } from "vitest";+import { groupInfoFor } from "./timelineGroupInfo";++it("sees a group the preview adds, whichever window built its node", () => {+ const frame = document.body.appendChild(document.createElement("iframe"));+ const doc = frame.contentDocument!;+ const member = doc.createElement("audio");+ member.id = "a1";+ member.setAttribute("data-audio-group", "g1");+ doc.body.append(member);+ expect(groupInfoFor(doc, "g1").label).toBe("g1");+ const group = doc.createElement("hf-audio-group");+ group.id = "g1";+ group.setAttribute("data-label", "Drums");+ doc.body.append(group);++ expect(groupInfoFor(doc, "g1").label).toBe("Drums");+ frame.remove();+});diff --git a/packages/studio/src/player/lib/timelineGroupInfo.ts b/packages/studio/src/player/lib/timelineGroupInfo.tsindex d145f2a9a4..251fc7b833 100644--- a/packages/studio/src/player/lib/timelineGroupInfo.ts+++ b/packages/studio/src/player/lib/timelineGroupInfo.ts@@ -6,6 +6,7 @@* cache, its revision counter, the observer that bumps it, and the one reader.*/+import { isElementNode } from "@hyperframes/core/runtime/dom-realm";import {HF_AUDIO_GROUP_ATTR,HF_AUDIO_GROUP_TAG,@@ -52,7 +53,7 @@ function countGroupChanges(doc: Document, records: readonly MutationRecord[]): vrecord.type !== "childList" ||[...record.addedNodes, ...record.removedNodes].some((node) =>- node instanceof Element &&+ isElementNode(node) &&(node.tagName.toLowerCase() === HF_AUDIO_GROUP_TAG ||node.hasAttribute(HF_AUDIO_GROUP_ATTR) ||node.querySelector?.(`${HF_AUDIO_GROUP_TAG},[${HF_AUDIO_GROUP_ATTR}]`) != null),diff --git a/packages/studio/src/webmcp/webmcpTestUtils.ts b/packages/studio/src/webmcp/webmcpTestUtils.tsindex 8d68fee394..8e6d1df49b 100644--- a/packages/studio/src/webmcp/webmcpTestUtils.ts+++ b/packages/studio/src/webmcp/webmcpTestUtils.ts@@ -5,6 +5,7 @@* existing `hooks/domSelectionTestHarness.ts` convention.*/+import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";import { expect } from "vitest";import type { DomEditSelection } from "../components/editor/domEditingTypes";import type { ToolFailure, ToolResult } from "./toolResult";@@ -31,8 +32,7 @@ export function previewDoc(html: string): Document {export function previewElement(html: string, id: string): HTMLElement {const doc = previewDoc(html);const element = doc.getElementById(id);- const HTMLElementCtor = doc.defaultView?.HTMLElement;- if (!HTMLElementCtor || !(element instanceof HTMLElementCtor)) {+ if (!isHtmlElement(element)) {throw new Error(`expected preview element #${id}`);}return element;diff --git a/packages/studio/tests/e2e/motion-path-home.mjs b/packages/studio/tests/e2e/motion-path-home.mjsnew file mode 100644index 0000000000..69b17833e7--- /dev/null+++ b/packages/studio/tests/e2e/motion-path-home.mjs@@ -0,0 +1,123 @@+// Run with: node packages/studio/tests/e2e/motion-path-home.mjs+// Real Chromium and real GSAP: a layer's motion path home leaves its CSS translate alone (GSAP's+// transform parse folds it) and puts a created path's end on the click; happy-dom computes no translate.+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import puppeteer from "puppeteer-core";+import { resolveChromeExecutable } from "./chrome-executable.mjs";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");+const output = mkdtempSync(join(tmpdir(), "motion-path-home-"));+const studio = createRequire(join(root, "packages/studio/package.json"));+const gsapSource = readFileSync(studio.resolve("gsap/dist/gsap.js"), "utf8");+let browser;+try {+ execFileSync(+ "bun",+ [+ "build",+ "packages/studio/src/components/editor/motionPathHome.ts",+ "--target",+ "browser",+ "--outdir",+ output,+ ],+ { cwd: root },+ );+ const homeUrl = `data:text/javascript;base64,${readFileSync(join(output, "motionPathHome.js")).toString("base64")}`;+ browser = await puppeteer.launch({+ executablePath: resolveChromeExecutable(),+ headless: true,+ pipe: true,+ args: ["--no-sandbox", "--disable-dev-shm-usage"],+ });+ const page = await browser.newPage();+ await page.setContent(+ `<style>.centred{transform:translate(-50%,-50%)}</style><body style="margin:0"><div id="stage" style="position:relative;width:1920px;height:1080px"></div></body>`,+ );+ await page.addScriptTag({ content: gsapSource });+ await page.addScriptTag({+ content: readFileSync(studio.resolve("gsap/dist/MotionPathPlugin.js"), "utf8"),+ });+ const got = await page.evaluate(async (url) => {+ const { elementHome } = await import(url);+ window.gsap.registerPlugin(window.MotionPathPlugin);+ const layer = (css) => {+ const el = document.createElement("div");+ el.style.cssText = `position:absolute;left:10px;top:10px;width:240px;height:160px;${css}`;+ document.getElementById("stage").append(el);+ return el;+ };+ const centre = (el) => {+ const r = el.getBoundingClientRect();+ return [r.left + r.width / 2, r.top + r.height / 2];+ };+ // Create mode: a path to (click - home), as the overlay commits it, must end on the click.+ const create = (css, setup = () => {}) => {+ const el = layer(css);+ setup(el);+ const home = elementHome(el);+ const style = [el.style.translate, el.style.transform];+ const [cx, cy] = [700, 400];+ const path = [+ { x: 0, y: 0 },+ { x: cx - home.x, y: cy - home.y },+ ];+ window.gsap.timeline().to(el, { motionPath: { path }, duration: 1 }).progress(1);+ return { style, end: centre(el) };+ };+ // A drag's offset on a layer GSAP already moves composes with its transform.+ const dragged = layer("");+ window.gsap.set(dragged, { x: 20 });+ dragged.style.cssText += ";--hf-studio-offset-x:40px;--hf-studio-offset-y:30px";+ dragged.style.translate = "var(--hf-studio-offset-x) var(--hf-studio-offset-y)";+ const draggedHome = elementHome(dragged);+ const owned = layer("left: 50%; top: 50%");+ window.gsap.set(owned, { xPercent: -50, yPercent: -50 });+ return {+ plain: create("translate: 40px 30px"),+ centred: create("left: 50%; top: 50%; translate: -50% -50%"),+ halfPx: create("left: 50%; top: 50%; translate: -120px -80px"),+ none: create(""),+ transformed: create("left: 50%; top: 50%; transform: translate(-50%, -50%)"),+ classed: create("left: 50%; top: 50%", (el) => el.classList.add("centred")),+ mixed: create("left: 50%; top: 50%; transform: translate(-50%, -50%); translate: 10px 0"),+ // A fade's cache holds no transform yet: GSAP's next parse still folds the drag offset into x.+ faded: create(+ "--hf-studio-offset-x: 40px; --hf-studio-offset-y: 30px; translate: var(--hf-studio-offset-x) var(--hf-studio-offset-y)",+ (el) => window.gsap.set(el, { opacity: 0.9 }),+ ),+ dragged: { home: [draggedHome.x, draggedHome.y], centre: centre(dragged) },+ owned: elementHome(owned),+ };+ }, homeUrl);++ assert.deepEqual(got.plain.style, ["40px 30px", ""]);+ assert.deepEqual(got.centred.style, ["-50% -50%", ""]);+ for (const name of [+ "plain",+ "centred",+ "halfPx",+ "none",+ "transformed",+ "classed",+ "mixed",+ "faded",+ ]) {+ assert.deepEqual(got[name].end.map(Math.round), [700, 400], name);+ }+ assert.deepEqual(got.dragged.home, [got.dragged.centre[0] - 20, got.dragged.centre[1]]);+ const { x, y, ax, ay } = got.owned;+ assert.deepEqual([x, y, ax, ay], [960, 540, 0, 0]);+ console.log(+ "motion-path home: a created path ends on the click; translates kept; drag offsets count",+ );+} finally {+ await browser?.close();+ rmSync(output, { recursive: true, force: true });+}