Files
hyperframes/packages/studio/src/hooks/gsapShared.ts
T
Miguel ÁngelandMiguel Á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

158 lines
6.0 KiB
TypeScript

/**
* Shared GSAP primitives used across multiple hook files.
* Centralises duplicated interfaces, constants, and small utilities
* to reduce drift risk.
*/
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import {
absoluteToPercentage,
resolveTweenStart,
resolveTweenDuration,
} from "../utils/globalTimeCompiler";
// ── Types ─────────────────────────────────────────────────────────────────────
/** Canonical interface for the iframe-hosted GSAP runtime. */
export interface IframeGsap {
getProperty: (el: Element, prop: string) => number;
set?: (target: string, vars: Record<string, number | string>) => void;
}
// ── Constants ─────────────────────────────────────────────────────────────────
export const PROPERTY_DEFAULTS: Record<string, number> = {
opacity: 1,
x: 0,
y: 0,
scale: 1,
scaleX: 1,
scaleY: 1,
rotation: 0,
width: 100,
height: 100,
};
// ── Selector resolution ───────────────────────────────────────────────────────
/**
* Get a CSS selector string from a DomEditSelection.
* Returns `#id` if the selection has an id, otherwise the raw selector,
* or null if neither exists.
*/
export function selectorFromSelection(selection: DomEditSelection): string | null {
if (selection.id) return `#${selection.id}`;
if (selection.selector) return selection.selector;
return null;
}
// ── Percentage computation ────────────────────────────────────────────────────
/**
* Compute the current playback percentage within an element's animation range.
* Uses the animation's resolved timing if available, otherwise falls back to
* the element's data-start / data-duration attributes.
*/
export function computeElementPercentage(
currentTime: number,
selection: DomEditSelection,
animation?: GsapAnimation | null,
): number {
if (animation) {
const start = resolveTweenStart(animation);
const duration = resolveTweenDuration(animation);
if (start !== null) {
return absoluteToPercentage(currentTime, start, duration);
}
}
const elStart = Number.parseFloat(selection.dataAttributes?.start ?? "0") || 0;
const elDuration = Number.parseFloat(selection.dataAttributes?.duration ?? "1") || 1;
return elDuration > 0
? Math.max(0, Math.min(100, Math.round(((currentTime - elStart) / elDuration) * 1000) / 10))
: 0;
}
// ── Iframe accessors ──────────────────────────────────────────────────────────
/** Safely retrieve the GSAP runtime from the preview iframe. */
export function getIframeGsap(iframe: HTMLIFrameElement | null): IframeGsap | null {
if (!iframe?.contentWindow) return null;
try {
const gsap = (iframe.contentWindow as unknown as { gsap?: IframeGsap }).gsap;
return gsap?.getProperty ? gsap : null;
} catch {
return null;
}
}
/** Safely query an element inside the preview iframe's document. */
export function queryIframeElement(
iframe: HTMLIFrameElement | null,
selector: string,
): Element | null {
try {
return iframe?.contentDocument?.querySelector(selector) ?? null;
} catch {
return null;
}
}
/** Safely access an iframe's contentDocument, returning null on cross-origin errors. */
export function getIframeDocument(iframe: HTMLIFrameElement | null): Document | null {
if (!iframe) return null;
try {
return iframe.contentDocument;
} catch {
return null;
}
}
// ── Keyframe parsing ──────────────────────────────────────────────────────────
export interface ParsedPercentageKeyframes {
keyframes: Array<{ percentage: number; properties: Record<string, number | string> }>;
easeEach?: string;
}
/**
* Parse a GSAP percentage-keyframe object (`{ "0%": { x: 10 }, "100%": { x: 200 } }`)
* into a sorted array of `{ percentage, properties }` entries.
* Returns `null` when the object contains no valid keyframe entries.
*/
export function parsePercentageKeyframes(
kfObj: Record<string, unknown>,
): ParsedPercentageKeyframes | null {
const keyframes: ParsedPercentageKeyframes["keyframes"] = [];
let easeEach: string | undefined;
for (const [key, val] of Object.entries(kfObj)) {
if (key === "easeEach") {
if (typeof val === "string") easeEach = val;
continue;
}
const pctMatch = key.match(/^(\d+(?:\.\d+)?)%$/);
if (!pctMatch || !val || typeof val !== "object") continue;
const percentage = parseFloat(pctMatch[1]);
const properties: Record<string, number | string> = {};
for (const [pk, pv] of Object.entries(val as Record<string, unknown>)) {
if (pk === "ease") continue;
if (typeof pv === "number") properties[pk] = Math.round(pv * 1000) / 1000;
else if (typeof pv === "string") properties[pk] = pv;
}
if (Object.keys(properties).length > 0) {
keyframes.push({ percentage, properties });
}
}
if (keyframes.length === 0) return null;
keyframes.sort((a, b) => a.percentage - b.percentage);
return { keyframes, easeEach };
}
// ── Time conversion ───────────────────────────────────────────────────────────
/** Convert a tween-relative percentage to an absolute time. */
export function toAbsoluteTime(tweenPos: number, tweenDur: number, percentage: number): number {
return tweenPos + (percentage / 100) * tweenDur;
}