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
5 changes: 5 additions & 0 deletions packages/core/src/runtime/editing/watchGeometry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ describe("geometryEvent", () => {
push({}, { ...element, members: [{ ...element.rect, z: 0 }] }),
push({}, { ...element, corners: { nw: { x: 0, y: 0 } } }),
push({}, { ...element, source: { width: 1, height: 1, declaredWidth: null } }),
push({}, { ...element, layout: { width: -1, height: 1 } }),
push({}, { ...element, layout: { width: 1, height: 100_001 } }),
push({}, { ...element, layout: { width: "1", height: 1 } }),
push({}, { ...element, layout: { width: 1, height: 1, depth: 1 } }),
push({}, { ...element, layout: undefined }),
])
expect(geometryEvent(bad, 1)).toBeNull();
});
Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/runtime/editing/watchGeometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// stamped on the clock both windows share, until an empty list, the page hiding, or the parent's release.
import {
EDITING_ELEMENT_HANDLE,
MAX_DRAFT_PX,
MAX_ELEMENT_ENTRIES,
MAX_ELEMENT_VALUE,
type EditingElementHandle,
Expand Down Expand Up @@ -47,14 +48,18 @@ const isSource = (value: unknown) =>
finiteOrNull(value.declaredHeight));
const isClipPath = (value: unknown) =>
value === null || (typeof value === "string" && value.length <= MAX_ELEMENT_VALUE);
const isLayout = (value: unknown) =>
keysAre(value, "height,width") &&
[value.width, value.height].every((side) => finite(side) && side >= 0 && side <= MAX_DRAFT_PX);
const isMembers = (value: unknown) =>
value === null ||
(Array.isArray(value) && value.length <= MAX_ELEMENT_ENTRIES && value.every(isRect));

function isGeometry(value: unknown): value is EditingElementGeometry {
if (!keysAre(value, "angle,clipPath,corners,members,rect,source,visible")) return false;
if (!keysAre(value, "angle,clipPath,corners,layout,members,rect,source,visible")) return false;
return (
isRect(value.rect) &&
isLayout(value.layout) &&
finite(value.angle) &&
isCorners(value.corners) &&
isSource(value.source) &&
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/runtime/editingElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export interface EditingElementMatch {
export const MAX_ELEMENT_ENTRIES = 256;
export const MAX_ELEMENT_TEXT = 10_000;
export const MAX_ELEMENT_VALUE = 2_000;
export const MAX_DRAFT_PX = 100_000;
export const MAX_SOURCE_GROUPS = 64;
export const MAX_DESCRIBE_HANDLES = 256;
export const MAX_POINT_STACK = 64;
Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/runtime/editingGeometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export interface EditingElementBox {
} | null;
/** Inline `clip-path`, else the computed one; null when longer than MAX_ELEMENT_VALUE. */
clipPath: string | null;
layout: { width: number; height: number };
}

export interface EditingElementGeometry extends EditingElementBox {
Expand Down Expand Up @@ -201,6 +202,11 @@ function clipPathOf(element: HTMLElement): string | null {
return value.length <= MAX_ELEMENT_VALUE ? value : null;
}

function layoutOf(element: Element): EditingElementBox["layout"] {
const { offsetWidth = 0, offsetHeight = 0 } = element as Partial<HTMLElement>;
return { width: offsetWidth, height: offsetHeight };
}

const finiteCorners = (corners: EditingCorners | null) =>
corners && Object.values(corners).every((p) => Number.isFinite(p.x) && Number.isFinite(p.y))
? corners
Expand All @@ -220,6 +226,7 @@ export function boxOf(
corners: finiteCorners(corners),
source: sourceOf(element),
clipPath: clipPathOf(element),
layout: layoutOf(element),
};
}

Expand Down
7 changes: 1 addition & 6 deletions packages/core/src/runtime/editingGestureStart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import {
import { elementForHandle } from "./editingHandles";

export interface EditingGestureStart extends EditingElementGeometry {
/** The transform-free border box a resize grows from. */
layout: { width: number; height: number };
/** Frame px its centre moves per px of translate, columns `a, b` (x) and `c, d` (y); null when it does not move measurably. */
move: { a: number; b: number; c: number; d: number } | null;
/** Frame px its centre moves per px of drawn width, `a, b`, and height, `c, d`; null when it has no box. */
Expand Down Expand Up @@ -193,14 +191,11 @@ export function gestureStart(handles: readonly EditingElementHandle[]): {
const starts = elements.map((geometry, i) => {
const element = pressed[i];
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),
grow: measureGrowResponse(element, geometry.layout),
gsap: gsapPosition(element),
gsapRotation: rotation,
cssRotation: rotation === null ? readCssRotationStart(element as HTMLElement) : null,
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/runtime/editingPort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import {
EDITING_ELEMENT_HANDLE,
MAX_DESCRIBE_HANDLES,
MAX_DRAFT_PX,
type EditingElementDescription,
type EditingElementHandle,
type EditingElementHit,
Expand Down Expand Up @@ -237,7 +238,7 @@ export interface EditingRuntimeSnapshot {
clipParents: Array<[string, string]>;
}

export const MAX_DRAFT_PX = 100_000;
export { MAX_DRAFT_PX };
export const MAX_DRAFT_DEG = 36_000;
export const MAX_WATCHED_KEYS = 32;

Expand Down
52 changes: 43 additions & 9 deletions packages/studio/src/components/editor/domEditOverlayCrop.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import {
composeElementTransform,
elementCornerPoints,
readElementTransformSnapshot,
type PlanarTransformOps,
} from "@hyperframes/core/runtime/editing-port";
import {
Expand Down Expand Up @@ -247,26 +249,58 @@ export function resolveCropInsetFromMoveDrag(input: {

/** Display-only hug: shrink a projected rect by the element's inset crop.
* For rects nothing writes back to (e.g. the hover ring). */
export function hugRectForElement(
rect: CropScreenRect & { editScaleX: number; editScaleY: number },
element: HTMLElement,
): CropScreenRect {
export function hugRectForElement(rect: HugRect, element: HTMLElement): CropScreenRect {
// A lifted clip shows the full element rect.
return isElementCropLifted(element)
? rect
: hugRectForClipPath(rect, readElementClipPath(element));
if (isElementCropLifted(element)) return rect;
return hugRectForClipPath(
rect,
readElementClipPath(element),
() => rect.ownScale ?? (previewStandIn(element) ? undefined : liveOwnScale(rect, element)),
);
}

type HugRect = CropScreenRect & {
editScaleX: number;
editScaleY: number;
ownScale?: { x: number; y: number };
angle?: number;
};

/** 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"] {
const { offsetWidth: w, offsetHeight: h } = element;
if (!(w > 0 && h > 0)) return undefined;
const upright = { x: rect.width / w, y: rect.height / h };
if (rect.angle !== undefined) return upright;
const win = element.ownerDocument.defaultView;
const transform = win && readElementTransformSnapshot(win, element);
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 ownScaleXY = (own: HugRect["ownScale"], rect: HugRect): [number, number] => [
own?.x ?? rect.editScaleX,
own?.y ?? rect.editScaleY,
];

/** `hugRectForElement` for a clip-path read elsewhere; null is one that could not be read. */
export function hugRectForClipPath(
rect: CropScreenRect & { editScaleX: number; editScaleY: number },
rect: HugRect,
clipPath: string | null,
ownScaleOf: () => HugRect["ownScale"] = () => rect.ownScale,
): CropScreenRect {
const insets = clipPath === null ? null : parseCropClipPath(clipPath);
// 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, rect.editScaleX, rect.editScaleY);
return cropRectFromInsets(rect, insets, ...ownScaleXY(ownScaleOf(), rect));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export interface OverlayRect {
height: number;
editScaleX: number;
editScaleY: number;
ownScale?: { x: number; y: number };
/** Live screen-space rotation; omitted for axis-aligned group bounds. */
angle?: number;
}
Expand Down Expand Up @@ -184,6 +185,7 @@ export function frameRectToOverlay(
scale: OverlayRootScale,
elementRect: { left: number; top: number; width: number; height: number },
source: FrameSource,
ownScale?: { x: number; y: number },
): OverlayRect {
const { iframeRect, overlayRect, rootScaleX, rootScaleY } = scale;
const editScale = resolveDomEditCoordinateScale({
Expand All @@ -202,6 +204,7 @@ export function frameRectToOverlay(
height: elementRect.height * rootScaleY,
editScaleX: editScale.scaleX,
editScaleY: editScale.scaleY,
...(ownScale && { ownScale }),
};
}

Expand Down Expand Up @@ -345,6 +348,7 @@ export function orientOverlayRect(
height,
editScaleX: base.editScaleX,
editScaleY: base.editScaleY,
...(base.ownScale && { ownScale: base.ownScale }),
angle,
};
}
Expand Down
53 changes: 51 additions & 2 deletions packages/studio/src/components/editor/previewOverlayRects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,18 @@ const settled = async (overlay: Awaited<ReturnType<typeof overlayOn>>) => {
return { overlayRect, childRects, group: groupOverlayItems.map((item) => item.rect), hoverRect };
};

const close = (rect: OverlayRect | null) =>
rect && Object.fromEntries(Object.entries(rect).map(([key, value]) => [key, +value.toFixed(9)]));
const rounded = (value: unknown): unknown =>
typeof value === "number"
? +value.toFixed(9)
: value && typeof value === "object"
? Object.fromEntries(Object.entries(value).map(([key, v]) => [key, rounded(v)]))
: value;
// Drawn fields only: a live rect works out its own scale when it cuts a crop, a frame's arrives with it.
const close = (rect: OverlayRect | null) => {
if (!rect) return rect;
const { ownScale: _ownScale, ...drawn } = rect;
return rounded(drawn);
};
const closeAll = (shown: Awaited<ReturnType<typeof settled>>) => ({
overlayRect: close(shown.overlayRect),
childRects: shown.childRects.map(close),
Expand All @@ -204,6 +214,45 @@ describe("overlay rects on an opaque frame match a scriptable one", () => {
else expect(live.overlayRect).not.toBeNull();
});

// fails without the fix: the hug cut the crop at the editor zoom alone, 175 px wide in both frames.
it("cuts a scaled layer's crop at its own scale, the same in both", async () => {
const grown = sized(document.createElement("div"), [1000, 100, 400, 200]);
grown.id = "grown";
grown.style.setProperty("clip-path", "inset(0px 50px 0px 0px)");
grown.style.setProperty("transform", "matrix(2, 0, 0, 2, 0, 0)");
Object.defineProperty(grown, "offsetWidth", { value: 200, configurable: true });
Object.defineProperty(grown, "offsetHeight", { value: 100, configurable: true });
document.querySelector("[data-composition-id]")!.append(grown);
for (const frame of [liveFrame, opaqueFrame]) {
const { group } = await settled(
await overlayOn(frame(), { selection: null, group: ["grp", "grown"] }),
);
expect(group[1]).toMatchObject({ width: 150, height: 100 });
}
});

// 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 () => {
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]);
spun.id = "spun";
spun.style.setProperty("clip-path", "inset(0px 50px 0px 0px)");
spun.style.setProperty(
"transform",
`matrix(${2 * cos}, ${2 * sin}, ${-2 * sin}, ${2 * cos}, 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"] }),
);
expect(group[1]!.width).toBeCloseTo((width - 100) / 2, 6);
}
});

it("covers what each case decides", async () => {
const host = await settled(
await overlayOn(opaqueFrame(), {
Expand Down
17 changes: 16 additions & 1 deletion packages/studio/src/components/editor/previewOverlayRects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { previewGeometry } from "../../player/lib/previewElements";
import { computeOverlayRootScale, type OverlayRootScale } from "./domEditOverlayBasis";
import { hugRectForClipPath } from "./domEditOverlayCrop";
import {
cornerEdgeLength,
frameCornersToOverlay,
frameRectToOverlay,
orientOverlayRect,
Expand All @@ -23,9 +24,23 @@ import {

const clientRect = ({ x, y, width, height }: EditingRect) => ({ left: x, top: y, width, height });

/** Overlay px per CSS px along the element's own edges, which a turn does not lengthen; undefined without a size. */
function ownScaleOf(scale: OverlayRootScale, box: EditingElementBox) {
const { layout } = box;
if (!(layout.width > 0 && layout.height > 0)) return undefined;
const corners = box.corners && frameCornersToOverlay(scale, box.corners);
const width = corners
? cornerEdgeLength(corners.nw, corners.ne)
: box.rect.width * scale.rootScaleX;
const height = corners
? cornerEdgeLength(corners.nw, corners.sw)
: box.rect.height * scale.rootScaleY;
return { x: width / layout.width, y: height / layout.height };
}

/** `toOverlayRect`. */
const baseRect = (scale: OverlayRootScale, box: EditingElementBox) =>
frameRectToOverlay(scale, clientRect(box.rect), box.source);
frameRectToOverlay(scale, clientRect(box.rect), box.source, ownScaleOf(scale, box));

/** `orientedOverlayRect`. */
function orientedRect(scale: OverlayRootScale, box: EditingElementBox): OverlayRect {
Expand Down
22 changes: 20 additions & 2 deletions packages/studio/src/hooks/useCropOverlay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ const rect: OverlayRect = {
};

/** The selection box's crop hug as the overlay last drew it. */
function drawn(element: HTMLElement) {
function drawn(element: HTMLElement, overlayRect: OverlayRect = rect) {
const seen: Array<number | null> = [];
function Probe() {
const { cropOutlineInsetPx } = useCropOverlay({
selection: { element } as DomEditSelection,
overlayRect: rect,
overlayRect,
});
seen.push(cropOutlineInsetPx?.right ?? null);
return null;
Expand All @@ -71,6 +71,24 @@ it("a sealed layer picked with no press drops its crop hug once the crop handles
expect(hug(), "a lift the frame refused leaves the crop showing").toBe(150);
});

// fails without the fix: the hug used the editor zoom alone, 150 where the layer's own 2x makes 300.
it.each([true, false])(
"a layer shown at twice its own size hugs its crop at that scale (sealed %s)",
(s) => {
sealed = s;
const element = document.body.appendChild(document.createElement("div"));
element.id = "grown";
Object.defineProperty(element, "offsetWidth", { value: 200, configurable: true });
Object.defineProperty(element, "offsetHeight", { value: 100, configurable: true });
if (s) rememberFrameClipPath(element, "inset(0px 150px 0px 0px)", "inset(0px 150px 0px 0px)");
else element.style.setProperty("clip-path", "inset(0px 150px 0px 0px)");
// A frame's rect arrives with its own scale; a live element's is read off the element.
const hug = drawn(element, s ? { ...rect, ownScale: { x: 2, y: 2 } } : rect);
expect(hug()).toBe(300);
element.remove();
},
);

it("an unsealed layer's crop hug follows its lift and its drop", () => {
sealed = false;
const element = document.body.appendChild(document.createElement("div"));
Expand Down
Loading
Loading