diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json
index 8697fafc43..fc46943d65 100644
--- a/packages/core/package-subpaths.json
+++ b/packages/core/package-subpaths.json
@@ -470,6 +470,12 @@
"types": "./dist/runtime/editingPort.d.ts",
"environments": ["browser", "bun", "node"]
},
+ "./runtime/css-rotation": {
+ "source": "./src/runtime/editing/cssRotation.ts",
+ "runtime": "./dist/runtime/editing/cssRotation.js",
+ "types": "./dist/runtime/editing/cssRotation.d.ts",
+ "environments": ["browser", "bun", "node"]
+ },
"./runtime/patch-tween": {
"source": "./src/runtime/editing/patchTween.ts",
"runtime": "./dist/runtime/editing/patchTween.js",
diff --git a/packages/core/package.json b/packages/core/package.json
index 6aa4a1c3e3..8ca5e5fb1f 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -477,6 +477,12 @@
"import": "./src/runtime/editingPort.ts",
"types": "./src/runtime/editingPort.ts"
},
+ "./runtime/css-rotation": {
+ "bun": "./src/runtime/editing/cssRotation.ts",
+ "node": "./dist/runtime/editing/cssRotation.js",
+ "import": "./src/runtime/editing/cssRotation.ts",
+ "types": "./src/runtime/editing/cssRotation.ts"
+ },
"./runtime/patch-tween": {
"bun": "./src/runtime/editing/patchTween.ts",
"node": "./dist/runtime/editing/patchTween.js",
@@ -1029,6 +1035,10 @@
"import": "./dist/runtime/editingPort.js",
"types": "./dist/runtime/editingPort.d.ts"
},
+ "./runtime/css-rotation": {
+ "import": "./dist/runtime/editing/cssRotation.js",
+ "types": "./dist/runtime/editing/cssRotation.d.ts"
+ },
"./runtime/patch-tween": {
"import": "./dist/runtime/editing/patchTween.js",
"types": "./dist/runtime/editing/patchTween.d.ts"
diff --git a/packages/core/src/runtime/editing/cssRotation.ts b/packages/core/src/runtime/editing/cssRotation.ts
new file mode 100644
index 0000000000..9831c29370
--- /dev/null
+++ b/packages/core/src/runtime/editing/cssRotation.ts
@@ -0,0 +1,113 @@
+// Read from the live element: by Studio for a preview it scripts, by the frame's gesture start when sealed.
+import { splitTopLevelWhitespace } from "../positionEdits";
+
+const cssValue = (style: CSSStyleDeclaration, prop: string) => {
+ const value = style.getPropertyValue(prop).trim();
+ return value === "none" ? "" : value;
+};
+
+// Without GSAP, the rotation GSAP will parse from the CSS `rotate`, `scale` and `transform`; with
+// `withRotate` false, only the part `scale` and `transform` draw. GSAP folds them into one transform,
+// and a list the browser rejects (e.g. `rotate: x 30deg`) leaves it only the plain transform.
+export function readCssRotation(element: HTMLElement, withRotate = true): number {
+ const view = element.ownerDocument.defaultView;
+ if (!view) return 0;
+ const style = view.getComputedStyle(element);
+ const rotate = withRotate ? cssValue(style, "rotate") : "";
+ const scale = cssValue(style, "scale");
+ const transform = cssValue(style, "transform");
+ const angle = (list: string) => {
+ if (!list) return 0;
+ const m = new view.DOMMatrix(list);
+ return (Math.atan2(m.b, m.a) * 180) / Math.PI;
+ };
+ const folded = [rotate && `rotate(${rotate})`, scale && `scale(${scale.split(/\s+/).join(",")})`];
+ try {
+ return angle([...folded, transform].join(" ").trim());
+ } catch {
+ return angle(transform);
+ }
+}
+
+function lastRuleTransform(element: HTMLElement): string {
+ let value = "";
+ for (const sheet of Array.from(element.ownerDocument.styleSheets)) {
+ let rules: CSSStyleRule[] = [];
+ try {
+ rules = Array.from(sheet.cssRules) as CSSStyleRule[];
+ } catch {
+ // a cross-origin sheet
+ }
+ for (const rule of rules) {
+ const declared = rule.style?.getPropertyValue("transform");
+ if (declared && element.matches(rule.selectorText)) value = declared;
+ }
+ }
+ return value;
+}
+
+// ponytail: the authored transform if it moves the box, from the last matching rule in sheet order;
+// specificity, !important and @media are not weighed. Weigh them when a film's rule is missed.
+function translatingTransform(element: HTMLElement): string {
+ const view = element.ownerDocument.defaultView;
+ const computed = view?.getComputedStyle(element).transform ?? "none";
+ const m = computed === "none" ? null : new view!.DOMMatrix(computed);
+ if (!m || (m.m41 === 0 && m.m42 === 0)) return "";
+ const value = element.style.getPropertyValue("transform") || lastRuleTransform(element);
+ return value === "none" ? "" : value;
+}
+
+/** Where a plain rotate draws its turn, read once at press: the element's own `rotate`, or, when its
+ * transform translates it (often the translate(-50%, -50%) centring), a rotate() right after that
+ * translate, so the box turns in place in screen space. `share` is what the rest already turns. */
+export interface CssRotationTarget {
+ property: "rotate" | "transform";
+ before: string;
+ after: string;
+ share: number;
+ /** -1 when a mirroring `scale` property flips a turn made inside the transform. */
+ sign: number;
+ /** An inline box does not transform, so the turn makes it inline-block. */
+ inline: boolean;
+}
+
+const TRANSLATE = /^translate(?:3d|X|Y|Z)?\(/i;
+const OWN_TURN = /^rotate\(\s*-?[\d.]+(?:e[+-]?\d+)?deg\s*\)$/i;
+
+export function readCssRotationTarget(element: HTMLElement): CssRotationTarget {
+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);
+ const inline = style?.display === "inline";
+ const transform = translatingTransform(element);
+ if (!transform) {
+ const share = readCssRotation(element, false);
+ return { property: "rotate", before: "", after: "", share, sign: 1, inline };
+ }
+ const parts = splitTopLevelWhitespace(transform);
+ const lead = parts.findIndex((part) => !TRANSLATE.test(part));
+ const split = lead < 0 ? parts.length : lead;
+ const rest = parts.slice(split);
+ if (OWN_TURN.test(rest[0] ?? "")) rest.shift();
+ const [before, after] = [parts.slice(0, split).join(" "), rest.join(" ")];
+ const [sx = 1, sy = sx] = splitTopLevelWhitespace(style?.getPropertyValue("scale") ?? "").map(
+ Number.parseFloat,
+ );
+ const inlineStyle = element.style;
+ const saved = [
+ inlineStyle.getPropertyValue("transform"),
+ inlineStyle.getPropertyPriority("transform"),
+ ];
+ inlineStyle.setProperty("transform", `${before} ${after}`.trim() || "none");
+ const share = readCssRotation(element);
+ inlineStyle.setProperty("transform", saved[0] ?? "", saved[1] ?? "");
+ return { property: "transform", before, after, share, sign: sx * sy < 0 ? -1 : 1, inline };
+}
+
+export interface CssRotationStart {
+ angle: number;
+ target: CssRotationTarget;
+}
+
+export const readCssRotationStart = (element: HTMLElement): CssRotationStart => ({
+ angle: readCssRotation(element),
+ target: readCssRotationTarget(element),
+});
diff --git a/packages/core/src/runtime/editingAgent.test.ts b/packages/core/src/runtime/editingAgent.test.ts
index ce7761e1c1..4ceddef941 100644
--- a/packages/core/src/runtime/editingAgent.test.ts
+++ b/packages/core/src/runtime/editingAgent.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { installEditingAgent } from "./editingAgent";
+import { handleFor } from "./editingHandles";
import { PREVIEW_FOR_ANOTHER_SITE_META, STUDIO_PREVIEW_MARK_META } from "../studioPreviewMark";
const CONNECT = { source: "hf-parent", type: "editing-connect", v: 1 };
@@ -422,6 +423,27 @@ describe("installEditingAgent", () => {
{
drafts: [{ handle: H, translate: null, size: null, rotate: { angle: NaN, route: "gsap" } }],
},
+ {
+ drafts: [
+ { handle: H, translate: null, size: null, rotate: { angle: 1, route: "transform" } },
+ ],
+ },
+ ...[
+ "url(x.png)",
+ "rotate(1deg);color:red",
+ "translate(1px",
+ "scale(2) /* x",
+ "x".repeat(513),
+ ].map((value) => ({
+ drafts: [
+ {
+ handle: H,
+ translate: null,
+ size: null,
+ rotate: { angle: 1, route: "transform", value },
+ },
+ ],
+ })),
].map((params, index) => [
{ v: 1, id: 150 + index, kind: "draft", params },
150 + index,
@@ -620,6 +642,23 @@ describe("installEditingAgent", () => {
});
});
+ // fails without the fix: the frame refused a turn drawn inside a translating transform, so it never turned.
+ it("draws a turn inside a translating transform through the port", async () => {
+ const port = connectedPort();
+ document.body.insertAdjacentHTML(
+ "beforeend",
+ '
',
+ );
+ const spun = document.getElementById("spun")!;
+ const value = "translate(-50%, -50%) rotate(20deg)";
+ const rotate = { angle: 20, route: "transform", value };
+ const drafts = [{ handle: handleFor(spun), translate: null, size: null, rotate }];
+ expect(await ask(port, { v: 1, id: 1, kind: "draft", params: { drafts } })).toMatchObject({
+ ok: true,
+ });
+ expect(spun.style.transform).toBe(value);
+ });
+
it("answers computed styles for the element a selector names", async () => {
document.body.innerHTML = `Hi
diff --git a/packages/core/src/runtime/editingDraft.test.ts b/packages/core/src/runtime/editingDraft.test.ts
index 3f9ce81681..d468cfeff4 100644
--- a/packages/core/src/runtime/editingDraft.test.ts
+++ b/packages/core/src/runtime/editingDraft.test.ts
@@ -41,6 +41,17 @@ describe("rotation drafts", () => {
expect([turned(element), shown(element)]).toEqual(["45deg", [5, 0]]);
});
+ it("turns inside a translating transform and puts the transform back on a cancel", () => {
+ const { element, handle } = card("transform: translate(-50%, -50%); width: 50px");
+ const value = "translate(-50%, -50%) rotate(20deg)";
+ drawDrafts([
+ { handle, translate: null, size: null, rotate: { angle: 20, route: "transform", value } },
+ ]);
+ expect(element.style.transform).toBe(value);
+ drawDrafts([{ handle, end: "restore" }]);
+ expect(element.style.transform).toBe("translate(-50%, -50%)");
+ });
+
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]]);
diff --git a/packages/core/src/runtime/editingDraft.ts b/packages/core/src/runtime/editingDraft.ts
index cb051bf09d..05daae202f 100644
--- a/packages/core/src/runtime/editingDraft.ts
+++ b/packages/core/src/runtime/editingDraft.ts
@@ -17,7 +17,7 @@ export const SIZE_PROPERTIES = [
"max-width",
"max-height",
] as const;
-const DRAWN = ["translate", "rotate", ...SIZE_PROPERTIES] as const;
+const DRAWN = ["translate", "rotate", "transform", ...SIZE_PROPERTIES] as const;
interface Before {
draft: number;
@@ -141,10 +141,12 @@ function restoreGsapRotation(element: Styled): void {
function drawRotate(element: Styled, rotate: EditingDraftRotate | null): void {
const saved = beforeOf(element);
if (!rotate) {
- restore(element, ["rotate"]);
+ restore(element, ["rotate", "transform"]);
return restoreGsapRotation(element);
}
if (rotate.route === "css") return void element.style.setProperty("rotate", `${rotate.angle}deg`);
+ if (rotate.route === "transform")
+ return void element.style.setProperty("transform", rotate.value);
const gsap = frameGsap();
saved.gsapRotation ??= Number(gsap?.getProperty?.(element, "rotation")) || 0;
element.style.setProperty("rotate", "none");
diff --git a/packages/core/src/runtime/editingGestureStart.test.ts b/packages/core/src/runtime/editingGestureStart.test.ts
index f32852ec30..1efc9517d1 100644
--- a/packages/core/src/runtime/editingGestureStart.test.ts
+++ b/packages/core/src/runtime/editingGestureStart.test.ts
@@ -173,6 +173,18 @@ describe("gesture start", () => {
expect(getProperty.mock.calls.some(([, name]) => name === "rotation")).toBe(turn !== null);
});
+ // fails without the fix: a sealed stand-in has no stylesheet, so a rotate started at 0 instead of 30.
+ it("reads the CSS turn a layer GSAP does not turn shows, for a stand-in that cannot", () => {
+ Object.assign(window, { DOMMatrix: Matrix2D });
+ const card = turnedCard("transform: matrix(0.866025, 0.5, -0.5, 0.866025, 0, 0)");
+ gsapWith([tween(card, { opacity: 0 }, 2)]);
+ const { cssRotation } = gestureStart([handleFor(card)]).elements[0]!;
+ expect(cssRotation!.angle).toBeCloseTo(30, 3);
+ expect(cssRotation!.target).toMatchObject({ property: "transform", before: "" });
+ gsapWith([tween(card, { rotation: 20 }, 2)], { x: 0, y: 0, rotation: 12 });
+ expect(gestureStart([handleFor(card)]).elements[0]!.cssRotation).toBeNull();
+ });
+
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 38f07acec3..5842df302f 100644
--- a/packages/core/src/runtime/editingGestureStart.ts
+++ b/packages/core/src/runtime/editingGestureStart.ts
@@ -12,6 +12,7 @@ import {
SIZE_PROPERTIES,
writeDrawnSize,
} from "./editingDraft";
+import { readCssRotationStart, type CssRotationStart } from "./editing/cssRotation";
import {
boxOf,
elementGeometry,
@@ -34,6 +35,7 @@ export interface EditingGestureStart extends EditingElementGeometry {
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;
+ cssRotation: CssRotationStart | null;
planar: { a: number; b: number; c: number; d: number } | null;
}
@@ -193,13 +195,15 @@ export function gestureStart(handles: readonly EditingElementHandle[]): {
if (!geometry || !isStylableElement(element)) return null;
const { offsetWidth = 0, offsetHeight = 0 } = element as Partial;
const layout = { width: offsetWidth, height: offsetHeight };
+ const rotation = gsapRotation(element);
return {
...geometry,
layout,
move: measureMoveResponse(element),
grow: measureGrowResponse(element, layout),
gsap: gsapPosition(element),
- gsapRotation: gsapRotation(element),
+ gsapRotation: rotation,
+ cssRotation: rotation === null ? readCssRotationStart(element as HTMLElement) : null,
planar: planarOf(element),
};
});
diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts
index a7224090ff..7f66d5bbb3 100644
--- a/packages/core/src/runtime/editingPort.ts
+++ b/packages/core/src/runtime/editingPort.ts
@@ -259,7 +259,9 @@ export type EditingKeyMessage = {
};
/** 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" };
+export type EditingDraftRotate =
+ | { angle: number; route: "css" | "gsap" }
+ | { angle: number; route: "transform"; value: string };
export type { EditingDraftEnd };
/** A gesture's draft on one element: null puts that part back; an end keeps what is drawn or restores. */
export type EditingDraft =
@@ -481,10 +483,33 @@ function draftPart(value: unknown, keys: string, min: number): boolean {
return keys.split(",").every((key) => isDraftPx(value[key], min));
}
+const TRANSFORM_CALL =
+ /^(?:(?:translate|scale|rotate)(?:[XYZ]|3d)?|skew[XY]?|matrix(?:3d)?|perspective|calc|var|min|max|clamp)$/;
+
+const INNER_CALL = /([\w-]+)\(([\w\s.,%+\-*/]*)\)/g;
+
+// Innermost known calls fold to a token until none is left: an unclosed paren or a comment never folds.
+export function isTransformList(value: unknown): value is string {
+ if (typeof value !== "string" || value.length > 512 || value.includes("/*")) return false;
+ let rest = value;
+ for (let last = ""; rest !== last; ) {
+ last = rest;
+ rest = rest.replace(INNER_CALL, (call, name: string) =>
+ TRANSFORM_CALL.test(name) ? "0" : call,
+ );
+ }
+ return /^[\s0]*$/.test(rest);
+}
+
+const isRotateRoute = (value: unknown): value is Record =>
+ (hasKeys(value, "angle,route") && (value.route === "css" || value.route === "gsap")) ||
+ (hasKeys(value, "angle,route,value") &&
+ value.route === "transform" &&
+ isTransformList(value.value));
+
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;
+ if (!isRotateRoute(value)) return false;
return Number.isFinite(value.angle) && Math.abs(value.angle as number) <= MAX_DRAFT_DEG;
}
diff --git a/packages/core/src/runtime/positionEdits.ts b/packages/core/src/runtime/positionEdits.ts
index 3a2550dc5c..1a832afa6e 100644
--- a/packages/core/src/runtime/positionEdits.ts
+++ b/packages/core/src/runtime/positionEdits.ts
@@ -37,7 +37,7 @@ const num = (value: string | null): number => {
};
/** Split "10px 20px" / "calc(1px + 2px) 3px" on top-level whitespace only. */
-const splitTopLevelWhitespace = (value: string): string[] => {
+export const splitTopLevelWhitespace = (value: string): string[] => {
const parts: string[] = [];
let depth = 0;
let current = "";
diff --git a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts
index fcb7be32a6..ee956d00b2 100644
--- a/packages/studio/src/components/editor/domEditOverlayStartGesture.ts
+++ b/packages/studio/src/components/editor/domEditOverlayStartGesture.ts
@@ -264,9 +264,11 @@ export function startGesture(
const plain =
!!pathOffsetMember?.plainTranslate ||
(frameRotation !== undefined ? frameRotation === null : editsPlainCss(sel.element, "rotate"));
- const plainRotation = plain && kind === "rotate" ? readCssRotationTarget(sel.element) : null;
+ const frameCss = plain ? start?.cssRotation : undefined;
+ const plainRotation =
+ plain && kind === "rotate" ? (frameCss?.target ?? readCssRotationTarget(sel.element)) : null;
const rotation = {
- angle: readRotationBase(sel.element, plain, frameRotation ?? undefined),
+ angle: frameCss?.angle ?? readRotationBase(sel.element, plain, frameRotation ?? undefined),
};
const overlayBounds = overlayEl?.getBoundingClientRect();
const centerX = (overlayBounds?.left ?? 0) + rect.left + rect.width / 2;
diff --git a/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts b/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts
index eab4af52cf..bbb8f90b99 100644
--- a/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts
+++ b/packages/studio/src/components/editor/gsapMoveSealedPreview.test.ts
@@ -363,8 +363,8 @@ it("turns a sealed frame's element by its own GSAP, and keeps the turn when the
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);
+async function sealedRotate(script: string, extra = "") {
+ mount(script, extra);
const iframe = opaqueFrame();
const handle = (await queryPreviewElements(iframe, "#box"))!.matches[0]!.handle;
const standIn = standInFor(iframe, (await describePreviewElements(iframe, [handle]))![0]!);
@@ -381,8 +381,8 @@ async function sealedRotate(script: string) {
return { selection, iframe, standIn, pressRotate };
}
-async function pressRotateOnSealedFrame(script: string) {
- const sealed = await sealedRotate(script);
+async function pressRotateOnSealedFrame(script: string, extra = "") {
+ const sealed = await sealedRotate(script, extra);
return { ...sealed, ...(await sealed.pressRotate()) };
}
@@ -414,6 +414,15 @@ it("turns a layer GSAP leaves alone by its own CSS rotate in a sealed preview",
expect(gesture.plainRotation).toMatchObject({ property: "rotate" });
});
+// fails without the fix: the stand-in has no stylesheet, so the turn began at 0 and drew 30deg short.
+it("turns a sealed layer its stylesheet rotates from the angle it shows", async () => {
+ const { gesture } = await pressRotateOnSealedFrame(
+ timeline(""),
+ "",
+ );
+ expect(gesture.actualRotation).toBeCloseTo(30, 6);
+});
+
// 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 () => {
diff --git a/packages/studio/src/components/editor/plainTranslate.ts b/packages/studio/src/components/editor/plainTranslate.ts
index 725bd3017e..de4e384c98 100644
--- a/packages/studio/src/components/editor/plainTranslate.ts
+++ b/packages/studio/src/components/editor/plainTranslate.ts
@@ -1,6 +1,6 @@
import { roundTo3 } from "../../utils/rounding";
import { editsPlainCss } from "../../hooks/gsapRuntimeKeyframes";
-import { readCssRotation } from "../../hooks/draggedGsapPosition";
+import { readCssRotation } from "@hyperframes/core/runtime/css-rotation";
import { readStudioPathOffset, readStudioRotation, styleUsesStudioOffset } from "./manualEditsDom";
import { splitTopLevelWhitespace } from "./manualEditsStyleHelpers";
import {
diff --git a/packages/studio/src/components/editor/previewGestureStartRead.test.ts b/packages/studio/src/components/editor/previewGestureStartRead.test.ts
index 8e3aeb41f6..9e17a5bc4d 100644
--- a/packages/studio/src/components/editor/previewGestureStartRead.test.ts
+++ b/packages/studio/src/components/editor/previewGestureStartRead.test.ts
@@ -159,6 +159,7 @@ describe("a gesture's start on an opaque frame", () => {
gsap: { x: 200, y: 5, moving: false },
gsapRotation: 0,
grow: { a: -0.25, b: 0, c: 0, d: 0.25 },
+ cssRotation: null,
});
const selection = { ...makeSelection("card", standIn), handle };
const made = createManualOffsetDragMember({
diff --git a/packages/studio/src/components/editor/previewGestureStartRead.ts b/packages/studio/src/components/editor/previewGestureStartRead.ts
index 93e61d0d5f..844903f505 100644
--- a/packages/studio/src/components/editor/previewGestureStartRead.ts
+++ b/packages/studio/src/components/editor/previewGestureStartRead.ts
@@ -1,4 +1,5 @@
/** A gesture on a frame Studio cannot script starts from one `gesture-start` read (core `editingGestureStart.ts`). */
+import type { EditingGestureStart } from "@hyperframes/core/runtime/editing-port";
import { previewGestureStart } from "../../player/lib/previewElements";
import { computeOverlayRootScale } from "./domEditOverlayBasis";
import type { DomEditSelection } from "./domEditing";
@@ -18,6 +19,7 @@ export interface PreviewGestureStart {
gsap: { x: number; y: number; moving: boolean } | null;
gsapRotation?: number | null;
grow?: { a: number; b: number; c: number; d: number };
+ cssRotation?: EditingGestureStart["cssRotation"];
}
export interface PreviewGestureStarts {
@@ -79,6 +81,7 @@ export async function measurePreviewGestureStart(
d: start.grow.d * sy,
}
: undefined,
+ cssRotation: start.cssRotation,
},
},
),
diff --git a/packages/studio/src/components/editor/rotationDraft.ts b/packages/studio/src/components/editor/rotationDraft.ts
index e145eb3e7c..922eb17d8c 100644
--- a/packages/studio/src/components/editor/rotationDraft.ts
+++ b/packages/studio/src/components/editor/rotationDraft.ts
@@ -1,114 +1,48 @@
-import { readCssRotation } from "../../hooks/draggedGsapPosition";
+import {
+ readCssRotation,
+ readCssRotationTarget,
+ type CssRotationTarget,
+} from "@hyperframes/core/runtime/css-rotation";
import { roundTo3 } from "../../utils/rounding";
import type { PatchOperation } from "../../utils/sourcePatcher";
+import type { EditingDraftRotate } from "@hyperframes/core/runtime/editing-port";
import {
readStudioRotation,
restoreStudioRotation,
type StudioRotationSnapshot,
} from "./manualEdits";
import { getOffsetDragGsap } from "./manualOffsetDrag";
-import { splitTopLevelWhitespace } from "./manualEditsStyleHelpers";
import { endStudioManualEditGesture, isStudioManualEditGestureCurrent } from "./manualEditGesture";
import { drawPreviewDraft, endPreviewDraft } from "./previewDrafts";
-function lastRuleTransform(element: HTMLElement): string {
- let value = "";
- for (const sheet of Array.from(element.ownerDocument.styleSheets)) {
- let rules: CSSStyleRule[] = [];
- try {
- rules = Array.from(sheet.cssRules) as CSSStyleRule[];
- } catch {
- // a cross-origin sheet
- }
- for (const rule of rules) {
- const declared = rule.style?.getPropertyValue("transform");
- if (declared && element.matches(rule.selectorText)) value = declared;
- }
- }
- return value;
-}
-
-// ponytail: the authored transform if it moves the box, from the last matching rule in sheet order;
-// specificity, !important and @media are not weighed. Weigh them when a film's rule is missed.
-function translatingTransform(element: HTMLElement): string {
- const view = element.ownerDocument.defaultView;
- const computed = view?.getComputedStyle(element).transform ?? "none";
- const m = computed === "none" ? null : new view!.DOMMatrix(computed);
- if (!m || (m.m41 === 0 && m.m42 === 0)) return "";
- const value = element.style.getPropertyValue("transform") || lastRuleTransform(element);
- return value === "none" ? "" : value;
-}
-
-/** Where a plain rotate draws its turn, read once at press: the element's own `rotate`, or, when its
- * transform translates it (often the translate(-50%, -50%) centring), a rotate() right after that
- * translate, so the box turns in place in screen space. `share` is what the rest already turns. */
-export interface CssRotationTarget {
- property: "rotate" | "transform";
- before: string;
- after: string;
- share: number;
- /** -1 when a mirroring `scale` property flips a turn made inside the transform. */
- sign: number;
- /** An inline box does not transform, so the turn makes it inline-block. */
- inline: boolean;
-}
-
+export type { CssRotationTarget };
export type PressChoseGsap = null;
export type RotationCommit = { angle: number; plain?: CssRotationTarget | PressChoseGsap };
-const TRANSLATE = /^translate(?:3d|X|Y|Z)?\(/i;
-const OWN_TURN = /^rotate\(\s*-?[\d.]+(?:e[+-]?\d+)?deg\s*\)$/i;
-
-export function readCssRotationTarget(element: HTMLElement): CssRotationTarget {
- const style = element.ownerDocument.defaultView?.getComputedStyle(element);
- const inline = style?.display === "inline";
- const transform = translatingTransform(element);
- if (!transform) {
- const share = readCssRotation(element, false);
- return { property: "rotate", before: "", after: "", share, sign: 1, inline };
- }
- const parts = splitTopLevelWhitespace(transform);
- const lead = parts.findIndex((part) => !TRANSLATE.test(part));
- const split = lead < 0 ? parts.length : lead;
- const rest = parts.slice(split);
- if (OWN_TURN.test(rest[0] ?? "")) rest.shift();
- const [before, after] = [parts.slice(0, split).join(" "), rest.join(" ")];
- const [sx = 1, sy = sx] = splitTopLevelWhitespace(style?.getPropertyValue("scale") ?? "").map(
- Number.parseFloat,
- );
- const inlineStyle = element.style;
- const saved = [
- inlineStyle.getPropertyValue("transform"),
- inlineStyle.getPropertyPriority("transform"),
- ];
- inlineStyle.setProperty("transform", `${before} ${after}`.trim() || "none");
- const share = readCssRotation(element);
- inlineStyle.setProperty("transform", saved[0] ?? "", saved[1] ?? "");
- return { property: "transform", before, after, share, sign: sx * sy < 0 ? -1 : 1, inline };
-}
+export { readCssRotationTarget };
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 };
+const frameTurn = (angle: number, plain: CssRotationTarget | null): EditingDraftRotate => {
+ if (!plain) return { angle, route: "gsap" };
+ const turn = cssTurn(angle, plain);
return plain.property === "rotate"
- ? { angle: cssTurn(angle, plain), route: "css" as const }
- : null;
+ ? { angle: turn, route: "css" }
+ : { angle: turn, route: "transform", value: turnedTransform(turn, plain) };
};
+const turnedTransform = (turn: number, target: CssRotationTarget) =>
+ [target.before, `rotate(${turn}deg)`, target.after].filter(Boolean).join(" ");
+
/** 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 = `${cssTurn(angle, target)}deg`;
- const value =
- target.property === "rotate"
- ? turn
- : [target.before, `rotate(${turn})`, target.after].filter(Boolean).join(" ");
+ const turn = cssTurn(angle, target);
+ const value = target.property === "rotate" ? `${turn}deg` : turnedTransform(turn, target);
const patches: Array = [
{ type: "inline-style", property: target.property, value },
];
@@ -132,8 +66,7 @@ export function applyRotationDraft(
angle: number,
plain: CssRotationTarget | null,
): void {
- const rotate = frameTurn(angle, plain);
- if (rotate) drawPreviewDraft(element, { rotate });
+ drawPreviewDraft(element, { rotate: frameTurn(angle, plain) });
if (plain) return void applyCssRotation(element, angle, plain);
element.style.setProperty("rotate", "none");
getOffsetDragGsap(element)?.set(element, { rotation: angle });
diff --git a/packages/studio/src/hooks/draggedGsapPosition.ts b/packages/studio/src/hooks/draggedGsapPosition.ts
index acfaa635a3..ea9471c36b 100644
--- a/packages/studio/src/hooks/draggedGsapPosition.ts
+++ b/packages/studio/src/hooks/draggedGsapPosition.ts
@@ -9,34 +9,6 @@ import { STUDIO_EDIT_MOMENT_ATTR, type EditMoment } from "../components/editor/m
* it without pulling the GSAP commit graph into its module scope.
*/
-const cssValue = (style: CSSStyleDeclaration, prop: string) => {
- const value = style.getPropertyValue(prop).trim();
- return value === "none" ? "" : value;
-};
-
-// Without GSAP, the rotation GSAP will parse from the CSS `rotate`, `scale` and `transform`; with
-// `withRotate` false, only the part `scale` and `transform` draw. GSAP folds them into one transform,
-// and a list the browser rejects (e.g. `rotate: x 30deg`) leaves it only the plain transform.
-export function readCssRotation(element: HTMLElement, withRotate = true): number {
- const view = element.ownerDocument.defaultView;
- if (!view) return 0;
- const style = view.getComputedStyle(element);
- const rotate = withRotate ? cssValue(style, "rotate") : "";
- const scale = cssValue(style, "scale");
- const transform = cssValue(style, "transform");
- const angle = (list: string) => {
- if (!list) return 0;
- const m = new view.DOMMatrix(list);
- return (Math.atan2(m.b, m.a) * 180) / Math.PI;
- };
- const folded = [rotate && `rotate(${rotate})`, scale && `scale(${scale.split(/\s+/).join(",")})`];
- try {
- return angle([...folded, transform].join(" ").trim());
- } catch {
- return angle(transform);
- }
-}
-
export const DRAG_MOVING_ATTR = "data-hf-drag-gsap-moving";
export interface DragStamp {
diff --git a/packages/studio/src/player/lib/previewElements.test.ts b/packages/studio/src/player/lib/previewElements.test.ts
index affd510544..3586762549 100644
--- a/packages/studio/src/player/lib/previewElements.test.ts
+++ b/packages/studio/src/player/lib/previewElements.test.ts
@@ -7,11 +7,14 @@ import {
MAX_ELEMENT_VALUE,
type EditingElementDescription,
} from "@hyperframes/core/runtime/editing-port";
+import { gestureStart } from "../../../../core/src/runtime/editingGestureStart";
+import { handleFor } from "../../../../core/src/runtime/editingHandles";
import {
describePreviewElements,
previewElementSelectorIndex,
previewElementSourceFile,
previewElementsAtPoint,
+ previewGestureStart,
previewStackingSiblings,
readPreviewElement,
type PreviewElement,
@@ -157,6 +160,33 @@ describe("element requests over an opaque frame's port", () => {
expect(handed).not.toHaveBeenCalled();
});
+ // fails without the fix: the frame's reading of a CSS turn never reached Studio, and its text goes into the source.
+ it("takes a frame's CSS turn only with plain transform text", async () => {
+ document.body.innerHTML = ``;
+ const [start] = gestureStart([handleFor(document.getElementById("card")!)]).elements;
+ let after = "scale(2)";
+ const { iframe } = opaqueFrame(() => ({
+ elements: [
+ {
+ ...start,
+ cssRotation: { ...start!.cssRotation!, target: { ...start!.cssRotation!.target, after } },
+ },
+ ],
+ snap: [],
+ }));
+ const read = async () => (await previewGestureStart(iframe, [h(1)]))!.elements[0]!.cssRotation;
+ expect(await read()).toMatchObject({ target: { after: "scale(2)" } });
+ for (after of [
+ "url(https://example.com/x)",
+ "translate(1px",
+ "scale(2) /* x",
+ "scale(2));color:red",
+ ])
+ expect(await read()).toBeUndefined();
+ after = "translateX(calc(10px + var(--a))) rotate(1deg)";
+ expect(await read()).toMatchObject({ target: { after } });
+ });
+
it("reads an element's stacking family, and refuses one that is not a family of it", async () => {
const family = [
{ handle: h(1), zIndex: 1 },
diff --git a/packages/studio/src/player/lib/previewElements.ts b/packages/studio/src/player/lib/previewElements.ts
index a7b15d7625..e925ec15be 100644
--- a/packages/studio/src/player/lib/previewElements.ts
+++ b/packages/studio/src/player/lib/previewElements.ts
@@ -14,6 +14,7 @@ import {
MAX_QUERY_MATCHES,
MAX_SNAP_TARGETS,
MAX_SOURCE_GROUPS,
+ isTransformList,
type EditingElementBox,
type EditingElementDescription,
type EditingElementGeometry,
@@ -258,14 +259,32 @@ const isTurnOrNull = (value: unknown) =>
const kept = (value: T, valid: boolean) => (valid ? value : undefined);
-export type ReadGestureStart = Omit & {
+const isTurn = (value: unknown) => value !== null && isTurnOrNull(value);
+
+const isRotationTarget = (target: unknown) =>
+ isFields(target) &&
+ (target.property === "rotate" || target.property === "transform") &&
+ isTransformList(target.before) &&
+ isTransformList(target.after) &&
+ isTurn(target.share) &&
+ (target.sign === 1 || target.sign === -1) &&
+ isFlag(target.inline);
+
+const isCssRotation = (value: unknown) =>
+ value === null || (isFields(value) && isTurn(value.angle) && isRotationTarget(value.target));
+
+export type ReadGestureStart = Omit<
+ EditingGestureStart,
+ "gsapRotation" | "cssRotation" | "planar" | "grow"
+> & {
gsapRotation?: number | null;
grow?: EditingGestureStart["grow"];
+ cssRotation?: EditingGestureStart["cssRotation"];
};
const readGestureStart = (value: unknown): ReadGestureStart | null => {
if (!readGeometry(value) || !isFields(value)) return null;
- const { layout, move, gsap, gsapRotation, grow } = value;
+ const { layout, move, gsap, gsapRotation, grow, cssRotation } = value;
const valid = [
isLayout(layout),
move === null || isFiniteFields(move, ["a", "b", "c", "d"]),
@@ -277,6 +296,7 @@ const readGestureStart = (value: unknown): ReadGestureStart | null => {
...start,
gsapRotation: kept(start.gsapRotation, isTurnOrNull(gsapRotation)),
grow: kept(start.grow, isFiniteFields(grow, ["a", "b", "c", "d"])),
+ cssRotation: kept(start.cssRotation, isCssRotation(cssRotation)),
};
};