diff --git a/packages/core/src/runtime/editingGeometry.test.ts b/packages/core/src/runtime/editingGeometry.test.ts index a26737e3b4..b92a790f19 100644 --- a/packages/core/src/runtime/editingGeometry.test.ts +++ b/packages/core/src/runtime/editingGeometry.test.ts @@ -13,6 +13,11 @@ const CONNECT = { source: "hf-parent", type: "editing-connect", v: 1 }; // jsdom has neither; the 2D slice of each is all the geometry reads. class FakeDOMMatrix { a = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; b = 0; c = 0; d = 1; diff --git a/packages/core/src/runtime/editingGeometry.ts b/packages/core/src/runtime/editingGeometry.ts index 5244b0c970..d26e8ce142 100644 --- a/packages/core/src/runtime/editingGeometry.ts +++ b/packages/core/src/runtime/editingGeometry.ts @@ -12,7 +12,7 @@ import { type EditingRect, } from "./editingElement"; import { elementForHandle } from "./editingHandles"; -import { composeElementTransform, type PlanarTransformOps } from "./elementTransform"; +import { composeElementTransform } from "./elementTransform"; export type EditingCorner = "nw" | "ne" | "sw" | "se"; export type EditingCorners = Record; @@ -103,17 +103,10 @@ export function readElementTransformSnapshot( const DOMMatrixCtor = (win as Window & typeof globalThis).DOMMatrix; if (!DOMMatrixCtor) return null; const cs = win.getComputedStyle(element); - // The corner math transforms points, so this keeps the full matrix, translation included. - const ops: PlanarTransformOps = { - identity: () => new DOMMatrixCtor(), - fromTransform: (value) => new DOMMatrixCtor(value), - fromRotate: (degrees) => new DOMMatrixCtor().rotateSelf(degrees), - compose: (outer, inner) => outer.multiply(inner), - }; try { const matrix = composeElementTransform( element, - ops, + DOMMatrixCtor, (node) => (node === element ? cs : win.getComputedStyle(node)), memo, ); @@ -212,6 +205,8 @@ const finiteCorners = (corners: EditingCorners | null) => ? corners : null; +const turnedMirroredOrSkewed = ({ a, b, c, d }: DOMMatrix) => b !== 0 || c !== 0 || a < 0 || d < 0; + export function boxOf( element: HTMLElement, memo: Map, @@ -219,7 +214,10 @@ export function boxOf( const transform = readElementTransformSnapshot(window, element, memo); const turned = transform ? rotationDegreesFromMatrix(transform.matrix) : 0; const angle = Math.abs(turned) < ROTATION_GATE_EPSILON_DEG ? 0 : turned; - const corners = angle && transform ? elementCornerPoints(window, element, transform) : null; + const corners = + transform && turnedMirroredOrSkewed(transform.matrix) + ? elementCornerPoints(window, element, transform) + : null; return { rect: rectOf(element), angle, diff --git a/packages/core/src/runtime/editingGestureStart.test.ts b/packages/core/src/runtime/editingGestureStart.test.ts index 1efc9517d1..a64072f0ab 100644 --- a/packages/core/src/runtime/editingGestureStart.test.ts +++ b/packages/core/src/runtime/editingGestureStart.test.ts @@ -59,6 +59,11 @@ const GSAP_RENDERS = { _gsap: { renderTransform: () => {} } }; /** jsdom has no DOMMatrix: a 2D one reading `matrix(...)` and composing as the browser's does. */ class Matrix2D { a = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; b = 0; c = 0; d = 1; diff --git a/packages/core/src/runtime/editingPort.ts b/packages/core/src/runtime/editingPort.ts index a8a7d3b27a..3a9307edc1 100644 --- a/packages/core/src/runtime/editingPort.ts +++ b/packages/core/src/runtime/editingPort.ts @@ -168,11 +168,6 @@ export { type EditingStackingSibling, type LayerKind, } from "./editingLayers"; -export { - composeElementTransform, - individualRotateDegrees, - type PlanarTransformOps, -} from "./elementTransform"; export const EDITING_PROTOCOL_VERSION = 1 as const; /** Parent to frame, on the window: asks the runtime for the port. */ diff --git a/packages/core/src/runtime/elementTransform.test.ts b/packages/core/src/runtime/elementTransform.test.ts new file mode 100644 index 0000000000..4a75d8e252 --- /dev/null +++ b/packages/core/src/runtime/elementTransform.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { rotateFunction, scaleFunction } from "./elementTransform"; + +describe("the individual properties as transform functions", () => { + it("writes each computed rotate form Chrome serializes", () => { + expect(rotateFunction("45deg")).toBe("rotate(45deg)"); + expect(rotateFunction("x 30deg")).toBe("rotateX(30deg)"); + expect(rotateFunction("1 1 0 30deg")).toBe("rotate3d(1, 1, 0, 30deg)"); + expect(rotateFunction("none")).toBe(""); + expect(rotateFunction(undefined)).toBe(""); + }); + + it("writes each computed scale form, a depth scale as scale3d", () => { + expect(scaleFunction("2")).toBe("scale(2)"); + expect(scaleFunction("2 3")).toBe("scale(2, 3)"); + expect(scaleFunction("1 1 2")).toBe("scale3d(1, 1, 2)"); + expect(scaleFunction("none")).toBe(""); + }); +}); diff --git a/packages/core/src/runtime/elementTransform.ts b/packages/core/src/runtime/elementTransform.ts index 59d755da9e..89252858f2 100644 --- a/packages/core/src/runtime/elementTransform.ts +++ b/packages/core/src/runtime/elementTransform.ts @@ -1,109 +1,78 @@ /** - * One walk from an element up to its composition root, composing the transform - * it actually paints under. - * - * The overlay measures an element's angle in two places — the selection box and - * the crop frame — and they need different arithmetic: one works in DOMMatrix - * because it goes on to transform corner points, the other in plain 2D - * components because it only needs an angle and a scale. What they must never - * differ on is *which* transforms count and in what order, because when they - * disagree the chrome disagrees with itself: the selection box drawn at one - * angle and the crop outline at another, on the same element. - * - * So the walk lives here once and takes the arithmetic as a parameter. Adding - * an individual property CSS grew later — `translate`, `scale` — means adding - * one step here and one method to each algebra, rather than finding both walks - * and hoping. + * The one matrix every overlay measure reads: each node's `rotate`, `scale` and `transform`, in CSS's + * order, parsed and composed by the browser's `DOMMatrix`; null once a node or the chain leaves the plane. `translate` + * never changes a shape (callers re-anchor to the measured box) and `DOMMatrix` refuses its `50%`. */ /** The composition's own root; the walk stops there rather than at the document. */ const COMPOSITION_ROOT_ATTR = "data-composition-id"; -/** - * The arithmetic the walk needs, whatever the caller's matrix type is. - * - * `fromTransform` returns null for a transform the caller cannot use — a - * perspective matrix, say — which aborts the walk rather than composing a - * matrix that describes something other than what is painted. - */ -export interface PlanarTransformOps { - identity(): M; - fromTransform(value: string): M | null; - fromRotate(degrees: number): M; - /** `outer` applied around `inner`, as an ancestor composes over a child. */ - compose(outer: M, inner: M): M; +/** Computed `rotate` (`45deg`, `x 30deg`, `1 1 0 30deg`) as its transform function; "" for none. */ +export function rotateFunction(value: string | undefined): string { + const parts = value && value !== "none" ? value.trim().split(/\s+/) : []; + const angle = parts.pop(); + if (!angle) return ""; + if (parts.length === 0) return `rotate(${angle})`; + if (parts.length === 1) return `rotate${parts[0]!.toUpperCase()}(${angle})`; + return `rotate3d(${parts.join(", ")}, ${angle})`; } -/** - * The planar rotation in the CSS `rotate` property, in degrees. - * - * Computes to `none`, an angle (`-22deg`), or an axis plus an angle - * (`0 0 1 -22deg`). Only a rotation about z stays in the overlay's plane; any - * other axis is 3D and reports 0, which leaves the caller on its axis-aligned - * fallback rather than drawing a box at a plausible-looking wrong angle. - */ -export function individualRotateDegrees(value: string | undefined): number { - if (!value || value === "none") return 0; - const parts = value.trim().split(/\s+/); - const angle = parts.at(-1); - if (!angle?.endsWith("deg")) return 0; - if (parts.length === 4) { - const [x, y, z] = parts; - if (Number(x) !== 0 || Number(y) !== 0 || Math.abs(Number(z)) !== 1) return 0; - const deg = Number.parseFloat(angle); - return Number.isFinite(deg) ? deg * Math.sign(Number(z)) : 0; - } - if (parts.length !== 1) return 0; - const deg = Number.parseFloat(angle); - return Number.isFinite(deg) ? deg : 0; +/** Computed `scale` (`2`, `2 3`, `1 1 2`) as its transform function; "" for none. */ +export function scaleFunction(value: string | undefined): string { + const parts = value && value !== "none" ? value.trim().split(/\s+/) : []; + if (parts.length === 0) return ""; + return `${parts.length === 3 ? "scale3d" : "scale"}(${parts.join(", ")})`; } -/** One node's own contribution, with the individual properties applied before - * `transform` the way CSS does. Null when the node's transform is unusable. */ -function ownNodeTransform( +function ownNodeTransform( node: HTMLElement, - ops: PlanarTransformOps, + Matrix: typeof DOMMatrix, getStyle: (node: HTMLElement) => CSSStyleDeclaration | null, -): M | null { +): DOMMatrix | null { const style = getStyle(node); - if (!style) return null; - const transform = style.transform; - const own = transform && transform !== "none" ? ops.fromTransform(transform) : ops.identity(); - if (!own) return null; - const spin = individualRotateDegrees(style.rotate); - return spin === 0 ? own : ops.compose(ops.fromRotate(spin), own); + if (!style || inThreeDContext(node, getStyle)) return null; + const transform = style.transform && style.transform !== "none" ? style.transform : ""; + const list = [rotateFunction(style.rotate), scaleFunction(style.scale), transform]; + try { + const own = new Matrix(list.filter(Boolean).join(" ")); + return planar(own) ? own : null; + } catch { + return null; + } } -/** - * The element's transform composed with every ancestor's, up to the composition - * root. - * - * Within a node, CSS applies the individual properties before `transform`, so - * `rotate` composes on the left of it. Between nodes, an ancestor applies - * outside its child. Null means some node's transform was unusable and the - * caller should fall back rather than guess. - * - * `memo` holds each node's COMPOSED chain, for a caller walking many elements - * in one synchronous pass. - * - * A chain is `chain(parent)` composed with the node's own, so siblings share - * everything above them and the whole tree costs one style read and one - * compose per node instead of one per node PER DESCENDANT. Valid only for the - * length of one pass, which is why the caller owns it: nothing here writes to - * the DOM, so nothing can move under it, and it is dropped before anything - * else runs. Omitted, every call composes its own chain from scratch. - */ -export function composeElementTransform( - element: HTMLElement, - ops: PlanarTransformOps, +/** A parent's `perspective` or `preserve-3d` projects its children in ways a matrix product does not show. */ +function inThreeDContext( + node: HTMLElement, getStyle: (node: HTMLElement) => CSSStyleDeclaration | null, - memo?: Map, -): M | null { +) { + const parent = node.parentElement && getStyle(node.parentElement); + if (!parent) return false; + return ( + (!!parent.perspective && parent.perspective !== "none") || + parent.transformStyle === "preserve-3d" + ); +} + +/** Keeps the layer's plane flat and unprojected; anything else is left to the box the browser paints. */ +const planar = (m: DOMMatrix) => + [m.m13, m.m23, m.m14, m.m24, m.m44 - 1].every((v) => Math.abs(v) < 1e-9); + +/** + * The element's transform composed with every ancestor's, up to the composition root; an ancestor + * applies outside its child. Null when some node's transform cannot be parsed, so the caller falls back. + * + * `memo` holds each node's composed chain for a caller walking many elements in one synchronous pass: + * siblings share everything above them. Valid only for that pass, which is why the caller owns it. + */ +export function composeElementTransform( + element: HTMLElement, + Matrix: typeof DOMMatrix, + getStyle: (node: HTMLElement) => CSSStyleDeclaration | null, + memo?: Map, +): DOMMatrix | null { const pending: HTMLElement[] = []; - // `undefined` means nothing on the way up was already composed, so the chain - // starts from identity. A memoized `null` is an answer, not a miss: some node - // above carries a transform this algebra cannot represent. - let above: M | null | undefined; + let above: DOMMatrix | null | undefined; for (let node: HTMLElement | null = element; node; node = node.parentElement) { above = memo?.get(node); if (above !== undefined) break; @@ -111,14 +80,13 @@ export function composeElementTransform( if (node.hasAttribute(COMPOSITION_ROOT_ATTR)) break; } - let acc: M | null = above === undefined ? ops.identity() : above; + let acc: DOMMatrix | null = above === undefined ? new Matrix() : above; for (let i = pending.length - 1; i >= 0; i -= 1) { const node = pending[i]!; if (acc !== null) { - const own = ownNodeTransform(node, ops, getStyle); - // The ancestors' chain is the OUTER of the pair, as an ancestor applies - // around its child. - acc = own === null ? null : ops.compose(acc, own); + const own = ownNodeTransform(node, Matrix, getStyle); + const composed = own && acc.multiply(own); + acc = composed && planar(composed) ? composed : null; } memo?.set(node, acc); } diff --git a/packages/studio/src/components/editor/domEditOverlayCrop.test.ts b/packages/studio/src/components/editor/domEditOverlayCrop.test.ts index 088dd0f221..bb1211ce8c 100644 --- a/packages/studio/src/components/editor/domEditOverlayCrop.test.ts +++ b/packages/studio/src/components/editor/domEditOverlayCrop.test.ts @@ -8,7 +8,6 @@ import { resolveCropInsetFromMoveDrag, rotateDeltaIntoFrame, } from "./domEditOverlayCrop"; -import { individualRotateDegrees } from "@hyperframes/core/runtime/editing-port"; describe("resolveCropInsetFromEdgeDrag", () => { const startInsets = { top: 10, right: 20, bottom: 30, left: 40 }; @@ -158,6 +157,38 @@ describe("readElementCropInsets tri-state", () => { // Regression: crop UI drawn on the axis-aligned bounding box visually // "straightens" a rotated element — the dim masks the rotated corners. The // frame gives the element's own box + rotation so the UI rotates with it. +// A computed `transform` is always `matrix(...)` or `matrix3d(...)`, so this reads only those two forms. +class ComputedMatrix { + a = 1; + b = 0; + c = 0; + d = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; + constructor(list = "") { + const flat = /^matrix\(([^)]+)\)$/.exec(list)?.[1]?.split(",").map(Number); + const deep = /^matrix3d\(([^)]+)\)$/.exec(list)?.[1]?.split(",").map(Number); + if (flat) [this.a, this.b, this.c, this.d] = flat; + if (deep) + [this.a, this.b, this.c, this.d, this.m13, this.m23, this.m14, this.m24, this.m44] = [ + 0, 1, 4, 5, 2, 6, 3, 7, 15, + ].map((i) => deep[i]!); + } + multiply(inner: ComputedMatrix) { + const out = new ComputedMatrix(); + out.a = this.a * inner.a + this.c * inner.b; + out.b = this.b * inner.a + this.d * inner.b; + out.c = this.a * inner.c + this.c * inner.d; + out.d = this.b * inner.c + this.d * inner.d; + for (const k of ["m13", "m23", "m14", "m24"] as const) out[k] = this[k] + inner[k]; + out.m44 = this.m44 * inner.m44; + return out; + } +} + describe("readElementCropFrame", () => { const overlayRect = { left: 100, top: 50, width: 220, height: 130, editScaleX: 1, editScaleY: 1 }; @@ -170,7 +201,9 @@ describe("readElementCropFrame", () => { offsetHeight, parentElement: null, hasAttribute: () => false, - ownerDocument: { defaultView: { getComputedStyle: () => ({ transform }) } }, + ownerDocument: { + defaultView: { DOMMatrix: ComputedMatrix, getComputedStyle: () => ({ transform }) }, + }, }) as unknown as HTMLElement; it("identity transform → the axis-aligned overlay rect", () => { @@ -282,38 +315,6 @@ describe("rotateDeltaIntoFrame", () => { }); }); -describe("individualRotateDegrees", () => { - /** - * Studio's rotate handle writes the CSS `rotate` property, not `transform`. - * Everything that measured an element's angle read `transform` alone, so a - * turned element reported upright and the selection box, crop outline and - * child outlines all drew square across it. - */ - it("reads a plain angle", () => { - expect(individualRotateDegrees("-22deg")).toBeCloseTo(-22, 6); - expect(individualRotateDegrees("45deg")).toBeCloseTo(45, 6); - }); - - it("reads an explicit z-axis rotation, honouring the axis sign", () => { - expect(individualRotateDegrees("0 0 1 30deg")).toBeCloseTo(30, 6); - expect(individualRotateDegrees("0 0 -1 30deg")).toBeCloseTo(-30, 6); - }); - - it("reports nothing for a rotation that leaves the overlay's plane", () => { - // A 3D turn has no single in-plane angle. Reporting one would draw the - // chrome at a plausible-looking wrong angle instead of falling back square. - expect(individualRotateDegrees("1 0 0 45deg")).toBe(0); - expect(individualRotateDegrees("0 1 0 45deg")).toBe(0); - }); - - it("reports nothing when the property is absent or unparseable", () => { - expect(individualRotateDegrees("none")).toBe(0); - expect(individualRotateDegrees(undefined)).toBe(0); - expect(individualRotateDegrees("")).toBe(0); - expect(individualRotateDegrees("12")).toBe(0); - }); -}); - describe("readElementCropFrame — the composed walk", () => { /** * The case the crop outline got wrong: a text layer inside a rotated card. @@ -328,7 +329,9 @@ describe("readElementCropFrame — the composed walk", () => { offsetHeight: 300, parentElement: null, hasAttribute: (name: string) => name === "data-composition-id", - ownerDocument: { defaultView: { getComputedStyle: () => style(parentTransform) } }, + ownerDocument: { + defaultView: { DOMMatrix: ComputedMatrix, getComputedStyle: () => style(parentTransform) }, + }, }; return { offsetWidth: 200, @@ -337,6 +340,7 @@ describe("readElementCropFrame — the composed walk", () => { hasAttribute: () => false, ownerDocument: { defaultView: { + DOMMatrix: ComputedMatrix, getComputedStyle: (node: unknown) => node === parent ? style(parentTransform) : style(childTransform), }, diff --git a/packages/studio/src/components/editor/domEditOverlayCrop.ts b/packages/studio/src/components/editor/domEditOverlayCrop.ts index 8bd3b74ec9..32774ee389 100644 --- a/packages/studio/src/components/editor/domEditOverlayCrop.ts +++ b/packages/studio/src/components/editor/domEditOverlayCrop.ts @@ -1,8 +1,6 @@ import { - composeElementTransform, elementCornerPoints, readElementTransformSnapshot, - type PlanarTransformOps, } from "@hyperframes/core/runtime/editing-port"; import { parseInsetClipPathSides, @@ -22,25 +20,42 @@ export interface CropScreenRect { height: number; } -/** Element-space insets → the cropped region in overlay (screen) space. */ +/** + * Element-space insets → the cropped region's bounds in overlay (screen) space. With `corners` (a transformed + * layer's own corners) the insets cut along its own edges; insets that cross shrink until they meet, as CSS does. + */ export function cropRectFromInsets( rect: CropScreenRect, insets: ClipPathInsetSides, scaleX: number, scaleY: number, + corners?: OwnCorners, ): CropScreenRect { const sx = scaleX > 0 ? scaleX : 1; const sy = scaleY > 0 ? scaleY : 1; - const left = rect.left + insets.left * sx; - const top = rect.top + insets.top * sy; - return { - left, - top, - width: Math.max(0, rect.width - (insets.left + insets.right) * sx), - height: Math.max(0, rect.height - (insets.top + insets.bottom) * sy), + const { left: x, top: y, width: w, height: h } = rect; + const { nw, ne, sw } = corners ?? { nw: { x, y }, ne: { x: x + w, y }, sw: { x, y: y + h } }; + const [width, height] = [edge(nw, ne), edge(nw, sw)]; + const [l, r] = meet(insets.left * sx, insets.right * sx, width); + const [t, b] = meet(insets.top * sy, insets.bottom * sy, height); + const at = (u: number, v: number) => { + const [fu, fv] = [width > 0 ? u / width : 0, height > 0 ? v / height : 0]; + return { + x: nw.x + (ne.x - nw.x) * fu + (sw.x - nw.x) * fv, + y: nw.y + (ne.y - nw.y) * fu + (sw.y - nw.y) * fv, + }; }; + const cut = [at(l, t), at(width - r, t), at(width - r, height - b), at(l, height - b)]; + const xs = cut.map((p) => p.x); + const ys = cut.map((p) => p.y); + const [left, top] = [Math.min(...xs), Math.min(...ys)]; + return { left, top, width: Math.max(...xs) - left, height: Math.max(...ys) - top }; } +const edge = (a: Point, b: Point) => Math.hypot(b.x - a.x, b.y - a.y); +const meet = (a: number, b: number, side: number): [number, number] => + a + b > side && a + b > 0 ? [(a * side) / (a + b), (b * side) / (a + b)] : [a, b]; + // A selected croppable element shows uncropped so the crop UI can dim what is cut away. A rule keyed on its // identity does that, so the element's own clip-path stays the one record undo, redo and panel edits rewrite. // A sealed preview's lift is that rule in the frame (core `editing/cropLift.ts`), and `rule` is null. @@ -262,9 +277,13 @@ export function hugRectForElement(rect: HugRect, element: HTMLElement): CropScre type HugRect = CropScreenRect & { editScaleX: number; editScaleY: number; - ownScale?: { x: number; y: number }; + ownScale?: OwnScale; angle?: number; }; +type Point = { x: number; y: number }; +type OwnCorners = Record<"nw" | "ne" | "se" | "sw", Point>; +/** Overlay px per own CSS px along the layer's edges, and its own corners in overlay px when it is transformed. */ +export type OwnScale = { x: number; y: number; corners?: OwnCorners }; /** A live element's own-axis scale: an oriented rect's edges, or its turned corners' edges over its upright box. */ function liveOwnScale(rect: HugRect, element: HTMLElement): HugRect["ownScale"] { @@ -277,12 +296,17 @@ function liveOwnScale(rect: HugRect, element: HTMLElement): HugRect["ownScale"] const corners = transform && elementCornerPoints(win, element, transform); const box = element.getBoundingClientRect(); if (!corners || !(box.width > 0 && box.height > 0)) return upright; - const edge = (a: { x: number; y: number }, b: { x: number; y: number }) => - Math.hypot(b.x - a.x, b.y - a.y); - return { - x: (edge(corners.nw, corners.ne) / box.width) * upright.x, - y: (edge(corners.nw, corners.sw) / box.height) * upright.y, + const toOverlay = ({ x, y }: Point) => ({ + x: rect.left + ((x - box.left) * rect.width) / box.width, + y: rect.top + ((y - box.top) * rect.height) / box.height, + }); + const own = { + nw: toOverlay(corners.nw), + ne: toOverlay(corners.ne), + se: toOverlay(corners.se), + sw: toOverlay(corners.sw), }; + return { x: edge(own.nw, own.ne) / w, y: edge(own.nw, own.sw) / h, corners: own }; } const ownScaleXY = (own: HugRect["ownScale"], rect: HugRect): [number, number] => [ @@ -300,7 +324,9 @@ export function hugRectForClipPath( // Uneditable clip — show the full element rect. if (!insets || (insets.top <= 0 && insets.right <= 0 && insets.bottom <= 0 && insets.left <= 0)) return rect; - return cropRectFromInsets(rect, insets, ...ownScaleXY(ownScaleOf(), rect)); + const own = ownScaleOf(); + const corners = rect.angle === undefined ? own?.corners : undefined; + return cropRectFromInsets(rect, insets, ...ownScaleXY(own, rect), corners); } /** @@ -327,94 +353,28 @@ export interface CropFrame { scaleY: number; } -/** - * The element's own 2D transform as matrix components, plus the `rotate` - * property's angle. - * - * `rotate` is a separate CSS property, not part of `transform`, and it is the - * one Studio's rotate handle writes — reading `transform` alone reported a - * turned element as upright, so the crop outline drew square across it. - * - * Null means there is nothing planar to draw against: no transform and no - * rotation, or a 3D/unparseable matrix. The caller falls back to the - * axis-aligned box rather than guessing an angle. - */ -const IDENTITY = { a: 1, b: 0, c: 0, d: 1 }; - -/** Perspective terms this far from zero mean the mapping is not affine. */ -const PERSPECTIVE_EPSILON = 1e-6; +/** Components this close to the identity's count as the identity. */ +const IDENTITY_EPSILON = 1e-6; type Planar2D = { a: number; b: number; c: number; d: number }; -/** - * The 2D components of a computed transform, or null when it cannot be used. - * - * Accepts `matrix3d` as well as `matrix`, taking the same 2D projection the - * rest of the overlay reads through DOMMatrix. GSAP writes a 3D matrix for an - * ordinary 2D move or spin (force3D), and a composition that flips an element - * writes one with a negative z scale — treating either as unmeasurable left the - * crop outline square on an element every other piece of chrome drew rotated. - * - * Only a perspective term rules the matrix out, because that is where the - * mapping stops being affine and a single angle stops describing it. - */ -function parseMatrixComponents(transform: string): Planar2D | null { - const flat = /^matrix\(([^)]+)\)$/.exec(transform); - if (flat) { - const [a, b, c, d] = flat[1]!.split(",").map((v) => Number.parseFloat(v)); - return [a, b, c, d].every(Number.isFinite) ? { a: a!, b: b!, c: c!, d: d! } : null; - } - const spatial = /^matrix3d\(([^)]+)\)$/.exec(transform); - if (!spatial) return null; - const m = spatial[1]!.split(",").map((v) => Number.parseFloat(v)); - if (m.length !== 16 || !m.every(Number.isFinite)) return null; - const affine = [m[3], m[7], m[11]].every((v) => Math.abs(v!) < PERSPECTIVE_EPSILON); - if (!affine) return null; - return { a: m[0]!, b: m[1]!, c: m[4]!, d: m[5]! }; -} - -/** The crop frame only needs an angle and a scale, so it composes plain 2D components. */ -const PLANAR_2D_OPS: PlanarTransformOps = { - identity: () => IDENTITY, - fromTransform: parseMatrixComponents, - fromRotate: (degrees) => { - const rad = (degrees * Math.PI) / 180; - return { a: Math.cos(rad), b: Math.sin(rad), c: -Math.sin(rad), d: Math.cos(rad) }; - }, - compose: (outer, inner) => ({ - a: outer.a * inner.a + outer.c * inner.b, - b: outer.b * inner.a + outer.d * inner.b, - c: outer.a * inner.c + outer.c * inner.d, - d: outer.b * inner.c + outer.d * inner.d, - }), -}; - /** Whether the matrix leaves the box exactly as it found it. */ function isIdentity(m: Planar2D): boolean { return ( - Math.abs(m.a - 1) < PERSPECTIVE_EPSILON && - Math.abs(m.b) < PERSPECTIVE_EPSILON && - Math.abs(m.c) < PERSPECTIVE_EPSILON && - Math.abs(m.d - 1) < PERSPECTIVE_EPSILON + Math.abs(m.a - 1) < IDENTITY_EPSILON && + Math.abs(m.b) < IDENTITY_EPSILON && + Math.abs(m.c) < IDENTITY_EPSILON && + Math.abs(m.d - 1) < IDENTITY_EPSILON ); } -/** - * The transform the element paints under, in 2D components. - * - * Null when nothing up the chain transforms it: the caller's axis-aligned rect - * already describes it, and that comes from real layout rather than the - * element's untransformed box. - */ +/** The 2D components of the matrix the element paints under; null when upright and unscaled, or 3D. */ function readPlanarTransform(element: HTMLElement): Planar2D | null { - const acc = composeElementTransform(element, PLANAR_2D_OPS, (node) => { - try { - return node.ownerDocument.defaultView?.getComputedStyle(node) ?? null; - } catch { - return null; - } - }); - return acc && !isIdentity(acc) ? acc : null; + const win = element.ownerDocument.defaultView; + const matrix = win && readElementTransformSnapshot(win, element)?.matrix; + if (!matrix) return null; + const { a, b, c, d } = matrix; + return isIdentity({ a, b, c, d }) ? null : { a, b, c, d }; } /** What the frame measured of a stand-in's element at the press: a stand-in has no box of its own. */ diff --git a/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts b/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts index 914e12dfe8..7279aedc5c 100644 --- a/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts +++ b/packages/studio/src/components/editor/domEditOverlayGeometry.test.ts @@ -50,6 +50,11 @@ describe("orientedOverlayRect — rotation gate (perf fix, V15 18a/18b)", () => // anchoredResizeCommitFeedsOffset.test.ts, which mock this module entirely. class FakeDOMMatrix { a = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; b = 0; c = 0; d = 1; diff --git a/packages/studio/src/components/editor/domEditOverlayGeometry.ts b/packages/studio/src/components/editor/domEditOverlayGeometry.ts index 5eb9b9e36a..94052de9ea 100644 --- a/packages/studio/src/components/editor/domEditOverlayGeometry.ts +++ b/packages/studio/src/components/editor/domEditOverlayGeometry.ts @@ -5,7 +5,7 @@ import { readPositiveDimension, } from "./domEditOverlayBasis"; import { isElementVisibleThroughAncestors } from "./domEditingDom"; -import { hugRectForElement } from "./domEditOverlayCrop"; +import { hugRectForElement, type OwnScale } from "./domEditOverlayCrop"; import { elementCornerPoints, readElementTransformSnapshot, @@ -26,7 +26,7 @@ export interface OverlayRect { height: number; editScaleX: number; editScaleY: number; - ownScale?: { x: number; y: number }; + ownScale?: OwnScale; /** Live screen-space rotation; omitted for axis-aligned group bounds. */ angle?: number; } @@ -185,7 +185,7 @@ export function frameRectToOverlay( scale: OverlayRootScale, elementRect: { left: number; top: number; width: number; height: number }, source: FrameSource, - ownScale?: { x: number; y: number }, + ownScale?: OwnScale, ): OverlayRect { const { iframeRect, overlayRect, rootScaleX, rootScaleY } = scale; const editScale = resolveDomEditCoordinateScale({ diff --git a/packages/studio/src/components/editor/overlayTransform.browser.test.ts b/packages/studio/src/components/editor/overlayTransform.browser.test.ts new file mode 100644 index 0000000000..20c1e259eb --- /dev/null +++ b/packages/studio/src/components/editor/overlayTransform.browser.test.ts @@ -0,0 +1,118 @@ +// @vitest-environment happy-dom +import { build } from "esbuild"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { closeTestChrome, launchTestChrome } from "../../../tests/chromeTestUtils"; + +vi.setConfig({ testTimeout: 60_000 }); + +let browser: Awaited> | undefined; + +afterEach(async () => { + await closeTestChrome(browser); + browser = undefined; +}); + +// Each layer is 200 x 100 CSS px; `own` is the size it paints at along its own edges, null for a layer +// turned out of its plane, which the walk declines so callers use the box Chrome paints. +const LAYERS: Array<{ id: string; style: string; own: [number, number] | null; parent?: string }> = + [ + { id: "depthScaled", style: "transform: rotate(45deg); scale: 1 1 2", own: [200, 100] }, + { id: "scaleProperty", style: "scale: 2", own: [400, 200] }, + { id: "turnedScaleProperty", style: "rotate: 45deg; scale: 2", own: [400, 200] }, + { id: "matrix", style: "transform: rotate(30deg) scale(2)", own: [400, 200] }, + { id: "mirrored", style: "transform: scaleX(-1); rotate: 20deg", own: [200, 100] }, + { id: "translated", style: "translate: 50% 10px; rotate: 10deg", own: [200, 100] }, + { id: "tipped", style: "rotate: x 60deg", own: null }, + { id: "tippedBack", style: "rotate: x -60deg", own: null, parent: "rotate: x 60deg" }, + { + id: "projected", + style: "transform: translateZ(100px) rotate(30deg)", + own: null, + parent: "transform: perspective(500px); transform-style: preserve-3d", + }, + { + id: "underPerspective", + style: "transform: translateZ(100px) rotate(30deg)", + own: null, + parent: "perspective: 500px", + }, + { + id: "inPreserved", + style: "rotate: 30deg", + own: null, + parent: "transform-style: preserve-3d", + }, + { + id: "spunFlat", + style: "transform: matrix3d(0.866, 0.5, 0, 0, -0.5, 0.866, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)", + own: [200, 100], + }, + { id: "nested", style: "scale: 1.5; rotate: 15deg", own: [300, 150], parent: "rotate: 30deg" }, + ]; + +// fails without the fix: under a parent's `perspective: 500px` a depth-moved child is projected, and the corners +// spanned 223 x 187 where Chrome paints 279 x 233. Any 3D context above a layer now leaves it to the painted box. +it("reads every layer's painted corners as Chrome paints them", async () => { + const bundle = await build({ + stdin: { + contents: `export { readElementTransformSnapshot, elementCornerPoints } from "./editingGeometry";`, + resolveDir: join(import.meta.dirname, "../../../../core/src/runtime"), + loader: "ts", + }, + bundle: true, + format: "iife", + globalName: "OverlayTransform", + platform: "browser", + write: false, + }); + browser = await launchTestChrome(); + const page = await browser.newPage(); + await page.setViewport({ width: 1600, height: 1200 }); + const layer = ({ id, style }: (typeof LAYERS)[number]) => + `
`; + await page.setContent(` +
+ ${LAYERS.map((l) => (l.parent ? `
${layer(l)}
` : layer(l))).join("")} +
`); + await page.addScriptTag({ content: bundle.outputFiles[0]?.text }); + + const measured = await page.evaluate( + (ids: string[]) => { + type Point = { x: number; y: number }; + const api = (window as unknown as { OverlayTransform: Record }) + .OverlayTransform; + const edge = (a: Point, b: Point) => Math.hypot(b.x - a.x, b.y - a.y); + return ids.map((id) => { + const element = document.getElementById(id)!; + const snapshot = api.readElementTransformSnapshot!(window, element); + const corners = snapshot && api.elementCornerPoints!(window, element, snapshot); + if (!corners) return { id, corners: null }; + const points = Object.values(corners) as Point[]; + const box = element.getBoundingClientRect(); + const xs = points.map((p) => p.x); + const ys = points.map((p) => p.y); + return { + id, + own: [edge(corners.nw, corners.ne), edge(corners.nw, corners.sw)], + bounds: [Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)], + painted: [box.width, box.height], + }; + }); + }, + LAYERS.map((l) => l.id), + ); + + for (const [i, { id, own }] of LAYERS.entries()) { + const got = measured[i]!; + if (!own) { + expect(got.corners, `${id} is declined`).toBeNull(); + continue; + } + expect(got.corners, id).not.toBeNull(); + expect(got.own![0], `${id} own width`).toBeCloseTo(own[0], 1); + expect(got.own![1], `${id} own height`).toBeCloseTo(own[1], 1); + expect(got.bounds![0], `${id} painted width`).toBeCloseTo(got.painted![0], 1); + expect(got.bounds![1], `${id} painted height`).toBeCloseTo(got.painted![1], 1); + } +}); diff --git a/packages/studio/src/components/editor/previewOverlayRects.test.ts b/packages/studio/src/components/editor/previewOverlayRects.test.ts index 6efdf0b3d4..d92b271c5d 100644 --- a/packages/studio/src/components/editor/previewOverlayRects.test.ts +++ b/packages/studio/src/components/editor/previewOverlayRects.test.ts @@ -39,6 +39,11 @@ installReactActEnvironment(); // The 2D slice of each that the overlay reads; one set for both frames, which share this window. class FakeDOMMatrix { a = 1; + m13 = 0; + m23 = 0; + m14 = 0; + m24 = 0; + m44 = 1; b = 0; c = 0; d = 1; @@ -58,9 +63,6 @@ class FakeDOMMatrix { out.f = this.b * o.e + this.d * o.f + this.f; return out; } - rotateSelf() { - return this; - } transformPoint(p: { x: number; y: number }) { return { x: this.a * p.x + this.c * p.y + this.e, y: this.b * p.x + this.d * p.y + this.f }; } @@ -231,8 +233,8 @@ describe("overlay rects on an opaque frame match a scriptable one", () => { } }); - // fails without the fix: the cut took the turned layer's wider upright box as its scale, 167.4 px, not 173.2. - it("cuts a turned, scaled layer's crop at its own scale, not its upright box's, the same in both", async () => { + // fails without the fix: the cut took the turned layer's upright box, 167.4 or 173.2 px wide, not 179.9. + it("cuts a turned, scaled layer's crop at its own scale, along its own edges, the same in both", async () => { const [cos, sin] = [Math.cos(Math.PI / 6), Math.sin(Math.PI / 6)]; const [width, height] = [2 * (200 * cos + 100 * sin), 2 * (200 * sin + 100 * cos)]; const spun = sized(document.createElement("div"), [1000, 100, width, height]); @@ -249,7 +251,69 @@ describe("overlay rects on an opaque frame match a scriptable one", () => { const { group } = await settled( await overlayOn(frame(), { selection: null, group: ["grp", "spun"] }), ); - expect(group[1]!.width).toBeCloseTo((width - 100) / 2, 6); + const [cutW, cutH] = [2 * 150, 2 * 100]; + expect(group[1]!.width).toBeCloseTo((cutW * cos + cutH * sin) / 2, 6); + expect(group[1]!.height).toBeCloseTo((cutW * sin + cutH * cos) / 2, 6); + } + }); + + // fails without the fix: the crop was cut out of the upright box, 81.1 x 106.1 where the cut is 88.4 square. + const layer = (id: string, transform: string, clip: string, box = [1000, 100, 200, 100]) => { + const element = sized(document.createElement("div"), box); + element.id = id; + if (clip) element.style.setProperty("clip-path", clip); + if (transform) element.style.setProperty("transform", transform); + Object.defineProperty(element, "offsetWidth", { value: 200, configurable: true }); + Object.defineProperty(element, "offsetHeight", { value: 100, configurable: true }); + document.querySelector("[data-composition-id]")!.append(element); + }; + const pairIn = async (frame: () => HTMLIFrameElement, ids: [string, string]) => { + const { group } = await settled(await overlayOn(frame(), { selection: null, group: ids })); + return [group[0]!, group[1]!] as const; + }; + + // fails without the fix: a scaled layer's insets crossing past its width drew a box live, none sealed. + it("shrinks crossed insets until they meet, as CSS does, the same in both", async () => { + const half = "matrix(0.5, 0, 0, 0.5, 0, 0)"; + layer("whole", half, "", [1050, 125, 100, 50]); + layer("met", half, "inset(0px 300px 0px 100px)", [1050, 125, 100, 50]); + for (const frame of [liveFrame, opaqueFrame]) { + const [whole, met] = await pairIn(frame, ["whole", "met"]); + expect(met.width).toBeCloseTo(0, 6); + expect(met.left - whole.left).toBeCloseTo(((200 * 100) / 400) * 0.5 * 0.5, 6); + } + }); + + // fails without the fix: a mirrored layer's right inset cut its visual left live and its visual right sealed. + it("cuts a mirrored layer's right inset off its visual left, the same in both", async () => { + layer("plain", "", "inset(0px 50px 0px 0px)"); + layer("mirrored", "matrix(-1, 0, 0, 1, 0, 0)", "inset(0px 50px 0px 0px)"); + for (const frame of [liveFrame, opaqueFrame]) { + const [plain, mirrored] = await pairIn(frame, ["plain", "mirrored"]); + expect(mirrored.width).toBeCloseTo(plain.width, 6); + expect(mirrored.left - plain.left).toBeCloseTo(50 / 2, 6); + } + }); + + it("bounds a turned layer's cropped box by its cut corners, the same in both", async () => { + const half = Math.SQRT1_2; + const side = (200 + 100) * half; + const spun = sized(document.createElement("div"), [1000, 100, side, side]); + spun.id = "spun"; + spun.style.setProperty("clip-path", "inset(0px 50px 0px 0px)"); + spun.style.setProperty("transform", `matrix(${half}, ${half}, ${-half}, ${half}, 0, 0)`); + Object.defineProperty(spun, "offsetWidth", { value: 200, configurable: true }); + Object.defineProperty(spun, "offsetHeight", { value: 100, configurable: true }); + document.querySelector("[data-composition-id]")!.append(spun); + for (const frame of [liveFrame, opaqueFrame]) { + const { group } = await settled( + await overlayOn(frame(), { selection: null, group: ["grp", "spun"] }), + ); + const cut = ((150 + 100) * half) / 2; + expect(group[1]).toMatchObject({ + width: expect.closeTo(cut, 6), + height: expect.closeTo(cut, 6), + }); } }); diff --git a/packages/studio/src/components/editor/previewOverlayRects.ts b/packages/studio/src/components/editor/previewOverlayRects.ts index e00ebe75cf..a7ee35593b 100644 --- a/packages/studio/src/components/editor/previewOverlayRects.ts +++ b/packages/studio/src/components/editor/previewOverlayRects.ts @@ -35,7 +35,11 @@ function ownScaleOf(scale: OverlayRootScale, box: EditingElementBox) { const height = corners ? cornerEdgeLength(corners.nw, corners.sw) : box.rect.height * scale.rootScaleY; - return { x: width / layout.width, y: height / layout.height }; + return { + x: width / layout.width, + y: height / layout.height, + ...(corners && { corners }), + }; } /** `toOverlayRect`. */