Skip to content
Closed
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
3 changes: 3 additions & 0 deletions packages/studio/src/components/editor/manualOffsetDrag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,13 +517,15 @@ function restoreManualOffsetDragMember(member: ManualOffsetDragMember): void {
endStudioManualEditGesture(member.element, member.gestureToken);
}

/** Roll back a FAILED drag to the exact gesture-start state. */
export function restoreManualOffsetDragMembers(members: ManualOffsetDragMember[]): void {
for (const member of members) {
restoreManualOffsetDragMember(member);
resumeGsapTimelines(member.element);
}
}

/** Teardown after a COMMITTED drag. */
export function endManualOffsetDragMembers(members: ManualOffsetDragMember[]): void {
for (const member of members) {
endStudioManualEditGesture(member.element, member.gestureToken);
Expand Down Expand Up @@ -552,6 +554,7 @@ export function endManualOffsetDragMembers(members: ManualOffsetDragMember[]): v
}
}

/** Shared timeline teardown for either the committed or restored path. */
export function resumeGsapTimelines(element: HTMLElement): void {
const ids = element.getAttribute("data-hf-drag-paused-timelines");
element.removeAttribute("data-hf-drag-paused-timelines");
Expand Down
19 changes: 7 additions & 12 deletions packages/studio/src/hooks/gestureTransaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ function runTwoMutationTransaction(
describe("runGestureTransaction", () => {
beforeEach(() => {
trackStudioEventMock.mockReset();
localStorage.clear();
});

it("settles synchronously before persist reaches its first await", async () => {
Expand Down Expand Up @@ -249,7 +250,7 @@ describe("runGestureTransaction", () => {
.spyOn(element, "getBoundingClientRect")
.mockReturnValueOnce(rect(10.04, 20.05, 100.05, 80.05))
.mockReturnValueOnce(rect(11.19, 17.89, 100.29, 78.99));
const error = vi.spyOn(console, "error").mockImplementation(() => undefined);
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
const now = vi.spyOn(performance, "now").mockReturnValueOnce(50).mockReturnValueOnce(58.44);

await runGestureTransaction({
Expand All @@ -261,13 +262,7 @@ describe("runGestureTransaction", () => {
});

expect(getRect).toHaveBeenCalledTimes(2);
expect(error).toHaveBeenCalledWith(
"[hf-commit] persist changed pixels",
expect.objectContaining({
label: "Resize layer",
delta: expect.objectContaining({ x: expect.any(Number) }),
}),
);
expect(log).not.toHaveBeenCalled();
expect(trackStudioEventMock).toHaveBeenCalledWith("commit_invariant_violation", {
label: "Resize layer",
delta_x: 1.2,
Expand All @@ -283,13 +278,13 @@ describe("runGestureTransaction", () => {
expect.objectContaining({ pixel_asserted: true }),
);
now.mockRestore();
error.mockRestore();
log.mockRestore();
});

it("skips the pixel assertion for live position tweens", async () => {
const element = document.createElement("div");
const getRect = vi.spyOn(element, "getBoundingClientRect");
const error = vi.spyOn(console, "error").mockImplementation(() => undefined);
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);

await runGestureTransaction({
element,
Expand All @@ -301,11 +296,11 @@ describe("runGestureTransaction", () => {
});

expect(getRect).not.toHaveBeenCalled();
expect(error).not.toHaveBeenCalledWith("[hf-commit] persist changed pixels", expect.anything());
expect(log).not.toHaveBeenCalled();
expect(trackStudioEventMock).not.toHaveBeenCalledWith(
"commit_invariant_violation",
expect.anything(),
);
error.mockRestore();
log.mockRestore();
});
});
27 changes: 7 additions & 20 deletions packages/studio/src/hooks/gestureTransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
CommitMutationOptions,
} from "./gsapScriptCommitTypes";
import { trackStudioEvent } from "../utils/studioTelemetry";
import { makeStudioDebugLogger } from "../utils/studioDebug";

type PixelRect = Pick<DOMRect, "x" | "y" | "width" | "height">;

Expand Down Expand Up @@ -108,14 +109,7 @@ async function dispatchBufferedCommits(calls: BufferedCommit[]): Promise<number>
return reloadsRequested(calls);
}

/**
* Dev-only [hf-commit] lifecycle trace. The production observability lives in
* the trackStudioEvent commit_* events (always on); these console lines are a
* developer aid and stay out of end users' consoles.
*/
function traceCommit(stage: string, data: Record<string, unknown>): void {
if (import.meta.env.DEV) console.info(`[hf-commit] ${stage}`, data);
}
const logCommit = makeStudioDebugLogger("commit");

/**
* Owns the visual + persistence + history lifecycle for one gesture release.
Expand All @@ -127,9 +121,9 @@ export function runGestureTransaction(tx: GestureTransaction): Promise<void> {
let mutationCount = 0;
let reloadCount = 0;
const bufferedCommits: BufferedCommit[] = [];
traceCommit("start", { label: tx.label, coalesceKey });
logCommit("start", { label: tx.label, coalesceKey });
tx.settle();
traceCommit("settled", { label: tx.label, coalesceKey });
logCommit("settled", { label: tx.label, coalesceKey });

const before = !tx.skipPixelAssert ? readPixelRect(tx.element) : null;
const commit: TxCommit = (commitMutation) => {
Expand All @@ -152,19 +146,12 @@ export function runGestureTransaction(tx: GestureTransaction): Promise<void> {
.then(async () => {
reloadCount = await dispatchBufferedCommits(bufferedCommits);
const durationMs = Math.round(performance.now() - startedAt);
traceCommit("persisted", { label: tx.label, coalesceKey });
logCommit("persisted", { label: tx.label, coalesceKey });
if (before) {
const after = readPixelRect(tx.element);
const delta = pixelDelta(before, after);
if (exceedsPixelTolerance(delta)) {
if (import.meta.env.DEV) {
console.error("[hf-commit] persist changed pixels", {
label: tx.label,
before,
after,
delta,
});
}
logCommit("persist-changed-pixels", { label: tx.label, before, after, delta });
trackStudioEvent("commit_invariant_violation", {
label: tx.label,
delta_x: roundToOneDecimal(delta.x),
Expand Down Expand Up @@ -193,7 +180,7 @@ export function runGestureTransaction(tx: GestureTransaction): Promise<void> {
error_name: error instanceof Error ? error.name : "unknown",
restore_ran: true,
});
traceCommit("restore", { label: tx.label, coalesceKey });
logCommit("restore", { label: tx.label, coalesceKey });
throw error;
});
}
43 changes: 43 additions & 0 deletions packages/studio/src/hooks/gsapRuntimePatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -523,3 +523,46 @@ describe("patchRuntimeTweenInPlace — composition isolation", () => {
expect(otherTween.invalidate).not.toHaveBeenCalled();
});
});

describe("patchRuntimeTweenInPlace — deferSeek", () => {
/**
* A group drag commits one member at a time. Each in-place patch used to seek,
* and a seek re-renders the WHOLE timeline — so every member still queued behind
* the current one got repainted from its un-patched tween, back to where it sat
* before the drag, and stayed there until its own patch landed. That is the jump.
*/
it("does not seek while a group commit is still writing its other members", () => {
const a = { id: "a" };
const rendered = { a: 0, b: 0 };
const tweenA = makeTween({ vars: { x: 0 }, targetIds: ["a"], duration: 0 }, a);
const tweenB = makeTween({ vars: { x: 0 }, targetIds: ["b"], duration: 0 }, a);
const { iframe, seek } = fakeIframe(a, [tweenA, tweenB], {
onSeek: () => {
rendered.a = tweenA.vars.x as number;
rendered.b = tweenB.vars.x as number;
},
});

const first = patchRuntimeTweenInPlace(
iframe,
"#a",
{ kind: "set", props: { x: 500 } },
undefined,
true,
);

expect(first).toBe(true);
expect(tweenA.vars.x).toBe(500);
// No repaint yet: "b" keeps the transform the gesture left on it instead of
// being rendered from its own tween, which still holds the pre-drag value.
expect(seek).not.toHaveBeenCalled();
expect(rendered).toEqual({ a: 0, b: 0 });

tweenB.vars.x = 600;
const last = patchRuntimeTweenInPlace(iframe, "#a", { kind: "set", props: { x: 500 } });

expect(last).toBe(true);
expect(seek).toHaveBeenCalledTimes(1);
expect(rendered).toEqual({ a: 500, b: 600 });
});
});
12 changes: 11 additions & 1 deletion packages/studio/src/hooks/gsapRuntimePatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,12 +277,16 @@ function applyChange(tween: RuntimeTween, change: RuntimeTweenChange): boolean {
/**
* Edit one tween in `window.__timelines` in place + re-seek to the current playhead.
* Returns `true` on a confident patch, `false` otherwise (caller soft-reloads).
*
* `deferSeek` skips the re-render, for a caller patching several tweens in a row
* that will render once after the last one.
*/
export function patchRuntimeTweenInPlace(
iframe: HTMLIFrameElement | null,
selector: string,
change: RuntimeTweenChange,
compositionId?: string,
deferSeek = false,
): boolean {
if (!iframe) return false;
// A base `gsap.set` has no timeline tween to resolve — apply the value straight
Expand Down Expand Up @@ -312,7 +316,13 @@ export function patchRuntimeTweenInPlace(
if (change.kind !== "keyframe-rebuild") {
tween.invalidate?.();
}
seekToCurrent(iframe, timeline);
// A seek re-renders the WHOLE timeline, not just the tween we patched. Under a
// multi-element commit that is a visible jump: the members still queued behind
// this one get repainted from their un-patched tweens, back to where they were
// before the gesture, and stay there until their own patch lands. Deferring
// leaves them showing the gesture's own transform, and the caller's last patch
// seeks once for the whole group.
if (!deferSeek) seekToCurrent(iframe, timeline);
return true;
} catch {
return false;
Expand Down
20 changes: 20 additions & 0 deletions packages/studio/src/hooks/gsapScriptCommitTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@ export interface CommitMutationOptions {
coalesceMs?: number;
softReload?: boolean;
skipReload?: boolean;
/**
* Write the source but leave the preview alone; the caller renders once when it
* is done. For a multi-write action like a group drag, rendering after each
* write shows a source where the members not yet written still hold their old
* values, so they snap back until their own write lands. This also defers the
* in-place runtime patch's seek, which re-renders the whole timeline and repaints
* the queued members the same way. Unlike `skipReload` this changes nothing about
* error handling — a failed write still throws.
*/
deferPreviewSync?: boolean;
/** Shares an in-place patch miss with the final render of one multi-write action. */
previewFallbackLatch?: { pending: boolean };
beforeReload?: () => void;
/**
* Serialize this commit against others sharing the same key. Used to chain
Expand All @@ -39,6 +51,14 @@ export interface CommitMutationOptions {
* existing soft/full reload path. Structural edits omit this and reload as before.
*/
instantPatch?: { selector: string; change: RuntimeTweenChange };
/**
* The same fast path for a batched commit: one patch per element the batch
* wrote, applied in order. All of them must land for the reload to be skipped
* — one that can't be applied leaves the preview half-patched, so the whole
* batch falls back to the reload. Only the last patch re-renders (see
* `deferSeek`), so a ten-element batch repaints once.
*/
instantPatches?: Array<{ selector: string; change: RuntimeTweenChange }>;
}

export interface CommitMutationCall {
Expand Down
108 changes: 108 additions & 0 deletions packages/studio/src/hooks/keyframeCacheAstLoad.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fetchParsedAnimations } from "./keyframeCacheAstLoad";

/**
* Parsing a composition is a whole-file read + parse on the server, and a
* multi-element action asks for the same file once per element. Callers that
* overlap in time share one request; a caller that comes after the last one
* settled does not, so a parse issued after a write is never served a
* pre-write answer.
*/
describe("fetchParsedAnimations — in-flight sharing", () => {
afterEach(() => {
vi.unstubAllGlobals();
});

function stubFetch(): { calls: () => number; settle: () => void } {
let calls = 0;
const pending: Array<() => void> = [];
vi.stubGlobal("fetch", () => {
calls++;
return new Promise((resolve) => {
pending.push(() =>
resolve({
ok: true,
json: () => Promise.resolve({ animations: [{ id: "a", targetSelector: "#a" }] }),
} as Response),
);
});
});
return {
calls: () => calls,
settle: () => {
for (const release of pending.splice(0, pending.length)) release();
},
};
}

it("serves overlapping reads of one file from a single request", async () => {
const fetchStub = stubFetch();

const pending = [
fetchParsedAnimations("p", "index.html"),
fetchParsedAnimations("p", "index.html"),
fetchParsedAnimations("p", "index.html"),
];
fetchStub.settle();
const results = await Promise.all(pending);

expect(fetchStub.calls()).toBe(1);
expect(results.map((parsed) => parsed?.animations.length)).toEqual([1, 1, 1]);
});

it("does not share across files", async () => {
const fetchStub = stubFetch();

const pending = [
fetchParsedAnimations("p", "index.html"),
fetchParsedAnimations("p", "other.html"),
];
fetchStub.settle();
await Promise.all(pending);

expect(fetchStub.calls()).toBe(2);
});

it("re-requests once the previous read has settled", async () => {
const fetchStub = stubFetch();

const first = fetchParsedAnimations("p", "index.html");
fetchStub.settle();
await first;
const second = fetchParsedAnimations("p", "index.html");
fetchStub.settle();
await second;

expect(fetchStub.calls()).toBe(2);
});

it("supersedes an in-flight pre-write parse with a fresh post-write read", async () => {
const releases: Array<(response: Response) => void> = [];
const fetch = vi.fn(
() =>
new Promise<Response>((resolve) => {
releases.push(resolve);
}),
);
vi.stubGlobal("fetch", fetch);
const response = (id: string) =>
({
ok: true,
json: () => Promise.resolve({ animations: [{ id, targetSelector: `#${id}` }] }),
}) as Response;

const stale = fetchParsedAnimations("p", "index.html");
const fresh = fetchParsedAnimations("p", "index.html", { fresh: true });
expect(fetch).toHaveBeenCalledTimes(2);

releases[0]?.(response("stale"));
await stale;
const overlappingFreshRead = fetchParsedAnimations("p", "index.html");
expect(fetch).toHaveBeenCalledTimes(2);

releases[1]?.(response("fresh"));
const [freshResult, sharedResult] = await Promise.all([fresh, overlappingFreshRead]);
expect(freshResult?.animations[0]?.id).toBe("fresh");
expect(sharedResult?.animations[0]?.id).toBe("fresh");
});
});
Loading
Loading