From 468ab907ee9836e076abdd7d0e0611c475dc1271 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Fri, 20 Nov 2026 11:12:47 +0000 Subject: [PATCH] fix(studio): a sealed move, resize or turn takes GSAP's route when GSAP animates the layer (#8286) * fix(studio): a sealed move, resize or turn takes GSAP's route when GSAP animates the layer * fix(studio): a live layer's route is decided at once, and a turn the press routed keeps it * fix(studio): a sealed resize's anchor move waits for the frame's GSAP read before choosing CSS --- .../components/editor/propertyPanelHelpers.ts | 10 +- .../editor/propertyPanelTransformCommit.ts | 4 +- .../studio/src/hooks/gsapFrameSnapshot.ts | 8 +- .../src/hooks/gsapRoute.sealed.test.tsx | 210 ++++++++++++++++++ .../studio/src/hooks/gsapRuntimeKeyframes.ts | 35 ++- .../studio/src/hooks/useGsapAwareEditing.ts | 15 +- 6 files changed, 258 insertions(+), 24 deletions(-) create mode 100644 packages/studio/src/hooks/gsapRoute.sealed.test.tsx diff --git a/packages/studio/src/components/editor/propertyPanelHelpers.ts b/packages/studio/src/components/editor/propertyPanelHelpers.ts index ef1a7f8b2a..c0e341f7c1 100644 --- a/packages/studio/src/components/editor/propertyPanelHelpers.ts +++ b/packages/studio/src/components/editor/propertyPanelHelpers.ts @@ -9,11 +9,7 @@ import { playbackStartAttributeForElement, readPlaybackStartAttributes, } from "../../player/lib/timelineElementHelpers"; -import { - editsPlainCss, - GSAP_TRANSFORM_KEYS, - sealedGsapRendersTransform, -} from "../../hooks/gsapRuntimeKeyframes"; +import { editsPlainCss, GSAP_TRANSFORM_KEYS } from "../../hooks/gsapRuntimeKeyframes"; import { getIframeGsap } from "../../hooks/gsapShared"; import { previewFrameOpaque } from "../../player/lib/previewChannel"; @@ -498,9 +494,7 @@ export function readGsapRuntimeValuesForPanel( const el = sealed ? element.element : findPreviewNode(iframe.contentDocument, element); if (!gsap || !el) return null; const propKeys = collectPanelPropKeys(gsapAnimations); - const readsTransform = sealed - ? sealedGsapRendersTransform(iframe, el) - : !editsPlainCss(el, "move"); + const readsTransform = !editsPlainCss(el, "move"); const result: Record = {}; for (const prop of propKeys) { if (!readsTransform && GSAP_TRANSFORM_KEYS.has(prop)) continue; diff --git a/packages/studio/src/components/editor/propertyPanelTransformCommit.ts b/packages/studio/src/components/editor/propertyPanelTransformCommit.ts index c379392068..f4101a7944 100644 --- a/packages/studio/src/components/editor/propertyPanelTransformCommit.ts +++ b/packages/studio/src/components/editor/propertyPanelTransformCommit.ts @@ -1,4 +1,4 @@ -import { editsPlainCss } from "../../hooks/gsapRuntimeKeyframes"; +import { editsPlainCssSettled } from "../../hooks/gsapRuntimeKeyframes"; import type { DomEditSelection } from "./domEditingTypes"; import { readStudioBoxSize } from "./manualEdits"; import { readMoveOffset, UNREADABLE_TRANSLATE } from "./plainTranslate"; @@ -75,7 +75,7 @@ export function createTransformCommitHandlers({ ) ) return; - const plainTranslate = editsPlainCss(element.element, "move"); + const plainTranslate = await editsPlainCssSettled(element.element, "move"); const current = readMoveOffset(element.element, plainTranslate); if (!Number.isFinite(current.x) || !Number.isFinite(current.y)) return void showToast?.(UNREADABLE_TRANSLATE); diff --git a/packages/studio/src/hooks/gsapFrameSnapshot.ts b/packages/studio/src/hooks/gsapFrameSnapshot.ts index 22eaf8815c..f43c8862f3 100644 --- a/packages/studio/src/hooks/gsapFrameSnapshot.ts +++ b/packages/studio/src/hooks/gsapFrameSnapshot.ts @@ -7,7 +7,7 @@ import { previewFrameOpaque, previewRequest, } from "../player/lib/previewChannel"; -import { onPreviewContentReplaced } from "../player/sceneSwap"; +import { onPreviewContentReplaced, onPreviewRestoredInPlace } from "../player/sceneSwap"; import { usePlayerStore } from "../player/store/playerStore"; import { usePreviewIframeStore } from "../player/store/previewIframeStore"; import { previewStandInHandle } from "../components/editor/previewDrafts"; @@ -91,8 +91,14 @@ async function read(iframe: HTMLIFrameElement, client: EditingPortClient): Promi watchPlayhead(); if (!watched.has(client)) { watched.add(client); + const stopOnUndoRerun = onPreviewRestoredInPlace(iframe, () => { + held.delete(client); + asking.delete(client); + void refreshGsapSnapshot(iframe); + }); const stop = onPreviewContentReplaced(iframe, () => { stop(); + stopOnUndoRerun(); held.delete(client); watched.delete(client); void refreshGsapSnapshot(iframe); diff --git a/packages/studio/src/hooks/gsapRoute.sealed.test.tsx b/packages/studio/src/hooks/gsapRoute.sealed.test.tsx new file mode 100644 index 0000000000..766f8ab528 --- /dev/null +++ b/packages/studio/src/hooks/gsapRoute.sealed.test.tsx @@ -0,0 +1,210 @@ +// @vitest-environment happy-dom + +import React, { act } from "react"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { DomEditSelection } from "../components/editor/domEditingTypes"; + +(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +const mocks = vi.hoisted(() => ({ request: vi.fn(), drag: vi.fn(), resize: vi.fn() })); + +vi.mock("../player/lib/previewChannel", async (original) => { + const clients = new WeakMap(); + return { + ...(await original()), + previewEditingClient: (iframe: HTMLIFrameElement) => { + if (!clients.has(iframe)) clients.set(iframe, {}); + return clients.get(iframe); + }, + previewFrameOpaque: () => true, + previewRequest: mocks.request, + }; +}); +vi.mock("./gsapRuntimeBridge", () => ({ + tryGsapDragIntercept: mocks.drag, + tryGsapRotationIntercept: vi.fn(), +})); +vi.mock("./gsapResizeIntercept", () => ({ tryGsapResizeIntercept: mocks.resize })); +vi.mock("./useSafeGsapCommitMutation", () => ({ + useGsapSaveFailureTelemetry: () => vi.fn(), + useSafeGsapCommitMutation: (commit: unknown) => commit, +})); + +import { registerPreviewStandIn } from "../components/editor/previewDrafts"; +import { createTransformCommitHandlers } from "../components/editor/propertyPanelTransformCommit"; +import { announcePreviewRestoredInPlace } from "../player/sceneSwap"; +import { usePlayerStore } from "../player/store/playerStore"; +import { mountReactHarness } from "./domSelectionTestHarness"; +import { editsPlainCss, editsPlainCssSettled } from "./gsapRuntimeKeyframes"; +import { useGsapAwareEditing } from "./useGsapAwareEditing"; + +const HANDLE = "0123456789abcdef:1"; + +/** The frame's GSAP read: one timeline whose only tween sets `vars` on the layer. */ +const snapshot = (vars: Record | null) => ({ + time: 0.5, + defaultEase: null, + timelines: [ + { + id: "main", + time: 0.5, + defaultEase: null, + tweens: vars + ? [ + { + targets: [HANDLE], + vars, + start: 0, + duration: 1, + from: false, + initted: true, + parsed: Object.entries(vars).map(([p, c]) => ({ p, s: 0, c })), + parts: [], + }, + ] + : [], + }, + ], + targets: [{ handle: HANDLE, id: "card", className: "", values: {} }], +}); + +afterEach(() => { + mocks.request.mockReset(); + vi.clearAllMocks(); + usePlayerStore.setState({ currentTime: 0, isPlaying: false }); +}); + +/** A sealed layer GSAP animates with `vars`, its frame not yet read. */ +function sealedLayer(vars: Record | null) { + usePlayerStore.setState({ currentTime: 0.5, isPlaying: false }); + mocks.request.mockImplementation(async (_iframe, kind) => + kind === "gsap-snapshot" ? snapshot(vars) : null, + ); + const iframe = document.createElement("iframe"); + const standIn = document.createElement("div"); + registerPreviewStandIn(standIn, iframe, HANDLE); + const selection = { + element: standIn, + handle: HANDLE, + id: "card", + selector: "#card", + boundingBox: { x: 0, y: 0, width: 100, height: 50 }, + } as unknown as DomEditSelection; + return { iframe, standIn, selection }; +} + +function gsapAwareEditing(selection: DomEditSelection) { + mocks.drag.mockResolvedValue({ status: "persisted" }); + mocks.resize.mockResolvedValue({ status: "persisted" }); + const stageElementPositionOffset = vi.fn(() => ({ + save: vi.fn().mockResolvedValue(undefined), + rollback: vi.fn(), + })); + const handleDomBoxSizeCommit = vi.fn().mockResolvedValue(undefined); + let editing!: ReturnType; + function Harness() { + editing = useGsapAwareEditing({ + domEditSelection: selection, + selectedGsapAnimations: [], + gsapCommitMutation: vi.fn().mockResolvedValue(undefined), + previewIframeRef: { current: null }, + showToast: vi.fn(), + bumpGsapCache: vi.fn(), + makeFetchFallback: () => vi.fn().mockResolvedValue([]), + trackGsapInteractionFailure: vi.fn(), + stageElementPositionOffset, + handleDomBoxSizeCommit, + handleDomRotationCommit: vi.fn(), + commitPositionPatchToHtml: vi.fn(), + addGsapAnimation: vi.fn(), + convertToKeyframes: vi.fn(), + setArcPath: vi.fn(), + updateArcSegment: vi.fn(), + }); + return null; + } + const root = mountReactHarness(); + return { editing, stageElementPositionOffset, handleDomBoxSizeCommit, root }; +} + +describe("the GSAP-or-CSS route for a layer in a sealed preview", () => { + it("takes GSAP's route for an X typed in the inspector, before the frame was ever read", async () => { + const { selection } = sealedLayer({ x: 200 }); + const onSetManualOffset = vi.fn(); + const { commitManualOffset } = createTransformCommitHandlers({ + element: selection, + styles: {}, + hasGsapAnimation: false, + gsapAnimId: null, + gsapKeyframes: null, + currentPct: 0, + onCommitAnimatedProperty: undefined, + onAddKeyframe: undefined, + onSetManualOffset, + onSetManualSize: vi.fn(), + onSetManualRotation: vi.fn(), + }); + + await commitManualOffset("x", "40"); + + expect(onSetManualOffset.mock.calls[0]?.[2]).toEqual({ plainTranslate: false }); + }); + + it("takes GSAP's route for a move made by the agent", async () => { + const { selection } = sealedLayer({ x: 200 }); + const { editing, stageElementPositionOffset, root } = gsapAwareEditing(selection); + + await act(() => editing.handleGsapAwarePathOffsetCommit(selection, { x: 40, y: 0 })); + + expect(stageElementPositionOffset).not.toHaveBeenCalledWith(selection, { x: 40, y: 0 }, true); + expect(mocks.drag).toHaveBeenCalled(); + act(() => root.unmount()); + }); + + it("takes GSAP's route for a resize of a layer whose tween sets its width", async () => { + const { selection } = sealedLayer({ width: 300 }); + const { editing, handleDomBoxSizeCommit, root } = gsapAwareEditing(selection); + + await act(() => editing.handleGsapAwareBoxSizeCommit(selection, { width: 200, height: 80 })); + + expect(handleDomBoxSizeCommit).not.toHaveBeenCalled(); + expect(editsPlainCss(selection.element, "move")).toBe(true); + act(() => root.unmount()); + }); + + it("saves a resize's anchor move on GSAP's marks when only a shared tween positions the layer", async () => { + const { selection } = sealedLayer({ x: 200 }); + const { editing, stageElementPositionOffset, root } = gsapAwareEditing(selection); + mocks.drag.mockResolvedValue({ status: "element-offset" }); + + await act(() => + editing.handleGsapAwareBoxSizeCommit( + selection, + { width: 200, height: 80 }, + { x: 10, y: 5 }, + undefined, + { plainTranslate: false }, + ), + ); + + expect(stageElementPositionOffset).toHaveBeenCalledWith( + selection, + { x: 10, y: 5 }, + false, + expect.anything(), + ); + act(() => root.unmount()); + }); + + it("decides again from the frame after an undo restored in place re-ran its script", async () => { + const { iframe, standIn } = sealedLayer(null); + expect(await editsPlainCssSettled(standIn, "move")).toBe(true); + mocks.request.mockImplementation(async (_iframe, kind) => + kind === "gsap-snapshot" ? snapshot({ x: 200 }) : null, + ); + + announcePreviewRestoredInPlace(iframe); + + expect(await editsPlainCssSettled(standIn, "move")).toBe(false); + }); +}); diff --git a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts b/packages/studio/src/hooks/gsapRuntimeKeyframes.ts index 64ef1d3408..6eed96130a 100644 --- a/packages/studio/src/hooks/gsapRuntimeKeyframes.ts +++ b/packages/studio/src/hooks/gsapRuntimeKeyframes.ts @@ -19,7 +19,8 @@ import { withParsedStart } from "./gsapParsedTween"; import { BOX_SIZE_STYLE_PROPS } from "../components/editor/manualEditsDomPatches"; import { gsapRendersTransform } from "../components/editor/gsapAnimatesProperty"; import { previewFrameOpaque } from "../player/lib/previewChannel"; -import { frameQuery, frameTarget, frameTimelines } from "./gsapFrameSnapshot"; +import { frameQuery, frameTarget, frameTimelines, settleGsapSnapshot } from "./gsapFrameSnapshot"; +import { previewStandIn } from "../components/editor/previewDrafts"; /** * A GSAP tween's `vars` object — intentionally open: it mixes channel values @@ -282,12 +283,6 @@ export const GSAP_TRANSFORM_KEYS = new Set( ); const TRANSFORM_CHANNELS = [...MOVE_CHANNELS, ...GSAP_TRANSFORM_KEYS]; -/** Sealed `!editsPlainCss(el, "move")`: the frame snapshot's tweens move or transform `el`. */ -export function sealedGsapRendersTransform(iframe: HTMLIFrameElement, el: Element): boolean { - const target = frameTarget(iframe, el); - return !!target && timelinesWriteChannels(frameTimelines(iframe), target, TRANSFORM_CHANNELS); -} - /** Whether a live timeline tween or hold writes any of `channels` on `el`. Sync, no fetch. */ export function gsapWritesChannels(el: Element, channels: string[]): boolean { const win = el.ownerDocument.defaultView as { __timelines?: Record }; @@ -356,7 +351,31 @@ const GSAP_OWNS: Record boolean> = { /** The one GSAP-or-CSS route decision. Make it when an edit starts and carry it: mid-gesture * writes make GSAP render the element, so asking again at commit can flip the route. */ export function editsPlainCss(el: Element, gesture: EditGesture): boolean { - return !GSAP_OWNS[gesture](el); + const standIn = previewStandIn(el); + return standIn ? !sealedGsapOwns(standIn.iframe, el, gesture) : !GSAP_OWNS[gesture](el); +} + +// A sealed frame's snapshot cannot say whether GSAP renders the transform: a transform tween stands in. +const SEALED_OWNED_CHANNELS: Record = { + move: TRANSFORM_CHANNELS, + rotate: TRANSFORM_CHANNELS, + resize: [...TRANSFORM_CHANNELS, ...BOX_CHANNELS], +}; + +function sealedGsapOwns(iframe: HTMLIFrameElement, el: Element, gesture: EditGesture): boolean { + const target = frameTarget(iframe, el); + const timelines = frameTimelines(iframe); + return !!target && timelinesWriteChannels(timelines, target, SEALED_OWNED_CHANNELS[gesture]); +} + +/** `editsPlainCss`, once a sealed frame's snapshot is read at the playhead; a live element answers now. */ +export function editsPlainCssSettled( + el: Element, + gesture: EditGesture, +): boolean | Promise { + const standIn = previewStandIn(el); + if (!standIn) return editsPlainCss(el, gesture); + return settleGsapSnapshot(standIn.iframe).then(() => editsPlainCss(el, gesture)); } /** `hasNonHoldTweenForElement` for an element in hand, read from its own window's timelines. */ diff --git a/packages/studio/src/hooks/useGsapAwareEditing.ts b/packages/studio/src/hooks/useGsapAwareEditing.ts index 11f992667c..c40c33b574 100644 --- a/packages/studio/src/hooks/useGsapAwareEditing.ts +++ b/packages/studio/src/hooks/useGsapAwareEditing.ts @@ -31,7 +31,7 @@ import { logResize, logResizeSettle } from "../utils/resizeDebug"; import type { MoveCommitOptions } from "../components/editor/domEditOverlayGestures"; import { runGestureTransaction } from "./gestureTransaction"; import { - editsPlainCss, + editsPlainCssSettled, hasNonHoldTweenForElement, POSITION_CHANNELS, } from "./gsapRuntimeKeyframes"; @@ -150,7 +150,7 @@ export function useGsapAwareEditing({ modifiers?: MoveCommitOptions, ) => { const writes = observeGsapGesture(gsapCommitMutation); - if (modifiers?.plainTranslate ?? editsPlainCss(selection.element, "move")) { + if (modifiers?.plainTranslate ?? (await editsPlainCssSettled(selection.element, "move"))) { const result = await stageElementPositionOffset(selection, next, true).save(); return writes.finish(result?.changed === true); } @@ -214,7 +214,8 @@ export function useGsapAwareEditing({ route?: { plainTranslate: boolean }, ) => { const writes = observeGsapGesture(gsapCommitMutation); - if (route?.plainTranslate ?? editsPlainCss(selection.element, "resize")) { + const routed = route?.plainTranslate ?? editsPlainCssSettled(selection.element, "resize"); + if (typeof routed === "boolean" ? routed : await routed) { const result = await handleDomBoxSizeCommit(selection, next, offset, restore); return writes.finish(result?.changed === true); } @@ -268,7 +269,7 @@ export function useGsapAwareEditing({ ); // Saved after the size, under its undo key, so the two are one step. await saveMove(dragOutcome, async () => { - const plainAfterSettle = editsPlainCss(selection.element, "move"); + const plainAfterSettle = await editsPlainCssSettled(selection.element, "move"); anchorMove = writes.drawKeepingUndone(() => stageElementPositionOffset(selection, offset, plainAfterSettle, coalesceKey), ); @@ -376,7 +377,11 @@ export function useGsapAwareEditing({ const handleGsapAwareRotationCommit = useCallback( async (selection: DomEditSelection, next: RotationCommit) => { const writes = observeGsapGesture(gsapCommitMutation); - if (next.plain === undefined ? editsPlainCss(selection.element, "rotate") : next.plain) { + const plain = + next.plain !== undefined + ? next.plain + : await editsPlainCssSettled(selection.element, "rotate"); + if (plain) { const result = await handleDomRotationCommit(selection, next); return writes.finish(result?.changed === true); }