Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/core/package-subpaths.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
10 changes: 10 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -1023,6 +1029,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"
Expand Down
113 changes: 113 additions & 0 deletions packages/core/src/runtime/editing/cssRotation.ts
Original file line number Diff line number Diff line change
@@ -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),
});
39 changes: 39 additions & 0 deletions packages/core/src/runtime/editingAgent.test.ts
Original file line number Diff line number Diff line change
@@ -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 };
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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",
'<div id="spun" style="transform: translate(-50%, -50%)"></div>',
);
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 = `<p id="title" style="color: rgb(1, 2, 3); opacity: 0.5">Hi</p>
<canvas data-hf-preview-video-canvas style="opacity: 0.25"></canvas>
Expand Down
11 changes: 11 additions & 0 deletions packages/core/src/runtime/editingDraft.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, number>([[element, 12]]);
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/runtime/editingDraft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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");
Expand Down
12 changes: 12 additions & 0 deletions packages/core/src/runtime/editingGestureStart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)]);
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/runtime/editingGestureStart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
SIZE_PROPERTIES,
writeDrawnSize,
} from "./editingDraft";
import { readCssRotationStart, type CssRotationStart } from "./editing/cssRotation";
import {
boxOf,
elementGeometry,
Expand All @@ -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;
}

Expand Down Expand Up @@ -193,13 +195,15 @@ export function gestureStart(handles: readonly EditingElementHandle[]): {
if (!geometry || !isStylableElement(element)) return null;
const { offsetWidth = 0, offsetHeight = 0 } = element as Partial<HTMLElement>;
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),
};
});
Expand Down
31 changes: 28 additions & 3 deletions packages/core/src/runtime/editingPort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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<string, unknown> =>
(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;
}

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/runtime/positionEdits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading