Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 2 additions & 8 deletions packages/studio/src/components/editor/propertyPanelHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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<string, number> = {};
for (const prop of propKeys) {
if (!readsTransform && GSAP_TRANSFORM_KEYS.has(prop)) continue;
Expand Down
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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);
Expand Down
8 changes: 7 additions & 1 deletion packages/studio/src/hooks/gsapFrameSnapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down
210 changes: 210 additions & 0 deletions packages/studio/src/hooks/gsapRoute.sealed.test.tsx
Original file line number Diff line number Diff line change
@@ -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<HTMLIFrameElement, object>();
return {
...(await original<object>()),
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<string, number> | 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<string, number> | 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<typeof useGsapAwareEditing>;
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(<Harness />);
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);
});
});
35 changes: 27 additions & 8 deletions packages/studio/src/hooks/gsapRuntimeKeyframes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<string, RuntimeTimeline> };
Expand Down Expand Up @@ -356,7 +351,31 @@ const GSAP_OWNS: Record<EditGesture, (el: Element) => 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<EditGesture, string[]> = {
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<boolean> {
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. */
Expand Down
15 changes: 10 additions & 5 deletions packages/studio/src/hooks/useGsapAwareEditing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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),
);
Expand Down Expand Up @@ -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);
}
Expand Down
Loading