Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): hide handles Studio would refuse to commit (#4666)
Miguel Ángel7e0711505a1a
diff --git a/packages/studio/src/components/editor/DomEditOverlay.tsx b/packages/studio/src/components/editor/DomEditOverlay.tsxindex 61421d72de..de4b1294bf 100644--- a/packages/studio/src/components/editor/DomEditOverlay.tsx+++ b/packages/studio/src/components/editor/DomEditOverlay.tsx@@ -518,7 +518,6 @@ export const DomEditOverlay = memo(function DomEditOverlay({boxClipPath={boxClipPath}selectionKey={selectionKey}groupSelectionCount={groupSelections.length}- blockedMoveRef={blockedMoveRef}gestures={gestures}onStyleCommit={onStyleCommitRef.current}onBoxMouseDown={suppressBoxMouseDown}diff --git a/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsx b/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsxindex 31972ab126..801fb585ca 100644--- a/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsx+++ b/packages/studio/src/components/editor/DomEditSelectionChrome.test.tsx@@ -53,7 +53,6 @@ describe("DomEditSelectionChrome crop composition", () => {boxClipPath={undefined}selectionKey="headline"groupSelectionCount={0}- blockedMoveRef={createRef()}gestures={{ startGesture: vi.fn() } as never}onStyleCommit={vi.fn()}onBoxMouseDown={vi.fn()}@@ -109,7 +108,6 @@ describe("DomEditSelectionChrome crop composition", () => {boxClipPath={undefined}selectionKey="clip"groupSelectionCount={0}- blockedMoveRef={createRef()}gestures={{ startGesture: vi.fn() } as never}onStyleCommit={vi.fn()}onBoxMouseDown={vi.fn()}@@ -170,7 +168,6 @@ describe("DomEditSelectionChrome while editing text", () => {boxClipPath={undefined}selectionKey="copy"groupSelectionCount={0}- blockedMoveRef={createRef()}gestures={{ startGesture: vi.fn() } as never}onStyleCommit={vi.fn()}onBoxMouseDown={vi.fn()}diff --git a/packages/studio/src/components/editor/DomEditSelectionChrome.tsx b/packages/studio/src/components/editor/DomEditSelectionChrome.tsxindex 23aaaeeff2..ef900cbe2f 100644--- a/packages/studio/src/components/editor/DomEditSelectionChrome.tsx+++ b/packages/studio/src/components/editor/DomEditSelectionChrome.tsx@@ -1,7 +1,7 @@import type { RefObject } from "react";import { type DomEditSelection } from "./domEditing";import type { GroupOverlayItem, OverlayRect } from "./domEditOverlayGeometry";-import type { BlockedMoveState, ResizeHandle } from "./domEditOverlayGestures";+import type { ResizeHandle } from "./domEditOverlayGestures";import type { createDomEditOverlayGestureHandlers } from "./useDomEditOverlayGestures";import { DomEditCropHandles } from "./DomEditCropHandles";import { DomEditRotateHandle } from "./DomEditRotateHandle";@@ -103,7 +103,7 @@ export function DomEditGroupChrome({cursor: canManipulate && groupCanMove ? "move" : "default",}}onPointerDown={(e) => {- if (!canManipulate || !groupCanMove || e.shiftKey) return;+ if (!canManipulate || e.shiftKey) return;gestures.startGroupDrag(e);}}onMouseDown={onBoxMouseDown}@@ -123,7 +123,6 @@ interface DomEditSelectionChromeProps {boxClipPath: string | undefined;selectionKey: string;groupSelectionCount: number;- blockedMoveRef: RefObject<BlockedMoveState | null>;gestures: GestureHandlers;onStyleCommit?: (property: string, value: string) => Promise<unknown> | void;onBoxMouseDown: (e: React.MouseEvent) => void;@@ -152,7 +151,6 @@ export function DomEditSelectionChrome({boxClipPath,selectionKey,groupSelectionCount,- blockedMoveRef,gestures,onStyleCommit,onBoxMouseDown,@@ -218,15 +216,7 @@ export function DomEditSelectionChrome({gestures.startGesture("drag", e);return;}- e.preventDefault();- e.stopPropagation();- e.currentTarget.setPointerCapture(e.pointerId);- blockedMoveRef.current = {- pointerId: e.pointerId,- startX: e.clientX,- startY: e.clientY,- notified: false,- };+ gestures.startBlockedMove(e, selection);}}onMouseDown={onBoxMouseDown}onClick={onBoxClick}diff --git a/packages/studio/src/components/editor/commitPreflightHandles.test.tsx b/packages/studio/src/components/editor/commitPreflightHandles.test.tsxnew file mode 100644index 0000000000..0ea8c5f722--- /dev/null+++ b/packages/studio/src/components/editor/commitPreflightHandles.test.tsx@@ -0,0 +1,466 @@+// @vitest-environment happy-dom++import React, { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import { makeSelection } from "../../hooks/domSelectionTestHarness";+import { GSAP_EDIT_BLOCK_COPY } from "../../hooks/gsapEditOutcome";+import { tryGsapDragIntercept } from "../../hooks/gsapRuntimeBridge";+import { getAnimationsForElement } from "../../hooks/useGsapTweenCache";+import { useCommitPreflightCapabilities } from "../../hooks/useCommitPreflightCapabilities";+import { CANVAS_NUDGE_COMMIT_DEBOUNCE_MS } from "./domEditNudge";+import { __resetForTests } from "../../utils/canvasNudgeGate";+import type { DomEditSelection } from "./domEditing";+import "./domEditOverlayTestMocks";+import { DomEditOverlay } from "./DomEditOverlay";++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++type Parse = { animations: GsapAnimation[] } | null;+const parses = vi.hoisted(() => ({ fetch: vi.fn<(...args: unknown[]) => Promise<unknown>>() }));+const layout = vi.hoisted(() => ({ group: [] as unknown[] }));++vi.mock("../../hooks/keyframeCacheAstLoad", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../hooks/keyframeCacheAstLoad")>()),+ fetchParsedAnimations: (...args: unknown[]) => parses.fetch(...args),+}));++vi.mock("./useDomEditOverlayRects", () => {+ const rect = { left: 100, top: 100, width: 200, height: 100, editScaleX: 1, editScaleY: 1 };+ return {+ useDomEditOverlayRects: () => ({+ overlayRect: rect,+ overlayRectRef: { current: rect },+ setOverlayRect: () => undefined,+ hoverRect: null,+ groupOverlayItems: layout.group,+ groupOverlayItemsRef: { current: layout.group },+ setGroupOverlayItems: () => undefined,+ childRects: [],+ }),+ };+});++const BOX = '[data-dom-edit-selection-box="true"]';+const DOTS = "div.h-4.w-4";+const ROTATE = '[aria-label="Rotate selection"]';+const RECT = { left: 100, top: 100, width: 200, height: 100, editScaleX: 1, editScaleY: 1 };+let root: Root;+let host: HTMLElement;++function tween(+ properties: Record<string, number>,+ extra: Partial<GsapAnimation> = {},+): GsapAnimation {+ return {+ id: `#title-to-${Object.keys(properties).join("-")}`,+ targetSelector: "#title",+ method: "to",+ properties,+ position: 0,+ resolvedStart: 0,+ duration: 2,+ ...extra,+ } as unknown as GsapAnimation;+}++const loop = (properties: Record<string, number>, targetSelector = "#title") =>+ tween(properties, { targetSelector, provenance: { kind: "loop" } } as never);++function element(id: string, className = "") {+ const el = document.createElement("h1");+ el.id = id;+ el.className = className;+ document.body.append(el);+ return el;+}++function resolved(el: HTMLElement): DomEditSelection {+ const selection = makeSelection(el.id, el);+ selection.capabilities.canApplyManualRotation = true;+ return selection;+}++/** A preview whose runtime timeline is visibly moving `els` with one shared tween. */+function livePreview(els: HTMLElement[], vars: Record<string, number>) {+ const liveTween = {+ targets: () => els,+ vars: { ...vars, duration: 1 },+ duration: () => 1,+ startTime: () => 0,+ };+ const timeline = { getChildren: () => [liveTween], duration: () => 6 };+ const byId = (sel: string) => els.find((el) => sel === `#${el.id}`) ?? null;+ return {+ contentWindow: { __timelines: { root: timeline }, gsap: { getProperty: () => 0 } },+ contentDocument: { querySelector: byId },+ } as unknown as HTMLIFrameElement;+}++interface EditorProps {+ selection: DomEditSelection | null;+ groups?: DomEditSelection[];+ version?: number;+ preview?: HTMLIFrameElement | null;+ projectId?: string;+}++/** Studio's session narrowing feeding the real overlay, as the editor mounts it. */+function mount(first: EditorProps) {+ const spies = {+ onBlockedMove: vi.fn(),+ onPathOffsetCommit: vi.fn(),+ onManualDragStart: vi.fn(),+ };+ const seen: { selection: DomEditSelection | null; groups: DomEditSelection[] } = {+ selection: null,+ groups: [],+ };+ const iframeRef = { current: document.createElement("iframe") };+ function Editor({+ selection,+ groups,+ version = 0,+ preview = null,+ projectId = "p",+ }: EditorProps) {+ const groupSelections = groups ?? (selection ? [selection] : []);+ const narrowed = useCommitPreflightCapabilities({+ projectId,+ enabled: true,+ selection,+ groupSelections,+ previewIframeRef: { current: preview },+ version,+ });+ seen.selection = narrowed.selection;+ seen.groups = narrowed.groupSelections;+ layout.group =+ groupSelections.length > 1+ ? narrowed.groupSelections.map((s) => ({+ key: s.id,+ selection: s,+ element: s.element,+ rect: RECT,+ }))+ : [];+ return (+ <DomEditOverlay+ iframeRef={iframeRef}+ activeCompositionPath={null}+ selection={groupSelections.length > 1 ? null : narrowed.selection}+ groupSelections={groupSelections.length > 1 ? narrowed.groupSelections : []}+ hoverSelection={null}+ onCanvasMouseDown={() => undefined}+ onCanvasPointerMove={() => Promise.resolve(narrowed.selection)}+ onCanvasPointerLeave={() => undefined}+ onSelectionChange={() => undefined}+ onGroupPathOffsetCommit={() => undefined}+ onBoxSizeCommit={() => undefined}+ onRotationCommit={() => undefined}+ {...spies}+ />+ );+ }+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+ const render = (props: EditorProps) => act(() => root.render(<Editor {...props} />));+ render(first);+ return { spies, seen, render, overlay: () => host.firstElementChild as HTMLElement };+}++const answer = (animations: GsapAnimation[]) =>+ parses.fetch.mockResolvedValueOnce({ animations } satisfies Parse);++async function settle() {+ await act(async () => {+ for (let tick = 0; tick < 10; tick++) await Promise.resolve();+ });+}++const fire = (target: Element, type: string, init: MouseEventInit = {}) => {+ act(() => {+ target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, ...init }));+ });+};++const flags = (selection: DomEditSelection | null) => {+ const c = selection?.capabilities;+ return [c?.canApplyManualOffset, c?.canApplyManualSize, c?.canApplyManualRotation];+};++const handles = (overlay: HTMLElement) => ({+ dots: overlay.querySelectorAll(DOTS).length,+ rotate: Boolean(overlay.querySelector(ROTATE)),+});++/** Select `#title` in a file whose parse is `animations` (none queued when null). */+async function select(animations: GsapAnimation[] | null, props: Partial<EditorProps> = {}) {+ if (animations) answer(animations);+ const view = mount({ selection: resolved(element("title")), ...props });+ await settle();+ return view;+}++describe("handles follow what Studio would commit", () => {+ beforeEach(() => {+ HTMLElement.prototype.setPointerCapture = () => undefined;+ __resetForTests();+ parses.fetch.mockReset();+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ act(() => root.unmount());+ document.body.innerHTML = "";+ layout.group = [];+ });++ it("hides every handle on a helper-loop animation and says why", async () => {+ const { seen, overlay, spies } = await select([loop({ x: 120, rotation: 30, width: 320 })]);++ expect(flags(seen.selection)).toEqual([false, false, false]);+ expect(seen.selection?.capabilities.reasonIfDisabled).toBe(+ GSAP_EDIT_BLOCK_COPY["unroll-required"],+ );+ expect(handles(overlay())).toEqual({ dots: 0, rotate: false });+ expect((overlay().querySelector(BOX) as HTMLElement).style.cursor).toBe("default");+ act(() => {+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));+ vi.advanceTimersByTime(CANVAS_NUDGE_COMMIT_DEBOUNCE_MS + 10);+ });+ expect(spies.onPathOffsetCommit).not.toHaveBeenCalled();+ });++ it("hides every handle on a runtime-computed animation and says why", async () => {+ const computed = { provenance: { kind: "runtime-dynamic" } } as never;+ const { seen, overlay } = await select([tween({ x: 120, rotation: 30, width: 320 }, computed)]);++ expect(flags(seen.selection)).toEqual([false, false, false]);+ expect(seen.selection?.capabilities.reasonIfDisabled).toBe(+ GSAP_EDIT_BLOCK_COPY["source-uneditable"],+ );+ expect(handles(overlay())).toEqual({ dots: 0, rotate: false });+ });++ it("keeps every handle on a plain keyframed element, and a drag still commits", async () => {+ const frames = [+ { percentage: 0, properties: { x: 0, y: 0 } },+ { percentage: 100, properties: { x: 200, y: 40 } },+ ];+ const keyframed = { propertyGroup: "position", keyframes: { keyframes: frames } } as never;+ const { seen, overlay, spies } = await select([tween({}, keyframed)]);++ expect(flags(seen.selection)).toEqual([true, true, true]);+ expect(handles(overlay())).toEqual({ dots: 4, rotate: true });+ fire(overlay().querySelector(BOX)!, "pointerdown", { clientX: 150, clientY: 150 });+ fire(overlay(), "pointermove", { clientX: 190, clientY: 150 });+ fire(overlay(), "pointerup", { clientX: 190, clientY: 150 });+ await settle();+ expect(spies.onBlockedMove).not.toHaveBeenCalled();+ expect(spies.onPathOffsetCommit).toHaveBeenCalledTimes(1);+ });++ it("keeps the handles of an element a class tween animates, as the commit does", async () => {+ const card = element("card-1", "card");+ const preview = livePreview([card], { y: 40 });+ const stagger = tween({ y: 40 }, { targetSelector: ".card", method: "from" } as never);+ const selection = resolved(card);+ const { seen, overlay } = await select([stagger], { selection, preview });++ expect(flags(seen.selection)).toEqual([true, true, true]);+ expect(handles(overlay()).dots).toBe(4);+ const commitList = getAnimationsForElement(+ [stagger],+ { id: "card-1", selector: "#card-1" },+ card,+ );+ const preflightOnly = { preflightOnly: true };+ const commit = tryGsapDragIntercept(+ selection,+ { x: 0, y: 0 },+ commitList,+ preview,+ vi.fn(),+ undefined,+ preflightOnly,+ );+ expect(await commit).toEqual({ status: "persisted" });+ });++ it("shows no handles and stays silent on a press while the check is still running", async () => {+ parses.fetch.mockReturnValue(new Promise<Parse>(() => undefined));+ const { seen, overlay, spies } = await select(null);++ expect(flags(seen.selection)).toEqual([false, false, false]);+ expect(seen.selection?.capabilities.commitCheckPending).toBe(true);+ expect(handles(overlay())).toEqual({ dots: 0, rotate: false });+ fire(overlay().querySelector(BOX)!, "pointerdown", { clientX: 150, clientY: 150 });+ expect(spies.onBlockedMove).not.toHaveBeenCalled();+ });++ it("gives a plain element in a file with no animations its handles after one read", async () => {+ const { seen, overlay, render } = await select([]);++ expect(flags(seen.selection)).toEqual([true, true, true]);+ expect(handles(overlay()).dots).toBe(4);+ render({ selection: resolved(element("subtitle")) });+ expect(flags(seen.selection)).toEqual([true, true, true]);+ expect(parses.fetch).toHaveBeenCalledTimes(1);+ });++ it("asks again after a failed read instead of keeping the failure", async () => {+ parses.fetch.mockResolvedValueOnce(null);+ const { seen, render } = await select(null);+ const title = seen.selection!.element;+ expect(flags(seen.selection)[0]).toBe(false);++ answer([]);+ render({ selection: null });+ render({ selection: resolved(title) });+ await settle();+ expect(parses.fetch).toHaveBeenCalledTimes(2);+ expect(flags(seen.selection)[0]).toBe(true);+ });++ it("re-checks when the animations change, keeping the last answer until the new one lands", async () => {+ const selection = resolved(element("title"));+ const { seen, render } = await select([tween({ x: 120 })], { selection });+ expect(flags(seen.selection)[0]).toBe(true);++ let land: (parse: Parse) => void = () => undefined;+ parses.fetch.mockReturnValueOnce(new Promise<Parse>((resolve) => (land = resolve)));+ render({ selection, version: 1 });+ await settle();+ // The save re-resolves the selection while the new read is still in flight.+ render({ selection: resolved(selection.element), version: 1 });+ expect(flags(seen.selection)[0]).toBe(true);+ await act(async () => land({ animations: [loop({ x: 120 })] }));+ await settle();+ expect(flags(seen.selection)[0]).toBe(false);+ expect(parses.fetch).toHaveBeenCalledTimes(2);+ });++ it("keeps the last answer when a re-check read fails, and takes the next good one", async () => {+ const selection = resolved(element("title"));+ const { seen, render } = await select([], { selection });+ expect(flags(seen.selection)[0]).toBe(true);++ parses.fetch.mockResolvedValueOnce(null);+ render({ selection, version: 1 });+ await settle();+ let land: (parse: Parse) => void = () => undefined;+ parses.fetch.mockReturnValueOnce(new Promise<Parse>((resolve) => (land = resolve)));+ render({ selection: resolved(selection.element), version: 1 });+ await settle();+ expect(parses.fetch).toHaveBeenCalledTimes(3);+ expect(flags(seen.selection)[0]).toBe(true);+ expect(seen.selection?.capabilities.commitCheckPending).toBeUndefined();++ await act(async () => land({ animations: [loop({ x: 120 })] }));+ await settle();+ expect(flags(seen.selection)[0]).toBe(false);+ });++ it("checks another project's file against that project's own parse", async () => {+ const { seen, render } = await select([loop({ x: 120 })], { projectId: "a" });+ const title = seen.selection!.element;+ expect(flags(seen.selection)[0]).toBe(false);++ answer([]);+ render({ selection: resolved(title), projectId: "b" });+ await settle();+ expect(parses.fetch).toHaveBeenLastCalledWith("b", "index.html");+ expect(flags(seen.selection)[0]).toBe(true);+ });++ it("refuses a group move carried by one shared tween, while a single member stays movable", async () => {+ const dots = [element("dot-1", "dot"), element("dot-2", "dot")];+ const preview = livePreview(dots, { y: 40 });+ const stagger = tween({ y: 40 }, { targetSelector: ".dot", method: "from" } as never);+ const [a, b] = dots.map(resolved);+ const { seen, overlay, spies, render } = await select([stagger], {+ selection: a!,+ groups: [a!, b!],+ preview,+ });++ expect(seen.groups.map((s) => flags(s)[0])).toEqual([false, false]);+ expect(seen.groups[0]?.capabilities.reasonIfDisabled).toBe(+ GSAP_EDIT_BLOCK_COPY["source-uneditable"],+ );+ fire(overlay().querySelector(BOX)!, "pointerdown", { clientX: 150, clientY: 150 });+ expect(spies.onBlockedMove).toHaveBeenCalledTimes(1);+ const commitList = getAnimationsForElement(+ [stagger],+ { id: "dot-1", selector: "#dot-1" },+ dots[0],+ );+ const groupPreflight = { preflightOnly: true, group: true };+ const commit = tryGsapDragIntercept(+ a!,+ { x: 0, y: 0 },+ commitList,+ preview,+ vi.fn(),+ undefined,+ groupPreflight,+ );+ expect(await commit).toMatchObject({+ status: "blocked",+ detail: "live-position-no-source-tween",+ });++ render({ selection: a!, preview });+ expect(flags(seen.selection)[0]).toBe(true);+ });++ it("toasts once on the primary press of a blocked element, before any travel", async () => {+ const { overlay, spies } = await select([loop({ x: 120 })]);+ const box = overlay().querySelector(BOX)!;++ fire(box, "pointerdown", { button: 2, clientX: 150, clientY: 150 });+ fire(overlay(), "pointerup", { button: 2 });+ expect(spies.onBlockedMove).not.toHaveBeenCalled();+ fire(box, "pointerdown", { clientX: 150, clientY: 150 });+ expect(spies.onBlockedMove).toHaveBeenCalledTimes(1);+ expect(spies.onBlockedMove.mock.calls[0]![0].capabilities.reasonIfDisabled).toBe(+ GSAP_EDIT_BLOCK_COPY["unroll-required"],+ );+ fire(overlay(), "pointermove", { clientX: 200, clientY: 150 });+ fire(overlay(), "pointerup", { clientX: 200, clientY: 150 });+ expect(spies.onBlockedMove).toHaveBeenCalledTimes(1);+ expect(spies.onManualDragStart).not.toHaveBeenCalled();+ expect(spies.onPathOffsetCommit).not.toHaveBeenCalled();+ });++ it("narrows each group member on its own and toasts the blocked one on a group press", async () => {+ const a = resolved(element("a"));+ const b = resolved(element("b"));+ const { seen, overlay, spies } = await select([loop({ x: 120 }, "#a")], {+ selection: a,+ groups: [a, b],+ });++ expect(seen.groups.map((s) => flags(s)[0])).toEqual([false, true]);+ fire(overlay().querySelector(BOX)!, "pointerdown", { clientX: 150, clientY: 150 });+ expect(spies.onBlockedMove).toHaveBeenCalledTimes(1);+ expect(spies.onBlockedMove.mock.calls[0]![0].element).toBe(a.element);+ expect(spies.onManualDragStart).not.toHaveBeenCalled();+ });++ it.each([+ ["rotation", loop({ rotation: 90 }), [true, true, false], { dots: 4, rotate: false }],+ ["resize", loop({ width: 320, height: 90 }), [true, false, true], { dots: 0, rotate: true }],+ ])(+ "narrows only %s when only that channel is a helper's",+ async (_, animation, expected, shown) => {+ const { seen, overlay } = await select([animation]);+ expect(flags(seen.selection)).toEqual(expected);+ expect(handles(overlay())).toEqual(shown);+ },+ );+});diff --git a/packages/studio/src/components/editor/domEditOverlayGestures.ts b/packages/studio/src/components/editor/domEditOverlayGestures.tsindex 34d6519c19..adc280fd16 100644--- a/packages/studio/src/components/editor/domEditOverlayGestures.ts+++ b/packages/studio/src/components/editor/domEditOverlayGestures.ts@@ -102,7 +102,6 @@ export interface BlockedMoveState {pointerId: number;startX: number;startY: number;- notified: boolean;}export type FocusableDomEditOverlay = {diff --git a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts b/packages/studio/src/components/editor/domEditOverlayStartGesture.tsindex 390e05e66e..8cba144431 100644--- a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts+++ b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts@@ -35,6 +35,15 @@ import { collectSnapContext, buildExcludeElements } from "./snapTargetCollectionimport { logResize, resetResizeMoveLog } from "../../utils/resizeDebug";import { logDrag, readDragPositions, resetDragMoveLog } from "../../utils/dragDebug";+export function notifyBlockedPress(+ e: React.PointerEvent<HTMLElement>,+ opts: UseDomEditOverlayGesturesOptions,+ selection: DomEditSelection,+): void {+ if (e.button !== 0 || selection.capabilities.commitCheckPending) return;+ opts.onBlockedMoveRef.current(selection);+}+export function startGroupDrag(e: React.PointerEvent<HTMLElement>,opts: UseDomEditOverlayGesturesOptions,@@ -48,7 +57,7 @@ export function startGroupDrag(if (blockedSelection) {e.preventDefault();e.stopPropagation();- opts.onBlockedMoveRef.current(blockedSelection);+ notifyBlockedPress(e, opts, blockedSelection);return false;}diff --git a/packages/studio/src/components/editor/domEditingTypes.ts b/packages/studio/src/components/editor/domEditingTypes.tsindex c61751fd8c..adfe2fe5d3 100644--- a/packages/studio/src/components/editor/domEditingTypes.ts+++ b/packages/studio/src/components/editor/domEditingTypes.ts@@ -61,6 +61,7 @@ export interface DomEditCapabilities {canApplyManualSize: boolean;canApplyManualRotation: boolean;reasonIfDisabled?: string;+ commitCheckPending?: boolean;}export interface DomEditTextField {diff --git a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts b/packages/studio/src/components/editor/useDomEditOverlayGestures.tsindex b31b16f3a2..7cad80a20f 100644--- a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts+++ b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts@@ -45,6 +45,7 @@ import {import { resolveCenterResizeSize } from "./domEditResizeLocal";import { resolveResizeDraftRect } from "./resizeDraft";import {+ notifyBlockedPress,startGesture as _startGesture,startGroupDrag as _startGroupDrag,} from "./domEditOverlayStartGesture";@@ -103,6 +104,15 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu},) => _startGesture(kind, e, opts, options);+ // A press on a box that cannot move says why at once.+ const startBlockedMove = (e: React.PointerEvent<HTMLElement>, selection: DomEditSelection) => {+ e.preventDefault();+ e.stopPropagation();+ e.currentTarget.setPointerCapture(e.pointerId);+ opts.blockedMoveRef.current = { pointerId: e.pointerId, startX: e.clientX, startY: e.clientY };+ notifyBlockedPress(e, opts, selection);+ };+const moveGroupDrag = createGroupDragMover(opts, setDraftGroupOverlayItems);// fallow-ignore-next-line complexity@@ -116,13 +126,11 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestuopts.onCanvasPointerMoveRef.current(e, { preferClipAncestor: false });}- if (blockedMove && sel) {+ if (blockedMove) {const dx = e.clientX - blockedMove.startX;const dy = e.clientY - blockedMove.startY;- if (!blockedMove.notified && Math.hypot(dx, dy) >= BLOCKED_MOVE_THRESHOLD_PX) {- blockedMove.notified = true;+ if (Math.hypot(dx, dy) >= BLOCKED_MOVE_THRESHOLD_PX) {opts.suppressNextBoxClickRef.current = true;- opts.onBlockedMoveRef.current(sel);}return;}@@ -545,5 +553,12 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestuopts.rafPausedRef.current = false;};- return { startGesture, startGroupDrag, onPointerMove, onPointerUp, clearPointerState };+ return {+ startGesture,+ startGroupDrag,+ startBlockedMove,+ onPointerMove,+ onPointerUp,+ clearPointerState,+ };}diff --git a/packages/studio/src/hooks/gsapEditOutcome.ts b/packages/studio/src/hooks/gsapEditOutcome.tsindex 71f4cf0ab7..1459f4e8ff 100644--- a/packages/studio/src/hooks/gsapEditOutcome.ts+++ b/packages/studio/src/hooks/gsapEditOutcome.ts@@ -45,7 +45,7 @@ export type GsapEditOutcome =}| { status: "blocked"; reason: GsapEditBlockReason; detail?: GsapEditBlockDetail };-const COPY: Record<GsapEditBlockReason, string> = {+export const GSAP_EDIT_BLOCK_COPY: Record<GsapEditBlockReason, string> = {"no-selector": "This layer needs a stable selector before Studio can save the edit.","unroll-required":"This motion comes from a helper or loop. Choose Unroll to edit it explicitly.",@@ -57,7 +57,7 @@ export class GsapEditBlockedError extends Error {readonly reason: GsapEditBlockReason,readonly detail?: GsapEditBlockDetail,) {- super(COPY[reason]);+ super(GSAP_EDIT_BLOCK_COPY[reason]);this.name = "GsapEditBlockedError";}}diff --git a/packages/studio/src/hooks/gsapElementMatch.ts b/packages/studio/src/hooks/gsapElementMatch.tsnew file mode 100644index 0000000000..3e8d571d96--- /dev/null+++ b/packages/studio/src/hooks/gsapElementMatch.ts@@ -0,0 +1,38 @@+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";++interface GsapElementTarget {+ id?: string | null;+ selector?: string | null;+}++/**+ * Tweens whose target addresses the element: by id, by its selection selector, as one part of a+ * group selector, or, given the live element, by any selector part the element matches.+ */+export function getAnimationsForElement(+ animations: GsapAnimation[],+ target: GsapElementTarget,+ element?: Element | null,+): GsapAnimation[] {+ const matchers = new Set<string>();+ if (target.id) matchers.add(`#${target.id}`);+ if (target.selector) matchers.add(target.selector);+ if (matchers.size === 0 && !element) return [];+ return animations.filter((a) =>+ a.targetSelector.split(",").some((part) => {+ const trimmed = part.trim();+ if (!trimmed) return false;+ if (matchers.has(trimmed)) return true;+ const lastSimple = trimmed.split(/\s+/).pop();+ if (lastSimple && matchers.has(lastSimple)) return true;+ if (element) {+ try {+ if (element.matches(trimmed)) return true;+ } catch {+ return false;+ }+ }+ return false;+ }),+ );+}diff --git a/packages/studio/src/hooks/gsapResizeIntercept.ts b/packages/studio/src/hooks/gsapResizeIntercept.tsindex 9353213dba..2a008bd1af 100644--- a/packages/studio/src/hooks/gsapResizeIntercept.ts+++ b/packages/studio/src/hooks/gsapResizeIntercept.ts@@ -5,7 +5,7 @@* frame can't jump. Split from gsapRuntimeBridge, which owns the shared* group-tween resolution used by the drag/resize/rotate intercepts.*/-import type { GsapAnimation, PropertyGroupName } from "@hyperframes/core/gsap-parser";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditingTypes";import { clearStudioBoxSize } from "../components/editor/manualEdits";import {@@ -14,7 +14,6 @@ import {} from "../components/editor/manualEditsTypes";import { setElementGsapPosition, setElementGsapScale } from "../utils/elementGsap";import { usePlayerStore } from "../player/store/playerStore";-import { hasNonHoldTweenForElement } from "./gsapRuntimeKeyframes";import { readAllAnimatedProperties, readGsapProperty } from "./gsapRuntimeReaders";import {commitStaticGsapPosition,@@ -35,11 +34,8 @@ import { isInstantHold, selectorFromSelection, writeTargetSelector } from "./gsaimport { roundTo3 } from "../utils/rounding";import { resolveGroupTween } from "./gsapRuntimeBridge";import { logResize } from "../utils/resizeDebug";-import {- animationWritesAnyProperty,- directEditOutcomeForProperties,- type GsapEditOutcome,-} from "./gsapEditOutcome";+import { animationWritesAnyProperty, type GsapEditOutcome } from "./gsapEditOutcome";+import { preflightGsapResizeIntercept, resizeRoute } from "./gsapResizePreflight";const IDENTITY_ONE_PROPS = new Set(["opacity", "autoAlpha", "scale", "scaleX", "scaleY"]);@@ -103,17 +99,12 @@ export async function tryGsapResizeIntercept(fetchFallbackAnimations?: () => Promise<GsapAnimation[]>,): Promise<GsapEditOutcome> {const fetchedAnimations = fetchFallbackAnimations ? await fetchFallbackAnimations() : [];- const allKnownAnimations = [...animations, ...fetchedAnimations];- // If the element already has a scale-group tween, resize should modify scale- // (the user is resizing something whose visual size is driven by scale).- // Otherwise, use the size group (width/height).- const hasScaleGroup = allKnownAnimations.some((a) => a.propertyGroup === "scale");- const resizeGroup: PropertyGroupName = hasScaleGroup ? "scale" : "size";- const resizeProperties =- resizeGroup === "scale" ? new Set(["scale", "scaleX", "scaleY"]) : new Set(["width", "height"]);- const editability = directEditOutcomeForProperties(allKnownAnimations, resizeProperties);- if (editability.status === "blocked") return editability;- const workingAnimations = animations.length > 0 ? animations : fetchedAnimations;+ const outcome = preflightGsapResizeIntercept(selection, animations, iframe, fetchedAnimations);+ if (outcome.status === "blocked") return outcome;+ const { resizeGroup, resizeProperties, workingAnimations } = resizeRoute(+ animations,+ fetchedAnimations,+ );// The initial ownership fetch already supplied the complete parse. Only retain// the fetch callback when a legacy mixed tween may be split and must then be// re-read; otherwise resolveGroupTween would perform the same network read twice.@@ -132,20 +123,8 @@ export async function tryGsapResizeIntercept(resolved?.anim && animationWritesAnyProperty(resolved.anim, resizeProperties)? resolved.anim: null;- const liveSelector = selectorFromSelection(selection);- const hasLiveResizeTween = liveSelector- ? hasNonHoldTweenForElement(iframe, liveSelector, undefined, [...resizeProperties])- : false;- if (!anim && hasLiveResizeTween) {- // Third twin of the position/rotation cases: a live tween with no source match.- return {- status: "blocked",- reason: "source-uneditable",- detail: "live-resize-no-source-tween",- };- }logResize("intercept-enter", {- hasScaleGroup,+ hasScaleGroup: resizeGroup === "scale",resizeGroup,animMethod: anim?.method ?? null,animId: anim?.id ?? null,diff --git a/packages/studio/src/hooks/gsapResizePreflight.ts b/packages/studio/src/hooks/gsapResizePreflight.tsnew file mode 100644index 0000000000..4a98133433--- /dev/null+++ b/packages/studio/src/hooks/gsapResizePreflight.ts@@ -0,0 +1,56 @@+import type { GsapAnimation, PropertyGroupName } from "@hyperframes/core/gsap-parser";+import type { DomEditSelection } from "../components/editor/domEditingTypes";+import { hasNonHoldTweenForElement } from "./gsapRuntimeKeyframes";+import { selectorFromSelection } from "./gsapShared";+import {+ animationWritesAnyProperty,+ directEditOutcomeForProperties,+ type GsapEditOutcome,+} from "./gsapEditOutcome";++export function resizeRoute(animations: GsapAnimation[], fetchedAnimations: GsapAnimation[]) {+ const allKnownAnimations = [...animations, ...fetchedAnimations];+ // If the element already has a scale-group tween, resize should modify scale+ // (the user is resizing something whose visual size is driven by scale).+ // Otherwise, use the size group (width/height).+ const hasScaleGroup = allKnownAnimations.some((a) => a.propertyGroup === "scale");+ const resizeGroup: PropertyGroupName = hasScaleGroup ? "scale" : "size";+ const resizeProperties =+ resizeGroup === "scale" ? new Set(["scale", "scaleX", "scaleY"]) : new Set(["width", "height"]);+ const workingAnimations = animations.length > 0 ? animations : fetchedAnimations;+ return { allKnownAnimations, resizeGroup, resizeProperties, workingAnimations };+}++/** The resize commit's refusal rule, also run ahead of time to hide the resize handles. */+export function preflightGsapResizeIntercept(+ selection: DomEditSelection,+ animations: GsapAnimation[],+ iframe: HTMLIFrameElement | null,+ fetchedAnimations: GsapAnimation[] = [],+): GsapEditOutcome {+ const { allKnownAnimations, resizeGroup, resizeProperties, workingAnimations } = resizeRoute(+ animations,+ fetchedAnimations,+ );+ const editability = directEditOutcomeForProperties(allKnownAnimations, resizeProperties);+ if (editability.status === "blocked") return editability;+ const hasSourceTween = workingAnimations.some(+ (a) =>+ (a.propertyGroup === resizeGroup || !a.propertyGroup) &&+ animationWritesAnyProperty(a, resizeProperties),+ );+ const liveSelector = selectorFromSelection(selection);+ if (+ !hasSourceTween &&+ liveSelector &&+ hasNonHoldTweenForElement(iframe, liveSelector, undefined, [...resizeProperties])+ ) {+ // Third twin of the position/rotation cases: a live tween with no source match.+ return {+ status: "blocked",+ reason: "source-uneditable",+ detail: "live-resize-no-source-tween",+ };+ }+ return { status: "persisted" };+}diff --git a/packages/studio/src/hooks/gsapRuntimeBridge.ts b/packages/studio/src/hooks/gsapRuntimeBridge.tsindex e66ed6335a..08efd9fad0 100644--- a/packages/studio/src/hooks/gsapRuntimeBridge.ts+++ b/packages/studio/src/hooks/gsapRuntimeBridge.ts@@ -33,6 +33,7 @@ import {readGsapPositionFromIframe,} from "./gsapPositionDetection";import { hasNonHoldTweenForElement } from "./gsapRuntimeKeyframes";+import { getAnimationsForElement } from "./gsapElementMatch";import {animationWritesAnyProperty,directEditOutcomeForProperties,@@ -133,17 +134,28 @@ export type { GsapDragCommitCallbacks };* Returns an explicit persisted/blocked outcome. Callers must reject blocked* outcomes so the gesture layer restores its runtime and overlay drafts.*/-// fallow-ignore-next-line complexityasync function preflightGsapDragIntercept(selection: DomEditSelection,animations: GsapAnimation[],iframe: HTMLIFrameElement | null,fetchFallbackAnimations?: () => Promise<GsapAnimation[]>,+ group?: boolean,): Promise<GsapEditOutcome> {+ const fetchedAnimations = fetchFallbackAnimations ? await fetchFallbackAnimations() : [];+ return dragEditOutcome(selection, animations, iframe, fetchedAnimations, group);+}++/** The move commit's refusal rule, also run ahead of time to hide the move handles. */+// fallow-ignore-next-line complexity+export function dragEditOutcome(+ selection: DomEditSelection,+ animations: GsapAnimation[],+ iframe: HTMLIFrameElement | null,+ fetchedAnimations: GsapAnimation[] = [],+ group = false,+): GsapEditOutcome {const selector = selectorFromSelection(selection);if (!selector) return { status: "blocked", reason: "no-selector" };-- const fetchedAnimations = fetchFallbackAnimations ? await fetchFallbackAnimations() : [];// The fallback API currently represents both a definitive empty parse and an// exhausted fetch failure as `[]`. Keep the selected cache in the preflight// set as well: ignoring it would let a transient fetch failure bypass helper /@@ -152,7 +164,12 @@ async function preflightGsapDragIntercept(const editability = directEditOutcomeForProperties(allKnownAnimations, POSITION_CHANNEL_SET);if (editability.status === "blocked") return editability;const sourceAnimations = fetchedAnimations.length > 0 ? fetchedAnimations : animations;- const posAnim = findGsapPositionAnimation(sourceAnimations, selector);+ // In a group only a tween naming this member by id or by its own selector counts,+ // so a class tween shared with id-selected members cannot take one member's write.+ const positionSources = group+ ? getAnimationsForElement(sourceAnimations, { id: selection.id ?? null, selector })+ : sourceAnimations;+ const posAnim = findGsapPositionAnimation(positionSources, selector);const hasLivePosition = hasNonHoldTweenForElement(iframe, selector, undefined, POSITION_CHANNELS);if (hasLivePosition && !posAnim) {@@ -177,7 +194,12 @@ export async function tryGsapDragIntercept(iframe: HTMLIFrameElement | null,commitMutation: GsapDragCommitCallbacks["commitMutation"],fetchFallbackAnimations?: () => Promise<GsapAnimation[]>,- options?: { altKey?: boolean; preflightOnly?: boolean; preflightPassed?: boolean },+ options?: {+ altKey?: boolean;+ preflightOnly?: boolean;+ preflightPassed?: boolean;+ group?: boolean;+ },): Promise<GsapEditOutcome> {if (!options?.preflightPassed) {const preflight = await preflightGsapDragIntercept(@@ -185,6 +207,7 @@ export async function tryGsapDragIntercept(animations,iframe,fetchFallbackAnimations,+ options?.group,);if (preflight.status === "blocked" || options?.preflightOnly) return preflight;}@@ -312,6 +335,41 @@ export { readGsapProperty, readAllAnimatedProperties };// ── Identity-prop synthesis ───────────────────────────────────────────────+/** The rotation commit's refusal rule, also run ahead of time to hide the rotate handle. */+export function preflightGsapRotationIntercept(+ selection: DomEditSelection,+ animations: GsapAnimation[],+ iframe: HTMLIFrameElement | null,+ fetchedAnimations: GsapAnimation[] = [],+): GsapEditOutcome {+ const liveSelector = selectorFromSelection(selection);+ if (!(liveSelector ?? writeTargetSelector(selection))) {+ return { status: "blocked", reason: "no-selector" };+ }+ const editability = directEditOutcomeForProperties(+ [...animations, ...fetchedAnimations],+ ROTATION_CHANNEL_SET,+ );+ if (editability.status === "blocked") return editability;+ const workingAnimations = animations.length > 0 ? animations : fetchedAnimations;+ const hasSourceTween = workingAnimations.some((a) =>+ animationWritesAnyProperty(a, ROTATION_CHANNEL_SET),+ );+ if (+ !hasSourceTween &&+ liveSelector &&+ hasNonHoldTweenForElement(iframe, liveSelector, undefined, ROTATION_CHANNELS)+ ) {+ // Rotation twin of the position case above: live tween, no source match.+ return {+ status: "blocked",+ reason: "source-uneditable",+ detail: "live-rotation-no-source-tween",+ };+ }+ return { status: "persisted" };+}+export async function tryGsapRotationIntercept(selection: DomEditSelection,angle: number,@@ -320,16 +378,11 @@ export async function tryGsapRotationIntercept(commitMutation: GsapDragCommitCallbacks["commitMutation"],fetchFallbackAnimations?: () => Promise<GsapAnimation[]>,): Promise<GsapEditOutcome> {- const selector = selectorFromSelection(selection) ?? writeTargetSelector(selection);- if (!selector) return { status: "blocked", reason: "no-selector" };-const fetchedAnimations = fetchFallbackAnimations ? await fetchFallbackAnimations() : [];+ const outcome = preflightGsapRotationIntercept(selection, animations, iframe, fetchedAnimations);+ if (outcome.status === "blocked") return outcome;+ const selector = (selectorFromSelection(selection) ?? writeTargetSelector(selection))!;const workingAnimations = animations.length > 0 ? animations : fetchedAnimations;- const editability = directEditOutcomeForProperties(- [...animations, ...fetchedAnimations],- ROTATION_CHANNEL_SET,- );- if (editability.status === "blocked") return editability;const postSplitFetch = workingAnimations.some((animation) => !animation.propertyGroup)? fetchFallbackAnimations: undefined;@@ -354,19 +407,6 @@ export async function tryGsapRotationIntercept(workingAnimations.find((a) => animationWritesAnyProperty(a, ROTATION_CHANNEL_SET)) ?? null;}- const liveSelector = selectorFromSelection(selection);- const hasLiveRotationTween = liveSelector- ? hasNonHoldTweenForElement(iframe, liveSelector, undefined, ROTATION_CHANNELS)- : false;- if (!anim && hasLiveRotationTween) {- // Rotation twin of the position case above: live tween, no source match.- return {- status: "blocked",- reason: "source-uneditable",- detail: "live-rotation-no-source-tween",- };- }-// `angle` is the ABSOLUTE target rotation resolved by the gesture (gsap base +// pointer sweep) or the inspector — so it IS the new rotation. No base re-add: the// gesture's live preview already gsap.set this value (single source of truth).diff --git a/packages/studio/src/hooks/keyframeCacheAstLoad.ts b/packages/studio/src/hooks/keyframeCacheAstLoad.tsindex 036b55bf48..9bafb53adf 100644--- a/packages/studio/src/hooks/keyframeCacheAstLoad.ts+++ b/packages/studio/src/hooks/keyframeCacheAstLoad.ts@@ -53,12 +53,15 @@ function hasAnimations(value: unknown): value is ParsedGsapAnimations {*/const inFlightParses = new Map<string, Promise<ParsedGsapAnimations | null>>();+export const parseCacheKey = (projectId: string, sourceFile: string) =>+ `${projectId}|${sourceFile}`;+export function fetchParsedAnimations(projectId: string,sourceFile: string,options: { fresh?: boolean } = {},): Promise<ParsedGsapAnimations | null> {- const key = `${projectId}|${sourceFile}`;+ const key = parseCacheKey(projectId, sourceFile);if (options.fresh) inFlightParses.delete(key);const inFlight = inFlightParses.get(key);if (inFlight) return inFlight;diff --git a/packages/studio/src/hooks/useCommitPreflightCapabilities.ts b/packages/studio/src/hooks/useCommitPreflightCapabilities.tsnew file mode 100644index 0000000000..d08b2518e3--- /dev/null+++ b/packages/studio/src/hooks/useCommitPreflightCapabilities.ts@@ -0,0 +1,147 @@+import { useEffect, useMemo, useRef, useState } from "react";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";+import type { DomEditSelection } from "../components/editor/domEditingTypes";+import { dragEditOutcome, preflightGsapRotationIntercept } from "./gsapRuntimeBridge";+import { preflightGsapResizeIntercept } from "./gsapResizePreflight";+import { GSAP_EDIT_BLOCK_COPY, type GsapEditOutcome } from "./gsapEditOutcome";+import { fetchParsedAnimations, parseCacheKey } from "./keyframeCacheAstLoad";+import {+ gsapSourceFileForSelection,+ selectElementAnimationsOrRetry,+} from "./useGsapAnimationFetchFallback";++interface CommitPreflight {+ offset: GsapEditOutcome;+ size: GsapEditOutcome;+ rotation: GsapEditOutcome;+}++function runCommitPreflights(+ selection: DomEditSelection,+ fileAnimations: GsapAnimation[],+ iframe: HTMLIFrameElement | null,+ group: boolean,+): CommitPreflight {+ const target = { id: selection.id ?? null, selector: selection.selector ?? null };+ const matched = selectElementAnimationsOrRetry(+ { animations: fileAnimations },+ target,+ selection.element,+ );+ // A file the server parsed with no tweens at all is a definitive answer here.+ const animations = matched.kind === "resolved" ? matched.animations : [];+ return {+ offset: dragEditOutcome(selection, animations, iframe, [], group),+ size: preflightGsapResizeIntercept(selection, animations, iframe),+ rotation: preflightGsapRotationIntercept(selection, animations, iframe),+ };+}++// Studio can hand a narrowed copy back as a new selection; narrowing starts from the resolved one.+const resolvedSelections = new WeakMap<DomEditSelection, DomEditSelection>();++const resolvedOf = (selection: DomEditSelection) => resolvedSelections.get(selection) ?? selection;++const MANUAL_FLAGS = [+ ["canApplyManualOffset", "offset"],+ ["canApplyManualSize", "size"],+ ["canApplyManualRotation", "rotation"],+] as const;++/** Null when the commit would go through; "" while the check is still running. */+function refusal(preflight: CommitPreflight | null, check: keyof CommitPreflight): string | null {+ const outcome = preflight?.[check];+ if (outcome?.status === "persisted") return null;+ return outcome ? GSAP_EDIT_BLOCK_COPY[outcome.reason] : "";+}++/** Closes each manual flag whose commit Studio would refuse, and says why. */+function narrowCapabilities(+ selection: DomEditSelection,+ preflight: CommitPreflight | null,+): DomEditSelection {+ const resolved = resolvedOf(selection);+ const next = { ...resolved.capabilities };+ const reasons: string[] = [];+ for (const [flag, check] of MANUAL_FLAGS) {+ const reason = refusal(preflight, check);+ if (!next[flag] || reason === null) continue;+ next[flag] = false;+ reasons.push(reason);+ }+ if (reasons.length === 0) return resolved;+ next.reasonIfDisabled = reasons.find(Boolean) || next.reasonIfDisabled;+ if (!preflight) next.commitCheckPending = true;+ const narrowed = { ...resolved, capabilities: next };+ resolvedSelections.set(narrowed, resolved);+ return narrowed;+}++interface FileParse {+ version: number;+ animations: GsapAnimation[] | null;+}++/**+ * The one place selection capabilities learn what the GSAP commit would refuse,+ * so chrome, nudge and group gates never offer an edit that snaps back.+ */+export function useCommitPreflightCapabilities({+ projectId,+ enabled,+ selection,+ groupSelections,+ previewIframeRef,+ version,+}: {+ projectId: string | null;+ enabled: boolean;+ selection: DomEditSelection | null;+ groupSelections: DomEditSelection[];+ previewIframeRef: React.RefObject<HTMLIFrameElement | null>;+ version: number;+}) {+ // One parse per project file and version; the last good parse answers while a newer one loads.+ const parsesRef = useRef(new Map<string, FileParse>());+ const [parseTick, setParseTick] = useState(0);++ useEffect(() => {+ if (!enabled || !projectId) return;+ const targets = selection ? [selection, ...groupSelections] : groupSelections;+ for (const file of new Set(targets.map(gsapSourceFileForSelection))) {+ const key = parseCacheKey(projectId, file);+ const known = parsesRef.current.get(key);+ if (known?.version === version) continue;+ parsesRef.current.set(key, { version, animations: known?.animations ?? null });+ void fetchParsedAnimations(projectId, file).then((parsed) => {+ if (parsesRef.current.get(key)?.version !== version) return;+ if (parsed) {+ parsesRef.current.set(key, { version, animations: parsed.animations });+ setParseTick((tick) => tick + 1);+ return;+ }+ // A failed read is not an answer: keep the last one, and the next selection asks again.+ if (known?.animations) parsesRef.current.set(key, known);+ else parsesRef.current.delete(key);+ });+ }+ }, [enabled, projectId, selection, groupSelections, version]);++ return useMemo(() => {+ void parseTick;+ if (!enabled || !projectId) return { selection, groupSelections };+ const group = groupSelections.length > 1;+ const narrow = (target: DomEditSelection) => {+ const file = gsapSourceFileForSelection(target);+ const animations = parsesRef.current.get(parseCacheKey(projectId, file))?.animations;+ const preflight = animations+ ? runCommitPreflights(resolvedOf(target), animations, previewIframeRef.current, group)+ : null;+ return narrowCapabilities(target, preflight);+ };+ return {+ selection: selection && narrow(selection),+ groupSelections: groupSelections.map(narrow),+ };+ }, [enabled, projectId, selection, groupSelections, parseTick, previewIframeRef]);+}diff --git a/packages/studio/src/hooks/useDomEditSession.test.tsx b/packages/studio/src/hooks/useDomEditSession.test.tsxindex 66efe06fc1..ffdbb85b4c 100644--- a/packages/studio/src/hooks/useDomEditSession.test.tsx+++ b/packages/studio/src/hooks/useDomEditSession.test.tsx@@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest";import { shouldUseSdkCutover } from "../utils/sdkCutover";import type { PatchOperation } from "../utils/sourcePatcher";import type { Composition } from "@hyperframes/sdk";+import type { GsapAnimation } from "@hyperframes/core/gsap-parser";import type { DomEditSelection } from "../components/editor/domEditingTypes";import type { TimelineElement } from "../player";import type { UseDomEditSessionParams } from "./useDomEditSession";@@ -62,6 +63,8 @@ const domEditSelectionRef: { current: DomEditSelection | null } = { current: nulconst domEditGroupSelectionsRef: { current: DomEditSelection[] } = { current: [] };const groupSelectionSpy = vi.fn();const gsapCommitMutation = Object.assign(vi.fn(), { batch: vi.fn() });+const neverParsed = new Promise<{ animations: GsapAnimation[] }>(() => undefined);+const parsedFile = { current: neverParsed };function createSessionParams(overrides: Partial<UseDomEditSessionParams> = {},@@ -166,7 +169,12 @@ vi.mock("./useAskAgentModal", () => ({vi.mock("./useStudioSelectionPublisher", () => ({useStudioSelectionPublisher: () => {},}));-vi.mock("./useGsapTweenCache", () => ({+vi.mock("./keyframeCacheAstLoad", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./keyframeCacheAstLoad")>()),+ fetchParsedAnimations: () => parsedFile.current,+}));+vi.mock("./useGsapTweenCache", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./useGsapTweenCache")>()),useGsapCacheVersion: () => ({ version: 0, bump: vi.fn() }),}));vi.mock("./useGsapScriptCommits", () => ({@@ -413,6 +421,48 @@ describe("bulk segment ease commits", () => {});});+describe("the session hands out selections narrowed to what the GSAP commit accepts", () => {+ it("closes the move of a helper-loop element once its preflight lands", async () => {+ const { useDomEditSession } = await import("./useDomEditSession");+ domEditSelectionRef.current = {+ id: "hero",+ selector: "#hero",+ element: document.createElement("div"),+ sourceFile: "index.html",+ capabilities: {+ canApplyManualOffset: true,+ canApplyManualSize: true,+ canApplyManualRotation: true,+ },+ } as unknown as DomEditSelection;+ const loop = { targetSelector: "#hero", properties: { x: 100 }, provenance: { kind: "loop" } };+ parsedFile.current = Promise.resolve({ animations: [loop as unknown as GsapAnimation] });+ const seen: { selection?: DomEditSelection | null } = {};+ function Probe() {+ seen.selection = useDomEditSession(createSessionParams()).domEditSelection;+ return null;+ }+ const root = createRoot(document.createElement("div"));+ try {+ act(() => root.render(<Probe />));+ expect(seen.selection?.capabilities.canApplyManualOffset).toBe(false);+ await act(async () => {+ for (let tick = 0; tick < 10; tick++) await Promise.resolve();+ });+ expect(seen.selection?.capabilities).toMatchObject({+ canApplyManualOffset: false,+ canApplyManualSize: true,+ canApplyManualRotation: true,+ reasonIfDisabled: expect.stringContaining("helper or loop"),+ });+ } finally {+ domEditSelectionRef.current = null;+ parsedFile.current = neverParsed;+ act(() => root.unmount());+ }+ });+});+// ── Grouping refuses audio ───────────────────────────────────────────────────//// A layout group is a positioned wrapper: it takes the members' bounding box,diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.tsindex 69485ddf2c..abc965be8e 100644--- a/packages/studio/src/hooks/useDomEditSession.ts+++ b/packages/studio/src/hooks/useDomEditSession.ts@@ -19,6 +19,7 @@ import { useDomEditWiring } from "./useDomEditWiring";import { useGsapAwareEditing } from "./useGsapAwareEditing";import { useStudioSelectionPublisher } from "./useStudioSelectionPublisher";import { useKeyframeEaseCommits } from "./useKeyframeEaseCommits";+import { useCommitPreflightCapabilities } from "./useCommitPreflightCapabilities";import type { DomEditSelection } from "../components/editor/domEditingTypes";import { membersForDelete, timelineElementsForDelete } from "./domEditDeleteMembers";import type { RecordEditInput } from "./domEditDeleteMembers";@@ -494,9 +495,17 @@ export function useDomEditSession({});const { handleUpdateSegmentEase, handleUpdateKeyframeEase, handleSetAllKeyframeEases } =useKeyframeEaseCommits({ gsapCommitMutation, domEditSelectionRef });+ const committable = useCommitPreflightCapabilities({+ projectId,+ enabled: gsapCommitMutation !== null,+ selection: domEditSelection,+ groupSelections: domEditGroupSelections,+ previewIframeRef,+ version: gsapCacheVersion,+ });return {- domEditSelection,- domEditGroupSelections,+ domEditSelection: committable.selection,+ domEditGroupSelections: committable.groupSelections,domEditHoverSelection,activeGroupElement,agentModalOpen,diff --git a/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.ts b/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.tsindex edefdcdff9..95e882a951 100644--- a/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.ts+++ b/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.ts@@ -1,3 +1,5 @@+// @vitest-environment happy-dom+import { describe, expect, it } from "vitest";import type { GsapAnimation, ParsedGsap } from "@hyperframes/core/gsap-parser";import {@@ -41,6 +43,16 @@ describe("selectElementAnimationsOrRetry", () => {]);});+ it("matches a class tween through the live element, as the selected-element list does", () => {+ const element = document.createElement("div");+ element.id = "puck-a";+ element.className = "puck";+ const outcome = selectElementAnimationsOrRetry(parsed([anim(".puck")]), target, element);+ expect(outcome.kind === "resolved" && outcome.animations.map((a) => a.targetSelector)).toEqual([+ ".puck",+ ]);+ });+it("resolves to [] (no retry) for a warm parse with no match — element genuinely has no animation", () => {const outcome = selectElementAnimationsOrRetry(parsed([anim("#other")]), target);expect(outcome).toEqual({ kind: "resolved", animations: [] });diff --git a/packages/studio/src/hooks/useGsapAnimationFetchFallback.ts b/packages/studio/src/hooks/useGsapAnimationFetchFallback.tsindex c5e98c60c9..8f4382d529 100644--- a/packages/studio/src/hooks/useGsapAnimationFetchFallback.ts+++ b/packages/studio/src/hooks/useGsapAnimationFetchFallback.ts@@ -49,10 +49,14 @@ export function gsapSourceFileForSelection(selection: DomEditSelection): stringexport function selectElementAnimationsOrRetry(parsed: Pick<ParsedGsap, "animations"> | null,target: { id: string | null; selector: string | null },+ element?: Element | null,): ElementAnimationsOutcome {if (!parsed) return { kind: "fetch-error" };if (parsed.animations.length === 0) return { kind: "cold" };- return { kind: "resolved", animations: getAnimationsForElement(parsed.animations, target) };+ return {+ kind: "resolved",+ animations: getAnimationsForElement(parsed.animations, target, element),+ };}// Retry policy deliberately distinguishes cold parses from hard fetch errors.@@ -61,6 +65,7 @@ async function fetchElementAnimationsWithRetry(projectId: string,gsapSourceFile: string,target: { id: string | null; selector: string | null },+ element: Element,failOnFetchError: boolean,fresh: boolean,): Promise<GsapAnimation[]> {@@ -69,7 +74,7 @@ async function fetchElementAnimationsWithRetry(for (;;) {const parsed = await fetchParsedAnimations(projectId, gsapSourceFile, { fresh });fresh = false;- const outcome = selectElementAnimationsOrRetry(parsed, target);+ const outcome = selectElementAnimationsOrRetry(parsed, target, element);if (outcome.kind === "resolved") return outcome.animations;if (outcome.kind === "fetch-error") {if (errorAttempts >= FETCH_ERROR_RETRIES) {@@ -96,6 +101,7 @@ export function useGsapAnimationFetchFallback(projectId: string | null) {projectId,gsapSourceFileForSelection(selection),target,+ selection.element,options?.failOnFetchError === true,options?.fresh === true,);diff --git a/packages/studio/src/hooks/useGsapAwareEditing.test.tsx b/packages/studio/src/hooks/useGsapAwareEditing.test.tsxindex 4997a10901..07b3095de2 100644--- a/packages/studio/src/hooks/useGsapAwareEditing.test.tsx+++ b/packages/studio/src/hooks/useGsapAwareEditing.test.tsx@@ -300,6 +300,10 @@ describe("useGsapAwareEditing anchored resize", () => {});expect(commitMutation).not.toHaveBeenCalled();expect(mocks.drag).toHaveBeenCalledTimes(2);+ expect(mocks.drag.mock.calls.map((call) => call[6])).toEqual([+ { preflightOnly: true, group: true },+ { preflightOnly: true, group: true },+ ]);expect(makeFetchFallback).toHaveBeenNthCalledWith(1, updates[0]!.selection, {failOnFetchError: true,});diff --git a/packages/studio/src/hooks/useGsapAwareEditing.ts b/packages/studio/src/hooks/useGsapAwareEditing.tsindex ea1e2accd3..b92889dd0f 100644--- a/packages/studio/src/hooks/useGsapAwareEditing.ts+++ b/packages/studio/src/hooks/useGsapAwareEditing.ts@@ -240,7 +240,7 @@ export function useGsapAwareEditing({previewIframeRef.current,coalescedCommit,undefined,- { preflightOnly: true },+ { preflightOnly: true, group: true },);assertGsapEditPersisted(outcome);}),diff --git a/packages/studio/src/hooks/useGsapTweenCache.ts b/packages/studio/src/hooks/useGsapTweenCache.tsindex 1551b9ddf5..255fd886d1 100644--- a/packages/studio/src/hooks/useGsapTweenCache.ts+++ b/packages/studio/src/hooks/useGsapTweenCache.ts@@ -19,58 +19,12 @@ import {type MergeableKeyframe,} from "./gsapTweenSynth";import { fetchParsedAnimations, populateKeyframeCacheFromAst } from "./keyframeCacheAstLoad";+import { getAnimationsForElement } from "./gsapElementMatch";// Re-exported so callers keep importing the GSAP cache surface from one module.export { resolveClipTimingBasis } from "./gsapShared";export { fetchParsedAnimations, resolveSelectorElementIds } from "./keyframeCacheAstLoad";--/** The selected element's identity for matching tweens to it. */-export interface GsapElementTarget {- id?: string | null;- selector?: string | null;-}--/**- * A tween belongs to the selected element when its target selector addresses- * that element — by id (`#id`), by the exact CSS selector the element was- * selected through (`.kicker`), or as one member of a group selector- * (`.clock-face, .clock-hand`, emitted for array/`toArray` targets). Real- * compositions target tweens by class via `querySelector`, so id-only matching- * misses them.- *- * When the live DOM `element` is supplied, each comma-part of a tween's selector- * is also tested with `element.matches(part)` — true CSS semantics — so a- * class/descendant tween shared across elements (e.g. `gsap.from(".dot", {stagger})`)- * is attributed to *every* matching element, not just the one whose exact- * selector string happens to equal the tween's.- */-export function getAnimationsForElement(- animations: GsapAnimation[],- target: GsapElementTarget,- element?: Element | null,-): GsapAnimation[] {- const matchers = new Set<string>();- if (target.id) matchers.add(`#${target.id}`);- if (target.selector) matchers.add(target.selector);- if (matchers.size === 0 && !element) return [];- return animations.filter((a) =>- a.targetSelector.split(",").some((part) => {- const trimmed = part.trim();- if (!trimmed) return false;- if (matchers.has(trimmed)) return true;- const lastSimple = trimmed.split(/\s+/).pop();- if (lastSimple && matchers.has(lastSimple)) return true;- if (element) {- try {- if (element.matches(trimmed)) return true;- } catch {- /* tween selector isn't a valid CSS selector for matches() — skip */- }- }- return false;- }),- );-}+export { getAnimationsForElement } from "./gsapElementMatch";export function useGsapAnimationsForElement(projectId: string | null,