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:
Miguel Ángel
2026-06-13 18:25:11 -04:00
committed by GitHub
co-authored by Miguel Ángel
parent 6f677292ae
commit 7bff49ecf0
77 changed files with 3165 additions and 3572 deletions
+18 -52
View File
@@ -20,37 +20,20 @@ import {
} from "./gsapDragCommit";
import { resolveTweenStart, resolveTweenDuration } from "../utils/globalTimeCompiler";
import type { GsapDragCommitCallbacks } from "./gsapDragCommit";
import { getIframeGsap, queryIframeElement, selectorFromSelection } from "./gsapShared";
import { roundTo3 } from "../utils/rounding";
// ── Runtime reads ──────────────────────────────────────────────────────────
interface IframeGsap {
getProperty: (el: Element, prop: string) => number;
}
// fallow-ignore-next-line complexity
function readGsapPositionFromIframe(
iframe: HTMLIFrameElement | null,
elementSelector: string,
): { x: number; y: number } | null {
if (!iframe?.contentWindow) return null;
const gsap = getIframeGsap(iframe);
if (!gsap) return null;
let gsap: IframeGsap | undefined;
try {
gsap = (iframe.contentWindow as unknown as { gsap?: IframeGsap }).gsap;
} catch {
return null;
}
if (!gsap?.getProperty) return null;
let doc: Document | null = null;
try {
doc = iframe.contentDocument;
} catch {
return null;
}
if (!doc) return null;
const element = doc.querySelector(elementSelector);
const element = queryIframeElement(iframe, elementSelector);
if (!element) return null;
const x = Number(gsap.getProperty(element, "x")) || 0;
@@ -99,12 +82,6 @@ function findGsapPositionAnimation(
// ── Selector resolution ────────────────────────────────────────────────────
function selectorForSelection(selection: DomEditSelection): string | null {
if (selection.id) return `#${selection.id}`;
if (selection.selector) return selection.selector;
return null;
}
// ── Property-group tween resolution ───────────────────────────────────────
/**
@@ -193,7 +170,7 @@ export async function tryGsapDragIntercept(
commitMutation: GsapDragCommitCallbacks["commitMutation"],
fetchFallbackAnimations?: () => Promise<GsapAnimation[]>,
): Promise<boolean> {
const selector = selectorForSelection(selection);
const selector = selectorFromSelection(selection);
if (!selector) return false;
// Resolve the position-group tween, splitting legacy mixed tweens if needed.
@@ -284,15 +261,15 @@ export async function tryGsapResizeIntercept(
const elDuration = Number.parseFloat(selection.dataAttributes?.duration ?? "5") || 5;
const ct = usePlayerStore.getState().currentTime;
const pct = elDuration > 0 ? Math.round(((ct - elStart) / elDuration) * 1000) / 10 : 0;
const sel = selectorForSelection(selection);
const sel = selectorFromSelection(selection);
if (!sel) return false;
await commitMutation(
selection,
{
type: "add-with-keyframes",
targetSelector: sel,
position: Math.round(elStart * 1000) / 1000,
duration: Math.round(elDuration * 1000) / 1000,
position: roundTo3(elStart),
duration: roundTo3(elDuration),
keyframes: [
{
percentage: Math.max(0, Math.min(100, pct)),
@@ -310,7 +287,7 @@ export async function tryGsapResizeIntercept(
if (activeKeyframePct != null) setActiveKeyframePct(null);
const coalesceKey = `gsap:resize:${anim.id}`;
const selector = selectorForSelection(selection);
const selector = selectorFromSelection(selection);
const runtimeProps = selector ? readAllAnimatedProperties(iframe, selector, anim) : {};
let resizeProps: Record<string, number>;
@@ -320,7 +297,7 @@ export async function tryGsapResizeIntercept(
// saved by the draft system before it ran.
const origW = Number.parseFloat(el?.getAttribute("data-hf-studio-original-width") ?? "");
const cssW = Number.isFinite(origW) && origW > 0 ? origW : 200;
const newScale = Math.round((size.width / cssW) * 1000) / 1000;
const newScale = roundTo3(size.width / cssW);
resizeProps = { scale: newScale };
} else {
resizeProps = {
@@ -395,8 +372,8 @@ export async function tryGsapResizeIntercept(
type: "replace-with-keyframes",
animationId: anim.id,
targetSelector: anim.targetSelector,
position: Math.round(newStart * 1000) / 1000,
duration: Math.round(newDuration * 1000) / 1000,
position: roundTo3(newStart),
duration: roundTo3(newDuration),
keyframes: remapped,
},
{ label: `Resize (extended to ${ct.toFixed(2)}s)`, softReload: true, coalesceKey },
@@ -455,25 +432,14 @@ export async function tryGsapRotationIntercept(
}
if (!anim) return false;
const selector = selectorForSelection(selection);
const selector = selectorFromSelection(selection);
if (!selector) return false;
let gsapRotation = 0;
if (iframe?.contentWindow) {
try {
const gsap = (
iframe.contentWindow as unknown as {
gsap?: { getProperty: (el: Element, prop: string) => number };
}
).gsap;
const doc = iframe.contentDocument;
const el = doc?.querySelector(selector);
if (gsap?.getProperty && el) {
gsapRotation = Number(gsap.getProperty(el, "rotation")) || 0;
}
} catch {
/* cross-origin guard */
}
const gsap = getIframeGsap(iframe);
const rotEl = gsap ? queryIframeElement(iframe, selector) : null;
if (gsap && rotEl) {
gsapRotation = Number(gsap.getProperty(rotEl, "rotation")) || 0;
}
const pct = computeCurrentPercentage(selection, anim);