mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-09-10 22:20:14 +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
@@ -1,43 +1,22 @@
|
||||
import { useCallback, useRef } from "react";
|
||||
import { findUnsafeDomPatchValues } from "@hyperframes/core/studio-api/finite-mutation";
|
||||
import { usePlayerStore } from "../player";
|
||||
import { STUDIO_GSAP_DRAG_INTERCEPT_ENABLED } from "../components/editor/manualEditingAvailability";
|
||||
import { FONT_EXT } from "../utils/mediaTypes";
|
||||
import type { PatchOperation } from "../utils/sourcePatcher";
|
||||
import { trackStudioEvent } from "../utils/studioTelemetry";
|
||||
import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
|
||||
import { primaryFontFamilyValue } from "../utils/studioFontHelpers";
|
||||
import { createStudioSaveHttpError } from "../utils/studioSaveDiagnostics";
|
||||
import {
|
||||
buildDomEditPatchTarget,
|
||||
getDomEditTargetKey,
|
||||
readHfId,
|
||||
type DomEditSelection,
|
||||
} from "../components/editor/domEditing";
|
||||
import {
|
||||
applyStudioPathOffset,
|
||||
applyStudioBoxSize,
|
||||
applyStudioRotation,
|
||||
clearStudioPathOffset,
|
||||
clearStudioBoxSize,
|
||||
clearStudioRotation,
|
||||
} from "../components/editor/manualEdits";
|
||||
import {
|
||||
buildPathOffsetPatches,
|
||||
buildBoxSizePatches,
|
||||
buildRotationPatches,
|
||||
buildClearPathOffsetPatches,
|
||||
buildClearBoxSizePatches,
|
||||
buildClearRotationPatches,
|
||||
} from "../components/editor/manualEditsDom";
|
||||
import { buildDomEditPatchTarget, type DomEditSelection } from "../components/editor/domEditing";
|
||||
import { fontFamilyFromAssetPath, type ImportedFontAsset } from "../components/editor/fontAssets";
|
||||
import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
|
||||
import type { EditHistoryKind } from "../utils/editHistory";
|
||||
import { useDomEditPositionPatchCommit } from "./useDomEditPositionPatchCommit";
|
||||
import { useDomEditTextCommits } from "./useDomEditTextCommits";
|
||||
import { useDomGeometryCommits } from "./useDomGeometryCommits";
|
||||
import { useElementLifecycleOps } from "./useElementLifecycleOps";
|
||||
|
||||
// Re-export so existing consumers keep their import path
|
||||
export { GSAP_CSS_FALLBACK_BLOCKED_MESSAGE } from "./useDomGeometryCommits";
|
||||
|
||||
// ── Helpers ──
|
||||
type TimelineLike = { getChildren?: (nested: boolean) => Array<{ targets?: () => Element[] }> };
|
||||
|
||||
function formatUnsafeFieldList(fields: Array<{ path: string }>): string {
|
||||
return fields.map((field) => field.path).join(", ");
|
||||
@@ -60,40 +39,6 @@ function formatPatchRejectionMessage(body: { error?: string; fields?: string[] }
|
||||
return `Couldn't save edit: ${body.error}${suffix}`;
|
||||
}
|
||||
|
||||
export const GSAP_CSS_FALLBACK_BLOCKED_MESSAGE =
|
||||
"This element is GSAP-animated — dragging via CSS would corrupt keyframes";
|
||||
|
||||
// fallow-ignore-next-line complexity
|
||||
function isElementGsapTargeted(iframe: HTMLIFrameElement | null, element: HTMLElement): boolean {
|
||||
// When the GSAP drag intercept is disabled for debugging, treat every
|
||||
// element as un-targeted so commits take the plain CSS persist path.
|
||||
if (!STUDIO_GSAP_DRAG_INTERCEPT_ENABLED) return false;
|
||||
if (!iframe?.contentWindow) return false;
|
||||
let timelines: Record<string, TimelineLike> | undefined;
|
||||
try {
|
||||
timelines = (iframe.contentWindow as Window & { __timelines?: Record<string, TimelineLike> })
|
||||
.__timelines;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (!timelines) return false;
|
||||
const id = element.id;
|
||||
for (const tl of Object.values(timelines)) {
|
||||
if (!tl?.getChildren) continue;
|
||||
try {
|
||||
for (const child of tl.getChildren(true)) {
|
||||
if (!child.targets) continue;
|
||||
for (const t of child.targets()) {
|
||||
if (t === element || (id && t.id === id)) return true;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── Types ──
|
||||
|
||||
interface RecordEditInput {
|
||||
@@ -322,6 +267,8 @@ export function useDomEditCommits({
|
||||
resolveImportedFontAsset,
|
||||
});
|
||||
|
||||
// ── Position patch helper (shared by geometry + lifecycle hooks) ──
|
||||
|
||||
const commitPositionPatchToHtml = useDomEditPositionPatchCommit({
|
||||
activeCompPath,
|
||||
persistDomEditOperations,
|
||||
@@ -329,229 +276,33 @@ export function useDomEditCommits({
|
||||
showToast,
|
||||
});
|
||||
|
||||
// ── Position commits ──
|
||||
// ── Geometry commits (path offset, box size, rotation) ──
|
||||
|
||||
const handleDomPathOffsetCommit = useCallback(
|
||||
(selection: DomEditSelection, next: { x: number; y: number }) => {
|
||||
if (isElementGsapTargeted(previewIframeRef.current, selection.element)) {
|
||||
const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
|
||||
showToast(error.message, "error");
|
||||
return Promise.reject(error);
|
||||
}
|
||||
applyStudioPathOffset(selection.element, next);
|
||||
return commitPositionPatchToHtml(selection, buildPathOffsetPatches(selection.element), {
|
||||
label: "Move layer",
|
||||
coalesceKey: `path-offset:${getDomEditTargetKey(selection)}`,
|
||||
});
|
||||
},
|
||||
[commitPositionPatchToHtml, previewIframeRef, showToast],
|
||||
);
|
||||
const {
|
||||
handleDomPathOffsetCommit,
|
||||
handleDomGroupPathOffsetCommit,
|
||||
handleDomBoxSizeCommit,
|
||||
handleDomRotationCommit,
|
||||
handleDomManualEditsReset,
|
||||
} = useDomGeometryCommits({
|
||||
previewIframeRef,
|
||||
showToast,
|
||||
commitPositionPatchToHtml,
|
||||
});
|
||||
|
||||
const handleDomGroupPathOffsetCommit = useCallback(
|
||||
(updates: DomEditGroupPathOffsetCommit[]) => {
|
||||
if (updates.length === 0) return Promise.resolve();
|
||||
const blockedUpdate = updates.find(({ selection }) =>
|
||||
isElementGsapTargeted(previewIframeRef.current, selection.element),
|
||||
);
|
||||
if (blockedUpdate) {
|
||||
const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
|
||||
showToast(error.message, "error");
|
||||
return Promise.reject(error);
|
||||
}
|
||||
const coalesceKey = updates
|
||||
.map((u) => getDomEditTargetKey(u.selection))
|
||||
.sort()
|
||||
.join(":");
|
||||
const saves = updates.map(({ selection, next }) => {
|
||||
applyStudioPathOffset(selection.element, next);
|
||||
return commitPositionPatchToHtml(selection, buildPathOffsetPatches(selection.element), {
|
||||
label: `Move ${updates.length} layers`,
|
||||
coalesceKey: `group-path-offset:${coalesceKey}`,
|
||||
});
|
||||
});
|
||||
return Promise.all(saves).then(() => undefined);
|
||||
},
|
||||
[commitPositionPatchToHtml, previewIframeRef, showToast],
|
||||
);
|
||||
// ── Element lifecycle (delete, z-index reorder) ──
|
||||
|
||||
const handleDomBoxSizeCommit = useCallback(
|
||||
(selection: DomEditSelection, next: { width: number; height: number }) => {
|
||||
if (isElementGsapTargeted(previewIframeRef.current, selection.element)) {
|
||||
const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
|
||||
showToast(error.message, "error");
|
||||
return Promise.reject(error);
|
||||
}
|
||||
applyStudioBoxSize(selection.element, next);
|
||||
return commitPositionPatchToHtml(selection, buildBoxSizePatches(selection.element), {
|
||||
label: "Resize layer box",
|
||||
coalesceKey: `box-size:${getDomEditTargetKey(selection)}`,
|
||||
});
|
||||
},
|
||||
[commitPositionPatchToHtml, previewIframeRef, showToast],
|
||||
);
|
||||
|
||||
const handleDomRotationCommit = useCallback(
|
||||
(selection: DomEditSelection, next: { angle: number }) => {
|
||||
if (isElementGsapTargeted(previewIframeRef.current, selection.element)) {
|
||||
const error = new Error(GSAP_CSS_FALLBACK_BLOCKED_MESSAGE);
|
||||
showToast(error.message, "error");
|
||||
return Promise.reject(error);
|
||||
}
|
||||
applyStudioRotation(selection.element, next);
|
||||
return commitPositionPatchToHtml(selection, buildRotationPatches(selection.element), {
|
||||
label: "Rotate layer",
|
||||
coalesceKey: `rotation:${getDomEditTargetKey(selection)}`,
|
||||
});
|
||||
},
|
||||
[commitPositionPatchToHtml, previewIframeRef, showToast],
|
||||
);
|
||||
|
||||
const handleDomManualEditsReset = useCallback(
|
||||
(selection: DomEditSelection) => {
|
||||
const element = selection.element;
|
||||
const clearPatches = [
|
||||
...buildClearPathOffsetPatches(element),
|
||||
...buildClearBoxSizePatches(element),
|
||||
...buildClearRotationPatches(element),
|
||||
];
|
||||
clearStudioPathOffset(element);
|
||||
clearStudioBoxSize(element);
|
||||
clearStudioRotation(element);
|
||||
// skipRefresh:false triggers reloadPreview() which re-syncs selection on load
|
||||
void commitPositionPatchToHtml(selection, clearPatches, {
|
||||
label: "Reset layer edits",
|
||||
coalesceKey: `manual-reset:${getDomEditTargetKey(selection)}`,
|
||||
skipRefresh: false,
|
||||
}).catch(() => undefined);
|
||||
},
|
||||
[commitPositionPatchToHtml],
|
||||
);
|
||||
|
||||
// fallow-ignore-next-line complexity
|
||||
const handleDomEditElementDelete = useCallback(
|
||||
// fallow-ignore-next-line complexity
|
||||
async (selection: DomEditSelection) => {
|
||||
const pid = projectIdRef.current;
|
||||
if (!pid) return;
|
||||
const label = selection.label || selection.id || selection.selector || selection.tagName;
|
||||
|
||||
const targetPath = selection.sourceFile || activeCompPath || "index.html";
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/projects/${pid}/files/${encodeURIComponent(targetPath)}`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw await createStudioSaveHttpError(response, `Failed to read ${targetPath}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as { content?: string };
|
||||
const originalContent = data.content;
|
||||
if (typeof originalContent !== "string")
|
||||
throw new Error(`Missing file contents for ${targetPath}`);
|
||||
|
||||
const patchTarget = buildDomEditPatchTarget(selection);
|
||||
if (!patchTarget.id && !patchTarget.selector && !patchTarget.hfId) {
|
||||
throw new Error("Selected element has no patchable target");
|
||||
}
|
||||
|
||||
domEditSaveTimestampRef.current = Date.now();
|
||||
const removeResponse = await fetch(
|
||||
`/api/projects/${pid}/file-mutations/remove-element/${encodeURIComponent(targetPath)}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ target: patchTarget }),
|
||||
},
|
||||
);
|
||||
if (!removeResponse.ok) {
|
||||
throw await createStudioSaveHttpError(
|
||||
removeResponse,
|
||||
`Failed to delete element from ${targetPath}`,
|
||||
);
|
||||
}
|
||||
|
||||
const removeData = (await removeResponse.json()) as { changed?: boolean; content?: string };
|
||||
const patchedContent =
|
||||
typeof removeData.content === "string" ? removeData.content : originalContent;
|
||||
await saveProjectFilesWithHistory({
|
||||
projectId: pid,
|
||||
label: "Delete element",
|
||||
kind: "timeline",
|
||||
files: { [targetPath]: patchedContent },
|
||||
readFile: async () => originalContent,
|
||||
writeFile: writeProjectFile,
|
||||
recordEdit: editHistory.recordEdit,
|
||||
});
|
||||
|
||||
clearDomSelection();
|
||||
usePlayerStore.getState().setSelectedElementId(null);
|
||||
reloadPreview();
|
||||
showToast(`Deleted ${label}. Use Undo to restore it.`, "info");
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to delete element";
|
||||
showToast(message);
|
||||
}
|
||||
},
|
||||
[
|
||||
activeCompPath,
|
||||
clearDomSelection,
|
||||
domEditSaveTimestampRef,
|
||||
editHistory.recordEdit,
|
||||
projectIdRef,
|
||||
reloadPreview,
|
||||
showToast,
|
||||
writeProjectFile,
|
||||
],
|
||||
);
|
||||
|
||||
const handleDomZIndexReorderCommit = useCallback(
|
||||
(
|
||||
entries: Array<{
|
||||
element: HTMLElement;
|
||||
zIndex: number;
|
||||
id?: string;
|
||||
selector?: string;
|
||||
selectorIndex?: number;
|
||||
sourceFile: string;
|
||||
}>,
|
||||
) => {
|
||||
if (entries.length === 0) return;
|
||||
const coalesceKey = `z-reorder:${entries.map((e) => e.id ?? e.selector ?? e.element.getAttribute("data-hf-id") ?? "el").join(":")}`;
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i];
|
||||
entry.element.style.zIndex = String(entry.zIndex);
|
||||
const patches: Array<{ type: "inline-style"; property: string; value: string }> = [
|
||||
{ type: "inline-style", property: "z-index", value: String(entry.zIndex) },
|
||||
];
|
||||
try {
|
||||
const win = entry.element.ownerDocument?.defaultView;
|
||||
if (win && win.getComputedStyle(entry.element).position === "static") {
|
||||
entry.element.style.position = "relative";
|
||||
patches.push({ type: "inline-style", property: "position", value: "relative" });
|
||||
}
|
||||
} catch {
|
||||
/* cross-origin or detached — skip */
|
||||
}
|
||||
void commitPositionPatchToHtml(
|
||||
{
|
||||
element: entry.element,
|
||||
id: entry.id ?? null,
|
||||
hfId: readHfId(entry.element),
|
||||
selector: entry.selector,
|
||||
selectorIndex: entry.selectorIndex,
|
||||
sourceFile: entry.sourceFile,
|
||||
} as unknown as DomEditSelection,
|
||||
patches,
|
||||
{
|
||||
label: "Reorder layers",
|
||||
coalesceKey,
|
||||
skipRefresh: i < entries.length - 1,
|
||||
},
|
||||
).catch(() => undefined);
|
||||
}
|
||||
},
|
||||
[commitPositionPatchToHtml],
|
||||
);
|
||||
const { handleDomEditElementDelete, handleDomZIndexReorderCommit } = useElementLifecycleOps({
|
||||
activeCompPath,
|
||||
showToast,
|
||||
writeProjectFile,
|
||||
domEditSaveTimestampRef,
|
||||
editHistory,
|
||||
projectIdRef,
|
||||
reloadPreview,
|
||||
clearDomSelection,
|
||||
commitPositionPatchToHtml,
|
||||
});
|
||||
|
||||
return {
|
||||
resolveImportedFontAsset,
|
||||
|
||||
Reference in New Issue
Block a user