mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-17 15:24:19 +00:00
feat(studio): optimistic update pattern for keyframe mutations
Keyframe mutations (add, remove, convert-to-keyframes) now update the player store cache immediately and persist to the server async. On failure the cache rolls back to its pre-mutation state. Adds a generic executeOptimistic utility that takes apply/persist/rollback callbacks, used by the three keyframe mutation paths in useGsapScriptCommits.
This commit is contained in:
@@ -3,6 +3,8 @@ import type { ParsedGsap } from "@hyperframes/core/gsap-parser";
|
||||
import type { DomEditSelection } from "../components/editor/domEditingTypes";
|
||||
import type { EditHistoryKind } from "../utils/editHistory";
|
||||
import { applySoftReload } from "../utils/gsapSoftReload";
|
||||
import { executeOptimistic } from "../utils/optimisticUpdate";
|
||||
import { usePlayerStore, type KeyframeCacheEntry } from "../player/store/playerStore";
|
||||
|
||||
const PROPERTY_DEFAULTS: Record<string, number> = {
|
||||
opacity: 1,
|
||||
@@ -70,6 +72,23 @@ async function mutateGsapScript(
|
||||
}
|
||||
}
|
||||
|
||||
/** Read the current keyframe cache entry for an element from the player store. */
|
||||
function readKeyframeSnapshot(
|
||||
elementId: string | null | undefined,
|
||||
): KeyframeCacheEntry | undefined {
|
||||
if (!elementId) return undefined;
|
||||
return usePlayerStore.getState().keyframeCache.get(elementId);
|
||||
}
|
||||
|
||||
/** Write a keyframe cache entry (or clear it) in the player store. */
|
||||
function writeKeyframeCache(
|
||||
elementId: string | null | undefined,
|
||||
data: KeyframeCacheEntry | undefined,
|
||||
): void {
|
||||
if (!elementId) return;
|
||||
usePlayerStore.getState().setKeyframeCache(elementId, data);
|
||||
}
|
||||
|
||||
interface GsapScriptCommitsParams {
|
||||
projectIdRef: React.MutableRefObject<string | null>;
|
||||
activeCompPath: string | null;
|
||||
@@ -361,32 +380,98 @@ export function useGsapScriptCommits({
|
||||
property: string,
|
||||
value: number | string,
|
||||
) => {
|
||||
void commitMutation(
|
||||
selection,
|
||||
{ type: "add-keyframe", animationId, percentage, properties: { [property]: value } },
|
||||
{ label: `Add keyframe at ${percentage}%`, softReload: true },
|
||||
);
|
||||
const elementId = selection.id;
|
||||
void executeOptimistic<KeyframeCacheEntry | undefined>({
|
||||
apply: () => {
|
||||
const prev = readKeyframeSnapshot(elementId);
|
||||
if (prev) {
|
||||
const newKeyframes = [
|
||||
...prev.keyframes,
|
||||
{ percentage, properties: { [property]: value } },
|
||||
].sort((a, b) => a.percentage - b.percentage);
|
||||
writeKeyframeCache(elementId, { ...prev, keyframes: newKeyframes });
|
||||
}
|
||||
return prev;
|
||||
},
|
||||
persist: () =>
|
||||
commitMutation(
|
||||
selection,
|
||||
{ type: "add-keyframe", animationId, percentage, properties: { [property]: value } },
|
||||
{ label: `Add keyframe at ${percentage}%`, softReload: true },
|
||||
),
|
||||
rollback: (prev) => {
|
||||
writeKeyframeCache(elementId, prev);
|
||||
},
|
||||
});
|
||||
},
|
||||
[commitMutation],
|
||||
);
|
||||
|
||||
const removeKeyframe = useCallback(
|
||||
(selection: DomEditSelection, animationId: string, percentage: number) => {
|
||||
void commitMutation(
|
||||
selection,
|
||||
{ type: "remove-keyframe", animationId, percentage },
|
||||
{ label: `Remove keyframe at ${percentage}%`, softReload: true },
|
||||
);
|
||||
const elementId = selection.id;
|
||||
void executeOptimistic<KeyframeCacheEntry | undefined>({
|
||||
apply: () => {
|
||||
const prev = readKeyframeSnapshot(elementId);
|
||||
if (prev) {
|
||||
const newKeyframes = prev.keyframes.filter((kf) => kf.percentage !== percentage);
|
||||
writeKeyframeCache(elementId, { ...prev, keyframes: newKeyframes });
|
||||
}
|
||||
return prev;
|
||||
},
|
||||
persist: () =>
|
||||
commitMutation(
|
||||
selection,
|
||||
{ type: "remove-keyframe", animationId, percentage },
|
||||
{ label: `Remove keyframe at ${percentage}%`, softReload: true },
|
||||
),
|
||||
rollback: (prev) => {
|
||||
writeKeyframeCache(elementId, prev);
|
||||
},
|
||||
});
|
||||
},
|
||||
[commitMutation],
|
||||
);
|
||||
|
||||
const convertToKeyframes = useCallback(
|
||||
(selection: DomEditSelection, animationId: string) => {
|
||||
const elementId = selection.id;
|
||||
void executeOptimistic<KeyframeCacheEntry | undefined>({
|
||||
apply: () => {
|
||||
const prev = readKeyframeSnapshot(elementId);
|
||||
if (!prev) {
|
||||
// Seed a minimal percentage-format entry so the UI shows keyframe
|
||||
// diamonds immediately, before the server responds.
|
||||
writeKeyframeCache(elementId, {
|
||||
format: "percentage",
|
||||
keyframes: [
|
||||
{ percentage: 0, properties: {} },
|
||||
{ percentage: 100, properties: {} },
|
||||
],
|
||||
});
|
||||
}
|
||||
return prev;
|
||||
},
|
||||
persist: () =>
|
||||
commitMutation(
|
||||
selection,
|
||||
{ type: "convert-to-keyframes", animationId },
|
||||
{ label: "Convert to keyframes" },
|
||||
),
|
||||
rollback: (prev) => {
|
||||
writeKeyframeCache(elementId, prev);
|
||||
},
|
||||
});
|
||||
},
|
||||
[commitMutation],
|
||||
);
|
||||
|
||||
const removeAllKeyframes = useCallback(
|
||||
(selection: DomEditSelection, animationId: string) => {
|
||||
void commitMutation(
|
||||
selection,
|
||||
{ type: "convert-to-keyframes", animationId },
|
||||
{ label: "Convert to keyframes" },
|
||||
{ type: "remove-all-keyframes", animationId },
|
||||
{ label: "Remove all keyframes", softReload: true },
|
||||
);
|
||||
},
|
||||
[commitMutation],
|
||||
@@ -405,5 +490,6 @@ export function useGsapScriptCommits({
|
||||
addKeyframe,
|
||||
removeKeyframe,
|
||||
convertToKeyframes,
|
||||
removeAllKeyframes,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { executeOptimistic } from "./optimisticUpdate";
|
||||
|
||||
describe("executeOptimistic", () => {
|
||||
it("calls apply then persist on success, never rollback", async () => {
|
||||
const apply = vi.fn(() => "snapshot");
|
||||
const persist = vi.fn(() => Promise.resolve());
|
||||
const rollback = vi.fn();
|
||||
|
||||
await executeOptimistic({ apply, persist, rollback });
|
||||
|
||||
expect(apply).toHaveBeenCalledOnce();
|
||||
expect(persist).toHaveBeenCalledOnce();
|
||||
expect(rollback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls rollback with snapshot on persist failure", async () => {
|
||||
const apply = vi.fn(() => ({ prev: "data" }));
|
||||
const persist = vi.fn(() => Promise.reject(new Error("network")));
|
||||
const rollback = vi.fn();
|
||||
|
||||
await executeOptimistic({ apply, persist, rollback });
|
||||
|
||||
expect(apply).toHaveBeenCalledOnce();
|
||||
expect(persist).toHaveBeenCalledOnce();
|
||||
expect(rollback).toHaveBeenCalledWith({ prev: "data" });
|
||||
});
|
||||
|
||||
it("preserves complex snapshot objects through rollback", async () => {
|
||||
const snapshot = {
|
||||
format: "percentage",
|
||||
keyframes: [{ percentage: 0, properties: { opacity: 0 } }],
|
||||
};
|
||||
const apply = vi.fn(() => structuredClone(snapshot));
|
||||
const persist = vi.fn(() => Promise.reject(new Error("500")));
|
||||
const rollback = vi.fn();
|
||||
|
||||
await executeOptimistic({ apply, persist, rollback });
|
||||
|
||||
expect(rollback).toHaveBeenCalledOnce();
|
||||
expect(rollback.mock.calls[0][0]).toEqual(snapshot);
|
||||
});
|
||||
|
||||
it("handles undefined snapshot for rollback", async () => {
|
||||
const apply = vi.fn(() => undefined);
|
||||
const persist = vi.fn(() => Promise.reject(new Error("timeout")));
|
||||
const rollback = vi.fn();
|
||||
|
||||
await executeOptimistic({ apply, persist, rollback });
|
||||
|
||||
expect(rollback).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
export interface OptimisticUpdateOptions<TSnapshot> {
|
||||
/** Apply the change to local state immediately. Return a snapshot for rollback. */
|
||||
apply: () => TSnapshot;
|
||||
/** Persist the change to the server. */
|
||||
persist: () => Promise<unknown>;
|
||||
/** Revert local state using the snapshot if persist fails. */
|
||||
rollback: (snapshot: TSnapshot) => void;
|
||||
}
|
||||
|
||||
export async function executeOptimistic<T>(options: OptimisticUpdateOptions<T>): Promise<void> {
|
||||
const snapshot = options.apply();
|
||||
try {
|
||||
await options.persist();
|
||||
} catch (error) {
|
||||
options.rollback(snapshot);
|
||||
console.warn("[optimistic] Mutation failed, rolled back:", error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user