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
31 changes: 31 additions & 0 deletions packages/core/src/runtime/editing/cropLift.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Studio's crop lift in a frame it cannot script. While an element's crop is edited, a rule hides
* its clip-path so the cropped-away part shows; the element's own clip-path stays the saved record.
*/
import { elementForHandle } from "../editingHandles";
import type { EditingParams, EditingResult } from "../editingPort";

const lifts = new WeakMap<Element, HTMLStyleElement>();

/** The same selector Studio's own lift writes: only an element with a data-hf-id or an id is lifted. */
function liftSelector(element: Element): string | null {
const quote = (value: string) => `"${value.replace(/["\\]/g, "\\$&")}"`;
const hfId = element.getAttribute("data-hf-id");
if (hfId) return `[data-hf-id=${quote(hfId)}]`;
return element.id ? `[id=${quote(element.id)}]` : null;
}

export function cropLift({ handle, lift }: EditingParams<"crop-lift">): EditingResult<"crop-lift"> {
const element = elementForHandle(handle);
if (!element) return { lifted: false, clipPath: null };
lifts.get(element)?.remove();
lifts.delete(element);
const clipPath = window.getComputedStyle(element).clipPath.trim();
const selector = lift ? liftSelector(element) : null;
if (!selector) return { lifted: false, clipPath };
const rule = document.createElement("style");
rule.textContent = `${selector}{clip-path:none!important}`;
(document.head ?? document.documentElement).append(rule);
lifts.set(element, rule);
return { lifted: true, clipPath };
}
1 change: 1 addition & 0 deletions packages/core/src/runtime/editingAgent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ describe("installEditingAgent", () => {
"gsap-snapshot",
"motion-path-home",
"max-z-index",
"crop-lift",
],
},
});
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/runtime/editingAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { maxZIndex } from "./editing/maxZIndex";
import { gestureStart } from "./editingGestureStart";
import { gsapSnapshot } from "./editing/gsapSnapshot";
import { motionPathHome } from "./editing/motionPathHome";
import { cropLift } from "./editing/cropLift";
import {
getLogicalOpacity,
markedForStudio,
Expand Down Expand Up @@ -216,6 +217,7 @@ const HANDLERS: Handlers = {
"gsap-snapshot": () => gsapSnapshot(),
"motion-path-home": ({ selector }) => motionPathHome(selector),
"max-z-index": () => maxZIndex(),
"crop-lift": cropLift,
};

function serve(port: MessagePort): void {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/runtime/editingPort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ describe("createEditingPortClient", () => {
"gsap-snapshot",
"motion-path-home",
"max-z-index",
"crop-lift",
],
});
} finally {
Expand Down
9 changes: 9 additions & 0 deletions packages/core/src/runtime/editingPort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ export const EDITING_REQUEST_KINDS = [
"gsap-snapshot",
"motion-path-home",
"max-z-index",
"crop-lift",
] as const;
export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number];

Expand Down Expand Up @@ -298,6 +299,10 @@ export interface EditingRequests {
"gsap-snapshot": { params: NoParams; result: GsapSnapshot };
"motion-path-home": { params: { selector: string }; result: MotionPathFrameHome };
"max-z-index": { params: NoParams; result: { zIndex: number } };
"crop-lift": {
params: { handle: EditingElementHandle; lift: boolean };
result: { lifted: boolean; clipPath: string | null };
};
}
export type EditingParams<K extends EditingRequestKind> = EditingRequests[K]["params"];
export type EditingResult<K extends EditingRequestKind> = EditingRequests[K]["result"];
Expand Down Expand Up @@ -501,6 +506,10 @@ const PARAM_PARSERS: {
? { selector: params.selector }
: null,
"max-z-index": noParams,
"crop-lift": (params) =>
hasKeys(params, "handle,lift") && isHandle(params.handle) && typeof params.lift === "boolean"
? { handle: params.handle, lift: params.lift }
: null,
};

/** Validates one request off the wire. Never throws: anything unusable becomes a typed error. */
Expand Down
93 changes: 78 additions & 15 deletions packages/studio/src/components/editor/domEditOverlayCrop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import {
type ClipPathInsetSides,
type ParsedInsetClipPathSides,
} from "./clipPathHelpers";
import { MAX_DRAFT_PX, MAX_ELEMENT_VALUE } from "@hyperframes/core/runtime/editing-port";
import { previewRequest } from "../../player/lib/previewChannel";
import { previewStandIn } from "./previewDrafts";

export type CropEdge = "top" | "right" | "bottom" | "left";

Expand Down Expand Up @@ -38,7 +41,11 @@ export function cropRectFromInsets(

// 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.
const cropLifts = new WeakMap<HTMLElement, { rule: HTMLStyleElement; sheetClip?: string }>();
// A sealed preview's lift is that rule in the frame (core `editing/cropLift.ts`), and `rule` is null.
// A frame lift is kept until the frame says it is gone, so a lost reply never leaves the crop hidden there.
type CropLift = { rule: HTMLStyleElement | null; sheetClip?: string; dropped?: boolean };
const cropLifts = new WeakMap<HTMLElement, CropLift>();
const UNLIFT_TRIES = 3;

function liftSelector(element: HTMLElement): string | null {
const quote = (value: string) => `"${value.replace(/["\\]/g, "\\$&")}"`;
Expand All @@ -47,7 +54,38 @@ function liftSelector(element: HTMLElement): string | null {
return element.id ? `[id=${quote(element.id)}]` : null;
}

function unliftInFrame(element: HTMLElement, record: CropLift, tries = UNLIFT_TRIES): void {
const target = previewStandIn(element);
if (!target) return;
void previewRequest(target.iframe, "crop-lift", { handle: target.handle, lift: false }).then(
(reply) => {
if (cropLifts.get(element) !== record) return;
if (reply?.lifted === false) cropLifts.delete(element);
else if (tries > 1) unliftInFrame(element, record, tries - 1);
},
);
}

function liftInFrame(element: HTMLElement): boolean {
const target = previewStandIn(element);
if (!target) return false;
// Until the frame answers, the clip it last reported is the one under the lift.
const record: CropLift = { rule: null, sheetClip: frameClipPaths.get(element)?.computed ?? "" };
cropLifts.set(element, record);
void previewRequest(target.iframe, "crop-lift", { handle: target.handle, lift: true }).then(
(reply) => {
if (cropLifts.get(element) !== record || !reply) return;
if (!reply.lifted) cropLifts.delete(element);
else if (typeof reply.clipPath === "string" && reply.clipPath.length <= MAX_ELEMENT_VALUE)
record.sheetClip = reply.clipPath.trim();
},
);
return true;
}

export function liftElementCrop(element: HTMLElement): void {
const held = cropLifts.get(element);
if ((held && !held.dropped) || liftInFrame(element)) return;
const selector = liftSelector(element);
if (!selector || cropLifts.has(element)) return;
const doc = element.ownerDocument;
Expand All @@ -58,37 +96,62 @@ export function liftElementCrop(element: HTMLElement): void {
}

export function dropElementCropLift(element: HTMLElement): void {
cropLifts.get(element)?.rule.remove();
cropLifts.delete(element);
const lift = cropLifts.get(element);
if (!lift || lift.dropped) return;
if (lift.rule) {
lift.rule.remove();
cropLifts.delete(element);
return;
}
lift.dropped = true;
unliftInFrame(element, lift);
}

export function isElementCropLifted(element: HTMLElement): boolean {
return cropLifts.has(element);
const lift = cropLifts.get(element);
return !!lift && !lift.dropped;
}

const computedClipPath = (element: HTMLElement) =>
element.ownerDocument.defaultView?.getComputedStyle(element).clipPath.trim() || "";
// A sealed preview's stand-in has no styles of its own: its clip-path is the one the frame reported.
const frameClipPaths = new WeakMap<Element, { inline: string; computed: string }>();

/** The element's clip-path, inline first, then the stylesheet's as it is without the lift. */
function readElementClipPath(element: HTMLElement): string {
const inline = element.style.getPropertyValue("clip-path").trim();
const lift = cropLifts.get(element);
if (inline || !lift) return inline || computedClipPath(element);
// Only inline writes happen while selected, so the stylesheet's clip is read once per lift.
if (lift.sheetClip === undefined) {
export function rememberFrameClipPath(element: HTMLElement, inline: string, computed: string) {
frameClipPaths.set(element, { inline: inline.trim(), computed: computed.trim() });
}

const computedClipPath = (element: HTMLElement) => {
const view = element.ownerDocument.defaultView;
if (!view) return frameClipPaths.get(element)?.computed ?? "";
return view.getComputedStyle(element).clipPath.trim();
};

/** The stylesheet's clip under a lift, read once per lift: only inline writes happen while selected. */
function sheetClipUnder(element: HTMLElement, lift: CropLift): string {
if (lift.sheetClip === undefined && lift.rule) {
const { parentNode, nextSibling } = lift.rule;
lift.rule.remove();
lift.sheetClip = computedClipPath(element);
parentNode?.insertBefore(lift.rule, nextSibling);
}
return lift.sheetClip;
return lift.sheetClip ?? "";
}

/** The element's clip-path, inline first, then the stylesheet's as it is without the lift. */
function readElementClipPath(element: HTMLElement): string {
const inline =
element.style.getPropertyValue("clip-path").trim() || frameClipPaths.get(element)?.inline;
if (inline) return inline;
const lift = cropLifts.get(element);
return lift && !lift.dropped ? sheetClipUnder(element, lift) : computedClipPath(element);
}

/** Zeros = no clip yet. `null` = a clip this tool cannot represent (circle/polygon/non-px inset):
* croppers must not lift, edit, or restore it, or deselect silently replaces or destroys it. */
function parseCropClipPath(value: string): ParsedInsetClipPathSides | null {
if (!value || value === "none") return { top: 0, right: 0, bottom: 0, left: 0, radius: 0 };
return parseInsetClipPathSides(value);
const sides = parseInsetClipPathSides(value);
const sane = sides && Object.values(sides).every((side) => Math.abs(side) <= MAX_DRAFT_PX);
return sane ? sides : null;
}

export function readElementCropInsets(element: HTMLElement): ParsedInsetClipPathSides | null {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from "vitest";
import {
dropElementCropLift,
isElementCropLifted,
liftElementCrop,
readElementCropInsets,
} from "./domEditOverlayCrop";

const sent: Array<{ lift: boolean; answer: (reply: unknown) => void }> = [];
vi.mock("../../player/lib/previewChannel", () => ({
previewRequest: (_iframe: unknown, _kind: string, params: { lift: boolean }) =>
new Promise((answer) => sent.push({ lift: params.lift, answer })),
}));
vi.mock("./previewDrafts", () => ({
previewStandIn: () => ({ iframe: {}, handle: "hf-1" }),
}));

afterEach(() => {
sent.length = 0;
});

const settle = () => new Promise((done) => setTimeout(done, 0));

async function lifted(clipPath = "inset(10px)") {
const el = document.createElement("div");
liftElementCrop(el);
sent.at(-1)!.answer({ lifted: true, clipPath });
await settle();
return el;
}

describe("a crop lift in a frame Studio cannot script", () => {
it("is kept when the lift's reply is lost, so deselecting still asks the frame to drop it", async () => {
const el = document.createElement("div");
liftElementCrop(el);
sent[0]!.answer(null);
await settle();
expect(isElementCropLifted(el)).toBe(true);
dropElementCropLift(el);
expect(sent.map((request) => request.lift)).toEqual([true, false]);
});

it("asks again until the frame says the lift is gone, and only then forgets it", async () => {
const el = await lifted();
dropElementCropLift(el);
sent[1]!.answer(null);
await settle();
expect(sent.map((request) => request.lift)).toEqual([true, false, false]);
sent[2]!.answer({ lifted: false, clipPath: null });
await settle();
expect(sent).toHaveLength(3);
expect(isElementCropLifted(el)).toBe(false);
liftElementCrop(el);
expect(sent.map((request) => request.lift)).toEqual([true, false, false, true]);
});

it("ignores a clip-path past the element value cap, and an inset past the draft limit", async () => {
expect(readElementCropInsets(await lifted(`inset(5px) ${"x".repeat(3000)}`))).toMatchObject({
top: 0,
});
expect(readElementCropInsets(await lifted("inset(200000px 0px 0px 0px)"))).toBeNull();
});
});
2 changes: 2 additions & 0 deletions packages/studio/src/components/editor/previewDrafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export function registerPreviewStandIn(
standIns.set(standIn, { iframe, handle });
}

export const previewStandIn = (standIn: Element) => standIns.get(standIn);

function queueFor(iframe: HTMLIFrameElement): Queue {
let queue = queues.get(iframe);
if (!queue) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// @vitest-environment happy-dom

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
// The frame's real runtime agent, serving the opaque frame from this document.
import { installMarkedEditingAgent } from "../../../../core/src/runtime/editingAgent.test-helpers";
import { makeSelection } from "../../hooks/domSelectionTestHarness";
import { computeDraggedGsapPosition } from "../../hooks/draggedGsapPosition";
import { tryGsapResizeIntercept } from "../../hooks/gsapResizeIntercept";
import { watchPreviewFrame } from "../../player/lib/bridgePlayback";
import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements";
import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness";
Expand All @@ -15,7 +17,11 @@ import {
createManualOffsetDragMember,
restoreManualOffsetDragMembers,
} from "./manualOffsetDrag";
import { measurePreviewGestureStart, type PreviewGestureStart } from "./previewGestureStartRead";
import {
gestureStartLayout,
measurePreviewGestureStart,
type PreviewGestureStart,
} from "./previewGestureStartRead";
import { standInFor } from "./previewSelection";
import { collectSnapContext } from "./snapTargetCollection";

Expand Down Expand Up @@ -266,3 +272,52 @@ describe("starting a gesture from what an opaque frame read", () => {
restoreManualOffsetDragMembers(g.members);
});
});

describe("a resize in a preview Studio cannot script", () => {
it.each([-5, 1e-9, 1e9])("keeps no start box for a frame-reported width of %s", async (width) => {
const iframe = opaqueFrame();
Object.defineProperty(document.querySelector("#last"), "offsetWidth", {
value: width,
configurable: true,
});
const handle = (await queryPreviewElements(iframe, "#last"))!.matches[0]!.handle;
await measurePreviewGestureStart(iframe, overlayEl(), [handle]);
expect(gestureStartLayout(handle)).toBeNull();
});

it("scales from the box its gesture started from, not a 200 px fallback", async () => {
const iframe = opaqueFrame();
const handle = (await queryPreviewElements(iframe, "#last"))!.matches[0]!.handle;
const standIn = standInFor(iframe, (await describePreviewElements(iframe, [handle]))![0]!);
await measurePreviewGestureStart(iframe, overlayEl(), [handle]);
const scaleKeys = {
id: "#last-scale",
targetSelector: "#last",
propertyGroup: "scale",
method: "to",
properties: { scale: 1 },
position: 0,
resolvedStart: 0,
duration: 1,
keyframes: {
keyframes: [
{ percentage: 0, properties: { scale: 1 } },
{ percentage: 100, properties: { scale: 1 } },
],
},
} as unknown as GsapAnimation;
const commitMutation = vi.fn();

await tryGsapResizeIntercept(
{ ...makeSelection("last", standIn), handle },
{ width: 240, height: 120 },
[scaleKeys],
iframe,
commitMutation,
);

const scales = JSON.stringify(commitMutation.mock.calls.map((call) => call[1]));
// It measured 120 x 60 at the press, so 240 x 120 is a scale of 2; the 200 px fallback gave 1.2.
expect(scales).toMatch(/"scale":2\b/);
});
});
Loading
Loading