Files
hyperframes/packages/studio/src/hooks/useDomGeometryCommit.ts
T
Miguel Ángel 5606b31020 fix(studio): moving one word moves only that word, not every word sharing its animation (#4705)
* fix(studio): move only the dragged word, not every word sharing its tween

A drag on one element whose position tween also targets its siblings (a stagger on a
shared class) now persists that element's own offset instead of rewriting the shared
tween. The motion-path overlay leaves such a tween read-only, and every write of one
drag records as one undo step.

* fix(studio): keep the comment share flat in the word-move fix

* fix(studio): save a shared-tween word's move as left/top on that word

A CSS translate offset on an element a GSAP tween still drives gets folded into GSAP's
transform, so render, preview and a second drag disagreed. left/top is never parsed by
GSAP, adds to any offset the word already has, and is refused when it would not shift
the box exactly. The resize anchor move takes the same channel, and tweens that miss the
element or are shared with siblings no longer steer a drag that has its own tween.

* refactor(studio): drop the untested own-tween selector override in the drag

* fix(studio): keep a Layers-picked word's move and make a resize one undo step

A word picked in the Layers panel is lifted to position:relative for display only; the
move now reads the authored position, saves position:relative, and survives deselect.
An anchored resize saves its move after the size, under the same undo key, and drops it
when the size save fails. A percent left or top gets its own refusal message.

* fix(studio): give the host canvas hook the per-word left/top move

The host geometry hook now stages a shared-tween word's move with the same left/top
offset as the editor, saved through the host's patch path, so a Desktop drag of one
word moves only that word.

* fix(studio): keep host word moves saving after one failed save

The host canvas hook reset its save queue per save, as the host style hook does, so one
conflict no longer pauses every later word move. A save error the patch path already
showed is no longer covered by a generic failure toast.
2026-09-29 03:58:28 +00:00

189 lines
7.0 KiB
TypeScript

import { useCallback, useMemo, useRef, useState } from "react";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
import type { DomEditSelection } from "../components/editor/domEditing";
import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
import { isPreviewBooted } from "../player/store/playerStore";
import type { DomEditCommitOutcome } from "./domEditCommitRunner";
import type { UseDomStyleCommitOptions } from "./useDomStyleCommit";
import { useGsapAnimationFetchFallback } from "./useGsapAnimationFetchFallback";
import { useGsapAwareEditing } from "./useGsapAwareEditing";
import { useGsapInteractionFailureTelemetry } from "./useGsapInteractionFailureTelemetry";
import { useGsapScriptCommits } from "./useGsapScriptCommits";
import { useGsapCacheVersion } from "./useGsapTweenCache";
import { createDomEditSaveQueue } from "../utils/domEditSaveQueue";
import { useDomEditPersist } from "./useDomEditPersist";
import { useDomEditPositionPatchCommit } from "./useDomEditPositionPatchCommit";
import { useMountEffect } from "./useMountEffect";
import { stageElementOffset } from "./elementOffsetStager";
/**
* Studio's `Player` must show the project, with `beginTimelineSession(projectId)` run before it
* mounts; drain `waitForPendingSaves` before switching projects.
*/
export interface UseDomGeometryCommitOptions extends UseDomStyleCommitOptions {
/** Called when a save cannot patch the preview in place; defaults to reloading the iframe. */
reloadPreview?: () => void;
}
export interface DomGeometryCommits {
commitPathOffset: (
selection: DomEditSelection,
next: { x: number; y: number },
modifiers?: { altKey?: boolean },
) => Promise<DomEditCommitOutcome>;
commitGroupPathOffset: (updates: DomEditGroupPathOffsetCommit[]) => Promise<DomEditCommitOutcome>;
commitBoxSize: (
selection: DomEditSelection,
next: { width: number; height: number },
offset?: { x: number; y: number },
restore?: () => void,
) => Promise<DomEditCommitOutcome>;
commitRotation: (
selection: DomEditSelection,
next: { angle: number },
) => Promise<DomEditCommitOutcome>;
waitForPendingSaves: () => Promise<void>;
}
const noop = () => {};
const NO_SELECTED_ANIMATIONS: GsapAnimation[] = [];
// ponytail: unreachable, the GSAP writer always exists so a resize never takes the DOM route.
const noDomBoxSizeRoute = () => Promise.reject(new Error("Resize has no DOM route here"));
/**
* Saves canvas moves, resizes and rotations through Studio's own GSAP-aware commits, for a host
* without the editor. A failed save rejects, so DomEditOverlay undoes the live gesture.
*/
export function useDomGeometryCommit({
projectId,
iframeRef,
writeProjectFile,
recordEdit,
activeCompPath = null,
showToast = noop,
reloadPreview,
}: UseDomGeometryCommitOptions): DomGeometryCommits {
const projectIdRef = useRef(projectId);
projectIdRef.current = projectId;
const pending = useRef(new Set<Promise<void>>()).current;
const editHistory = useMemo(() => ({ recordEdit }), [recordEdit]);
const reload = useCallback(
() => (reloadPreview ? reloadPreview() : iframeRef.current?.contentWindow?.location.reload()),
[reloadPreview, iframeRef],
);
const { bump: bumpGsapCache } = useGsapCacheVersion();
const gsap = useGsapScriptCommits({
projectIdRef,
activeCompPath,
previewIframeRef: iframeRef,
editHistory,
reloadPreview: reload,
onCacheInvalidate: bumpGsapCache,
showToast,
writeProjectFile,
});
const [queue] = useState(createDomEditSaveQueue);
useMountEffect(() => () => queue.destroy());
const persistDomEditOperations = useDomEditPersist({
activeCompPath,
previewIframeRef: iframeRef,
showToast,
queueDomEditSave: queue.enqueue,
writeProjectFile,
editHistory,
projectIdRef,
reloadPreview: noop,
});
const commitPositionPatchToHtml = useDomEditPositionPatchCommit({
activeCompPath,
persistDomEditOperations,
showToast,
});
// No paused-save banner in a host: each save is a retry, as in useDomStyleCommit.
const commitWithFreshQueue = useCallback<typeof commitPositionPatchToHtml>(
(...args) => {
queue.reset();
return commitPositionPatchToHtml(...args);
},
[commitPositionPatchToHtml, queue],
);
const stageElementPositionOffset = useCallback(
(selection: DomEditSelection, next: { x: number; y: number }, coalesceKey?: string) =>
stageElementOffset(
{ commitPositionPatchToHtml: commitWithFreshQueue, showToast },
selection,
next,
coalesceKey,
),
[commitWithFreshQueue, showToast],
);
const makeFetchFallback = useGsapAnimationFetchFallback(projectId);
const trackGsapInteractionFailure = useGsapInteractionFailureTelemetry(activeCompPath, showToast);
const {
handleGsapAwarePathOffsetCommit,
handleGsapAwareGroupPathOffsetCommit,
handleGsapAwareBoxSizeCommit,
handleGsapAwareRotationCommit,
} = useGsapAwareEditing({
// The host owns selection, so every gesture reads its element's animations from the server.
domEditSelection: null,
selectedGsapAnimations: NO_SELECTED_ANIMATIONS,
gsapCommitMutation: gsap.commitMutation,
previewIframeRef: iframeRef,
showToast,
bumpGsapCache,
makeFetchFallback,
trackGsapInteractionFailure,
stageElementPositionOffset,
handleDomBoxSizeCommit: noDomBoxSizeRoute,
addGsapAnimation: gsap.addGsapAnimation,
convertToKeyframes: gsap.convertToKeyframes,
setArcPath: gsap.setArcPath,
updateArcSegment: gsap.updateArcSegment,
});
const saved = useCallback(
async (commit: () => Promise<void>, restore = noop): Promise<DomEditCommitOutcome> => {
const refusal = !projectIdRef.current
? "No project is open"
: !isPreviewBooted(projectIdRef.current)
? "The preview for this project has not loaded yet"
: null;
if (refusal) {
restore();
showToast(refusal, "error");
throw new Error(refusal);
}
const run = commit();
pending.add(run);
try {
await run;
} finally {
pending.delete(run);
}
return { ok: true };
},
[pending, showToast],
);
return useMemo(
() => ({
commitPathOffset: (selection, next, modifiers) =>
saved(() => handleGsapAwarePathOffsetCommit(selection, next, modifiers)),
commitGroupPathOffset: (updates) =>
saved(() => handleGsapAwareGroupPathOffsetCommit(updates)),
commitBoxSize: (selection, next, offset, restore) =>
saved(() => handleGsapAwareBoxSizeCommit(selection, next, offset, restore), restore),
commitRotation: (selection, next) =>
saved(() => handleGsapAwareRotationCommit(selection, next)),
waitForPendingSaves: () => Promise.allSettled([...pending]).then(noop),
}),
[
saved,
pending,
handleGsapAwarePathOffsetCommit,
handleGsapAwareGroupPathOffsetCommit,
handleGsapAwareBoxSizeCommit,
handleGsapAwareRotationCommit,
],
);
}