From 79eed9bb78482f76efb8d0cdf54fbbbbfb6bd828 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Mon, 1 Jun 2026 15:59:23 -0400 Subject: [PATCH] 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. --- .../studio/src/hooks/useGsapScriptCommits.ts | 110 ++++++++++++++++-- .../studio/src/utils/optimisticUpdate.test.ts | 53 +++++++++ packages/studio/src/utils/optimisticUpdate.ts | 18 +++ 3 files changed, 169 insertions(+), 12 deletions(-) create mode 100644 packages/studio/src/utils/optimisticUpdate.test.ts create mode 100644 packages/studio/src/utils/optimisticUpdate.ts diff --git a/packages/studio/src/hooks/useGsapScriptCommits.ts b/packages/studio/src/hooks/useGsapScriptCommits.ts index e4018c8b89..f13567c560 100644 --- a/packages/studio/src/hooks/useGsapScriptCommits.ts +++ b/packages/studio/src/hooks/useGsapScriptCommits.ts @@ -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 = { 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; 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({ + 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({ + 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({ + 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, }; } diff --git a/packages/studio/src/utils/optimisticUpdate.test.ts b/packages/studio/src/utils/optimisticUpdate.test.ts new file mode 100644 index 0000000000..b1c0ba297e --- /dev/null +++ b/packages/studio/src/utils/optimisticUpdate.test.ts @@ -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); + }); +}); diff --git a/packages/studio/src/utils/optimisticUpdate.ts b/packages/studio/src/utils/optimisticUpdate.ts new file mode 100644 index 0000000000..90e1bfe944 --- /dev/null +++ b/packages/studio/src/utils/optimisticUpdate.ts @@ -0,0 +1,18 @@ +export interface OptimisticUpdateOptions { + /** Apply the change to local state immediately. Return a snapshot for rollback. */ + apply: () => TSnapshot; + /** Persist the change to the server. */ + persist: () => Promise; + /** Revert local state using the snapshot if persist fails. */ + rollback: (snapshot: TSnapshot) => void; +} + +export async function executeOptimistic(options: OptimisticUpdateOptions): Promise { + const snapshot = options.apply(); + try { + await options.persist(); + } catch (error) { + options.rollback(snapshot); + console.warn("[optimistic] Mutation failed, rolled back:", error); + } +}