Files
heygen-com__hyperframes/packages/studio/src/hooks/gsapRuntimeKeyframes.ts
Miguel Ángel 7bff49ecf0 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>
2026-06-13 18:25:11 -04:00

173 lines
5.2 KiB
TypeScript

/**
* Read GSAP keyframe data from the live runtime in the preview iframe.
* Used to discover dynamic keyframes that the AST parser can't resolve
* (loops, variables, computed selectors).
*/
import { parsePercentageKeyframes } from "./gsapShared";
import { roundTo3 } from "../utils/rounding";
interface RuntimeTween {
targets?: () => Element[];
vars?: Record<string, unknown>;
duration?: () => number;
startTime?: () => number;
}
interface RuntimeTimeline {
getChildren?: (deep: boolean) => RuntimeTween[];
duration?: () => number;
}
export function readRuntimeKeyframes(
iframe: HTMLIFrameElement | null,
selector: string,
compositionId?: string,
): {
keyframes: Array<{ percentage: number; properties: Record<string, number | string> }>;
easeEach?: string;
} | null {
if (!iframe?.contentWindow) return null;
let timelines: Record<string, RuntimeTimeline | undefined> | undefined;
try {
timelines = (
iframe.contentWindow as unknown as { __timelines?: Record<string, RuntimeTimeline> }
).__timelines;
} catch {
return null;
}
if (!timelines) return null;
const tlId = compositionId || Object.keys(timelines)[0];
if (!tlId) return null;
const timeline = timelines[tlId];
if (!timeline?.getChildren) return null;
let doc: Document | null = null;
try {
doc = iframe.contentDocument;
} catch {
return null;
}
if (!doc) return null;
const targetEl = doc.querySelector(selector);
if (!targetEl) return null;
for (const tween of timeline.getChildren(true)) {
if (!tween.targets || !tween.vars) continue;
let matches = false;
for (const t of tween.targets()) {
if (t === targetEl || (targetEl.id && t.id === targetEl.id)) {
matches = true;
break;
}
}
if (!matches) continue;
const vars = tween.vars;
if (!vars.keyframes || typeof vars.keyframes !== "object") continue;
const parsed = parsePercentageKeyframes(vars.keyframes as Record<string, unknown>);
if (parsed) return parsed;
}
return null;
}
// fallow-ignore-next-line complexity
export function scanAllRuntimeKeyframes(iframe: HTMLIFrameElement | null): Map<
string,
{
keyframes: Array<{ percentage: number; properties: Record<string, number | string> }>;
easeEach?: string;
}
> {
const result = new Map<
string,
{
keyframes: Array<{ percentage: number; properties: Record<string, number | string> }>;
easeEach?: string;
}
>();
if (!iframe?.contentWindow) return result;
let timelines: Record<string, RuntimeTimeline | undefined> | undefined;
try {
timelines = (
iframe.contentWindow as unknown as { __timelines?: Record<string, RuntimeTimeline> }
).__timelines;
} catch {
return result;
}
if (!timelines) return result;
for (const timeline of Object.values(timelines)) {
if (!timeline?.getChildren) continue;
const tlDuration = typeof timeline.duration === "function" ? timeline.duration() : 0;
for (const tween of timeline.getChildren(true)) {
if (!tween.targets || !tween.vars) continue;
const vars = tween.vars;
if (vars.keyframes && typeof vars.keyframes === "object") {
const parsed = parsePercentageKeyframes(vars.keyframes as Record<string, unknown>);
if (parsed) {
for (const target of tween.targets()) {
const id = (target as HTMLElement).id;
if (id && !result.has(id)) {
result.set(id, parsed);
}
}
continue;
}
}
// Flat tweens: synthesize start + end keyframe entries
if (!tlDuration || tlDuration <= 0) continue;
const tweenStart = typeof tween.startTime === "function" ? tween.startTime() : undefined;
if (typeof tweenStart !== "number" || !Number.isFinite(tweenStart)) continue;
const tweenDur = typeof tween.duration === "function" ? tween.duration() : 0;
const startPct = Math.round((tweenStart / tlDuration) * 1000) / 10;
const endPct =
tweenDur > 0 ? Math.round(((tweenStart + tweenDur) / tlDuration) * 1000) / 10 : startPct;
const properties: Record<string, number | string> = {};
const skip = new Set([
"ease",
"duration",
"delay",
"stagger",
"motionPath",
"overwrite",
"immediateRender",
"onComplete",
"onUpdate",
"onStart",
]);
for (const [k, v] of Object.entries(vars)) {
if (skip.has(k)) continue;
if (typeof v === "number") properties[k] = roundTo3(v);
else if (typeof v === "string") properties[k] = v;
}
if (Object.keys(properties).length === 0) continue;
for (const target of tween.targets()) {
const id = (target as HTMLElement).id;
if (!id) continue;
const existing = result.get(id);
const entries = existing ?? { keyframes: [] };
entries.keyframes.push({ percentage: startPct, properties });
if (endPct !== startPct) {
entries.keyframes.push({ percentage: endPct, properties });
}
if (!existing) result.set(id, entries);
}
}
}
for (const entry of result.values()) {
entry.keyframes.sort((a, b) => a.percentage - b.percentage);
}
return result;
}