diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index c16b4c8095..f6d9cf5b3e 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -202,6 +202,7 @@ describe("installEditingAgent", () => { "layers", "draft", "gesture-start", + "gesture-base", "console-errors", "watch-keys", "restore-attributes", diff --git a/packages/core/src/runtime/editingAgent.ts b/packages/core/src/runtime/editingAgent.ts index d1a4cfc3ce..4f3a60d6de 100644 --- a/packages/core/src/runtime/editingAgent.ts +++ b/packages/core/src/runtime/editingAgent.ts @@ -34,7 +34,7 @@ import { layersOf } from "./editingLayers"; import { drawDrafts } from "./editingDraft"; import { stopWatchingGeometry, watchGeometry } from "./editing/watchGeometry"; import { maxZIndex } from "./editing/maxZIndex"; -import { gestureStart } from "./editingGestureStart"; +import { gestureBase, gestureStart } from "./editingGestureStart"; import { gsapSnapshot } from "./editing/gsapSnapshot"; import { motionPathHome } from "./editing/motionPathHome"; import { cropLift } from "./editing/cropLift"; @@ -206,6 +206,7 @@ const HANDLERS: Handlers = { layers: ({ group, offset }) => layersOf(group, offset), draft: ({ drafts }) => drawDrafts(drafts), "gesture-start": ({ handles }) => gestureStart(handles), + "gesture-base": ({ handles }) => ({ elements: handles.map(gestureBase) }), "console-errors": ({ from }) => { const seen = watchConsoleErrors(); const errors = seen.slice(from, from + MAX_QUERY_MATCHES); diff --git a/packages/core/src/runtime/editingGestureStart.test.ts b/packages/core/src/runtime/editingGestureStart.test.ts index 22887d9ba6..9b8ddccff4 100644 --- a/packages/core/src/runtime/editingGestureStart.test.ts +++ b/packages/core/src/runtime/editingGestureStart.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { gestureStart } from "./editingGestureStart"; +import { gestureBase, gestureStart } from "./editingGestureStart"; import { handleFor } from "./editingHandles"; type Tween = { vars: Record; targets: () => unknown[]; duration: () => number }; @@ -250,3 +250,20 @@ describe("gesture start", () => { expect(gestureStart(["0123456789abcdef:999"]).elements).toEqual([null]); }); }); + +// fails without the fix: a sealed recording had no read for a layer no tween touches, so it started a static +// opacity and scale at 1 where the unsealed recorder reads them from GSAP. +describe("gestureBase", () => { + it("reads GSAP's x, y, opacity and scale for a layer no tween touches", () => { + const card = turnedCard(""); + gsapWith([], { x: 12, y: -4, opacity: 0.5, scaleX: 1.5 }); + expect(gestureBase(handleFor(card))).toEqual({ x: 12, y: -4, opacity: 0.5, scale: 1.5 }); + }); + + it("answers null without GSAP, or for an element this load does not have", () => { + const card = turnedCard(""); + expect(gestureBase(handleFor(card))).toBeNull(); + gsapWith([]); + expect(gestureBase("0123456789abcdef:999")).toBeNull(); + }); +}); diff --git a/packages/core/src/runtime/editingGestureStart.ts b/packages/core/src/runtime/editingGestureStart.ts index 5a4eca3275..b96231de63 100644 --- a/packages/core/src/runtime/editingGestureStart.ts +++ b/packages/core/src/runtime/editingGestureStart.ts @@ -164,6 +164,18 @@ function tweensOn(element: Element): GsapTween[] { const rendersTransform = (element: Element) => !!(element as { _gsap?: { renderTransform?: unknown } })._gsap?.renderTransform; + +export type EditingGestureBase = { x: number; y: number; opacity: number; scale: number }; + +export function gestureBase(handle: EditingElementHandle): EditingGestureBase | null { + const element = elementForHandle(handle); + const gsap = (window as GsapWindow).gsap; + if (!element || !gsap?.getProperty) return null; + const read = (property: string) => Number(gsap.getProperty?.(element, property)); + const base = { x: read("x"), y: read("y"), opacity: read("opacity"), scale: read("scaleX") }; + return Object.values(base).every(Number.isFinite) ? base : null; +} + // Read only once GSAP owns it: asking GSAP for x makes it fold a CSS translate into its transform. const readGsap = (element: Element, property: string) => Number((window as GsapWindow).gsap?.getProperty?.(element, property)) || 0; diff --git a/packages/core/src/runtime/editingPort.test.ts b/packages/core/src/runtime/editingPort.test.ts index 82e58dc796..3f15d26547 100644 --- a/packages/core/src/runtime/editingPort.test.ts +++ b/packages/core/src/runtime/editingPort.test.ts @@ -85,6 +85,7 @@ describe("createEditingPortClient", () => { "layers", "draft", "gesture-start", + "gesture-base", "console-errors", "watch-keys", "restore-attributes", diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index 3a9307edc1..e792c836d8 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -26,7 +26,7 @@ import { type EditingElementMatch, } from "./editingElement"; import type { EditingElementBox, EditingElementGeometry } from "./editingGeometry"; -import type { EditingGestureStart } from "./editingGestureStart"; +import type { EditingGestureBase, EditingGestureStart } from "./editingGestureStart"; import type { GsapSnapshot } from "./editing/gsapSnapshot"; import type { MotionPathFrameHome } from "./editing/motionPathHome"; import type { EditingLayer, EditingStackingSibling } from "./editingLayers"; @@ -136,7 +136,7 @@ export { type EditingElementGeometry, type ElementTransformSnapshot, } from "./editingGeometry"; -export type { EditingGestureStart } from "./editingGestureStart"; +export type { EditingGestureBase, EditingGestureStart } from "./editingGestureStart"; export { MAX_CAPTION_TRANSFORM } from "./editing/captionTransform"; export { MAX_SNAPSHOT_CHANNELS, @@ -190,6 +190,7 @@ export const EDITING_REQUEST_KINDS = [ "layers", "draft", "gesture-start", + "gesture-base", "console-errors", "watch-keys", "restore-attributes", @@ -330,6 +331,10 @@ export interface EditingRequests { params: { handles: EditingElementHandle[] }; result: { elements: Array; snap: EditingElementBox[] }; }; + "gesture-base": { + params: { handles: EditingElementHandle[] }; + result: { elements: Array }; + }; "console-errors": { params: { from: number }; result: { errors: string[]; truncated: boolean } }; /** The frame cancels these combos outside the elements that own keys, and forwards them and their * keyups to this port; an empty list stops. */ @@ -598,6 +603,7 @@ const PARAM_PARSERS: { layers: (params) => noParams(params) ?? layerParams(params), draft: draftList, "gesture-start": handleList, + "gesture-base": handleList, "console-errors": (params) => hasKeys(params, "from") && isOffset(params.from) ? { from: params.from } : null, "watch-keys": comboList, diff --git a/packages/studio/src/hooks/newTweenTargetHooks.test.tsx b/packages/studio/src/hooks/newTweenTargetHooks.test.tsx index fc023d6ff9..3e2e54f9cd 100644 --- a/packages/studio/src/hooks/newTweenTargetHooks.test.tsx +++ b/packages/studio/src/hooks/newTweenTargetHooks.test.tsx @@ -25,7 +25,7 @@ const frozenSamples = [ vi.mock("./useGestureRecording", () => ({ useGestureRecording: () => ({ - startRecording: vi.fn(), + startRecording: vi.fn(() => true), stopRecording: () => frozenSamples, clearSamples: vi.fn(), samples: frozenSamples, diff --git a/packages/studio/src/hooks/useGestureCommit.test.tsx b/packages/studio/src/hooks/useGestureCommit.test.tsx index 93aaad0e36..834b62c0fb 100644 --- a/packages/studio/src/hooks/useGestureCommit.test.tsx +++ b/packages/studio/src/hooks/useGestureCommit.test.tsx @@ -15,7 +15,7 @@ import { xAtTime } from "./gsapPlaybackTestHarness"; vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); const gestureRecording = vi.hoisted(() => ({ - startRecording: vi.fn(), + startRecording: vi.fn(() => true), stopRecording: vi.fn(() => [ { time: 0, properties: { x: 0, y: 0, opacity: 1 } }, { time: 0.5, properties: { x: 50, y: 25, opacity: 0.5 } }, @@ -29,6 +29,22 @@ const gestureRecording = vi.hoisted(() => ({ trailRef: { current: [] }, })); +const sealedFrame = vi.hoisted(() => ({ + opaque: false, + answer: null as ((bases: unknown) => void) | null, +})); +vi.mock("../player/lib/previewChannel", async (load) => ({ + ...(await load()), + previewFrameOpaque: () => sealedFrame.opaque, +})); +vi.mock("../player/lib/previewElements", async (load) => ({ + ...(await load()), + previewGestureBase: () => + new Promise((resolve) => { + sealedFrame.answer = resolve; + }), +})); + vi.mock("./useGestureRecording", () => ({ useGestureRecording: () => gestureRecording, })); @@ -55,6 +71,8 @@ Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true); let cleanup: (() => void) | null = null; afterEach(() => { + sealedFrame.opaque = false; + sealedFrame.answer = null; cleanup?.(); cleanup = null; usePlayerStore.getState().reset(); @@ -416,3 +434,51 @@ it("writes one recording to its original selection after selecting another sourc method: "keyboard", }); }); + +describe("a sealed recording waiting for the frame's base", () => { + const BASE = [{ x: 0, y: 0, opacity: 1, scale: 1 }]; + const sealedSelection = (id: string) => { + const element = document.createElement("div"); + element.id = id; + return { ...makeSelection(element), handle: `0123456789abcdef:${id}` }; + }; + const answer = async () => { + await act(async () => { + sealedFrame.answer?.(BASE); + await Promise.resolve(); + }); + }; + + // fails without the fix: the reply started recording on the selection captured before it, even after the + // person picked another layer or the hook unmounted. + it("starts on the layer it was asked for once the frame answers", async () => { + sealedFrame.opaque = true; + const hook = mountRecording(vi.fn(async () => {})); + hook.select(sealedSelection("card"), []); + act(() => hook().handleToggleRecording()); + expect(gestureRecording.startRecording).not.toHaveBeenCalled(); + await answer(); + expect(gestureRecording.startRecording).toHaveBeenCalledTimes(1); + }); + + it("doesn't start once another layer is selected before the frame answers", async () => { + sealedFrame.opaque = true; + const hook = mountRecording(vi.fn(async () => {})); + hook.select(sealedSelection("card"), []); + act(() => hook().handleToggleRecording()); + hook.select(sealedSelection("other"), []); + await answer(); + expect(gestureRecording.startRecording).not.toHaveBeenCalled(); + }); + + it("doesn't start once Studio unmounts before the frame answers", async () => { + sealedFrame.opaque = true; + const hook = mountRecording(vi.fn(async () => {})); + hook.select(sealedSelection("card"), []); + act(() => hook().handleToggleRecording()); + cleanup?.(); + cleanup = null; + await answer(); + expect(gestureRecording.startRecording).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/studio/src/hooks/useGestureCommit.ts b/packages/studio/src/hooks/useGestureCommit.ts index d614a28865..9e3596be5a 100644 --- a/packages/studio/src/hooks/useGestureCommit.ts +++ b/packages/studio/src/hooks/useGestureCommit.ts @@ -24,6 +24,9 @@ import { tweenTargetsElement, } from "./gsapShared"; import { useStableHandlers } from "./useStableHandlers"; +import { previewFrameOpaque } from "../player/lib/previewChannel"; +import { previewGestureBase } from "../player/lib/previewElements"; +import type { EditingGestureBase } from "@hyperframes/core/runtime/editing-port"; import { progressAtTime, runEaseOf, timeAtProgress, warpsTime } from "../utils/gsapKeyframeEases"; import { countOf } from "../utils/countOf"; @@ -132,6 +135,7 @@ export function useGestureCommit({ const recordingMethodRef = useRef<"button" | "keyboard">("button"); const recordingStartTimeRef = useRef(0); const commitInFlightRef = useRef(false); + const pendingStartRef = useRef(0); // Capture selection at recording start so commit always targets the recorded element, // even if the user's selection changes mid-recording. const capturedSelectionRef = useRef(null); @@ -151,9 +155,18 @@ export function useGestureCommit({ }, [gestureRecording, isGestureRecordingRef]); useEffect(() => { - if (readOnlyPreview && gestureStateRef.current === "recording") cancelRecording(); + if (!readOnlyPreview) return; + pendingStartRef.current++; + if (gestureStateRef.current === "recording") cancelRecording(); }, [cancelRecording, readOnlyPreview]); + useEffect( + () => () => { + pendingStartRef.current++; + }, + [], + ); + // fallow-ignore-next-line complexity const stopAndCommitRecording = useCallback(async () => { clearInterval(recordingAutoStopRef.current); @@ -417,18 +430,34 @@ export function useGestureCommit({ return; } - const store = usePlayerStore.getState(); - recordingMethodRef.current = method; - recordingStartTimeRef.current = store.currentTime; - const elementEnd = recordingEnd(sel); - capturedSelectionRef.current = sel; - capturedAnimationsRef.current = domEditSessionRef.current.selectedGsapAnimations ?? []; - gestureRecording.startRecording(sel.element, iframe, elementEnd); - gestureStateRef.current = "recording"; - isGestureRecordingRef.current = true; - setGestureState("recording"); - - armAutoStop(elementEnd); + const begin = (sealedBase?: EditingGestureBase | null) => { + if (isGestureRecordingRef.current) return; + const elementEnd = recordingEnd(sel); + const startTime = usePlayerStore.getState().currentTime; + if (!gestureRecording.startRecording(sel.element, iframe, elementEnd, sealedBase)) { + showToast("Preview not ready. Try again", "error"); + return; + } + recordingMethodRef.current = method; + recordingStartTimeRef.current = startTime; + capturedSelectionRef.current = sel; + capturedAnimationsRef.current = domEditSessionRef.current.selectedGsapAnimations ?? []; + gestureStateRef.current = "recording"; + isGestureRecordingRef.current = true; + setGestureState("recording"); + armAutoStop(elementEnd); + }; + const pending = ++pendingStartRef.current; + const stillAimed = () => + pending === pendingStartRef.current && + previewIframeRef.current === iframe && + domEditSessionRef.current.domEditSelection?.element === sel.element; + if (!previewFrameOpaque(iframe)) begin(); + else if (!sel.handle) begin(null); + else + void previewGestureBase(iframe, [sel.handle]).then((bases) => { + if (stillAimed()) begin(bases?.[0] ?? null); + }); }, [ gestureRecording, diff --git a/packages/studio/src/hooks/useGestureRecording.sealed.test.tsx b/packages/studio/src/hooks/useGestureRecording.sealed.test.tsx new file mode 100644 index 0000000000..8d8ad27562 --- /dev/null +++ b/packages/studio/src/hooks/useGestureRecording.sealed.test.tsx @@ -0,0 +1,161 @@ +// @vitest-environment jsdom + +import React, { act } from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mountReactHarness } from "./domSelectionTestHarness"; +import { useGestureRecording, type GestureSample } from "./useGestureRecording"; +import { usePlayerStore } from "../player/store/playerStore"; +import type { EditingGestureBase } from "@hyperframes/core/runtime/editing-port"; + +const frame = vi.hoisted(() => ({ + sealed: true, + stage: null as { width: number; height: number } | null, +})); +vi.mock("../player/lib/previewChannel", async (load) => ({ + ...(await load()), + previewFrameOpaque: () => frame.sealed, +})); +vi.mock("../player/lib/bridgePlayback", async (load) => ({ + ...(await load()), + previewStageSize: () => frame.stage, +})); + +Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true); + +let ticks: FrameRequestCallback[] = []; +let nowMs = 0; + +beforeEach(() => { + ticks = []; + nowMs = 0; + vi.stubGlobal( + "requestAnimationFrame", + vi.fn((tick: FrameRequestCallback) => ticks.push(tick)), + ); + vi.stubGlobal("cancelAnimationFrame", vi.fn()); + vi.spyOn(performance, "now").mockImplementation(() => nowMs); + frame.sealed = true; + usePlayerStore.setState({ currentTime: 0, duration: 10, requestedSeekTime: null }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + document.body.replaceChildren(); +}); + +const AT_REST: EditingGestureBase = { x: 0, y: 0, opacity: 1, scale: 1 }; + +/** Starts recording on a frame drawn 960 px wide; a sealed one starts from `base`, as the frame answered it. */ +function startOn( + base: EditingGestureBase | null, + elementEnd?: number, + liveGsap?: Record, +) { + const iframe = document.createElement("iframe"); + document.body.append(iframe); + if (liveGsap) + Object.assign(iframe.contentWindow!, { + gsap: { getProperty: (_element: Element, prop: string) => liveGsap[prop] }, + }); + vi.spyOn(iframe, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 960, 540)); + const standIn = document.createElement("div"); + let recording: ReturnType | null = null; + function Harness() { + recording = useGestureRecording(); + return null; + } + const root = mountReactHarness(); + let started: boolean | undefined; + act(() => { + started = recording?.startRecording(standIn, iframe, elementEnd, base); + }); + const tick = (ms: number) => { + nowMs = ms; + act(() => ticks.shift()?.(ms)); + }; + const stop = () => { + let samples: GestureSample[] = []; + act(() => { + samples = recording?.stopRecording() ?? []; + }); + act(() => root.unmount()); + return samples; + }; + return { iframe, started, tick, stop }; +} + +/** Records a pointer move of `dx` screen px. */ +function recordOnSealedFrame(dx: number, base: EditingGestureBase | null, elementEnd?: number) { + const { started, tick, stop } = startOn(base, elementEnd); + const move = (clientX: number, ms: number) => { + document.dispatchEvent(new MouseEvent("pointermove", { bubbles: true, clientX })); + tick(ms); + }; + move(0, 0); + move(dx, 300); + const seekAfterMove = usePlayerStore.getState().requestedSeekTime; + move(dx, 900); + const samples = stop(); + return { started, samples, seekAfterMove, last: samples.at(-1)?.properties }; +} + +describe("a gesture recording on a sealed preview", () => { + // fails without the fix: the recorder read GSAP and the film size through the frame's window, which a sealed + // frame doesn't expose, so it recorded from 0/0 on a 1920-wide film and saved keyframes that dropped the offset. + it("starts from the layer's GSAP offset the frame reported", () => { + frame.stage = { width: 1920, height: 1080 }; + expect(recordOnSealedFrame(100, { ...AT_REST, x: 240, y: 80 }).last).toEqual({ x: 440, y: 80 }); + }); + + it("scales the pointer by the film's own width, not 1920", () => { + frame.stage = { width: 1080, height: 1920 }; + expect(recordOnSealedFrame(100, AT_REST).last).toEqual({ x: 113, y: 0 }); + }); + + it("moves the film's playhead with the recording, up to the layer's end, so auto-stop can fire", () => { + frame.stage = { width: 1920, height: 1080 }; + usePlayerStore.setState({ currentTime: 2 }); + const { seekAfterMove, samples } = recordOnSealedFrame(100, AT_REST, 2.5); + expect(seekAfterMove).toBeCloseTo(2.3); + expect(usePlayerStore.getState().requestedSeekTime).toBe(2.5); + expect(samples.at(-1)?.time).toBe(0.5); + }); + + it("saves no sample past a layer end that falls between frames", () => { + frame.stage = { width: 1920, height: 1080 }; + usePlayerStore.setState({ currentTime: 2 }); + const { samples } = recordOnSealedFrame(100, AT_REST, 2.52); + expect(usePlayerStore.getState().requestedSeekTime).toBe(2.52); + expect(samples.at(-1)?.time).toBe(0.5); + }); + + it("refuses to record when the frame hasn't reported the layer's values", () => { + frame.stage = { width: 1920, height: 1080 }; + const { started, samples } = recordOnSealedFrame(100, null); + expect([started, samples]).toEqual([false, []]); + }); + + it("refuses to record when the frame hasn't reported the film's size", () => { + frame.stage = null; + const { started, samples } = recordOnSealedFrame(100, AT_REST); + expect([started, samples]).toEqual([false, []]); + }); + + it("scales from a static scale the same sealed as unsealed", () => { + const scaledBy = (sealed: boolean) => { + ticks = []; + frame.sealed = sealed; + frame.stage = { width: 1920, height: 1080 }; + const { tick, stop } = startOn( + { x: 0, y: 0, opacity: 0.5, scale: 1.5 }, + undefined, + sealed ? undefined : { x: 0, y: 0, opacity: 0.5, scaleX: 1.5 }, + ); + document.dispatchEvent(new WheelEvent("wheel", { deltaY: 10, metaKey: true })); + tick(100); + return stop().at(-1)?.properties.scale; + }; + expect([scaledBy(false), scaledBy(true)]).toEqual([1.6, 1.6]); + }); +}); diff --git a/packages/studio/src/hooks/useGestureRecording.ts b/packages/studio/src/hooks/useGestureRecording.ts index 8248b0fd2d..573d9bea15 100644 --- a/packages/studio/src/hooks/useGestureRecording.ts +++ b/packages/studio/src/hooks/useGestureRecording.ts @@ -3,6 +3,10 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { usePlayerStore, liveTime } from "../player/store/playerStore"; import { frameToSeconds, secondsToFrame } from "../player/lib/time"; import { useLinkedClipPreferences } from "../utils/linkedClipPreferences"; +import { previewFrameOpaque } from "../player/lib/previewChannel"; +import { previewStageSize } from "../player/lib/bridgePlayback"; +import { getIframeGsap, type IframeGsap } from "./gsapShared"; +import type { EditingGestureBase } from "@hyperframes/core/runtime/editing-port"; export interface GestureSample { time: number; @@ -45,26 +49,22 @@ interface GsapRuntime { // Extracted helpers — pure functions, no refs, no React. // --------------------------------------------------------------------------- -function readBasePosition(element: HTMLElement, iframeEl: HTMLIFrameElement): BasePosition { +const baseReader = (base: EditingGestureBase): IframeGsap => ({ + getProperty: (_element, prop) => + ({ x: base.x, y: base.y, opacity: base.opacity, scaleX: base.scale })[prop] ?? Number.NaN, +}); + +function readBasePosition(element: HTMLElement, gsap: IframeGsap | null): BasePosition { let baseOpacity = 1; let baseScale = 1; let baseX = 0; let baseY = 0; - try { - const gsap = ( - iframeEl.contentWindow as Window & { - gsap?: { getProperty: (el: Element, prop: string) => number }; - } - ).gsap; - if (gsap?.getProperty) { - baseOpacity = Number(gsap.getProperty(element, "opacity")) || 1; - baseScale = Number(gsap.getProperty(element, "scaleX")) || 1; - baseX = Number(gsap.getProperty(element, "x")) || 0; - baseY = Number(gsap.getProperty(element, "y")) || 0; - } - } catch { - /* cross-origin guard */ + if (gsap) { + baseOpacity = Number(gsap.getProperty(element, "opacity")) || 1; + baseScale = Number(gsap.getProperty(element, "scaleX")) || 1; + baseX = Number(gsap.getProperty(element, "x")) || 0; + baseY = Number(gsap.getProperty(element, "y")) || 0; } // Path-offset CSS vars live on the element regardless of whether @@ -143,7 +143,8 @@ function recordSample(r: RecordingRefs, time: number, properties: Record r.lastTime + 1e-9) frame = Math.max(0, frame - 1); const sample = { time: frameToSeconds(frame, fps), properties: { ...properties } }; const lastIndex = r.samples.length - 1; const lastSample = r.samples[lastIndex]; @@ -158,8 +159,12 @@ function recordSample(r: RecordingRefs, time: number, properties: Record 0 ? iframeRect.width / stage.width : null; + } const doc = iframeEl.contentDocument; const root = doc?.querySelector("[data-composition-id]") ?? doc?.documentElement; const declaredWidth = Number(root?.getAttribute("data-width")) || 1920; @@ -231,6 +236,10 @@ interface RecordingRefs { samples: GestureSample[]; trail: Array<{ x: number; y: number }>; cleanup: (() => void) | null; + /** Where a recording without the in-frame runtime moves the film's playhead. */ + playhead: { start: number; end: number } | null; + /** Recording time at the layer's end: a sample past it would outlast what the playhead shows. */ + lastTime: number; } function createRecordingRefs(): RecordingRefs { @@ -249,6 +258,8 @@ function createRecordingRefs(): RecordingRefs { samples: [], trail: [], cleanup: null, + playhead: null, + lastTime: Infinity, }; } @@ -303,8 +314,17 @@ export function useGestureRecording() { }, []); const startRecording = useCallback( - (element: HTMLElement, iframeEl: HTMLIFrameElement, elementEndTime?: number) => { - if (isRecordingRef.current) return; + ( + element: HTMLElement, + iframeEl: HTMLIFrameElement, + elementEndTime?: number, + sealedBase?: EditingGestureBase | null, + ): boolean => { + if (isRecordingRef.current) return true; + const sealed = previewFrameOpaque(iframeEl); + const gsap = sealed ? (sealedBase ? baseReader(sealedBase) : null) : getIframeGsap(iframeEl); + const scale = computeIframeScale(iframeEl); + if (scale === null || (sealed && !gsap)) return false; isRecordingRef.current = true; const r = refs.current; @@ -317,7 +337,7 @@ export function useGestureRecording() { setRecordingDuration(0); // --- Phase 1: Read base position from GSAP + CSS vars --- - const base = readBasePosition(element, iframeEl); + const base = readBasePosition(element, gsap); r.cssVarOffset = { x: base.cssOffX, y: base.cssOffY }; r.accumulated = { opacity: base.baseOpacity, scale: base.baseScale, z: 0 }; r.basePosition = { x: base.baseX, y: base.baseY }; @@ -325,10 +345,18 @@ export function useGestureRecording() { // --- Phase 2: iframe → studio scale, measured BEFORE clearing the path offset --- // The pointer deltas in the RAF loop are in studio-viewport pixels; divide by // this scale to convert them to the iframe's composition pixels. - r.scale = computeIframeScale(iframeEl); + r.scale = scale; // --- Phase 3: Connect to the iframe GSAP runtime --- r.runtime = connectGsapRuntime(element, iframeEl, elementEndTime); + const { currentTime, duration } = usePlayerStore.getState(); + r.playhead = sealed + ? { start: currentTime, end: Math.min(elementEndTime ?? Infinity, duration) } + : null; + const seekable = r.runtime + ? { start: r.runtime.startTime, end: r.runtime.maxSeekTime } + : r.playhead; + r.lastTime = seekable ? Math.max(0, seekable.end - seekable.start) : Infinity; // Clear the optimistic path offset only while a live runtime owns the // preview. releaseRuntimePreview restores it on every exit path. if (r.runtime && (base.cssOffX || base.cssOffY)) { @@ -382,7 +410,7 @@ export function useGestureRecording() { const tick = () => { if (!isRecordingRef.current) return; const now = performance.now(); - const time = (now - startMs) / 1000; + const time = Math.min((now - startMs) / 1000, r.lastTime); const scale = r.scale || 1; const dx = (r.pointer.x - r.startPointer.x) / scale; @@ -416,6 +444,8 @@ export function useGestureRecording() { // continues). `r.runtime` is nulled so we don't retry on every frame. releaseRuntimePreview(r); } + } else if (r.playhead) { + usePlayerStore.getState().requestSeek(Math.min(r.playhead.start + time, r.playhead.end)); } recordSample(r, time, properties); @@ -435,6 +465,7 @@ export function useGestureRecording() { document.removeEventListener("keyup", handleKeyChange); document.removeEventListener("pointermove", captureStart); }; + return true; }, [], // No deps — uses refs only for all mutable state ); diff --git a/packages/studio/src/player/lib/previewElements.ts b/packages/studio/src/player/lib/previewElements.ts index 5396f9ca00..4c7f4a517a 100644 --- a/packages/studio/src/player/lib/previewElements.ts +++ b/packages/studio/src/player/lib/previewElements.ts @@ -18,6 +18,7 @@ import { type EditingElementBox, type EditingElementDescription, type EditingElementGeometry, + type EditingGestureBase, type EditingGestureStart, type EditingElementHit, type EditingElementMatch, @@ -320,6 +321,20 @@ export async function previewGestureStart( return { elements: elements.map(readGestureStart), snap }; } +export async function previewGestureBase( + iframe: HTMLIFrameElement, + handles: readonly string[], +): Promise | null> { + if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null; + const elements: unknown = ( + await previewRequest(iframe, "gesture-base", { handles: [...handles] }) + )?.elements; + if (!Array.isArray(elements) || elements.length !== handles.length) return null; + return elements.map((base) => + isFiniteFields(base, ["x", "y", "opacity", "scale"]) ? (base as EditingGestureBase) : null, + ); +} + const LAYER_KINDS = new Set(["image", "video", "audio", "vector", "group", "text", "shape"]); const isLayer = (value: unknown): value is EditingLayer => isFields(value) && diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index 5497555bb7..260db430e6 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -37,7 +37,7 @@ }, "@hyperframes/producer": { "packed": 993551, - "unpacked": 3491355 + "unpacked": 3702639 }, "@hyperframes/sdk": { "packed": 90662,