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
1 change: 1 addition & 0 deletions packages/core/src/runtime/editingAgent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ describe("installEditingAgent", () => {
"layers",
"draft",
"gesture-start",
"gesture-base",
"console-errors",
"watch-keys",
"restore-attributes",
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/runtime/editingAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down
19 changes: 18 additions & 1 deletion packages/core/src/runtime/editingGestureStart.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>; targets: () => unknown[]; duration: () => number };
Expand Down Expand Up @@ -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();
});
});
12 changes: 12 additions & 0 deletions packages/core/src/runtime/editingGestureStart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/runtime/editingPort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ describe("createEditingPortClient", () => {
"layers",
"draft",
"gesture-start",
"gesture-base",
"console-errors",
"watch-keys",
"restore-attributes",
Expand Down
10 changes: 8 additions & 2 deletions packages/core/src/runtime/editingPort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -190,6 +190,7 @@ export const EDITING_REQUEST_KINDS = [
"layers",
"draft",
"gesture-start",
"gesture-base",
"console-errors",
"watch-keys",
"restore-attributes",
Expand Down Expand Up @@ -330,6 +331,10 @@ export interface EditingRequests {
params: { handles: EditingElementHandle[] };
result: { elements: Array<EditingGestureStart | null>; snap: EditingElementBox[] };
};
"gesture-base": {
params: { handles: EditingElementHandle[] };
result: { elements: Array<EditingGestureBase | null> };
};
"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. */
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion packages/studio/src/hooks/newTweenTargetHooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const frozenSamples = [

vi.mock("./useGestureRecording", () => ({
useGestureRecording: () => ({
startRecording: vi.fn(),
startRecording: vi.fn(() => true),
stopRecording: () => frozenSamples,
clearSamples: vi.fn(),
samples: frozenSamples,
Expand Down
68 changes: 67 additions & 1 deletion packages/studio/src/hooks/useGestureCommit.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 } },
Expand All @@ -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<typeof import("../player/lib/previewChannel")>()),
previewFrameOpaque: () => sealedFrame.opaque,
}));
vi.mock("../player/lib/previewElements", async (load) => ({
...(await load<typeof import("../player/lib/previewElements")>()),
previewGestureBase: () =>
new Promise((resolve) => {
sealedFrame.answer = resolve;
}),
}));

vi.mock("./useGestureRecording", () => ({
useGestureRecording: () => gestureRecording,
}));
Expand All @@ -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();
Expand Down Expand Up @@ -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();
});
});
55 changes: 42 additions & 13 deletions packages/studio/src/hooks/useGestureCommit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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<DomEditSelection | null>(null);
Expand All @@ -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);
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading