fix(studio): canvas selection, drag and resize correctness (#3146)

* fix(studio): size the selection box by the transform the element actually paints under

The box around a text layer inside the playground card stopped mid-word. The
layer is 260px wide and paints 313, because its parent carries `scale(1.2)`,
and the chrome read only the element's OWN transform. The top-left looked
right, since the corners are anchored to the real bounding rect, so only the
right and bottom edges fell short, by exactly 1/1.2.

The same read decides whether to draw the box rotated at all, so an element
whose parent is rotated got an upright box over a rotated one.

The transform is now accumulated from the element up to the composition root.
Only the linear part matters: each transform's origin contributes translation,
and translation is already discarded by matching the corners to the element's
bounding rect, so composing the matrices is enough and no per-ancestor origin
has to be unpicked. The walk stops inside the composition document, because the
canvas zoom lives on the iframe in Studio's own document and is applied
separately.

The fake DOMMatrix the geometry tests use gained the `multiply` it now needs.

* fix(studio): drag by the movement the element actually makes, not the one assumed

An element that had never been dragged skipped the movement measurement and took
the canvas zoom as the whole screen mapping. Nothing above the element was
considered, so any parent transform broke the drag: a card at rotationY 180 with
scale 1.2 maps a rightward drag to -1.2x the zoom, meaning the text walked LEFT
while the overlay followed the pointer, and the overlay only snapped onto the
text at drop, when it re-measured.

Measured on the live element in that card: one unit of drag offset moved it
-0.757 px on x and +0.757 on y, where the skipped path assumed +0.631 on both.

The measurement it skipped already handles this — it moves the element, watches
where it lands, and inverts that, which is right for rotation, mirroring, scale
and perspective alike. So the special case is gone and every drag measures. Same
element after: a 120x80 pointer drag moves it 120.3x80.2.

Rewrote the test that asserted the skipped path's identity matrix for an
unmovable element. It now asserts the honest outcome: an element with no
measurable movement is reported unmeasurable whether or not it carries a path
offset, and the caller's existing fallback covers it.

* fix(studio): shift-click adds the element under the pointer, not the last one hovered

Shift-click read the hover cache and used it without checking what it described.
That cache is filled asynchronously as the pointer moves, so passing over one
element on the way to another leaves it naming the element you left. The
shift-click then added THAT element, and because the same branch prevented the
default and set the suppression flags, the mousedown path that would have
resolved the point correctly never ran. Multi-select looked like it grabbed
things at random, or like it did nothing.

Reproduced on the canvas with a trace: hover #card, shift-click #dot-b, and the
group gained #card. Same gesture after: the guard rejects the cache, the
mousedown path resolves the point, and the group gains #dot-b.

The cache is still used when it is provably about the point clicked, including
when it names a clip ancestor of the element there, so the fast path survives for
the common case of clicking straight at something.

Adds `hf-select-debug` (localStorage, off by default) recording which selection
branch ran and what it decided, and pulls the flag/format shared with
`hf-reload-debug` into one place rather than copying it.

* fix(studio): keep every element a marquee caught, not just the first

The marquee built the group correctly and then threw it away. It announced only
the primary to the timeline, and the timeline is the source of truth for what is
selected: the sync back to the canvas saw one selected id against a group of
several, decided the canvas was stale, and replaced the group with that single
element a moment after the drop. Drag a box around four things, get one.

The whole set is announced now, and the primary goes in as its anchor rather
than as a new single selection, so the set it just joined survives. This is the
same reason the single-select path already anchors with preserveSet.

A test drives applyMarqueeSelection with two elements and asserts both reach the
timeline; it fails against the old single-id announce.

* fix(studio): stop a group selection from erasing itself on the timeline

Every canvas selection is mirrored onto the timeline, and the timeline syncs
back — whatever it holds replaces the canvas selection a moment later. The
mirror announced only the primary and anchored it with preserveSet, but
preserving a set that does not contain the id empties the set, and an empty set
syncs back as "nothing is selected". Adding a second element, or re-resolving a
group after moving it, could therefore drop the whole selection rather than keep
it.

One helper now owns the mirror: publish the members, then anchor. A single
selection keeps the previous contract deliberately, so a late async primary
still cannot collapse a live group and a fresh click still collapses a stale
one. The group re-resolve path also gains the ancestor id fallback the other
callers already had — without it a member with no direct timeline row resolved
to null and deselected everything.

Two tests: a second element joining a selection, and a marquee, both assert the
full set reaches the timeline. Both fail against the announce-the-primary-only
version.

* chore(studio): trace what moves a dragged group and when

A drag that jumps is a position that changed without the pointer asking for it,
and nothing on that path says anything today, so the frame it diverges can only
be guessed at. `hf-drag-debug` (localStorage, off by default) records the whole
gesture: the mapping and start position each member got, the pointer delta
against the delta actually applied on every eighth move, what each member was
told to commit, and where they all sit at the drop, once the commit resolves, and
120/400/900ms later.

That last group is the point of it. The source write, the preview reload and the
timeline resume all land within a few frames of the drop, and any of them can put
the elements back where they started before the new position arrives — a
snap-back shows up as a settle sample reverting to the gesture-start reading.
A gap between `pointer` and `applied` instead means snapping pulled the group off
the cursor, which is a different fault with a different fix.

* chore(studio): name the path that clears a selection after a group move

The drag trace showed the group landing exactly where it was dropped and staying
there — no snap-back at any settle sample, and the pointer and the applied delta
never more than 2px apart — but two milliseconds after the drop the selection was
cleared with seven members still in it.

The clear comes from the timeline sync deciding the timeline holds nothing, and
that branch said nothing. It says so now, along with whether it is about to act
on it. The mirror alongside it reports how many members it managed to publish and
whether the anchor was among them, because a member with no timeline row of its
own resolves to null and is dropped silently — publish none and the sync reads it
back as an empty selection.

* fix(studio): losing one member of a group no longer deselects all of it

After a move the preview re-syncs and the selection is re-resolved against the
new document. When the primary could not be found there, both re-resolve paths
cleared the entire selection — so a group of five, all still on screen, was
deselected because one of them failed to resolve. The trace showed the clear
landing 600ms after the drop with five members still held, and the timeline sync
running afterwards on an already-empty canvas, which ruled it out as the cause.

A live group now re-resolves as a group and keeps whoever survived, picking a new
primary from them; it only clears when nobody did. That is what
refreshDomEditGroupSelectionsFromPreview was written for — it existed and was
never called.

Both clears also say which one they are and how many members were held, so if
this is not the last of it the next trace names the path immediately.

* feat(studio): carry a multi-selection in the URL, and name the member that breaks away

A link to a bug hit with several elements selected only reproduced one of them,
so the report read as "works for me". The hash now carries the rest as selGroup
and reopens the whole selection; members whose element is gone are dropped rather
than failing the others. Verified end to end in a real browser: select three,
copy the hash, open it fresh, the same three come back.

The drag trace also gains a rigidity check. A group moves as one object, so every
member travels the same distance; one that does not IS the fault. Drift was being
computed but only printed on every eighth frame, which is exactly how a
single-frame divergence hides — it now prints on the frame it happens.

The frame handler moves to its own module on the way past. It had grown a snap
block and a trace block inside a function already juggling four gesture kinds,
and it was over both the complexity and file-size gates.

Not fixed: the jump itself. Two headful runs driving a real group drag showed the
members staying rigid to the pixel, at the drop and 900ms after, so I have not
reproduced it yet and will not guess at a fix.

* fix(studio): stop snapping from moving a selection you have not dragged yet

Your log caught it on the first frame of the drag: pointer "0,0", applied "4,-3",
and all four members jumped 12,-8 composition px before the pointer had moved at
all. An element resting within the 6px snap threshold of a guide is already
snappable, so the snap computed on frame one closes that gap immediately —
picking the selection up moves it.

Snapping now sits out until the gesture has travelled the same 4px a drag needs
to count as a drag rather than a click, on both the group and single-element
paths. Nothing below that distance moves anything, and a real drag snaps exactly
as before.

The test builds a box resting 4px from a guide and asserts the ungated call still
returns dx 4 — the very displacement from your log — while the gated one returns
0 for a pointer that has not moved.

* fix(studio): a dropped group stays selected

Your Jam confirmed the first-frame jump is gone — pointer "0,0" now reads
applied "0,0" — and caught what was left: two milliseconds after each drop, a
`[hf-select] clear` with the group still holding three, then four members.

Every pointerup trails a click. The group gesture ref is cleared before the
commit runs, so by the time that click arrives the box no longer looks busy and
it reaches the canvas as an ordinary click — landing in the gap between the
members, resolving to nothing, and clearing the selection the drag just moved.
The under-threshold path already ate that click; the committed path never did.

The flag is now set before the two paths diverge, so neither can forget it. The
test drives a real pointerup through the handlers and fails on the committed
path with the flag moved back down.

* feat(studio): marquee from anywhere on the canvas, including outside the frame

An element dragged past the edge sits out in the grey, and the rubber band
refused to start there — it only began when the press landed inside the
composition rect. The one gesture that could reach those elements could not be
begun near them, so the timeline was the only way to select something plainly
visible on screen.

The collecting half never had that limit: it compares rects in overlay space and
never clipped to the frame, so those elements have always been selectable once
the band could begin. Only the start gate had to go.

A press in the grey that never travels still commits an empty selection, which is
the deselect it used to be, so the old behaviour of clicking out there to clear
is unchanged.

* refactor(studio): keep the selection files under the size cap

The selection work above pushed four files past the 600-line gate. Same
split the branch made later, landed with the changes that caused it.

* fix(studio): preserve selector groups in share URLs

* fix(studio): close multi-selection review gaps

* fix(studio): stabilize selection store reads

* fix(studio): preserve canvas-only group anchors

* fix(studio): stop a group drag from jumping one element back

Dragging several elements at once and dropping them made one of them snap
back to where it started for a frame or two, then jump forward again.

Each member of the group is written separately, and every write patched the
live GSAP tween in place and then seeked the player. A seek re-renders the
WHOLE timeline, not the tween that changed, so the members still queued
behind that write got repainted from their un-patched tweens: back to their
pre-drag position, where they sat until their own write landed. Only members
whose tween actually renders at the playhead showed it, which is why a group
of three flashed one element and left the others still.

The group commit now defers the seek for every member but the last, so the
queued members keep the transform the gesture left on them and the whole
group repaints once, from the fully patched timeline.

* perf(studio): commit a group drag in one request

Dragging N elements cost N writes and 9 reads for a three-element group: each
member fetched the composition's parse to preflight, fetched it again to
resolve its tween, then wrote the file on its own round trip. Every one of
those writes re-read, re-parsed and re-serialized the whole composition.

Three changes, same behaviour:

- The parse endpoint shares an in-flight request per file, so callers asking
  for the same composition at the same moment get one request. Only
  overlapping calls share — the entry is dropped as soon as it settles, so a
  read after a write still gets a fresh parse.
- The group preflight runs its members together instead of one at a time. A
  preflight writes nothing, so there is nothing to order.
- Members' mutations are queued and sent as one batch write. Anything that
  re-reads the file flushes the queue first, so a member resolving a shared or
  stale tween never reads a composition missing writes it is about to build
  on. The batch carries each member's runtime patch, and only the last one
  re-renders.

A three-element group drag now issues 2 reads and 1 write, down from 9 and 3.

* fix(studio): harden batched drag commits

* fix(studio): carry deferred preview fallbacks

* chore(studio): name whoever puts the pre-resize size back

Resizing the card commits correctly — the source and a fresh load both read
273x181 — but 200ms after the drop, mid-commit, the element renders at 395x261
with the studio size vars still holding 273x181. Something writes the
pre-gesture size back inline while the reload is still in flight, and every
writer of that size was silent.

Both are traced now under the existing hf-resize-debug flag, each with the size
going in, the size being replaced, and a short stack. Restoring the pre-gesture
size is right on a cancel and wrong after a successful commit, and the function
doing it cannot tell the two apart from the inside — so the caller has to be
named before this can be fixed at the right end.

* fix(studio): hold a resized element's size while the timeline is rebuilt

Your log caught it across two resizes. The first commits 305x202 and the element
is 305x202 at the drop; 200ms later it renders 395x261, its stylesheet size,
while --hf-studio-width still reads 305. The second gesture then starts with
`actual` at 305 against a live box of 395, and its very first move — a pointer
delta of 0.1px — snaps the element back to 305. That snap is the jump.

The gap belongs to the soft reload: it reverts the old timeline before building
the new one, and GSAP hands back each tween's recorded starting width on the way
out. Nothing held the size in between, because the seek reapply that exists for
exactly this stands aside for elements GSAP animates.

Standing aside is right for the offset — those channels compose, and applying
both doubles the move — and wrong for size, where both channels write width and
height so the later write simply wins on the same committed number. It applies
now. Only an element mid-edit carries the vars, so nothing else is touched.

A test seeks an element whose size GSAP owns after the revert put the stylesheet
size back, and fails with the skip restored.

* refactor(studio): keep the resize files under the size cap

* docs(studio): fold the resize note into the size-reapply comment

* fix(studio): rotate the child outlines with the element they outline

Selecting a rotated element drew upright dashed boxes across its children:
the chrome co-rotated with the element and the child outlines did not, so a
text layer inside a rotated card got a square outline lying across the
rotated glyphs.

The chrome already measures an oriented box; the child outlines were still
measured axis-aligned. They now use the same oriented measurement and render
with the same rotation. An unrotated element measures identically to before,
since the oriented rect returns the plain bounding box at angle 0.
This commit is contained in:
Miguel Ángel
2026-08-09 16:58:34 -07:00
committed by GitHub
parent bea32b8aae
commit 17ac986bfe
48 changed files with 2370 additions and 367 deletions
@@ -0,0 +1,73 @@
import type { SelectElementOptions, TimelineElement } from "../player";
import { findMatchingTimelineElementId, findTimelineIdByAncestor } from "../utils/studioHelpers";
import type { DomEditSelection } from "../components/editor/domEditing";
import { logSelect } from "../utils/selectDebug";
interface TimelineMirrorDeps {
timelineElements: TimelineElement[];
getTimelineSelectionSet: () => ReadonlySet<string>;
setSelectedTimelineElementId: (id: string | null, options?: SelectElementOptions) => void;
setTimelineSelectionSet: (ids: Set<string>) => void;
}
/**
* Mirror a canvas selection onto the timeline: the whole set first, then the
* primary as its anchor.
*
* The timeline is the source of truth for what is selected and it syncs back —
* whatever it holds replaces the canvas selection a moment later. Announcing only
* the primary therefore drops every other member. Worse, anchoring with
* `preserveSet` on an id the set does not yet contain empties the set outright,
* and an empty set syncs back as "nothing is selected" — which is how adding a
* second element, or moving a group, could wipe the selection instead of keeping
* it. Publishing the members first is what makes the anchor a member, so
* preserving the set is meaningful rather than destructive.
*/
export function announceTimelineSelection(
deps: TimelineMirrorDeps,
group: DomEditSelection[],
primary: DomEditSelection | null,
): void {
const {
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
} = deps;
if (!primary) {
setTimelineSelectionSet(new Set());
setSelectedTimelineElementId(null);
return;
}
const timelineIdFor = (selection: DomEditSelection) =>
findMatchingTimelineElementId(selection, timelineElements) ??
findTimelineIdByAncestor(
selection.element,
timelineElements,
selection.sourceFile || "index.html",
);
const members = group.map(timelineIdFor).filter((id): id is string => Boolean(id));
const anchor = timelineIdFor(primary);
const publishedMembers = new Set(members);
if (anchor) publishedMembers.add(anchor);
const timelineAnchor = anchor ?? members[0] ?? null;
// A member with no timeline row of its own resolves to null and is dropped here,
// so a group can announce fewer ids than it has — or none, which reads back as an
// empty selection and takes the canvas selection with it.
logSelect("announce", {
group: group.length,
published: publishedMembers.size,
anchor,
anchorPublished: anchor != null && publishedMembers.has(anchor),
});
// A canvas target can be editable without owning a timeline row. Preserve that
// canvas-only selection when the timeline has nothing truthful to represent.
if (!timelineAnchor) return;
// A late async primary that already belongs to the live set must preserve the
// group. A fresh single click does not belong to it, so publish the singleton
// first; otherwise `preserveSet` clears the set and sync wipes the canvas.
if (group.length > 1 || !getTimelineSelectionSet().has(timelineAnchor)) {
setTimelineSelectionSet(publishedMembers);
}
setSelectedTimelineElementId(timelineAnchor, { preserveSet: true });
}
@@ -36,6 +36,7 @@ function runTwoMutationTransaction(
describe("runGestureTransaction", () => {
beforeEach(() => {
trackStudioEventMock.mockReset();
localStorage.clear();
});
it("settles synchronously before persist reaches its first await", async () => {
@@ -249,7 +250,7 @@ describe("runGestureTransaction", () => {
.spyOn(element, "getBoundingClientRect")
.mockReturnValueOnce(rect(10.04, 20.05, 100.05, 80.05))
.mockReturnValueOnce(rect(11.19, 17.89, 100.29, 78.99));
const error = vi.spyOn(console, "error").mockImplementation(() => undefined);
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
const now = vi.spyOn(performance, "now").mockReturnValueOnce(50).mockReturnValueOnce(58.44);
await runGestureTransaction({
@@ -261,13 +262,7 @@ describe("runGestureTransaction", () => {
});
expect(getRect).toHaveBeenCalledTimes(2);
expect(error).toHaveBeenCalledWith(
"[hf-commit] persist changed pixels",
expect.objectContaining({
label: "Resize layer",
delta: expect.objectContaining({ x: expect.any(Number) }),
}),
);
expect(log).not.toHaveBeenCalled();
expect(trackStudioEventMock).toHaveBeenCalledWith("commit_invariant_violation", {
label: "Resize layer",
delta_x: 1.2,
@@ -283,13 +278,13 @@ describe("runGestureTransaction", () => {
expect.objectContaining({ pixel_asserted: true }),
);
now.mockRestore();
error.mockRestore();
log.mockRestore();
});
it("skips the pixel assertion for live position tweens", async () => {
const element = document.createElement("div");
const getRect = vi.spyOn(element, "getBoundingClientRect");
const error = vi.spyOn(console, "error").mockImplementation(() => undefined);
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
await runGestureTransaction({
element,
@@ -301,11 +296,11 @@ describe("runGestureTransaction", () => {
});
expect(getRect).not.toHaveBeenCalled();
expect(error).not.toHaveBeenCalledWith("[hf-commit] persist changed pixels", expect.anything());
expect(log).not.toHaveBeenCalled();
expect(trackStudioEventMock).not.toHaveBeenCalledWith(
"commit_invariant_violation",
expect.anything(),
);
error.mockRestore();
log.mockRestore();
});
});
@@ -4,6 +4,7 @@ import type {
CommitMutationOptions,
} from "./gsapScriptCommitTypes";
import { trackStudioEvent } from "../utils/studioTelemetry";
import { makeStudioDebugLogger } from "../utils/studioDebug";
type PixelRect = Pick<DOMRect, "x" | "y" | "width" | "height">;
@@ -108,14 +109,7 @@ async function dispatchBufferedCommits(calls: BufferedCommit[]): Promise<number>
return reloadsRequested(calls);
}
/**
* Dev-only [hf-commit] lifecycle trace. The production observability lives in
* the trackStudioEvent commit_* events (always on); these console lines are a
* developer aid and stay out of end users' consoles.
*/
function traceCommit(stage: string, data: Record<string, unknown>): void {
if (import.meta.env.DEV) console.info(`[hf-commit] ${stage}`, data);
}
const logCommit = makeStudioDebugLogger("commit");
/**
* Owns the visual + persistence + history lifecycle for one gesture release.
@@ -127,9 +121,9 @@ export function runGestureTransaction(tx: GestureTransaction): Promise<void> {
let mutationCount = 0;
let reloadCount = 0;
const bufferedCommits: BufferedCommit[] = [];
traceCommit("start", { label: tx.label, coalesceKey });
logCommit("start", { label: tx.label, coalesceKey });
tx.settle();
traceCommit("settled", { label: tx.label, coalesceKey });
logCommit("settled", { label: tx.label, coalesceKey });
const before = !tx.skipPixelAssert ? readPixelRect(tx.element) : null;
const commit: TxCommit = (commitMutation) => {
@@ -152,19 +146,12 @@ export function runGestureTransaction(tx: GestureTransaction): Promise<void> {
.then(async () => {
reloadCount = await dispatchBufferedCommits(bufferedCommits);
const durationMs = Math.round(performance.now() - startedAt);
traceCommit("persisted", { label: tx.label, coalesceKey });
logCommit("persisted", { label: tx.label, coalesceKey });
if (before) {
const after = readPixelRect(tx.element);
const delta = pixelDelta(before, after);
if (exceedsPixelTolerance(delta)) {
if (import.meta.env.DEV) {
console.error("[hf-commit] persist changed pixels", {
label: tx.label,
before,
after,
delta,
});
}
logCommit("persist-changed-pixels", { label: tx.label, before, after, delta });
trackStudioEvent("commit_invariant_violation", {
label: tx.label,
delta_x: roundToOneDecimal(delta.x),
@@ -193,7 +180,7 @@ export function runGestureTransaction(tx: GestureTransaction): Promise<void> {
error_name: error instanceof Error ? error.name : "unknown",
restore_ran: true,
});
traceCommit("restore", { label: tx.label, coalesceKey });
logCommit("restore", { label: tx.label, coalesceKey });
throw error;
});
}
@@ -523,3 +523,46 @@ describe("patchRuntimeTweenInPlace — composition isolation", () => {
expect(otherTween.invalidate).not.toHaveBeenCalled();
});
});
describe("patchRuntimeTweenInPlace — deferSeek", () => {
/**
* A group drag commits one member at a time. Each in-place patch used to seek,
* and a seek re-renders the WHOLE timeline — so every member still queued behind
* the current one got repainted from its un-patched tween, back to where it sat
* before the drag, and stayed there until its own patch landed. That is the jump.
*/
it("does not seek while a group commit is still writing its other members", () => {
const a = { id: "a" };
const rendered = { a: 0, b: 0 };
const tweenA = makeTween({ vars: { x: 0 }, targetIds: ["a"], duration: 0 }, a);
const tweenB = makeTween({ vars: { x: 0 }, targetIds: ["b"], duration: 0 }, a);
const { iframe, seek } = fakeIframe(a, [tweenA, tweenB], {
onSeek: () => {
rendered.a = tweenA.vars.x as number;
rendered.b = tweenB.vars.x as number;
},
});
const first = patchRuntimeTweenInPlace(
iframe,
"#a",
{ kind: "set", props: { x: 500 } },
undefined,
true,
);
expect(first).toBe(true);
expect(tweenA.vars.x).toBe(500);
// No repaint yet: "b" keeps the transform the gesture left on it instead of
// being rendered from its own tween, which still holds the pre-drag value.
expect(seek).not.toHaveBeenCalled();
expect(rendered).toEqual({ a: 0, b: 0 });
tweenB.vars.x = 600;
const last = patchRuntimeTweenInPlace(iframe, "#a", { kind: "set", props: { x: 500 } });
expect(last).toBe(true);
expect(seek).toHaveBeenCalledTimes(1);
expect(rendered).toEqual({ a: 500, b: 600 });
});
});
+11 -1
View File
@@ -277,12 +277,16 @@ function applyChange(tween: RuntimeTween, change: RuntimeTweenChange): boolean {
/**
* Edit one tween in `window.__timelines` in place + re-seek to the current playhead.
* Returns `true` on a confident patch, `false` otherwise (caller soft-reloads).
*
* `deferSeek` skips the re-render, for a caller patching several tweens in a row
* that will render once after the last one.
*/
export function patchRuntimeTweenInPlace(
iframe: HTMLIFrameElement | null,
selector: string,
change: RuntimeTweenChange,
compositionId?: string,
deferSeek = false,
): boolean {
if (!iframe) return false;
// A base `gsap.set` has no timeline tween to resolve — apply the value straight
@@ -312,7 +316,13 @@ export function patchRuntimeTweenInPlace(
if (change.kind !== "keyframe-rebuild") {
tween.invalidate?.();
}
seekToCurrent(iframe, timeline);
// A seek re-renders the WHOLE timeline, not just the tween we patched. Under a
// multi-element commit that is a visible jump: the members still queued behind
// this one get repainted from their un-patched tweens, back to where they were
// before the gesture, and stay there until their own patch lands. Deferring
// leaves them showing the gesture's own transform, and the caller's last patch
// seeks once for the whole group.
if (!deferSeek) seekToCurrent(iframe, timeline);
return true;
} catch {
return false;
@@ -22,6 +22,18 @@ export interface CommitMutationOptions {
coalesceMs?: number;
softReload?: boolean;
skipReload?: boolean;
/**
* Write the source but leave the preview alone; the caller renders once when it
* is done. For a multi-write action like a group drag, rendering after each
* write shows a source where the members not yet written still hold their old
* values, so they snap back until their own write lands. This also defers the
* in-place runtime patch's seek, which re-renders the whole timeline and repaints
* the queued members the same way. Unlike `skipReload` this changes nothing about
* error handling — a failed write still throws.
*/
deferPreviewSync?: boolean;
/** Shares an in-place patch miss with the final render of one multi-write action. */
previewFallbackLatch?: { pending: boolean };
beforeReload?: () => void;
/**
* Serialize this commit against others sharing the same key. Used to chain
@@ -39,6 +51,14 @@ export interface CommitMutationOptions {
* existing soft/full reload path. Structural edits omit this and reload as before.
*/
instantPatch?: { selector: string; change: RuntimeTweenChange };
/**
* The same fast path for a batched commit: one patch per element the batch
* wrote, applied in order. All of them must land for the reload to be skipped
* — one that can't be applied leaves the preview half-patched, so the whole
* batch falls back to the reload. Only the last patch re-renders (see
* `deferSeek`), so a ten-element batch repaints once.
*/
instantPatches?: Array<{ selector: string; change: RuntimeTweenChange }>;
}
export interface CommitMutationCall {
@@ -0,0 +1,108 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fetchParsedAnimations } from "./keyframeCacheAstLoad";
/**
* Parsing a composition is a whole-file read + parse on the server, and a
* multi-element action asks for the same file once per element. Callers that
* overlap in time share one request; a caller that comes after the last one
* settled does not, so a parse issued after a write is never served a
* pre-write answer.
*/
describe("fetchParsedAnimations — in-flight sharing", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
function stubFetch(): { calls: () => number; settle: () => void } {
let calls = 0;
const pending: Array<() => void> = [];
vi.stubGlobal("fetch", () => {
calls++;
return new Promise((resolve) => {
pending.push(() =>
resolve({
ok: true,
json: () => Promise.resolve({ animations: [{ id: "a", targetSelector: "#a" }] }),
} as Response),
);
});
});
return {
calls: () => calls,
settle: () => {
for (const release of pending.splice(0, pending.length)) release();
},
};
}
it("serves overlapping reads of one file from a single request", async () => {
const fetchStub = stubFetch();
const pending = [
fetchParsedAnimations("p", "index.html"),
fetchParsedAnimations("p", "index.html"),
fetchParsedAnimations("p", "index.html"),
];
fetchStub.settle();
const results = await Promise.all(pending);
expect(fetchStub.calls()).toBe(1);
expect(results.map((parsed) => parsed?.animations.length)).toEqual([1, 1, 1]);
});
it("does not share across files", async () => {
const fetchStub = stubFetch();
const pending = [
fetchParsedAnimations("p", "index.html"),
fetchParsedAnimations("p", "other.html"),
];
fetchStub.settle();
await Promise.all(pending);
expect(fetchStub.calls()).toBe(2);
});
it("re-requests once the previous read has settled", async () => {
const fetchStub = stubFetch();
const first = fetchParsedAnimations("p", "index.html");
fetchStub.settle();
await first;
const second = fetchParsedAnimations("p", "index.html");
fetchStub.settle();
await second;
expect(fetchStub.calls()).toBe(2);
});
it("supersedes an in-flight pre-write parse with a fresh post-write read", async () => {
const releases: Array<(response: Response) => void> = [];
const fetch = vi.fn(
() =>
new Promise<Response>((resolve) => {
releases.push(resolve);
}),
);
vi.stubGlobal("fetch", fetch);
const response = (id: string) =>
({
ok: true,
json: () => Promise.resolve({ animations: [{ id, targetSelector: `#${id}` }] }),
}) as Response;
const stale = fetchParsedAnimations("p", "index.html");
const fresh = fetchParsedAnimations("p", "index.html", { fresh: true });
expect(fetch).toHaveBeenCalledTimes(2);
releases[0]?.(response("stale"));
await stale;
const overlappingFreshRead = fetchParsedAnimations("p", "index.html");
expect(fetch).toHaveBeenCalledTimes(2);
releases[1]?.(response("fresh"));
const [freshResult, sharedResult] = await Promise.all([fresh, overlappingFreshRead]);
expect(freshResult?.animations[0]?.id).toBe("fresh");
expect(sharedResult?.animations[0]?.id).toBe("fresh");
});
});
@@ -42,7 +42,35 @@ function hasAnimations(value: unknown): value is ParsedGsapAnimations {
);
}
export async function fetchParsedAnimations(
/**
* Requests for the same file that overlap in time, keyed `projectId|sourceFile`.
*
* Every parse re-reads and re-parses the whole composition server-side, and a
* multi-element action asks for the same file once per element. Sharing the
* in-flight promise makes that one request. Only OVERLAPPING calls share: the
* entry is dropped the moment it settles, so a call made after a write still
* gets a fresh parse.
*/
const inFlightParses = new Map<string, Promise<ParsedGsapAnimations | null>>();
export function fetchParsedAnimations(
projectId: string,
sourceFile: string,
options: { fresh?: boolean } = {},
): Promise<ParsedGsapAnimations | null> {
const key = `${projectId}|${sourceFile}`;
if (options.fresh) inFlightParses.delete(key);
const inFlight = inFlightParses.get(key);
if (inFlight) return inFlight;
const request = requestParsedAnimations(projectId, sourceFile).finally(() => {
// A superseded pre-write request must not evict the fresh post-write one.
if (inFlightParses.get(key) === request) inFlightParses.delete(key);
});
inFlightParses.set(key, request);
return request;
}
async function requestParsedAnimations(
projectId: string,
sourceFile: string,
): Promise<ParsedGsapAnimations | null> {
@@ -8,13 +8,17 @@ import { findElementForSelection, type DomEditSelection } from "../components/ed
import { reapplyPositionEditsAfterSeek } from "../components/editor/manualEdits";
import type { SidebarTab } from "../components/sidebar/LeftSidebar";
import type { PatchTarget } from "../utils/sourcePatcher";
import { logSelect } from "../utils/selectDebug";
interface UseDomEditPreviewSyncParams {
previewIframe: HTMLIFrameElement | null;
activeCompPath: string | null;
captionEditMode: boolean;
domEditSelectionRef: React.MutableRefObject<DomEditSelection | null>;
domEditGroupSelectionsRef: React.MutableRefObject<DomEditSelection[]>;
domEditSelection: DomEditSelection | null;
/** Re-resolves a whole multi-selection against the current preview document. */
refreshDomEditGroupSelectionsFromPreview: (selections: DomEditSelection[]) => Promise<void>;
applyDomSelection: (
selection: DomEditSelection | null,
options?: { revealPanel?: boolean; preserveGroup?: boolean },
@@ -35,8 +39,10 @@ export function useDomEditPreviewSync({
activeCompPath,
captionEditMode,
domEditSelectionRef,
domEditGroupSelectionsRef,
domEditSelection,
applyDomSelection,
refreshDomEditGroupSelectionsFromPreview,
buildDomSelectionFromTarget,
refreshPreviewDocumentVersion,
syncPreviewHistoryHotkey,
@@ -72,6 +78,21 @@ export function useDomEditPreviewSync({
// Clear so overlay geometry isn't computed on a stale, detached node.
// (Drag-release-in-gray-zone is handled separately by
// suppressNextBoxClickRef; the dragged element still resolves here.)
//
// One lost member is not the whole selection though. A multi-select that
// loses its primary here used to be wiped entirely, so moving a group and
// having any one of its elements fail to re-resolve deselected all of
// them. Re-resolve the group instead and keep whoever survived; it only
// clears when nobody did.
const group = domEditGroupSelectionsRef.current;
logSelect("preview-sync-lost", {
target: currentSelection.selector ?? currentSelection.id ?? null,
group: group.length,
});
if (group.length > 1) {
await refreshDomEditGroupSelectionsFromPreview(group);
return;
}
applyDomSelection(null, { revealPanel: false });
return;
}
@@ -103,8 +124,10 @@ export function useDomEditPreviewSync({
applyDomSelection,
buildDomSelectionFromTarget,
captionEditMode,
domEditGroupSelectionsRef,
domEditSelectionRef,
previewIframe,
refreshDomEditGroupSelectionsFromPreview,
refreshPreviewDocumentVersion,
syncPreviewHistoryHotkey,
applyStudioManualEditsToPreviewRef,
@@ -60,6 +60,46 @@ const capturedOnReorderShadow: { fn: ((targets: string[]) => void) | undefined }
const domEditSelectionRef: { current: DomEditSelection | null } = { current: null };
const gsapCommitMutation = Object.assign(vi.fn(), { batch: vi.fn() });
function createSessionParams(
overrides: Partial<UseDomEditSessionParams> = {},
): UseDomEditSessionParams {
return {
projectId: "proj-1",
activeCompPath: "index.html",
compIdToSrc: new Map(),
captionEditMode: false,
compositionLoading: false,
previewIframeRef: { current: null },
timelineElements: [],
getTimelineSelectionSet: () => new Set(),
setSelectedTimelineElementId: vi.fn(),
setTimelineSelectionSet: vi.fn(),
setRightCollapsed: vi.fn(),
setRightPanelTab: vi.fn(),
showToast: vi.fn(),
refreshPreviewDocumentVersion: vi.fn(),
queueDomEditSave: async <T,>(save: () => Promise<T>) => save(),
readProjectFile: async () => "",
writeProjectFile: async () => {},
updateEditingFileContent: vi.fn(),
domEditSaveTimestampRef: { current: 0 },
editHistory: { recordEdit: async () => {} },
fileTree: [],
importedFontAssetsRef: { current: [] },
projectDir: null,
projectIdRef: { current: "proj-1" },
previewIframe: null,
refreshKey: 0,
previewDocumentVersion: 0,
rightPanelTab: "design",
applyStudioManualEditsToPreviewRef: { current: async () => {} },
syncPreviewHistoryHotkey: vi.fn(),
reloadPreview: vi.fn(),
setRefreshKey: vi.fn(),
...overrides,
};
}
vi.mock("../utils/sdkResolverShadow", () => ({
runResolverShadow: vi.fn(),
recordResolverParity: (...args: unknown[]) => recordResolverParity(...args),
@@ -220,43 +260,16 @@ describe("onReorderShadow source filter", () => {
const sdkSession = {} as unknown as Composition;
function Probe() {
const params: UseDomEditSessionParams = {
projectId: "proj-1",
activeCompPath: "index.html",
isMasterView: false,
compIdToSrc: new Map(),
captionEditMode: false,
compositionLoading: false,
previewIframeRef: { current: null },
timelineElements: [],
setSelectedTimelineElementId: vi.fn(),
setRightCollapsed: vi.fn(),
setRightPanelTab: vi.fn(),
showToast: vi.fn(),
refreshPreviewDocumentVersion: vi.fn(),
const params = createSessionParams({
queueDomEditSave: vi.fn(async <T,>(save: () => Promise<T>) => save()) as <T>(
save: () => Promise<T>,
) => Promise<T>,
readProjectFile,
writeProjectFile: vi.fn(async () => {}),
updateEditingFileContent: vi.fn(),
domEditSaveTimestampRef: { current: 0 },
editHistory: { recordEdit: vi.fn(async () => {}) },
fileTree: [],
importedFontAssetsRef: { current: [] },
projectDir: null,
projectIdRef: { current: "proj-1" },
previewIframe: null,
refreshKey: 0,
previewDocumentVersion: 0,
rightPanelTab: "design",
applyStudioManualEditsToPreviewRef: { current: async () => {} },
syncPreviewHistoryHotkey: vi.fn(),
reloadPreview: vi.fn(),
setRefreshKey: vi.fn(),
sdkSession,
forceReloadSdkSession: vi.fn(),
};
});
useDomEditSession(params);
return null;
}
@@ -318,39 +331,7 @@ describe("bulk segment ease commits", () => {
| undefined;
function Probe() {
const params: UseDomEditSessionParams = {
projectId: "proj-1",
activeCompPath: "index.html",
isMasterView: false,
compIdToSrc: new Map(),
captionEditMode: false,
compositionLoading: false,
previewIframeRef: { current: null },
timelineElements: [],
setSelectedTimelineElementId: vi.fn(),
setRightCollapsed: vi.fn(),
setRightPanelTab: vi.fn(),
showToast: vi.fn(),
refreshPreviewDocumentVersion: vi.fn(),
queueDomEditSave: async <T,>(save: () => Promise<T>) => save(),
readProjectFile: async () => "",
writeProjectFile: async () => {},
updateEditingFileContent: vi.fn(),
domEditSaveTimestampRef: { current: 0 },
editHistory: { recordEdit: async () => {} },
fileTree: [],
importedFontAssetsRef: { current: [] },
projectDir: null,
projectIdRef: { current: "proj-1" },
previewIframe: null,
refreshKey: 0,
previewDocumentVersion: 0,
rightPanelTab: "design",
applyStudioManualEditsToPreviewRef: { current: async () => {} },
syncPreviewHistoryHotkey: vi.fn(),
reloadPreview: vi.fn(),
setRefreshKey: vi.fn(),
};
const params = createSessionParams();
updateSegmentEase = useDomEditSession(params).handleUpdateSegmentEase;
return null;
}
+10 -2
View File
@@ -31,13 +31,14 @@ interface RecordEditInput {
export interface UseDomEditSessionParams {
projectId: string | null;
activeCompPath: string | null;
isMasterView: boolean;
compIdToSrc: Map<string, string>;
captionEditMode: boolean;
compositionLoading: boolean;
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
timelineElements: TimelineElement[];
getTimelineSelectionSet: () => ReadonlySet<string>;
setSelectedTimelineElementId: (id: string | null, options?: SelectElementOptions) => void;
setTimelineSelectionSet: (ids: Set<string>) => void;
setRightCollapsed: (collapsed: boolean) => void;
setRightPanelTab: (tab: RightPanelTab) => void;
showToast: (message: string, tone?: "error" | "info") => void;
@@ -73,13 +74,14 @@ export interface UseDomEditSessionParams {
export function useDomEditSession({
projectId,
activeCompPath,
isMasterView,
compIdToSrc,
captionEditMode,
compositionLoading,
previewIframeRef,
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
setRightCollapsed,
setRightPanelTab,
showToast,
@@ -109,6 +111,7 @@ export function useDomEditSession({
publishSdkSession,
forceReloadSdkSession,
}: UseDomEditSessionParams) {
const isMasterView = !activeCompPath || activeCompPath === "index.html";
void _setRefreshKey;
const {
domEditSelection,
@@ -127,6 +130,7 @@ export function useDomEditSession({
buildDomSelectionForTimelineElement,
handleTimelineElementSelect,
refreshDomEditSelectionFromPreview,
refreshDomEditGroupSelectionsFromPreview,
applyMarqueeSelection,
} = useDomSelection({
projectId,
@@ -136,7 +140,9 @@ export function useDomEditSession({
captionEditMode,
previewIframeRef,
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
setRightCollapsed,
setRightPanelTab,
previewIframe,
@@ -382,6 +388,8 @@ export function useDomEditSession({
activeCompPath,
domEditSelection,
domEditSelectionRef,
domEditGroupSelectionsRef,
refreshDomEditGroupSelectionsFromPreview,
previewIframeRef,
previewIframe,
captionEditMode,
@@ -23,6 +23,8 @@ export interface UseDomEditWiringParams {
activeCompPath: string | null;
domEditSelection: DomEditSelection | null;
domEditSelectionRef: React.MutableRefObject<DomEditSelection | null>;
domEditGroupSelectionsRef: React.MutableRefObject<DomEditSelection[]>;
refreshDomEditGroupSelectionsFromPreview: (selections: DomEditSelection[]) => Promise<void>;
previewIframeRef: React.RefObject<HTMLIFrameElement | null>;
previewIframe: HTMLIFrameElement | null;
captionEditMode: boolean;
@@ -115,6 +117,8 @@ export function useDomEditWiring({
activeCompPath,
domEditSelection,
domEditSelectionRef,
domEditGroupSelectionsRef,
refreshDomEditGroupSelectionsFromPreview,
previewIframeRef,
previewIframe,
captionEditMode,
@@ -254,8 +258,10 @@ export function useDomEditWiring({
activeCompPath,
captionEditMode,
domEditSelectionRef,
domEditGroupSelectionsRef,
domEditSelection,
applyDomSelection,
refreshDomEditGroupSelectionsFromPreview,
buildDomSelectionFromTarget,
refreshPreviewDocumentVersion,
syncPreviewHistoryHotkey,
@@ -5,6 +5,7 @@ import { createRoot } from "react-dom/client";
import { describe, expect, it, vi } from "vitest";
import { installReactActEnvironment, makeSelection } from "./domSelectionTestHarness";
import { useDomSelection } from "./useDomSelection";
import type { TimelineElement } from "../player";
installReactActEnvironment();
@@ -14,11 +15,24 @@ interface HarnessProps {
refreshKey: number;
}
function renderHarness(initialProps: HarnessProps): {
interface TimelineSpies {
setSelectedTimelineElementId: ReturnType<typeof vi.fn>;
setTimelineSelectionSet: ReturnType<typeof vi.fn>;
}
function renderHarness(
initialProps: HarnessProps,
options: { timelineElements?: TimelineElement[] } = {},
): {
current: () => ReturnType<typeof useDomSelection>;
rerender: (props: HarnessProps) => void;
cleanup: () => void;
timeline: TimelineSpies;
} {
const timeline: TimelineSpies = {
setSelectedTimelineElementId: vi.fn(),
setTimelineSelectionSet: vi.fn(),
};
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
@@ -32,8 +46,10 @@ function renderHarness(initialProps: HarnessProps): {
compIdToSrc: new Map(),
captionEditMode: false,
previewIframeRef: { current: null },
timelineElements: [],
setSelectedTimelineElementId: vi.fn(),
timelineElements: options.timelineElements ?? [],
getTimelineSelectionSet: () => new Set(),
setSelectedTimelineElementId: timeline.setSelectedTimelineElementId,
setTimelineSelectionSet: timeline.setTimelineSelectionSet,
setRightCollapsed: vi.fn(),
setRightPanelTab: vi.fn(),
previewIframe: null,
@@ -61,6 +77,7 @@ function renderHarness(initialProps: HarnessProps): {
act(() => root.unmount());
host.remove();
},
timeline,
};
}
@@ -77,6 +94,119 @@ function setupSelectedHarness() {
return { selection, harness };
}
function timelineElement(domId: string): TimelineElement {
return {
id: domId,
key: domId,
domId,
tag: "div",
start: 0,
duration: 1,
track: 0,
sourceFile: "index.html",
} as TimelineElement;
}
/**
* A marquee builds the group correctly and then used to lose it: it announced only
* the primary to the timeline, the timeline is the source of truth for what is
* selected, and the sync back to the canvas replaced the group with that one
* element a moment after the drop. The whole set has to be announced, with the
* primary as its anchor rather than as a new single selection.
*/
describe("useDomSelection marquee", () => {
it("announces every marquee'd element to the timeline, anchored on the primary", () => {
const first = document.createElement("div");
first.id = "card";
const second = document.createElement("div");
second.id = "chip";
document.body.append(first, second);
const harness = renderHarness(
{ activeCompPath: "index.html", projectId: "project-1", refreshKey: 0 },
{ timelineElements: [timelineElement("card"), timelineElement("chip")] },
);
act(() =>
harness
.current()
.applyMarqueeSelection(
[makeSelection("Card", first), makeSelection("Chip", second)],
false,
),
);
expect(harness.current().domEditGroupSelections).toHaveLength(2);
expect(harness.timeline.setTimelineSelectionSet).toHaveBeenCalledWith(
new Set(["card", "chip"]),
);
expect(harness.timeline.setSelectedTimelineElementId).toHaveBeenCalledWith("card", {
preserveSet: true,
});
harness.cleanup();
});
it("uses a surviving group member as the timeline anchor when the canvas primary has no row", () => {
const canvasOnly = document.createElement("div");
canvasOnly.id = "canvas-only";
const card = document.createElement("div");
card.id = "card";
document.body.append(canvasOnly, card);
const harness = renderHarness(
{ activeCompPath: "index.html", projectId: "project-1", refreshKey: 0 },
{ timelineElements: [timelineElement("card")] },
);
act(() =>
harness
.current()
.applyMarqueeSelection(
[makeSelection("Canvas only", canvasOnly), makeSelection("Card", card)],
false,
),
);
expect(harness.timeline.setTimelineSelectionSet).toHaveBeenCalledWith(new Set(["card"]));
expect(harness.timeline.setSelectedTimelineElementId).toHaveBeenCalledWith("card", {
preserveSet: true,
});
harness.cleanup();
});
});
/**
* Adding a second element announced only that element, with preserveSet — and
* preserving a set that does not contain the id empties it. An empty timeline
* selection syncs back as "nothing is selected", so growing a group could wipe
* it instead, and so could re-resolving one after a move.
*/
describe("useDomSelection additive", () => {
it("announces both members when a second element joins the selection", () => {
const first = document.createElement("div");
first.id = "card";
const second = document.createElement("div");
second.id = "chip";
document.body.append(first, second);
const harness = renderHarness(
{ activeCompPath: "index.html", projectId: "project-1", refreshKey: 0 },
{ timelineElements: [timelineElement("card"), timelineElement("chip")] },
);
act(() => harness.current().applyDomSelection(makeSelection("Card", first)));
act(() =>
harness.current().applyDomSelection(makeSelection("Chip", second), { additive: true }),
);
expect(harness.current().domEditGroupSelections).toHaveLength(2);
expect(harness.timeline.setTimelineSelectionSet).toHaveBeenLastCalledWith(
new Set(["card", "chip"]),
);
expect(harness.timeline.setSelectedTimelineElementId).toHaveBeenLastCalledWith("chip", {
preserveSet: true,
});
harness.cleanup();
});
});
describe("useDomSelection", () => {
it("clears a committed selection when the active composition path changes", () => {
const { selection, harness } = setupSelectedHarness();
+67 -40
View File
@@ -4,11 +4,7 @@ import {
getAllPreviewTargetsFromPointer,
getPreviewTargetFromPointer,
} from "../utils/studioPreviewHelpers";
import {
findMatchingTimelineElementId,
findTimelineIdByAncestor,
type RightPanelTab,
} from "../utils/studioHelpers";
import { type RightPanelTab } from "../utils/studioHelpers";
import {
domEditSelectionsTargetSame,
domEditSelectionInGroup,
@@ -24,6 +20,8 @@ import {
} from "../components/editor/domEditing";
import { reapplyPositionEditsAfterSeek } from "../components/editor/manualEdits";
import { useStudioTestHooks } from "./useStudioTestHooks";
import { logSelect } from "../utils/selectDebug";
import { announceTimelineSelection as announceSelectionToTimeline } from "./domSelectionTimelineMirror";
// ── Types ──
@@ -47,7 +45,10 @@ export interface UseDomSelectionParams {
captionEditMode: boolean;
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
timelineElements: TimelineElement[];
getTimelineSelectionSet: () => ReadonlySet<string>;
setSelectedTimelineElementId: (id: string | null, options?: SelectElementOptions) => void;
/** Publishes a whole multi-selection to the timeline; the anchor is set separately. */
setTimelineSelectionSet: (ids: Set<string>) => void;
setRightCollapsed: (collapsed: boolean) => void;
setRightPanelTab: (tab: RightPanelTab) => void;
previewIframe: HTMLIFrameElement | null;
@@ -109,7 +110,9 @@ export function useDomSelection({
captionEditMode,
previewIframeRef,
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
setRightCollapsed,
setRightPanelTab,
previewIframe,
@@ -145,6 +148,26 @@ export function useDomSelection({
// ── Callbacks ──
const announceTimelineSelection = useCallback(
(group: DomEditSelection[], primary: DomEditSelection | null) =>
announceSelectionToTimeline(
{
timelineElements,
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
},
group,
primary,
),
[
getTimelineSelectionSet,
setSelectedTimelineElementId,
setTimelineSelectionSet,
timelineElements,
],
);
const applyDomSelection = useCallback(
// fallow-ignore-next-line complexity
(
@@ -156,11 +179,12 @@ export function useDomSelection({
},
) => {
if (!selection) {
logSelect("clear", { hadGroup: domEditGroupSelectionsRef.current.length });
domEditSelectionRef.current = null;
domEditGroupSelectionsRef.current = [];
setDomEditSelection(null);
setDomEditGroupSelections([]);
setSelectedTimelineElementId(null);
announceTimelineSelection([], null);
return;
}
@@ -186,6 +210,13 @@ export function useDomSelection({
: (nextGroup[0] ?? null)
: selection;
logSelect("apply", {
additive: isAdditiveSelection,
target: selection.selector ?? selection.id ?? null,
wasInGroup,
prevGroup: previousGroup.length,
nextGroup: nextGroup.length,
});
domEditSelectionRef.current = nextSelection;
domEditGroupSelectionsRef.current = nextGroup;
setDomEditSelection(nextSelection);
@@ -208,21 +239,13 @@ export function useDomSelection({
setRightPanelTab("design");
}
}
const nextSelectedTimelineId =
findMatchingTimelineElementId(nextSelection, timelineElements) ??
findTimelineIdByAncestor(
nextSelection.element,
timelineElements,
nextSelection.sourceFile || "index.html",
);
// Late marquee notify: a primary already in the live set must not collapse it.
setSelectedTimelineElementId(nextSelectedTimelineId, { preserveSet: true });
announceTimelineSelection(nextGroup, nextSelection);
return;
}
setSelectedTimelineElementId(null);
announceTimelineSelection([], null);
},
[setSelectedTimelineElementId, timelineElements, setRightCollapsed, setRightPanelTab],
[announceTimelineSelection, setRightCollapsed, setRightPanelTab],
);
const clearDomSelection = useCallback(() => {
@@ -375,6 +398,13 @@ export function useDomSelection({
[applyDomSelection, buildDomSelectionForTimelineElement],
);
// Forward handle to the group refresher defined below: the single-selection
// refresher falls back to it when the primary is gone, and a ref keeps that from
// forcing either callback to be declared in the other's dependency list.
const refreshDomEditGroupSelectionsFromPreviewRef = useRef<
(selections: DomEditSelection[]) => Promise<void>
>(async () => {});
const refreshDomEditSelectionFromPreview = useCallback(
// fallow-ignore-next-line complexity
async (selection: DomEditSelection) => {
@@ -389,6 +419,17 @@ export function useDomSelection({
const element = findElementForSelection(doc, selection, activeCompPath);
if (!element) {
// Losing the primary is not losing the selection. When a group is live,
// re-resolve it and keep whoever still exists rather than wiping the lot.
const group = domEditGroupSelectionsRef.current;
logSelect("refresh-lost", {
target: selection.selector ?? selection.id ?? null,
group: group.length,
});
if (group.length > 1) {
await refreshDomEditGroupSelectionsFromPreviewRef.current(group);
return;
}
applyDomSelection(null, { revealPanel: false });
return;
}
@@ -436,25 +477,17 @@ export function useDomSelection({
setDomEditSelection(nextSelection);
setDomEditGroupSelections(nextGroup);
if (nextSelection) {
setSelectedTimelineElementId(
findMatchingTimelineElementId(nextSelection, timelineElements),
);
} else {
setSelectedTimelineElementId(null);
}
announceTimelineSelection(nextGroup, nextSelection);
},
[
activeCompPath,
buildDomSelectionFromTarget,
setSelectedTimelineElementId,
timelineElements,
previewIframeRef,
],
[activeCompPath, announceTimelineSelection, buildDomSelectionFromTarget, previewIframeRef],
);
// ── Effects ──
useEffect(() => {
refreshDomEditGroupSelectionsFromPreviewRef.current = refreshDomEditGroupSelectionsFromPreview;
}, [refreshDomEditGroupSelectionsFromPreview]);
// Clear hover unconditionally on composition/project/preview change
// eslint-disable-next-line no-restricted-syntax
useEffect(() => {
@@ -503,6 +536,7 @@ export function useDomSelection({
const applyMarqueeSelection = useCallback(
// fallow-ignore-next-line complexity
(selections: DomEditSelection[], additive: boolean) => {
logSelect("marquee", { hits: selections.length, additive });
if (selections.length === 0) {
if (!additive) applyDomSelection(null, { revealPanel: false });
return;
@@ -527,16 +561,9 @@ export function useDomSelection({
domEditGroupSelectionsRef.current = nextGroup;
setDomEditSelection(nextSelection);
setDomEditGroupSelections(nextGroup);
const nextTimelineId =
findMatchingTimelineElementId(nextSelection, timelineElements) ??
findTimelineIdByAncestor(
nextSelection.element,
timelineElements,
nextSelection.sourceFile || "index.html",
);
setSelectedTimelineElementId(nextTimelineId);
announceTimelineSelection(nextGroup, nextSelection);
},
[applyDomSelection, timelineElements, setSelectedTimelineElementId],
[applyDomSelection, announceTimelineSelection],
);
return {
@@ -49,6 +49,7 @@ interface HarnessProps {
iframe: HTMLIFrameElement | null;
timelineElements: TimelineElement[];
setSelectedTimelineElementId?: (id: string | null, options?: SelectElementOptions) => void;
setTimelineSelectionSet?: (ids: Set<string>) => void;
}
function renderHarness(props: HarnessProps) {
@@ -66,7 +67,10 @@ function renderHarness(props: HarnessProps) {
captionEditMode: false,
previewIframeRef: { current: props.iframe },
timelineElements: props.timelineElements,
getTimelineSelectionSet: () => usePlayerStore.getState().selectedElementIds,
setSelectedTimelineElementId: props.setSelectedTimelineElementId ?? vi.fn(),
setTimelineSelectionSet:
props.setTimelineSelectionSet ?? usePlayerStore.getState().setSelectedElementIds,
setRightCollapsed: vi.fn(),
setRightPanelTab: props.setRightPanelTab,
previewIframe: props.iframe,
@@ -236,7 +240,7 @@ describe("useDomSelection — marquee multi-select survives the late async prima
iframe.remove();
});
it("collapses the set when a late primary-set targets a non-member (fresh click)", async () => {
it("collapses the set to a fresh single-click target instead of publishing an empty set", async () => {
const iframe = document.createElement("iframe");
document.body.append(iframe);
const doc = iframe.contentDocument!;
@@ -268,7 +272,7 @@ describe("useDomSelection — marquee multi-select survives the late async prima
await pending;
});
expect(usePlayerStore.getState().selectedElementIds.size).toBe(0);
expect([...usePlayerStore.getState().selectedElementIds]).toEqual(["d"]);
expect(usePlayerStore.getState().selectedElementId).toBe("d");
harness.cleanup();
iframe.remove();
@@ -33,6 +33,8 @@ export type ElementAnimationsOutcome =
export interface GsapAnimationFetchOptions {
/** Refuse the edit when the parse endpoint is unavailable instead of treating it as no motion. */
failOnFetchError?: boolean;
/** Ignore an overlapping pre-write parse and read the source after a durable write. */
fresh?: boolean;
}
/**
@@ -56,11 +58,13 @@ async function fetchElementAnimationsWithRetry(
gsapSourceFile: string,
target: { id: string | null; selector: string | null },
failOnFetchError: boolean,
fresh: boolean,
): Promise<GsapAnimation[]> {
let coldAttempts = 0;
let errorAttempts = 0;
for (;;) {
const parsed = await fetchParsedAnimations(projectId, gsapSourceFile);
const parsed = await fetchParsedAnimations(projectId, gsapSourceFile, { fresh });
fresh = false;
const outcome = selectElementAnimationsOrRetry(parsed, target);
if (outcome.kind === "resolved") return outcome.animations;
if (outcome.kind === "fetch-error") {
@@ -89,6 +93,7 @@ export function useGsapAnimationFetchFallback(projectId: string | null, gsapSour
gsapSourceFile,
target,
options?.failOnFetchError === true,
options?.fresh === true,
);
},
[projectId, gsapSourceFile],
@@ -301,6 +301,42 @@ describe("useGsapAwareEditing anchored resize", () => {
act(() => root.unmount());
});
it("reports only the first group preflight failure in input order", async () => {
const failures = [new Error("first blocked"), new Error("second blocked")];
const trackGsapInteractionFailure = vi.fn();
const priorDragImplementation = mocks.drag.getMockImplementation();
mocks.drag.mockImplementation(async (selection) => {
throw selection.id === "a" ? failures[0] : failures[1];
});
const { groupCommit, root } = mountGroupHandler({
gsapCommitMutation: vi.fn().mockResolvedValue(undefined),
makeFetchFallback: () => vi.fn().mockResolvedValue([]),
trackGsapInteractionFailure,
});
const updates = [
{
selection: { element: document.createElement("div"), id: "a", selector: "#a" },
next: { x: 10, y: 10 },
},
{
selection: { element: document.createElement("div"), id: "b", selector: "#b" },
next: { x: 20, y: 20 },
},
] as unknown as DomEditGroupPathOffsetCommit[];
await expect(groupCommit(updates)).rejects.toBe(failures[0]);
expect(trackGsapInteractionFailure).toHaveBeenCalledOnce();
expect(trackGsapInteractionFailure).toHaveBeenCalledWith(
failures[0],
updates[0]?.selection,
"drag",
"Move animated layer (group)",
);
mocks.drag.mockReset();
if (priorDragImplementation) mocks.drag.mockImplementation(priorDragImplementation);
act(() => root.unmount());
});
it("restores once when resize persistence fails", async () => {
const error = new Error("resize failed");
const restore = vi.fn();
@@ -24,7 +24,11 @@ import {
useGsapSaveFailureTelemetry,
useSafeGsapCommitMutation,
} from "./useSafeGsapCommitMutation";
import type { CommitMutation } from "./gsapScriptCommitTypes";
import type {
CommitMutation,
CommitMutationCall,
CommitMutationOptions,
} from "./gsapScriptCommitTypes";
import { setElementGsapPosition } from "../utils/elementGsap";
import { logResize, logResizeSettle } from "../utils/resizeDebug";
import type { DomEditGroupPathOffsetCommit } from "../components/editor/DomEditOverlay";
@@ -37,6 +41,18 @@ import type { GsapAnimationFetchOptions } from "./useGsapAnimationFetchFallback"
// into one another's undo entry (module-local counter, not Date.now()).
let groupDragCommitCounter = 0;
function firstPreflightFailure(
results: PromiseSettledResult<void>[],
updates: DomEditGroupPathOffsetCommit[],
): { error: unknown; selection: DomEditSelection } | null {
for (const [index, result] of results.entries()) {
if (result.status !== "rejected") continue;
const selection = updates[index]?.selection;
if (selection) return { error: result.reason, selection };
}
return null;
}
export interface UseGsapAwareEditingParams {
domEditSelection: DomEditSelection | null;
selectedGsapAnimations: GsapAnimation[];
@@ -50,7 +66,7 @@ export interface UseGsapAwareEditingParams {
) => () => Promise<GsapAnimation[]>;
trackGsapInteractionFailure: (
error: unknown,
selection: DomEditSelection,
selection: DomEditSelection | null,
mutationType: string,
label: string,
) => void;
@@ -155,19 +171,54 @@ export function useGsapAwareEditing({
// it survives the N sequential server round-trips) onto each commit —
// otherwise each member records its own entry and it takes N presses to undo.
const coalesceKey = `group-drag:${++groupDragCommitCounter}`;
const coalescedCommit: typeof gsapCommitMutation = (selection, mutation, options) =>
gsapCommitMutation(selection, mutation, {
...options,
coalesceKey,
coalesceMs: Number.POSITIVE_INFINITY,
// Members are written one at a time, and a write that re-renders the preview
// re-runs the whole script — which still holds the OLD position of every
// member not yet written. Those members snap back to where they started and
// stay there until their own write lands, which is the single element seen
// jumping mid-commit while the rest of the group sat still. The drafted
// positions are already on screen, so holding the render until the last
// member has been written costs nothing and never shows a half-moved group.
let renderOnCommit = false;
const previewFallbackLatch = { pending: false };
const withGroupOptions = (options: CommitMutationOptions): CommitMutationOptions => ({
...options,
coalesceKey,
coalesceMs: Number.POSITIVE_INFINITY,
deferPreviewSync: !renderOnCommit,
previewFallbackLatch,
});
// Every member writes the same file. Queue their mutations and send them as
// ONE request instead of one round trip per member: the server reads, parses
// and writes the composition once, and the preview patches once.
const queued: CommitMutationCall[] = [];
const flushQueued = async () => {
if (queued.length === 0) return;
const calls = queued.splice(0, queued.length);
if (!gsapCommitMutation.batch) {
for (const call of calls) {
await gsapCommitMutation(call.selection, call.mutation, call.options);
}
return;
}
await gsapCommitMutation.batch(calls, {
...(calls.at(-1)?.options ?? { label: "Move animated layer (group)" }),
label: "Move animated layer (group)",
});
};
const coalescedCommit: typeof gsapCommitMutation = (selection, mutation, options) => {
queued.push({ selection, mutation, options: withGroupOptions(options) });
return Promise.resolve();
};
const preflightAnimations = new Map<DomEditSelection, GsapAnimation[]>();
// Editability is user-atomic: prove every member can be written before
// the first source mutation. Network failures after this point retain the
// existing multi-request semantics, but a blocked member can never leave
// earlier siblings partially moved.
for (const { selection } of updates) {
try {
// Every member reads the same file, and a preflight writes nothing — so run
// them together. The parse layer shares one in-flight request per file, which
// turns N sequential round trips into one.
const preflightResults = await Promise.allSettled(
updates.map(async ({ selection }) => {
const animations = await makeFetchFallback(selection, { failOnFetchError: true })();
preflightAnimations.set(selection, animations);
const outcome = await tryGsapDragIntercept(
@@ -180,12 +231,20 @@ export function useGsapAwareEditing({
{ preflightOnly: true },
);
assertGsapEditPersisted(outcome);
} catch (error) {
trackGsapInteractionFailure(error, selection, "drag", "Move animated layer (group)");
throw error;
}
}),
);
const preflightFailure = firstPreflightFailure(preflightResults, updates);
if (preflightFailure) {
trackGsapInteractionFailure(
preflightFailure.error,
preflightFailure.selection,
"drag",
"Move animated layer (group)",
);
throw preflightFailure.error;
}
for (const { selection, next } of updates) {
for (const [index, { selection, next }] of updates.entries()) {
renderOnCommit = index === updates.length - 1;
try {
const outcome = await tryGsapDragIntercept(
selection,
@@ -193,7 +252,13 @@ export function useGsapAwareEditing({
preflightAnimations.get(selection) ?? [],
previewIframeRef.current,
coalescedCommit,
makeFetchFallback(selection),
// The intercept re-reads the file to resolve a stale or shared tween.
// Anything already queued has to be on disk before that read, or it
// resolves against a file missing writes it is about to build on.
async () => {
await flushQueued();
return makeFetchFallback(selection, { fresh: true })();
},
{ preflightPassed: true },
);
assertGsapEditPersisted(outcome);
@@ -202,6 +267,14 @@ export function useGsapAwareEditing({
throw error;
}
}
try {
await flushQueued();
} catch (error) {
// The aggregate write has no uniquely failing member; do not misattribute
// its telemetry to whichever member happened to be last in the array.
trackGsapInteractionFailure(error, null, "drag", "Move animated layer (group)");
throw error;
}
},
[gsapCommitMutation, previewIframeRef, makeFetchFallback, trackGsapInteractionFailure],
);
@@ -8,16 +8,16 @@ export function useGsapInteractionFailureTelemetry(
showToast: (message: string, tone?: "error" | "info") => void,
) {
return useCallback(
(error: unknown, selection: DomEditSelection, mutationType: string, label: string) => {
(error: unknown, selection: DomEditSelection | null, mutationType: string, label: string) => {
trackStudioSaveFailure({
source: "gsap_commit",
error,
filePath: selection.sourceFile ?? activeCompPath ?? "index.html",
filePath: selection?.sourceFile ?? activeCompPath ?? "index.html",
mutationType,
label,
targetId: selection.id,
targetSelector: selection.selector,
targetSourceFile: selection.sourceFile,
targetId: selection?.id,
targetSelector: selection?.selector,
targetSourceFile: selection?.sourceFile,
});
showToast(
isGsapEditBlockedError(error) ? error.message : "Failed to save animated edit.",
@@ -73,14 +73,159 @@ describe("applyPreviewSync", () => {
syncDragPreview(result(), reloadPreview);
expect(patchRuntimeTweenInPlace).toHaveBeenCalledWith(FAKE_IFRAME, "#a", {
kind: "set",
props: { x: 10 },
});
expect(patchRuntimeTweenInPlace).toHaveBeenCalledWith(
FAKE_IFRAME,
"#a",
{
kind: "set",
props: { x: 10 },
},
undefined,
false,
);
expect(applySoftReload).not.toHaveBeenCalled();
expect(reloadPreview).not.toHaveBeenCalled();
});
it("instantPatches: patches every element the batch wrote, rendering once at the end", () => {
patchRuntimeTweenInPlace.mockReturnValue(true);
const reloadPreview = vi.fn();
applyPreviewSync(
FAKE_IFRAME,
result(),
{
label: "Move animated layer (group)",
softReload: true,
instantPatches: [
{ selector: "#a", change: { kind: "set" as const, props: { x: 1 } } },
{ selector: "#b", change: { kind: "set" as const, props: { x: 2 } } },
{ selector: "#c", change: { kind: "set" as const, props: { x: 3 } } },
],
},
reloadPreview,
);
// Only the last patch re-renders — the earlier two defer their seek, so the
// group repaints once instead of once per member.
expect(patchRuntimeTweenInPlace.mock.calls.map((call) => [call[1], call[4]])).toEqual([
["#a", true],
["#b", true],
["#c", false],
]);
expect(applySoftReload).not.toHaveBeenCalled();
expect(reloadPreview).not.toHaveBeenCalled();
});
it("applies both plural and singular patches when a caller supplies both", () => {
patchRuntimeTweenInPlace.mockReturnValue(true);
applyPreviewSync(
FAKE_IFRAME,
result(),
{
label: "mixed patch contract",
instantPatches: [
{ selector: "#group-a", change: { kind: "set" as const, props: { x: 1 } } },
],
instantPatch: {
selector: "#single-b",
change: { kind: "set" as const, props: { x: 2 } },
},
},
vi.fn(),
);
expect(patchRuntimeTweenInPlace.mock.calls.map((call) => [call[1], call[4]])).toEqual([
["#group-a", true],
["#single-b", false],
]);
});
it("instantPatches: one patch that misses falls the whole batch back to the reload", () => {
patchRuntimeTweenInPlace.mockImplementation((_iframe, selector) => selector !== "#b");
applySoftReload.mockReturnValue("applied");
const reloadPreview = vi.fn();
applyPreviewSync(
FAKE_IFRAME,
result({ scriptText: "SCRIPT" }),
{
label: "Move animated layer (group)",
softReload: true,
instantPatches: [
{ selector: "#a", change: { kind: "set" as const, props: { x: 1 } } },
{ selector: "#b", change: { kind: "set" as const, props: { x: 2 } } },
],
},
reloadPreview,
);
// A half-patched preview is worse than a reloaded one: "#a" landed, "#b" did
// not, so the reload repaints both from the written source.
expect(applySoftReload).toHaveBeenCalled();
expect(trackStudioEvent).toHaveBeenCalledWith("gsap_instant_patch_fallback", {
selector: "#b",
});
});
it("carries a deferred patch miss into the final batch render", () => {
const previewFallbackLatch = { pending: false };
applySoftReload.mockReturnValue("applied");
const reloadPreview = vi.fn();
patchRuntimeTweenInPlace.mockReturnValueOnce(false).mockReturnValueOnce(true);
applyPreviewSync(
FAKE_IFRAME,
result({ scriptText: "SCRIPT" }),
{
label: "Move animated layer (group)",
softReload: true,
deferPreviewSync: true,
previewFallbackLatch,
instantPatch: { selector: "#missed", change: { kind: "set", props: { x: 1 } } },
},
reloadPreview,
);
expect(previewFallbackLatch.pending).toBe(true);
expect(applySoftReload).not.toHaveBeenCalled();
applyPreviewSync(
FAKE_IFRAME,
result({ scriptText: "SCRIPT" }),
{
label: "Move animated layer (group)",
softReload: true,
previewFallbackLatch,
instantPatch: { selector: "#final", change: { kind: "set", props: { x: 2 } } },
},
reloadPreview,
);
expect(previewFallbackLatch.pending).toBe(false);
expect(applySoftReload).toHaveBeenCalledTimes(1);
});
it("falls back immediately when a deferred patch miss has no final-render latch", () => {
patchRuntimeTweenInPlace.mockReturnValue(false);
applySoftReload.mockReturnValue("applied");
applyPreviewSync(
FAKE_IFRAME,
result({ scriptText: "SCRIPT" }),
{
label: "Deferred standalone write",
softReload: true,
deferPreviewSync: true,
instantPatch: { selector: "#missed", change: { kind: "set", props: { x: 1 } } },
},
vi.fn(),
);
expect(applySoftReload).toHaveBeenCalledTimes(1);
});
it("instantPatch + patch fails: falls back to the soft reload, passing onAsyncFailure", () => {
patchRuntimeTweenInPlace.mockReturnValue(false);
applySoftReload.mockReturnValue("applied");
@@ -338,10 +483,51 @@ describe("runCommit — instantPatch wiring", () => {
// The file already matched (changed:false) but the runtime patch deferred
// from the paired first commit must still land.
expect(patchRuntimeTweenInPlace).toHaveBeenCalledWith(FAKE_IFRAME, "#a", {
kind: "set",
props: { x: 485, y: 311 },
expect(patchRuntimeTweenInPlace).toHaveBeenCalledWith(
FAKE_IFRAME,
"#a",
{
kind: "set",
props: { x: 485, y: 311 },
},
undefined,
false,
);
expect(deps.reloadPreview).not.toHaveBeenCalled();
});
it("no-op batch still applies every plural instant patch", async () => {
patchRuntimeTweenInPlace.mockReturnValue(true);
mockFetchResult({ changed: false });
const deps = renderCommitHook();
const batch = deps.api.commitMutation.batch;
if (!batch) throw new Error("batch capability missing");
await act(async () => {
await batch(
[
{
selection,
mutation: { type: "update-property", property: "x", value: 10 },
options: {
label: "Move layer",
instantPatch: { selector: "#a", change: { kind: "set", props: { x: 10 } } },
},
},
{
selection: { ...selection, id: "b", selector: "#b" },
mutation: { type: "update-property", property: "x", value: 20 },
options: {
label: "Move layer",
instantPatch: { selector: "#b", change: { kind: "set", props: { x: 20 } } },
},
},
],
{ label: "Move animated layer (group)" },
);
});
expect(patchRuntimeTweenInPlace.mock.calls.map((call) => call[1])).toEqual(["#a", "#b"]);
expect(deps.reloadPreview).not.toHaveBeenCalled();
});
@@ -126,7 +126,10 @@ function finishUnchangedMutation(
reloadPreview: () => void,
): boolean {
if (result.changed !== false) return false;
if (!options.skipReload && options.instantPatch) {
if (
!options.skipReload &&
(instantPatchesFor(options).length > 0 || options.previewFallbackLatch?.pending)
) {
applyPreviewSync(iframe, result, options, reloadPreview);
}
return true;
@@ -249,19 +252,37 @@ export function applyPreviewSync(
options: CommitMutationOptions,
reloadPreview: () => void,
): void {
if (options.instantPatch) {
const patched = patchRuntimeTweenInPlace(
iframe,
options.instantPatch.selector,
options.instantPatch.change,
const patches = instantPatchesFor(options);
let needsFallback = options.previewFallbackLatch?.pending === true;
if (patches.length > 0) {
const deferSeek = options.deferPreviewSync === true;
const missed = patches.find(
(patch, index) =>
!patchRuntimeTweenInPlace(
iframe,
patch.selector,
patch.change,
undefined,
deferSeek || index < patches.length - 1,
),
);
// Patched in place — element is already correct on screen; no reload needed.
if (patched) return;
// The instant path couldn't patch in place — record the fallback so we can
// track how often the fast path misses before the soft/full reload below.
trackStudioEvent("gsap_instant_patch_fallback", { selector: options.instantPatch.selector });
// Fall through to the soft/full reload path below.
if (missed) {
// The instant path couldn't patch in place — record the fallback so we can
// track how often the fast path misses before the soft/full reload below.
trackStudioEvent("gsap_instant_patch_fallback", { selector: missed.selector });
needsFallback = true;
}
// Patched in place — elements are already correct on screen; no reload needed
// unless an earlier deferred batch left one member unpatched.
if (!needsFallback) return;
}
// Written, but the caller has more writes to make and will render after the last.
if (options.deferPreviewSync && options.previewFallbackLatch) {
options.previewFallbackLatch.pending = needsFallback;
return;
}
if (options.deferPreviewSync && !needsFallback) return;
if (options.previewFallbackLatch) options.previewFallbackLatch.pending = false;
if (options.softReload && result.scriptText) {
// A soft-reloadable edit escalates to a full iframe remount ONLY on the
// PERMANENT "cannot-soft-reload" result (the preview is genuinely stale/
@@ -281,6 +302,15 @@ export function applyPreviewSync(
}
}
function instantPatchesFor(
options: CommitMutationOptions,
): NonNullable<CommitMutationOptions["instantPatches"]> {
return [
...(options.instantPatches ?? []),
...(options.instantPatch ? [options.instantPatch] : []),
];
}
// oxfmt-ignore
// fallow-ignore-next-line complexity
export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIframeRef, editHistory, domEditSaveTimestampRef, reloadPreview, onCacheInvalidate, onFileContentChanged, showToast, sdkSession, publishSdkSession, writeProjectFile, forceReloadSdkSession }: GsapScriptCommitsParams) {
@@ -356,7 +386,13 @@ export function useGsapScriptCommits({ projectIdRef, activeCompPath, previewIfra
);
if (!result) return;
options.onResult?.(result);
await finalizeSuccessfulMutation(pid, compositionPath, last.selection, last.mutation, targetPath, result, options);
// Each call brings its own fast-path patch; the batch wrote them all, so the
// preview sync applies them all rather than just the last call's.
const instantPatches = calls
.map(({ options: callOptions }) => callOptions.instantPatch)
.filter((patch) => patch !== undefined);
const { instantPatch: _instantPatch, ...batchOptions } = options;
await finalizeSuccessfulMutation(pid, compositionPath, last.selection, last.mutation, targetPath, result, instantPatches.length > 0 ? { ...batchOptions, instantPatches } : batchOptions);
}, [showToast, finalizeSuccessfulMutation]);
// Every GSAP-script commit is a read-modify-write of one file. Overlapping
+130 -7
View File
@@ -7,6 +7,7 @@ import {
buildStudioHash,
parseStudioUrlStateFromHash,
type StudioUrlSelectionState,
type StudioUrlSelectionTarget,
type StudioUrlState,
} from "../utils/studioUrlState";
@@ -22,6 +23,8 @@ interface UseStudioUrlStateParams {
rightCollapsed: boolean;
activeCompPathHydrated: boolean;
domEditSelection: DomEditSelection | null;
domEditGroupSelections: DomEditSelection[];
applyMarqueeSelection: (selections: DomEditSelection[], additive: boolean) => void;
buildDomSelectionFromTarget: (
target: HTMLElement,
options?: { preferClipAncestor?: boolean },
@@ -38,8 +41,7 @@ interface UseStudioUrlStateParams {
initialState: StudioUrlState;
}
function toPersistedSelection(selection: DomEditSelection | null): StudioUrlSelectionState | null {
if (!selection) return null;
function toPersistedTarget(selection: DomEditSelection): StudioUrlSelectionTarget | null {
if (!selection.id && !selection.selector) return null;
return {
sourceFile: selection.sourceFile || undefined,
@@ -49,12 +51,109 @@ function toPersistedSelection(selection: DomEditSelection | null): StudioUrlSele
};
}
function selectionTargetKey(selection: StudioUrlSelectionTarget): string {
return [
selection.sourceFile ?? "",
selection.id ?? "",
selection.selector ?? "",
selection.selectorIndex ?? "",
].join("|");
}
function toPersistedSelection(
selection: DomEditSelection | null,
// Optional: a caller that only ever has one selection has nothing to add, and
// the URL must still carry that one rather than throwing on the way out.
group: DomEditSelection[] = [],
): StudioUrlSelectionState | null {
if (!selection) return null;
const primary = toPersistedTarget(selection);
if (!primary) return null;
// The primary is already carried by the top-level fields; the rest ride along so the link
// reopens the same multi-selection instead of a single element.
const primaryKey = selectionTargetKey(primary);
const members = new Map<string, StudioUrlSelectionTarget>();
for (const member of group) {
const target = toPersistedTarget(member);
if (!target) continue;
const key = selectionTargetKey(target);
if (key !== primaryKey) members.set(key, target);
}
return {
...primary,
group: members.size > 0 ? [...members.values()] : undefined,
};
}
function replaceHash(nextHash: string) {
if (typeof window === "undefined") return;
if (window.location.hash === nextHash) return;
window.history.replaceState(null, "", nextHash);
}
interface ResolveUrlSelectionsParams {
doc: Document;
primaryElement: HTMLElement;
selection: StudioUrlSelectionState;
group: StudioUrlSelectionTarget[];
activeCompPath: string | null;
isCurrent: () => boolean;
buildDomSelection: UseStudioUrlStateParams["buildDomSelectionFromTarget"];
}
function findUrlSelectionElement(
doc: Document,
target: StudioUrlSelectionTarget,
fallbackSourceFile: string,
activeCompPath: string | null,
): HTMLElement | null {
return findElementForSelection(
doc,
{
sourceFile: target.sourceFile ?? fallbackSourceFile,
id: target.id,
selector: target.selector,
selectorIndex: target.selectorIndex,
},
activeCompPath,
);
}
async function buildOptionalDomSelection(
element: HTMLElement | null,
buildDomSelection: UseStudioUrlStateParams["buildDomSelectionFromTarget"],
): Promise<DomEditSelection | null> {
if (!element) return null;
return buildDomSelection(element, { preferClipAncestor: false });
}
async function resolveUrlSelections({
doc,
primaryElement,
selection,
group,
activeCompPath,
isCurrent,
buildDomSelection,
}: ResolveUrlSelectionsParams): Promise<DomEditSelection[] | null> {
const primary = await buildDomSelection(primaryElement, { preferClipAncestor: false });
if (!isCurrent()) return null;
if (!primary) return [];
const members = [primary];
for (const member of group) {
const element = findUrlSelectionElement(
doc,
member,
selection.sourceFile ?? "",
activeCompPath,
);
const resolved = await buildOptionalDomSelection(element, buildDomSelection);
if (!isCurrent()) return null;
if (resolved) members.push(resolved);
}
return members;
}
export function useStudioUrlState({
projectId,
activeCompPath,
@@ -67,6 +166,8 @@ export function useStudioUrlState({
rightCollapsed,
activeCompPathHydrated,
domEditSelection,
domEditGroupSelections,
applyMarqueeSelection,
buildDomSelectionFromTarget,
applyDomSelection,
setRightPanelTab,
@@ -82,6 +183,7 @@ export function useStudioUrlState({
const [selectionHydrated, setSelectionHydrated] = useState(initialState.selection == null);
const pendingSelectionRef = useRef(initialState.selection);
const stableTimeRef = useRef<number | null>(initialState.currentTime);
const selectionApplySeqRef = useRef(0);
const buildUrlState = useCallback(
(): StudioUrlState => ({
@@ -91,10 +193,10 @@ export function useStudioUrlState({
rightCollapsed,
timelineVisible: null,
selection: hydratedSelectionRef.current
? toPersistedSelection(domEditSelection)
? toPersistedSelection(domEditSelection, domEditGroupSelections)
: pendingSelectionRef.current,
}),
[activeCompPath, domEditSelection, rightCollapsed, rightPanelTab],
[activeCompPath, domEditGroupSelections, domEditSelection, rightCollapsed, rightPanelTab],
);
// Resolve a URL selection to a live element and apply it. Shared by the initial
@@ -103,6 +205,7 @@ export function useStudioUrlState({
// a missing element or null selection clears the selection and returns true.
const applyUrlSelection = useCallback(
(selection: StudioUrlSelectionState | null): boolean => {
const applySeq = ++selectionApplySeqRef.current;
if (!selection) {
applyDomSelection(null, { revealPanel: false });
return true;
@@ -128,12 +231,32 @@ export function useStudioUrlState({
applyDomSelection(null, { revealPanel: false });
return true;
}
void buildDomSelectionFromTarget(element, { preferClipAncestor: false }).then((resolved) => {
applyDomSelection(resolved, { revealPanel: false });
const group = selection.group ?? [];
void resolveUrlSelections({
doc,
primaryElement: element,
selection,
group,
activeCompPath,
isCurrent: () => applySeq === selectionApplySeqRef.current,
buildDomSelection: buildDomSelectionFromTarget,
}).then((members) => {
if (!members) return;
const primary = members[0];
if (!primary) return applyDomSelection(null, { revealPanel: false });
if (group.length === 0) return applyDomSelection(primary, { revealPanel: false });
// Missing group members are dropped without failing the rest.
applyMarqueeSelection(members, false);
});
return true;
},
[activeCompPath, applyDomSelection, buildDomSelectionFromTarget, previewIframeRef],
[
activeCompPath,
applyDomSelection,
applyMarqueeSelection,
buildDomSelectionFromTarget,
previewIframeRef,
],
);
useEffect(() => {
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef } from "react";
import type { TimelineElement } from "../player";
import type { DomEditSelection } from "../components/editor/domEditing";
import { resolveTimelineIdForSelection } from "../utils/studioHelpers";
import { logSelect } from "../utils/selectDebug";
interface UseTimelineSelectionPreviewSyncParams {
selectedElementId: string | null;
@@ -93,6 +94,13 @@ export function useTimelineSelectionPreviewSync({
if (selectedIds.length === 0) {
missingSelectionKeyRef.current = "";
// The timeline holds nothing, so the canvas is about to hold nothing either.
// This is the path that silently drops a selection the user can still see.
logSelect("timeline-empty", {
had: currentIds.length,
previousKey: previousSelectedKey.length > 0,
clearing: previousSelectedKey.length > 0 && currentIds.length > 0,
});
if (previousSelectedKey.length > 0 && currentIds.length > 0) {
applyDomSelection(null, { revealPanel: false });
}
@@ -127,6 +135,11 @@ export function useTimelineSelectionPreviewSync({
return;
}
missingSelectionKeyRef.current = "";
logSelect("timeline-sync", {
wanted: selectedIds.length,
had: currentIds.length,
resolved: selections.length,
});
if (selections.length === 0) {
applyDomSelection(null, { revealPanel: false });
} else if (selections.length === 1) {