mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-09-11 23:00:03 +00:00
refactor(studio): simplify hooks, split contexts, remove dead code (#1416)
* fix(studio): guard Zustand no-op setters and fix useConsoleErrorCapture memory leak - Guard setIsPlaying to skip set() when value unchanged (eliminates 60 notifications/sec during reverse playback) - Guard caption store selectGroup to bail before set() when group missing (prevents empty Zustand notifications) - Guard clearSelection to skip when already empty - Fix useConsoleErrorCapture: restore original console.error, remove error event listener, and delete __hfErrorCapture flag on cleanup * fix(studio): delete dead files and unused exports Remove 7 dead files (audioBeatDetection, keyframeSnapping, timelineInspector, DopesheetStrip, StaggerControls, TimelineLayerPanel, TimelineEditorNotice) and their test companions. Delete unused computeFitToChildrenSize export from propertyPanelHelpers. Fix re-export indirection: useDomEditCommits and studioMotionOps.test now import patch builders directly from manualEditsDomPatches instead of the re-export passthrough in manualEditsDom. * fix(studio): eliminate effect-chain state mirroring for lint findings, hover, and GSAP fetch Move lint findingsByElement sync from App.tsx into useLintModal where the value is produced, removing the mirroring useEffect. Consolidate 4 hover-clearing effects in useDomSelection into 2 (one unconditional on context change, one conditional combining caption mode, selection match, and disconnected element checks). Fold the GSAP retry effect into the fetch effect in useGsapTweenCache, scheduling a single retry via setTimeout when the initial fetch returns 0 animations. Eliminates 3 unnecessary render cycles from effect chains. * fix(studio): memoize renderQueue, toolbar, and canvas rect to prevent re-render cascade - Wrap renderQueue object in useMemo so StudioContext consumers don't re-render on every App render - Memoize timelineToolbar JSX so NLELayout memo isn't defeated - Move canvasRect getBoundingClientRect() from render-time IIFE to a useLayoutEffect-backed ref, eliminating layout thrashing - Track and clear setTimeout handles in refreshPreviewDocumentVersion to prevent stale timer accumulation on rapid calls and unmount * refactor(studio): consolidate GSAP shared primitives — defaults, iframe access, keyframe parsing Extract duplicated PROPERTY_DEFAULTS, IframeGsap interface, iframe accessors (getIframeGsap, queryIframeElement), percentage keyframe parsing, and toAbsoluteTime into a single gsapShared.ts module. Removes ~120 lines of copy-pasted logic across 8 hook files, reducing drift risk between the duplicate implementations. * fix(studio): remove dead store fields, dead file, duplicate helper, and unsafe assertions * refactor(studio): deduplicate selector helpers, rounding utils, percentage computation, and iframe access * fix(studio): split StudioContext into Shell + Playback to prevent cascade re-renders * refactor(studio): decompose useGsapScriptCommits into focused mutation hooks * refactor(studio): decompose useFileManager into focused file operation hooks Extract useFileTree (tree loading, refresh, derived assets/compositions) and useEditorSave (debounced save with history tracking) from the 508-LOC useFileManager. The parent hook composes both and retains file I/O, click-to-source, upload/import, and CRUD — preserving the same public interface so no consumers change. * refactor(studio): decompose useDomEditCommits into focused commit hooks Extract geometry (path offset, box size, rotation) and element lifecycle (delete, z-index reorder) into useDomGeometryCommits and useElementLifecycleOps. Parent keeps persistDomEditOperations as core and composes all sub-hooks — public interface unchanged. * refactor(studio): simplify useAppHotkeys with declarative command table * refactor(studio): simplify useAppHotkeys with declarative command table Replace 15 individual useRef callback refs with a single cbRef object. Extract keydown dispatch into pure dispatchModifierKey/dispatchPlainKey functions. Merge duplicate undo/redo logic into shared applyHistory. Extract cross-origin listener boilerplate into safeAddListener/safeRemoveListener. Hook body: 204 LOC (down from 445). Public API unchanged. * fix(studio): remove unused getDomEditTargetKey import * refactor(studio): decompose useDomEditSession into focused editing hooks Extract GSAP-aware geometry intercepts (move/resize/rotation) and animated property commit into useGsapAwareEditing, and selection wiring, GSAP cache management, preview sync, and selection handlers into useDomEditWiring. The parent remains a pure composition shell. * style(studio): fix formatting in 5 files * fix(studio): trim App.tsx to 598 lines (under 600 limit) --------- Co-authored-by: Miguel Ángel <miguel07alm@protonmail.com>
This commit is contained in:
co-authored by
Miguel Ángel
parent
6f677292ae
commit
7bff49ecf0
@@ -0,0 +1,167 @@
|
||||
import { useCallback } from "react";
|
||||
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
|
||||
import type { DomEditSelection } from "../components/editor/domEditingTypes";
|
||||
import { executeOptimistic } from "../utils/optimisticUpdate";
|
||||
import type { KeyframeCacheEntry } from "../player/store/playerStore";
|
||||
import { commitKeyframeAtTimeImpl } from "./gsapKeyframeCommit";
|
||||
import { readKeyframeSnapshot, writeKeyframeCache } from "./gsapKeyframeCacheHelpers";
|
||||
import type {
|
||||
CommitMutation,
|
||||
SafeGsapCommitMutation,
|
||||
TrackGsapSaveFailure,
|
||||
} from "./gsapScriptCommitTypes";
|
||||
|
||||
function executeOptimisticKeyframeCacheUpdate(options: {
|
||||
sourceFile: string;
|
||||
elementId: string | null | undefined;
|
||||
apply: (entry: KeyframeCacheEntry) => KeyframeCacheEntry;
|
||||
persist: () => Promise<void>;
|
||||
}): Promise<void> {
|
||||
return executeOptimistic<KeyframeCacheEntry | undefined>({
|
||||
apply: () => {
|
||||
const prev = readKeyframeSnapshot(options.sourceFile, options.elementId);
|
||||
if (prev) writeKeyframeCache(options.sourceFile, options.elementId, options.apply(prev));
|
||||
return prev;
|
||||
},
|
||||
persist: options.persist,
|
||||
rollback: (prev) => {
|
||||
writeKeyframeCache(options.sourceFile, options.elementId, prev);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
interface GsapKeyframeOpsParams {
|
||||
activeCompPath: string | null;
|
||||
commitMutation: CommitMutation;
|
||||
commitMutationSafely: SafeGsapCommitMutation;
|
||||
trackGsapSaveFailure: TrackGsapSaveFailure;
|
||||
}
|
||||
|
||||
export function useGsapKeyframeOps({
|
||||
activeCompPath,
|
||||
commitMutation,
|
||||
commitMutationSafely,
|
||||
trackGsapSaveFailure,
|
||||
}: GsapKeyframeOpsParams) {
|
||||
const addKeyframe = useCallback(
|
||||
(
|
||||
selection: DomEditSelection,
|
||||
animationId: string,
|
||||
percentage: number,
|
||||
property: string,
|
||||
value: number | string,
|
||||
) => {
|
||||
const sourceFile = selection.sourceFile || activeCompPath || "index.html";
|
||||
const mutation = {
|
||||
type: "add-keyframe",
|
||||
animationId,
|
||||
percentage,
|
||||
properties: { [property]: value },
|
||||
};
|
||||
void executeOptimisticKeyframeCacheUpdate({
|
||||
sourceFile,
|
||||
elementId: selection.id,
|
||||
apply: (prev) => ({
|
||||
...prev,
|
||||
keyframes: [...prev.keyframes, { percentage, properties: { [property]: value } }].sort(
|
||||
(a, b) => a.percentage - b.percentage,
|
||||
),
|
||||
}),
|
||||
persist: () =>
|
||||
commitMutation(selection, mutation, {
|
||||
label: `Add keyframe at ${percentage}%`,
|
||||
softReload: true,
|
||||
}),
|
||||
}).catch((error) => {
|
||||
trackGsapSaveFailure(error, selection, mutation, `Add keyframe at ${percentage}%`);
|
||||
});
|
||||
},
|
||||
[activeCompPath, commitMutation, trackGsapSaveFailure],
|
||||
);
|
||||
|
||||
const addKeyframeBatch = useCallback(
|
||||
(
|
||||
selection: DomEditSelection,
|
||||
animationId: string,
|
||||
percentage: number,
|
||||
properties: Record<string, number | string>,
|
||||
) => {
|
||||
return commitMutation(
|
||||
selection,
|
||||
{ type: "add-keyframe", animationId, percentage, properties },
|
||||
{ label: `Add keyframe at ${percentage}%`, softReload: true },
|
||||
);
|
||||
},
|
||||
[commitMutation],
|
||||
);
|
||||
|
||||
const removeKeyframe = useCallback(
|
||||
(selection: DomEditSelection, animationId: string, percentage: number) => {
|
||||
const sourceFile = selection.sourceFile || activeCompPath || "index.html";
|
||||
const mutation = { type: "remove-keyframe", animationId, percentage };
|
||||
void executeOptimisticKeyframeCacheUpdate({
|
||||
sourceFile,
|
||||
elementId: selection.id,
|
||||
apply: (prev) => ({
|
||||
...prev,
|
||||
keyframes: prev.keyframes.filter(
|
||||
(kf) => Math.abs((kf.tweenPercentage ?? kf.percentage) - percentage) > 0.2,
|
||||
),
|
||||
}),
|
||||
persist: () =>
|
||||
commitMutation(selection, mutation, {
|
||||
label: `Remove keyframe at ${percentage}%`,
|
||||
softReload: true,
|
||||
}),
|
||||
}).catch((error) => {
|
||||
trackGsapSaveFailure(error, selection, mutation, `Remove keyframe at ${percentage}%`);
|
||||
});
|
||||
},
|
||||
[activeCompPath, commitMutation, trackGsapSaveFailure],
|
||||
);
|
||||
|
||||
const convertToKeyframes = useCallback(
|
||||
(
|
||||
selection: DomEditSelection,
|
||||
animationId: string,
|
||||
resolvedFromValues?: Record<string, number | string>,
|
||||
) => {
|
||||
return commitMutation(
|
||||
selection,
|
||||
{ type: "convert-to-keyframes", animationId, resolvedFromValues },
|
||||
{ label: "Convert to keyframes" },
|
||||
);
|
||||
},
|
||||
[commitMutation],
|
||||
);
|
||||
|
||||
const removeAllKeyframes = useCallback(
|
||||
(selection: DomEditSelection, animationId: string) => {
|
||||
commitMutationSafely(
|
||||
selection,
|
||||
{ type: "remove-all-keyframes", animationId },
|
||||
{ label: "Remove all keyframes", softReload: true },
|
||||
);
|
||||
},
|
||||
[commitMutationSafely],
|
||||
);
|
||||
|
||||
const commitKeyframeAtTime = useCallback(
|
||||
(
|
||||
selection: DomEditSelection,
|
||||
absoluteTime: number,
|
||||
animations: GsapAnimation[],
|
||||
properties: Record<string, number | string>,
|
||||
) => commitKeyframeAtTimeImpl(selection, absoluteTime, animations, properties, commitMutation),
|
||||
[commitMutation],
|
||||
);
|
||||
|
||||
return {
|
||||
addKeyframe,
|
||||
addKeyframeBatch,
|
||||
removeKeyframe,
|
||||
convertToKeyframes,
|
||||
removeAllKeyframes,
|
||||
commitKeyframeAtTime,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user