From fdc7d676c49bfc6e084e46f8ae0e08aa3e019cb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Fri, 20 Nov 2026 05:50:24 +0000 Subject: [PATCH] fix(studio): a sealed preview turns a rotated element live and saves the turn on its own route (#8271) * fix(studio): a sealed preview turns a rotated element live and saves the turn on its own route * fix(studio): a sealed rotate regrabbed mid-save cancels to where it started on the frame too * refactor(studio): keep the gesture handlers file under the size limit --- .../core/src/runtime/editingAgent.test.ts | 11 ++ .../core/src/runtime/editingDraft.test.ts | 35 +++++ packages/core/src/runtime/editingDraft.ts | 36 ++++- .../src/runtime/editingGestureStart.test.ts | 19 ++- .../core/src/runtime/editingGestureStart.ts | 32 ++++- packages/core/src/runtime/editingPort.ts | 28 +++- .../editor/domEditOverlayStartGesture.ts | 11 +- .../editor/gsapMoveSealedPreview.test.ts | 129 +++++++++++++++++- .../src/components/editor/previewDrafts.ts | 7 +- .../editor/previewGestureStartRead.test.ts | 6 +- .../editor/previewGestureStartRead.ts | 2 + .../src/components/editor/rotationDraft.ts | 35 ++++- .../editor/useDomEditOverlayGestures.ts | 9 +- .../studio/src/player/lib/previewElements.ts | 18 ++- 14 files changed, 348 insertions(+), 30 deletions(-) diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts index 0e567d5935..fcca6b165c 100644 --- a/packages/core/src/runtime/editingAgent.test.ts +++ b/packages/core/src/runtime/editingAgent.test.ts @@ -408,6 +408,17 @@ describe("installEditingAgent", () => { { drafts: [{ handle: H, translate: { x: 1e6, y: 0 }, size: null }] }, { drafts: [{ handle: H, translate: null, size: { width: -1, height: 2 } }] }, { drafts: [{ handle: H, translate: null, size: { width: 1, height: 2, depth: 3 } }] }, + { drafts: [{ handle: H, translate: null, size: null, rotate: { angle: 1 } }] }, + { drafts: [{ handle: H, translate: null, size: null, rotate: { angle: 1, route: "x" } }] }, + { + drafts: [{ handle: H, translate: null, size: null, rotate: { angle: "1", route: "css" } }], + }, + { + drafts: [{ handle: H, translate: null, size: null, rotate: { angle: 1e6, route: "css" } }], + }, + { + drafts: [{ handle: H, translate: null, size: null, rotate: { angle: NaN, route: "gsap" } }], + }, ].map((params, index) => [ { v: 1, id: 150 + index, kind: "draft", params }, 150 + index, diff --git a/packages/core/src/runtime/editingDraft.test.ts b/packages/core/src/runtime/editingDraft.test.ts index b4f654f1b4..9f53e80f87 100644 --- a/packages/core/src/runtime/editingDraft.test.ts +++ b/packages/core/src/runtime/editingDraft.test.ts @@ -4,6 +4,7 @@ import { handleFor } from "./editingHandles"; afterEach(() => { document.body.innerHTML = ""; + delete (window as { gsap?: unknown }).gsap; }); function card(style: string): { element: HTMLElement; handle: string } { @@ -20,6 +21,40 @@ const shown = (element: HTMLElement) => [...axis.matchAll(/-?[\d.]+px/g)].reduce((sum, [px]) => sum + parseFloat(px), 0), ); +// fails without the fix: a sealed frame never turned the element a rotate gesture drew. +describe("rotation drafts", () => { + const turned = (element: HTMLElement) => element.style.getPropertyValue("rotate"); + + it("turns by the rotate property, leaves the turn to drafts that don't name it, and takes back only it", () => { + const { element, handle } = card("rotate: 5deg; width: 50px"); + const moved = { handle, translate: { x: 5, y: 0 }, size: null }; + drawDrafts([{ ...moved, rotate: { angle: 30, route: "css" } }]); + expect(turned(element)).toBe("30deg"); + drawDrafts([moved]); + expect(turned(element)).toBe("30deg"); + drawDrafts([{ ...moved, rotate: null }]); + expect([turned(element), shown(element)]).toEqual(["5deg", [5, 0]]); + drawDrafts([ + { ...moved, rotate: { angle: 45, route: "css" } }, + { handle, end: "keep" }, + ]); + expect([turned(element), shown(element)]).toEqual(["45deg", [5, 0]]); + }); + + it("turns by the frame's own GSAP and puts its rotation back on a cancel", () => { + const { element, handle } = card("width: 50px"); + const rotation = new Map([[element, 12]]); + (window as { gsap?: unknown }).gsap = { + getProperty: (el: Element) => rotation.get(el) ?? 0, + set: (el: Element, props: { rotation: number }) => rotation.set(el, props.rotation), + }; + drawDrafts([{ handle, translate: null, size: null, rotate: { angle: 40, route: "gsap" } }]); + expect([rotation.get(element), turned(element)]).toEqual([40, "none"]); + drawDrafts([{ handle, end: "restore" }]); + expect([rotation.get(element), turned(element)]).toEqual([12, ""]); + }); +}); + describe("drafts", () => { it("adds a drag to the translate the element had, and restores it on a cancel", () => { const { element, handle } = card("translate: 10px 20px; width: 50px"); diff --git a/packages/core/src/runtime/editingDraft.ts b/packages/core/src/runtime/editingDraft.ts index 559aec1448..c7b254ae1f 100644 --- a/packages/core/src/runtime/editingDraft.ts +++ b/packages/core/src/runtime/editingDraft.ts @@ -5,7 +5,7 @@ */ import { isStylableElement, type StylableElement as Styled } from "./domRealm"; import { elementForHandle } from "./editingHandles"; -import type { EditingDraft } from "./editingPort"; +import type { EditingDraft, EditingDraftRotate } from "./editingPort"; const SIZE_PROPERTIES = [ "box-sizing", @@ -16,14 +16,22 @@ const SIZE_PROPERTIES = [ "max-width", "max-height", ] as const; -const DRAWN = ["translate", ...SIZE_PROPERTIES] as const; +const DRAWN = ["translate", "rotate", ...SIZE_PROPERTIES] as const; interface Before { inline: Array<[name: string, value: string, priority: string]>; /** The computed translate, split into its axes with each % as px, that a draft's translate adds to. */ translate: string[]; + /** GSAP's rotation before the first GSAP turn drawn, to put back on "restore". */ + gsapRotation?: number; } +type Gsap = { + getProperty?: (el: Element, prop: string) => unknown; + set?: (el: Element, props: Record) => void; +}; +const frameGsap = () => (window as unknown as { gsap?: Gsap }).gsap; + const before = new WeakMap(); /** "calc(50% + 2px) 4px" as its top-level parts. */ @@ -115,12 +123,34 @@ function drawSize(element: Styled, size: { width: number; height: number }): voi for (const name of ["max-width", "max-height"]) style.setProperty(name, "none"); } +function restoreGsapRotation(element: Styled): void { + const rotation = before.get(element)?.gsapRotation; + if (rotation !== undefined) frameGsap()?.set?.(element, { rotation }); +} + +function drawRotate(element: Styled, rotate: EditingDraftRotate | null): void { + const saved = beforeOf(element); + if (!rotate) { + restore(element, ["rotate"]); + return restoreGsapRotation(element); + } + if (rotate.route === "css") return void element.style.setProperty("rotate", `${rotate.angle}deg`); + const gsap = frameGsap(); + saved.gsapRotation ??= Number(gsap?.getProperty?.(element, "rotation")) || 0; + element.style.setProperty("rotate", "none"); + gsap?.set?.(element, { rotation: rotate.angle }); +} + function apply(element: Styled, draft: EditingDraft): void { if ("end" in draft) { - if (draft.end === "restore") restore(element, DRAWN); + if (draft.end === "restore") { + restore(element, DRAWN); + restoreGsapRotation(element); + } before.delete(element); return; } + if ("rotate" in draft) drawRotate(element, draft.rotate ?? null); if (draft.translate) drawTranslate(element, draft.translate); else restore(element, ["translate"]); if (draft.size) drawSize(element, draft.size); diff --git a/packages/core/src/runtime/editingGestureStart.test.ts b/packages/core/src/runtime/editingGestureStart.test.ts index 5165515178..671fdf76b6 100644 --- a/packages/core/src/runtime/editingGestureStart.test.ts +++ b/packages/core/src/runtime/editingGestureStart.test.ts @@ -44,8 +44,8 @@ function turnedCard(style: string): HTMLElement { return card; } -function gsapWith(tweens: Tween[], position = { x: 200, y: 5 }) { - const getProperty = vi.fn((_: Element, axis: string) => position[axis as "x" | "y"]); +function gsapWith(tweens: Tween[], position: Record = { x: 200, y: 5 }) { + const getProperty = vi.fn((_: Element, axis: string) => position[axis]); Object.assign(window, { gsap: { getProperty }, __timelines: { main: { getChildren: () => tweens } }, @@ -53,6 +53,8 @@ function gsapWith(tweens: Tween[], position = { x: 200, y: 5 }) { return getProperty; } +const GSAP_RENDERS = { _gsap: { renderTransform: () => {} } }; + const tween = (target: unknown, vars: Record, duration = 0): Tween => ({ vars, targets: () => [target], @@ -97,6 +99,19 @@ describe("gesture start", () => { expect(gestureStart([handleFor(card)]).elements[0]!.gsap).toEqual({ x: 200, y: 5, moving }); }); + // fails without the fix: a sealed rotate never learned GSAP turns the element, so it saved a CSS rotate. + it.each<[string, (card: HTMLElement) => Tween[], number | null]>([ + ["a spin tween", (card) => [tween(card, { rotation: 20 }, 2)], 12], + ["keyframes that turn it", (card) => [tween(card, { keyframes: [{ rotate: 5 }] }, 2)], 12], + ["a transform GSAP renders", (card) => (Object.assign(card, GSAP_RENDERS), []), 12], + ["nothing GSAP does: its own CSS turns it", (card) => [tween(card, { opacity: 0 }, 2)], null], + ])("says how far GSAP turns it, through %s", (_name, make, turn) => { + const card = turnedCard(""); + const getProperty = gsapWith(make(card), { x: 0, y: 0, rotation: 12 }); + expect(gestureStart([handleFor(card)]).elements[0]!.gsapRotation).toBe(turn); + expect(getProperty.mock.calls.some(([, name]) => name === "rotation")).toBe(turn !== null); + }); + it("does not own a box that only fades", () => { const card = turnedCard(""); gsapWith([tween(card, { opacity: 0, keyframes: { "50%": { scale: 2 } } }, 3)]); diff --git a/packages/core/src/runtime/editingGestureStart.ts b/packages/core/src/runtime/editingGestureStart.ts index b42858dde0..4477d3530c 100644 --- a/packages/core/src/runtime/editingGestureStart.ts +++ b/packages/core/src/runtime/editingGestureStart.ts @@ -24,6 +24,8 @@ export interface EditingGestureStart extends EditingElementGeometry { move: { a: number; b: number; c: number; d: number } | null; /** Set when GSAP owns its position: its x/y now, and whether a tween with a duration moves it. */ gsap: { x: number; y: number; moving: boolean } | null; + /** GSAP's rotation now when it owns the element's turn; null when it turns by its own CSS `rotate`. */ + gsapRotation: number | null; } const PROBE_PX = 100; @@ -77,6 +79,16 @@ type GsapWindow = { // The channels Studio's move route and drag commit read as GSAP moving an element. const POSITION = ["x", "y", "xPercent", "yPercent", "left", "top", "translateX", "translateY"]; const MOVES = [...POSITION, "motionPath"]; +const TURNS = [ + "rotation", + "rotationX", + "rotationY", + "rotationZ", + "rotate", + "rotateX", + "rotateY", + "rotateZ", +]; function carries(vars: Record, channels: string[]): boolean { if (channels.some((channel) => channel in vars)) return true; @@ -103,16 +115,23 @@ function tweensOn(element: Element): GsapTween[] { ); } +const rendersTransform = (element: Element) => + !!(element as { _gsap?: { renderTransform?: unknown } })._gsap?.renderTransform; +// Read only once GSAP owns it: asking GSAP for x makes it fold a CSS translate into its transform. +const readGsap = (element: Element, property: string) => + Number((window as GsapWindow).gsap?.getProperty?.(element, property)) || 0; + /** GSAP's x/y when it owns the element's position: it renders its transform, or a tween writes it. */ function gsapPosition(element: Element): EditingGestureStart["gsap"] { const tweens = tweensOn(element).filter((tween) => tween.vars && carries(tween.vars, MOVES)); - const renders = !!(element as { _gsap?: { renderTransform?: unknown } })._gsap?.renderTransform; - if (!renders && !tweens.length) return null; - // Read only now: asking GSAP for x makes it fold a CSS translate into its transform. - const read = (axis: string) => - Number((window as GsapWindow).gsap?.getProperty?.(element, axis)) || 0; + if (!rendersTransform(element) && !tweens.length) return null; const moving = tweens.some((tween) => (tween.duration?.() ?? 0) > 0); - return { x: read("x"), y: read("y"), moving }; + return { x: readGsap(element, "x"), y: readGsap(element, "y"), moving }; +} + +function gsapRotation(element: Element): number | null { + const turned = tweensOn(element).some((tween) => tween.vars && carries(tween.vars, TURNS)); + return rendersTransform(element) || turned ? readGsap(element, "rotation") : null; } /** Each handle's gesture start, null as in `describe`, and the snap boxes of the page around them. */ @@ -131,6 +150,7 @@ export function gestureStart(handles: readonly EditingElementHandle[]): { layout: { width: offsetWidth, height: offsetHeight }, move: measureMoveResponse(element), gsap: gsapPosition(element), + gsapRotation: gsapRotation(element), }; }); const root = document.querySelector("[data-composition-id]") ?? document.documentElement; diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index 5e81d83adf..79b2239c99 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -221,6 +221,7 @@ export interface EditingRuntimeSnapshot { } export const MAX_DRAFT_PX = 100_000; +export const MAX_DRAFT_DEG = 36_000; export const MAX_WATCHED_KEYS = 32; /** A keystroke the frame forwards for `watch-keys`, as an unasked port message with no id. */ @@ -240,12 +241,15 @@ export type EditingKeyMessage = { key: EditingKeyEvent; }; +/** The `rotate` property's whole value in degrees, or GSAP's rotation; null takes the drawn turn back. */ +export type EditingDraftRotate = { angle: number; route: "css" | "gsap" }; /** A gesture's draft on one element: null puts that part back; `end` keeps what is drawn or restores. */ export type EditingDraft = | { handle: EditingElementHandle; translate: { x: number; y: number } | null; size: { width: number; height: number } | null; + rotate?: EditingDraftRotate | null; } | { handle: EditingElementHandle; end: "keep" | "restore" }; @@ -452,14 +456,30 @@ function draftPart(value: unknown, keys: string, min: number): boolean { return keys.split(",").every((key) => isDraftPx(value[key], min)); } +function draftRotate(value: unknown): boolean { + if (value === undefined || value === null) return true; + if (!hasKeys(value, "angle,route") || (value.route !== "css" && value.route !== "gsap")) + return false; + return Number.isFinite(value.angle) && Math.abs(value.angle as number) <= MAX_DRAFT_DEG; +} + function draftEntry(value: unknown): EditingDraft | null { if (!isPlainRecord(value) || !isHandle(value.handle)) return null; - const { handle, end, translate, size } = value; + const { handle, end } = value; if (hasKeys(value, "end,handle")) return end === "keep" || end === "restore" ? { handle, end } : null; - if (!hasKeys(value, "handle,size,translate")) return null; - const valid = draftPart(translate, "x,y", -MAX_DRAFT_PX) && draftPart(size, "height,width", 0); - return valid ? (value as EditingDraft) : null; + return drawnParts(value) ? (value as EditingDraft) : null; +} + +function drawnParts(value: Record): boolean { + const { translate, size, rotate } = value; + if (!hasKeys(value, "handle,size,translate") && !hasKeys(value, "handle,rotate,size,translate")) + return false; + return ( + draftPart(translate, "x,y", -MAX_DRAFT_PX) && + draftPart(size, "height,width", 0) && + draftRotate(rotate) + ); } function draftList(params: unknown): EditingParams<"draft"> | null { diff --git a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts index dde18971ce..d4ecac4e16 100644 --- a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts +++ b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts @@ -36,6 +36,7 @@ import { } from "./domEditOverlayGestures"; import { collectSnapContext, buildExcludeElements, type SnapContext } from "./snapTargetCollection"; import type { PreviewGestureStart } from "./previewGestureStartRead"; +import { endPreviewDraft } from "./previewDrafts"; import { editsPlainCss } from "../../hooks/gsapRuntimeKeyframes"; import { logResize, resetResizeMoveLog } from "../../utils/resizeDebug"; import { logDrag, readDragPositions, resetDragMoveLog } from "../../utils/dragDebug"; @@ -251,6 +252,7 @@ export function startGesture( kind === "rotate" ? "rotate" : "resize", at, ); + endPreviewDraft(sel.element, "keep"); } } @@ -258,9 +260,14 @@ export function startGesture( try { // Rotation base: the angle the element shows. An element GSAP does not turn, or a plain-translate // move, never asks GSAP: reading a property makes it bake the CSS into its transform. - const plain = !!pathOffsetMember?.plainTranslate || editsPlainCss(sel.element, "rotate"); + const frameRotation = start?.gsapRotation; + const plain = + !!pathOffsetMember?.plainTranslate || + (frameRotation !== undefined ? frameRotation === null : editsPlainCss(sel.element, "rotate")); const plainRotation = plain && kind === "rotate" ? readCssRotationTarget(sel.element) : null; - const rotation = { angle: readRotationBase(sel.element, plain) }; + const rotation = { + angle: readRotationBase(sel.element, plain, frameRotation ?? undefined), + }; const overlayBounds = overlayEl?.getBoundingClientRect(); const centerX = (overlayBounds?.left ?? 0) + rect.left + rect.width / 2; const centerY = (overlayBounds?.top ?? 0) + rect.top + rect.height / 2; diff --git a/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts b/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts index d89dbff4fa..3c406b592a 100644 --- a/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts +++ b/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts @@ -6,7 +6,7 @@ import { afterEach, expect, it, vi } from "vitest"; import { makeSelection } from "../../hooks/domSelectionTestHarness"; import { freezeDragStamp } from "../../hooks/draggedGsapPosition"; import { settleGsapSnapshot } from "../../hooks/gsapFrameSnapshot"; -import { tryGsapDragIntercept } from "../../hooks/gsapRuntimeBridge"; +import { tryGsapDragIntercept, tryGsapRotationIntercept } from "../../hooks/gsapRuntimeBridge"; import { watchPreviewFrame } from "../../player/lib/bridgePlayback"; import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements"; import { usePlayerStore } from "../../player/store/playerStore"; @@ -19,6 +19,14 @@ import { endManualOffsetDragMembers, } from "./manualOffsetDrag"; import { measurePreviewGestureStart } from "./previewGestureStartRead"; +import { captureStudioRotation } from "./manualEditsSnapshot"; +import { + applyRotationDraft, + endRotationDraft, + endRotationGestureIfCurrent, + readCssRotationTarget, + restoreRotationDraft, +} from "./rotationDraft"; import { standInFor } from "./previewSelection"; import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers"; @@ -269,3 +277,122 @@ it("a resize in a sealed preview keeps the anchor of a layer its tween moves on expect(start.gsap).toEqual({ x: 100, y: 40, moving: true }); expect(result.ok && result.member.plainTranslate).toBe(false); }); + +async function sealedBox() { + const iframe = opaqueFrame(); + const handle = (await queryPreviewElements(iframe, "#box"))!.matches[0]!.handle; + const described = (await describePreviewElements(iframe, [handle]))![0]!; + return { + box: document.getElementById("box")!, + standIn: standInFor(iframe, described) as HTMLElement, + }; +} + +// fails without the fix: a sealed frame never turned the element a rotate gesture drew. +it("turns a sealed frame's element by its rotate property as the gesture draws, and back on a cancel", async () => { + mount(SCRIPT); + const { box, standIn } = await sealedBox(); + const start = captureStudioRotation(standIn); + + applyRotationDraft(standIn, 30, readCssRotationTarget(standIn)); + await vi.waitFor(() => expect(box.style.getPropertyValue("rotate")).toBe("30deg")); + restoreRotationDraft(standIn, 30, start, true); + await vi.waitFor(() => expect(box.style.getPropertyValue("rotate")).toBe("")); +}); + +// fails without the fix: a GSAP rotation drew only on Studio's stand-in. +it("turns a sealed frame's element by its own GSAP, and keeps the turn when the gesture ends", async () => { + mount(SCRIPT); + const { box, standIn } = await sealedBox(); + + applyRotationDraft(standIn, 40, null); + endRotationDraft(standIn); + await vi.waitFor(() => expect(gsap.getProperty(box, "rotation")).toBe(40)); + expect(box.style.getPropertyValue("rotate")).toBe("none"); +}); + +const SPINS_BOX = timeline(`tl.to("#box", { rotation: 40, duration: 1, ease: "none" }, 0);`); + +/** The box on a sealed frame, and a press of its rotate handle as the overlay does it. */ +async function sealedRotate(script: string) { + mount(script); + const iframe = opaqueFrame(); + const handle = (await queryPreviewElements(iframe, "#box"))!.matches[0]!.handle; + const standIn = standInFor(iframe, (await describePreviewElements(iframe, [handle]))![0]!); + const made = makeSelection("box", standIn); + const capabilities = { ...made.capabilities, canApplyManualRotation: true }; + const selection = { ...made, capabilities, id: "box", handle }; + const pressRotate = async () => { + const opts = gestureOpts(iframe); + const read = await measurePreviewGestureStart(iframe, opts.overlayRef.current!, [handle]); + const { rect, start } = read!.elements[0]!; + startGesture("rotate", press(), opts, { selection, rect, start, snap: read!.snap }); + return { gesture: opts.gestureRef.current!, start }; + }; + return { selection, iframe, standIn, pressRotate }; +} + +async function pressRotateOnSealedFrame(script: string) { + const sealed = await sealedRotate(script); + return { ...sealed, ...(await sealed.pressRotate()) }; +} + +// fails without the fix: the rotate asked the stand-in, which has no GSAP, so a sealed spin saved a CSS rotate. +it("turns a layer its tween spins on GSAP's route in a sealed preview, from the angle GSAP shows, and saves the tween", async () => { + const { gesture, selection, iframe, standIn } = await pressRotateOnSealedFrame(SPINS_BOX); + expect(gesture.plainRotation).toBeNull(); + expect(gesture.actualRotation).toBe(20); + + const commit = vi.fn(async () => undefined); + const [anim] = parseGsapScriptAcorn(SPINS_BOX).animations; + const outcome = await tryGsapRotationIntercept( + selection, + 35, + [anim!], + iframe, + commit, + undefined, + freezeDragStamp(standIn), + ); + expect(outcome).toEqual({ status: "persisted" }); + expect(commit.mock.calls[0]![1]).toMatchObject({ + keyframes: expect.arrayContaining([{ percentage: 50, properties: { rotation: 35 } }]), + }); +}); + +it("turns a layer GSAP leaves alone by its own CSS rotate in a sealed preview", async () => { + const { gesture } = await pressRotateOnSealedFrame(timeline("")); + expect(gesture.plainRotation).toMatchObject({ property: "rotate" }); +}); + +// fails without the fix: the first rotate's save, landing after a regrab, ended the regrab's frame draft, so a +// cancelled regrab left the frame at its mid-drag angle. +it("cancels a rotate regrabbed while the first one saves back to where the regrab started, on the frame too", async () => { + const { standIn, pressRotate } = await sealedRotate(timeline("")); + const box = document.getElementById("box")!; + const turned = () => [box, standIn].map((el) => el.style.getPropertyValue("rotate")); + const first = (await pressRotate()).gesture; + applyRotationDraft(standIn, 30, first.plainRotation); + await vi.waitFor(() => expect(turned()).toEqual(["30deg", "30deg"])); + + const regrab = (await pressRotate()).gesture; + applyRotationDraft(standIn, 50, regrab.plainRotation); + await vi.waitFor(() => expect(turned()).toEqual(["50deg", "50deg"])); + endRotationGestureIfCurrent(standIn, first.manualEditDragToken); + restoreRotationDraft(standIn, 50, regrab.initialRotation, true); + + await vi.waitFor(() => expect(turned()).toEqual(["30deg", "30deg"])); +}); + +// fails without the fix: an out-of-range GSAP rotation made Studio refuse the whole start, so a drag lost GSAP's x/y. +it("keeps a sealed element's move start when GSAP's rotation is out of range, and drops only the turn", async () => { + mount(SCRIPT); + gsap.set("#box", { rotation: 100_000 }); + const iframe = opaqueFrame(); + const handle = (await queryPreviewElements(iframe, "#box"))!.matches[0]!.handle; + const overlay = sized(document.createElement("div"), [20, 10, 1200, 800]); + const { start } = (await measurePreviewGestureStart(iframe, overlay, [handle]))!.elements[0]!; + + expect(start.gsap).toEqual({ x: 100, y: 40, moving: true }); + expect(start.gsapRotation).toBeUndefined(); +}); diff --git a/packages/studio/src/components/editor/previewDrafts.ts b/packages/studio/src/components/editor/previewDrafts.ts index 85b7a0e41a..04e9ceb857 100644 --- a/packages/studio/src/components/editor/previewDrafts.ts +++ b/packages/studio/src/components/editor/previewDrafts.ts @@ -3,12 +3,17 @@ * gesture draws on the stand-in is drawn on the frame's own element too, over the frame's channel, * so the preview follows the pointer. One request is in flight per frame; later draws wait and merge. */ -import { MAX_DESCRIBE_HANDLES, type EditingDraft } from "@hyperframes/core/runtime/editing-port"; +import { + MAX_DESCRIBE_HANDLES, + type EditingDraft, + type EditingDraftRotate, +} from "@hyperframes/core/runtime/editing-port"; import { previewRequest } from "../../player/lib/previewChannel"; type Drawn = { translate: { x: number; y: number } | null; size: { width: number; height: number } | null; + rotate?: EditingDraftRotate | null; }; interface Queue { diff --git a/packages/studio/src/components/editor/previewGestureStartRead.test.ts b/packages/studio/src/components/editor/previewGestureStartRead.test.ts index c8adec83d9..31d051e648 100644 --- a/packages/studio/src/components/editor/previewGestureStartRead.test.ts +++ b/packages/studio/src/components/editor/previewGestureStartRead.test.ts @@ -119,7 +119,9 @@ function gsapHoldsCard(tweens: unknown[] = []) { const card = document.getElementById("card")!; Object.assign(card, { _gsap: { renderTransform: () => {} } }); Object.assign(window, { - gsap: { getProperty: (_: Element, axis: string) => (axis === "x" ? 200 : 5) }, + gsap: { + getProperty: (_: Element, axis: string) => (axis === "x" ? 200 : axis === "y" ? 5 : 0), + }, __timelines: { main: { getChildren: () => tweens } }, }); } @@ -151,6 +153,7 @@ describe("a gesture's start on an opaque frame", () => { layout: { width: 200, height: 100 }, screenToOffset: { a: -2, b: 0, c: 0, d: 2 }, gsap: { x: 200, y: 5, moving: false }, + gsapRotation: 0, }); const selection = { ...makeSelection("card", standIn), handle }; const made = createManualOffsetDragMember({ @@ -215,6 +218,7 @@ const START: PreviewGestureStart = { layout: { width: 200, height: 100 }, screenToOffset: { a: 2, b: 0, c: 0, d: 2 }, gsap: null, + gsapRotation: null, }; const SNAP = { targets: [], compositionTarget: null, gridEdges: null, snapEnabled: true }; diff --git a/packages/studio/src/components/editor/previewGestureStartRead.ts b/packages/studio/src/components/editor/previewGestureStartRead.ts index 3cb6e94ffc..6bf6786bac 100644 --- a/packages/studio/src/components/editor/previewGestureStartRead.ts +++ b/packages/studio/src/components/editor/previewGestureStartRead.ts @@ -13,6 +13,7 @@ export interface PreviewGestureStart { screenToOffset: ManualOffsetDragMatrix | null; /** GSAP's x/y when it owns the element's position, and whether a tween with a duration moves it. */ gsap: { x: number; y: number; moving: boolean } | null; + gsapRotation?: number | null; } export interface PreviewGestureStarts { @@ -65,6 +66,7 @@ export async function measurePreviewGestureStart( layout: start.layout, screenToOffset: screenToOffset(start.move), gsap: start.gsap, + gsapRotation: start.gsapRotation, }, }, ), diff --git a/packages/studio/src/components/editor/rotationDraft.ts b/packages/studio/src/components/editor/rotationDraft.ts index d4e35621e3..ef744b1ce1 100644 --- a/packages/studio/src/components/editor/rotationDraft.ts +++ b/packages/studio/src/components/editor/rotationDraft.ts @@ -8,6 +8,8 @@ import { } from "./manualEdits"; import { getOffsetDragGsap } from "./manualOffsetDrag"; import { splitTopLevelWhitespace } from "./manualEditsStyleHelpers"; +import { endStudioManualEditGesture, isStudioManualEditGestureCurrent } from "./manualEditsDom"; +import { drawPreviewDraft, endPreviewDraft } from "./previewDrafts"; function lastRuleTransform(element: HTMLElement): string { let value = ""; @@ -85,13 +87,24 @@ export function readCssRotationTarget(element: HTMLElement): CssRotationTarget { return { property: "transform", before, after, share, sign: sx * sy < 0 ? -1 : 1, inline }; } +const cssTurn = (angle: number, target: CssRotationTarget) => + roundTo3(target.sign * (angle - target.share)); + +// ponytail: a turn drawn inside a translating `transform` stays Studio-side; a sealed frame shows it on save. +const frameTurn = (angle: number, plain: CssRotationTarget | null) => { + if (!plain) return { angle, route: "gsap" as const }; + return plain.property === "rotate" + ? { angle: cssTurn(angle, plain), route: "css" as const } + : null; +}; + /** Draws `angle` where `target` says, and returns the source patches that save it as drawn. */ export function applyCssRotation( element: HTMLElement, angle: number, target = readCssRotationTarget(element), ): Array { - const turn = `${roundTo3(target.sign * (angle - target.share))}deg`; + const turn = `${cssTurn(angle, target)}deg`; const value = target.property === "rotate" ? turn @@ -119,11 +132,20 @@ export function applyRotationDraft( angle: number, plain: CssRotationTarget | null, ): void { + const rotate = frameTurn(angle, plain); + if (rotate) drawPreviewDraft(element, { rotate }); if (plain) return void applyCssRotation(element, angle, plain); element.style.setProperty("rotate", "none"); getOffsetDragGsap(element)?.set(element, { rotation: angle }); } +export const endRotationDraft = (element: HTMLElement) => endPreviewDraft(element, "keep"); + +export function endRotationGestureIfCurrent(element: HTMLElement, token: string | undefined): void { + if (!token || isStudioManualEditGestureCurrent(element, token)) endRotationDraft(element); + endStudioManualEditGesture(element, token); +} + /** Back to the gesture start: the CSS snapshot, and GSAP's rotation without the legacy var. */ export function restoreRotationDraft( element: HTMLElement, @@ -131,6 +153,8 @@ export function restoreRotationDraft( snapshot: StudioRotationSnapshot, plain: boolean, ): void { + drawPreviewDraft(element, { rotate: null }); + endRotationDraft(element); if (plain) return restorePlainRotation(element, snapshot); getOffsetDragGsap(element)?.set(element, { rotation: angle - (Number.parseFloat(snapshot.studioRotation) || 0), @@ -139,8 +163,13 @@ export function restoreRotationDraft( } /** The angle a rotate gesture starts from, as the element shows it. */ -export function readRotationBase(element: HTMLElement, plain: boolean): number { +export function readRotationBase( + element: HTMLElement, + plain: boolean, + frameGsapRotation?: number, +): number { if (plain) return readCssRotation(element); - const gsapRotation = Number(getOffsetDragGsap(element)?.getProperty(element, "rotation") ?? 0); + const gsapRotation = + frameGsapRotation ?? Number(getOffsetDragGsap(element)?.getProperty(element, "rotation") ?? 0); return gsapRotation + readStudioRotation(element).angle; } diff --git a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts index e4cce7ed7a..8f30b91f85 100644 --- a/packages/studio/src/components/editor/useDomEditOverlayGestures.ts +++ b/packages/studio/src/components/editor/useDomEditOverlayGestures.ts @@ -16,7 +16,11 @@ import { restoreManualOffsetDragMembers, } from "./manualOffsetDrag"; import { manualOffsetMoveRevert, elementLookRevert } from "./gestureUndoRevert"; -import { applyRotationDraft, restoreRotationDraft } from "./rotationDraft"; +import { + applyRotationDraft, + endRotationGestureIfCurrent, + restoreRotationDraft, +} from "./rotationDraft"; import { applyStudioBoxSize, applyStudioBoxSizeDraft, @@ -431,7 +435,6 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu endStudioManualEditGesture(sel.element, g.manualEditDragToken); return; } - // Hold the final angle while the commit lands. applyRotationDraft(sel.element, finalRotation.angle, g.plainRotation); const commit = { ...finalRotation, plain: g.plainRotation }; const edit = beginStudioPendingEdit(elementLookRevert(sel.element, g.initialLook)); @@ -445,7 +448,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu ) restoreRotation(); }) - .finally(() => endStudioManualEditGesture(sel.element, g.manualEditDragToken)); + .finally(() => endRotationGestureIfCurrent(sel.element, g.manualEditDragToken)); edit.settle(saved); } else if (g.kind === "drag") { // A release over another layer must keep this dragged layer selected. diff --git a/packages/studio/src/player/lib/previewElements.ts b/packages/studio/src/player/lib/previewElements.ts index bbf87f7887..8412548849 100644 --- a/packages/studio/src/player/lib/previewElements.ts +++ b/packages/studio/src/player/lib/previewElements.ts @@ -5,6 +5,7 @@ import { EDITING_ELEMENT_HANDLE, MAX_DESCRIBE_HANDLES, + MAX_DRAFT_DEG, MAX_DRAFT_PX, MAX_ELEMENT_ENTRIES, MAX_ELEMENT_TEXT, @@ -252,20 +253,29 @@ const isLayout = (value: unknown) => (side) => Number.isFinite(side) && (side as number) >= 0 && (side as number) <= MAX_DRAFT_PX, ); -const readGestureStart = (value: unknown): EditingGestureStart | null => { +const isTurnOrNull = (value: unknown) => + value === null || (Number.isFinite(value) && Math.abs(value as number) <= MAX_DRAFT_DEG); + +export type ReadGestureStart = Omit & { + gsapRotation?: number | null; +}; + +const readGestureStart = (value: unknown): ReadGestureStart | null => { if (!readGeometry(value) || !isFields(value)) return null; - const { layout, move, gsap } = value; + const { layout, move, gsap, gsapRotation } = value; const valid = [ isLayout(layout), move === null || isFiniteFields(move, ["a", "b", "c", "d"]), gsap === null || (isFields(gsap) && isFiniteFields(gsap, ["x", "y"]) && isFlag(gsap.moving)), ]; - return valid.includes(false) ? null : (value as unknown as EditingGestureStart); + if (valid.includes(false)) return null; + const start = value as unknown as ReadGestureStart; + return isTurnOrNull(gsapRotation) ? start : { ...start, gsapRotation: undefined }; }; export interface PreviewGestureStartReply { /** One entry per handle, in order: null for an element the frame no longer has. */ - elements: Array; + elements: Array; snap: EditingElementBox[]; }