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
@@ -0,0 +1,255 @@
/**
* Wiring layer for DOM edit sessions: click-to-source navigation,
* DOM selection to timeline sync, GSAP cache invalidation on refresh,
* GSAP cache population, animation resolution for the selected element,
* and preview sync side-effects.
*
* Extracted from useDomEditSession to isolate orchestration wiring from
* the GSAP-aware geometry intercept logic.
*/
import { useCallback, useEffect, useRef } from "react";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { STUDIO_GSAP_PANEL_ENABLED } from "../components/editor/manualEditingAvailability";
import { usePlayerStore } from "../player";
import { useDomEditPreviewSync } from "./useDomEditPreviewSync";
import { useGsapAnimationsForElement, usePopulateKeyframeCacheForFile } from "./useGsapTweenCache";
import { useGsapAnimationFetchFallback } from "./useGsapAnimationFetchFallback";
import { useGsapInteractionFailureTelemetry } from "./useGsapInteractionFailureTelemetry";
import { useGsapSelectionHandlers } from "./useGsapSelectionHandlers";
import type { PatchTarget } from "../utils/sourcePatcher";
import type { SidebarTab } from "../components/sidebar/LeftSidebar";
export interface UseDomEditWiringParams {
projectId: string | null;
activeCompPath: string | null;
domEditSelection: DomEditSelection | null;
domEditSelectionRef: React.MutableRefObject<DomEditSelection | null>;
previewIframeRef: React.RefObject<HTMLIFrameElement | null>;
previewIframe: HTMLIFrameElement | null;
captionEditMode: boolean;
refreshKey: number;
gsapCacheVersion: number;
bumpGsapCache: () => void;
showToast: (message: string, tone?: "error" | "info") => void;
refreshPreviewDocumentVersion: () => void;
syncPreviewHistoryHotkey: (iframe: HTMLIFrameElement | null) => void;
applyStudioManualEditsToPreviewRef: React.MutableRefObject<
(iframe: HTMLIFrameElement) => Promise<void>
>;
applyDomSelection: (
selection: DomEditSelection | null,
options?: { revealPanel?: boolean; preserveGroup?: boolean },
) => void;
buildDomSelectionFromTarget: (element: HTMLElement) => Promise<DomEditSelection | null>;
openSourceForSelection?: (sourceFile: string, target: PatchTarget) => void;
selectSidebarTab?: (tab: SidebarTab) => void;
getSidebarTab?: () => SidebarTab;
// GSAP script commit ops (from useGsapScriptCommits)
updateGsapProperty: (
sel: DomEditSelection,
animId: string,
prop: string,
value: number | string,
) => void;
updateGsapMeta: (
sel: DomEditSelection,
animId: string,
updates: { duration?: number; ease?: string; position?: number },
) => void;
deleteGsapAnimation: (sel: DomEditSelection, animId: string) => void;
deleteAllForSelector: (sel: DomEditSelection, targetSelector: string) => void;
addGsapAnimation: (
sel: DomEditSelection,
method: "to" | "from" | "set" | "fromTo",
time: number,
) => Promise<void>;
addGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
removeGsapProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
updateGsapFromProperty: (
sel: DomEditSelection,
animId: string,
prop: string,
value: number | string,
) => void;
addGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
removeGsapFromProperty: (sel: DomEditSelection, animId: string, prop: string) => void;
addKeyframe: (
sel: DomEditSelection,
animId: string,
percentage: number,
property: string,
value: number | string,
) => void;
addKeyframeBatch: (
sel: DomEditSelection,
animId: string,
percentage: number,
properties: Record<string, number | string>,
) => Promise<void>;
removeKeyframe: (sel: DomEditSelection, animId: string, percentage: number) => void;
convertToKeyframes: (
sel: DomEditSelection,
animId: string,
resolvedFromValues?: Record<string, number | string>,
) => Promise<void>;
removeAllKeyframes: (sel: DomEditSelection, animId: string) => void;
handleDomManualEditsReset: (sel: DomEditSelection) => void;
}
// fallow-ignore-next-line complexity
export function useDomEditWiring({
projectId,
activeCompPath,
domEditSelection,
domEditSelectionRef,
previewIframeRef,
previewIframe,
captionEditMode,
refreshKey,
gsapCacheVersion,
bumpGsapCache,
showToast,
refreshPreviewDocumentVersion,
syncPreviewHistoryHotkey,
applyStudioManualEditsToPreviewRef,
applyDomSelection,
buildDomSelectionFromTarget,
openSourceForSelection,
selectSidebarTab,
getSidebarTab,
updateGsapProperty,
updateGsapMeta,
deleteGsapAnimation,
deleteAllForSelector,
addGsapAnimation,
addGsapProperty,
removeGsapProperty,
updateGsapFromProperty,
addGsapFromProperty,
removeGsapFromProperty,
addKeyframe,
addKeyframeBatch,
removeKeyframe,
convertToKeyframes,
removeAllKeyframes,
handleDomManualEditsReset,
}: UseDomEditWiringParams) {
// ── Click-to-source navigation ──
const onClickToSource = useCallback(
(selection: DomEditSelection) => {
if (!openSourceForSelection || !selectSidebarTab) return;
if (!selection.sourceFile) return;
selectSidebarTab("code");
openSourceForSelection(selection.sourceFile, {
id: selection.id,
selector: selection.selector,
selectorIndex: selection.selectorIndex,
});
},
[openSourceForSelection, selectSidebarTab],
);
// ── DOM selection -> timeline element sync ──
useEffect(() => {
if (!domEditSelection?.id) return;
const { selectedElementId, elements, setSelectedElementId } = usePlayerStore.getState();
const matchKey = elements.find(
(el) => el.domId === domEditSelection.id || el.id === domEditSelection.id,
);
const key = matchKey ? (matchKey.key ?? matchKey.id) : null;
if (key && key !== selectedElementId) setSelectedElementId(key);
}, [domEditSelection?.id]);
// ── GSAP cache sync ──
// Bump GSAP cache when refreshKey changes (code-tab edits trigger iframe
// reload via refreshKey but don't go through commitMutation, so the cache
// would otherwise retain stale keyframe entries).
const prevRefreshKeyRef = useRef(refreshKey);
// eslint-disable-next-line no-restricted-syntax
useEffect(() => {
if (refreshKey !== prevRefreshKeyRef.current) {
prevRefreshKeyRef.current = refreshKey;
bumpGsapCache();
}
}, [refreshKey, bumpGsapCache]);
const gsapSourceFile = domEditSelection?.sourceFile || activeCompPath || "index.html";
usePopulateKeyframeCacheForFile(
STUDIO_GSAP_PANEL_ENABLED ? (projectId ?? null) : null,
gsapSourceFile,
gsapCacheVersion,
previewIframeRef,
);
const {
animations: selectedGsapAnimations,
multipleTimelines: gsapMultipleTimelines,
unsupportedTimelinePattern: gsapUnsupportedTimelinePattern,
} = useGsapAnimationsForElement(
STUDIO_GSAP_PANEL_ENABLED ? (projectId ?? null) : null,
gsapSourceFile,
domEditSelection
? { id: domEditSelection.id ?? null, selector: domEditSelection.selector ?? null }
: null,
gsapCacheVersion,
);
// ── Telemetry & fallback ──
const trackGsapInteractionFailure = useGsapInteractionFailureTelemetry(activeCompPath, showToast);
const makeFetchFallback = useGsapAnimationFetchFallback(projectId, gsapSourceFile);
// ── GSAP selection handlers ──
const gsapSelectionHandlers = useGsapSelectionHandlers({
domEditSelection,
updateGsapProperty,
updateGsapMeta,
deleteGsapAnimation,
deleteAllForSelector,
addGsapAnimation,
addGsapProperty,
removeGsapProperty,
updateGsapFromProperty,
addGsapFromProperty,
removeGsapFromProperty,
addKeyframe,
addKeyframeBatch,
removeKeyframe,
convertToKeyframes,
removeAllKeyframes,
handleDomManualEditsReset,
selectedGsapAnimations,
});
// ── Preview sync side-effects ──
useDomEditPreviewSync({
previewIframe,
activeCompPath,
captionEditMode,
domEditSelectionRef,
domEditSelection,
applyDomSelection,
buildDomSelectionFromTarget,
refreshPreviewDocumentVersion,
syncPreviewHistoryHotkey,
applyStudioManualEditsToPreviewRef,
openSourceForSelection,
getSidebarTab,
});
return {
onClickToSource,
selectedGsapAnimations,
gsapMultipleTimelines,
gsapUnsupportedTimelinePattern,
trackGsapInteractionFailure,
makeFetchFallback,
...gsapSelectionHandlers,
};
}