fix(studio): canvas selection, drag and resize correctness (#3146)

* fix(studio): size the selection box by the transform the element actually paints under

The box around a text layer inside the playground card stopped mid-word. The
layer is 260px wide and paints 313, because its parent carries `scale(1.2)`,
and the chrome read only the element's OWN transform. The top-left looked
right, since the corners are anchored to the real bounding rect, so only the
right and bottom edges fell short, by exactly 1/1.2.

The same read decides whether to draw the box rotated at all, so an element
whose parent is rotated got an upright box over a rotated one.

The transform is now accumulated from the element up to the composition root.
Only the linear part matters: each transform's origin contributes translation,
and translation is already discarded by matching the corners to the element's
bounding rect, so composing the matrices is enough and no per-ancestor origin
has to be unpicked. The walk stops inside the composition document, because the
canvas zoom lives on the iframe in Studio's own document and is applied
separately.

The fake DOMMatrix the geometry tests use gained the `multiply` it now needs.

* fix(studio): drag by the movement the element actually makes, not the one assumed

An element that had never been dragged skipped the movement measurement and took
the canvas zoom as the whole screen mapping. Nothing above the element was
considered, so any parent transform broke the drag: a card at rotationY 180 with
scale 1.2 maps a rightward drag to -1.2x the zoom, meaning the text walked LEFT
while the overlay followed the pointer, and the overlay only snapped onto the
text at drop, when it re-measured.

Measured on the live element in that card: one unit of drag offset moved it
-0.757 px on x and +0.757 on y, where the skipped path assumed +0.631 on both.

The measurement it skipped already handles this — it moves the element, watches
where it lands, and inverts that, which is right for rotation, mirroring, scale
and perspective alike. So the special case is gone and every drag measures. Same
element after: a 120x80 pointer drag moves it 120.3x80.2.

Rewrote the test that asserted the skipped path's identity matrix for an
unmovable element. It now asserts the honest outcome: an element with no
measurable movement is reported unmeasurable whether or not it carries a path
offset, and the caller's existing fallback covers it.

* fix(studio): shift-click adds the element under the pointer, not the last one hovered

Shift-click read the hover cache and used it without checking what it described.
That cache is filled asynchronously as the pointer moves, so passing over one
element on the way to another leaves it naming the element you left. The
shift-click then added THAT element, and because the same branch prevented the
default and set the suppression flags, the mousedown path that would have
resolved the point correctly never ran. Multi-select looked like it grabbed
things at random, or like it did nothing.

Reproduced on the canvas with a trace: hover #card, shift-click #dot-b, and the
group gained #card. Same gesture after: the guard rejects the cache, the
mousedown path resolves the point, and the group gains #dot-b.

The cache is still used when it is provably about the point clicked, including
when it names a clip ancestor of the element there, so the fast path survives for
the common case of clicking straight at something.

Adds `hf-select-debug` (localStorage, off by default) recording which selection
branch ran and what it decided, and pulls the flag/format shared with
`hf-reload-debug` into one place rather than copying it.

* fix(studio): keep every element a marquee caught, not just the first

The marquee built the group correctly and then threw it away. It announced only
the primary to the timeline, and the timeline is the source of truth for what is
selected: the sync back to the canvas saw one selected id against a group of
several, decided the canvas was stale, and replaced the group with that single
element a moment after the drop. Drag a box around four things, get one.

The whole set is announced now, and the primary goes in as its anchor rather
than as a new single selection, so the set it just joined survives. This is the
same reason the single-select path already anchors with preserveSet.

A test drives applyMarqueeSelection with two elements and asserts both reach the
timeline; it fails against the old single-id announce.

* fix(studio): stop a group selection from erasing itself on the timeline

Every canvas selection is mirrored onto the timeline, and the timeline syncs
back — whatever it holds replaces the canvas selection a moment later. The
mirror announced only the primary and anchored it with preserveSet, but
preserving a set that does not contain the id empties the set, and an empty set
syncs back as "nothing is selected". Adding a second element, or re-resolving a
group after moving it, could therefore drop the whole selection rather than keep
it.

One helper now owns the mirror: publish the members, then anchor. A single
selection keeps the previous contract deliberately, so a late async primary
still cannot collapse a live group and a fresh click still collapses a stale
one. The group re-resolve path also gains the ancestor id fallback the other
callers already had — without it a member with no direct timeline row resolved
to null and deselected everything.

Two tests: a second element joining a selection, and a marquee, both assert the
full set reaches the timeline. Both fail against the announce-the-primary-only
version.

* chore(studio): trace what moves a dragged group and when

A drag that jumps is a position that changed without the pointer asking for it,
and nothing on that path says anything today, so the frame it diverges can only
be guessed at. `hf-drag-debug` (localStorage, off by default) records the whole
gesture: the mapping and start position each member got, the pointer delta
against the delta actually applied on every eighth move, what each member was
told to commit, and where they all sit at the drop, once the commit resolves, and
120/400/900ms later.

That last group is the point of it. The source write, the preview reload and the
timeline resume all land within a few frames of the drop, and any of them can put
the elements back where they started before the new position arrives — a
snap-back shows up as a settle sample reverting to the gesture-start reading.
A gap between `pointer` and `applied` instead means snapping pulled the group off
the cursor, which is a different fault with a different fix.

* chore(studio): name the path that clears a selection after a group move

The drag trace showed the group landing exactly where it was dropped and staying
there — no snap-back at any settle sample, and the pointer and the applied delta
never more than 2px apart — but two milliseconds after the drop the selection was
cleared with seven members still in it.

The clear comes from the timeline sync deciding the timeline holds nothing, and
that branch said nothing. It says so now, along with whether it is about to act
on it. The mirror alongside it reports how many members it managed to publish and
whether the anchor was among them, because a member with no timeline row of its
own resolves to null and is dropped silently — publish none and the sync reads it
back as an empty selection.

* fix(studio): losing one member of a group no longer deselects all of it

After a move the preview re-syncs and the selection is re-resolved against the
new document. When the primary could not be found there, both re-resolve paths
cleared the entire selection — so a group of five, all still on screen, was
deselected because one of them failed to resolve. The trace showed the clear
landing 600ms after the drop with five members still held, and the timeline sync
running afterwards on an already-empty canvas, which ruled it out as the cause.

A live group now re-resolves as a group and keeps whoever survived, picking a new
primary from them; it only clears when nobody did. That is what
refreshDomEditGroupSelectionsFromPreview was written for — it existed and was
never called.

Both clears also say which one they are and how many members were held, so if
this is not the last of it the next trace names the path immediately.

* feat(studio): carry a multi-selection in the URL, and name the member that breaks away

A link to a bug hit with several elements selected only reproduced one of them,
so the report read as "works for me". The hash now carries the rest as selGroup
and reopens the whole selection; members whose element is gone are dropped rather
than failing the others. Verified end to end in a real browser: select three,
copy the hash, open it fresh, the same three come back.

The drag trace also gains a rigidity check. A group moves as one object, so every
member travels the same distance; one that does not IS the fault. Drift was being
computed but only printed on every eighth frame, which is exactly how a
single-frame divergence hides — it now prints on the frame it happens.

The frame handler moves to its own module on the way past. It had grown a snap
block and a trace block inside a function already juggling four gesture kinds,
and it was over both the complexity and file-size gates.

Not fixed: the jump itself. Two headful runs driving a real group drag showed the
members staying rigid to the pixel, at the drop and 900ms after, so I have not
reproduced it yet and will not guess at a fix.

* fix(studio): stop snapping from moving a selection you have not dragged yet

Your log caught it on the first frame of the drag: pointer "0,0", applied "4,-3",
and all four members jumped 12,-8 composition px before the pointer had moved at
all. An element resting within the 6px snap threshold of a guide is already
snappable, so the snap computed on frame one closes that gap immediately —
picking the selection up moves it.

Snapping now sits out until the gesture has travelled the same 4px a drag needs
to count as a drag rather than a click, on both the group and single-element
paths. Nothing below that distance moves anything, and a real drag snaps exactly
as before.

The test builds a box resting 4px from a guide and asserts the ungated call still
returns dx 4 — the very displacement from your log — while the gated one returns
0 for a pointer that has not moved.

* fix(studio): a dropped group stays selected

Your Jam confirmed the first-frame jump is gone — pointer "0,0" now reads
applied "0,0" — and caught what was left: two milliseconds after each drop, a
`[hf-select] clear` with the group still holding three, then four members.

Every pointerup trails a click. The group gesture ref is cleared before the
commit runs, so by the time that click arrives the box no longer looks busy and
it reaches the canvas as an ordinary click — landing in the gap between the
members, resolving to nothing, and clearing the selection the drag just moved.
The under-threshold path already ate that click; the committed path never did.

The flag is now set before the two paths diverge, so neither can forget it. The
test drives a real pointerup through the handlers and fails on the committed
path with the flag moved back down.

* feat(studio): marquee from anywhere on the canvas, including outside the frame

An element dragged past the edge sits out in the grey, and the rubber band
refused to start there — it only began when the press landed inside the
composition rect. The one gesture that could reach those elements could not be
begun near them, so the timeline was the only way to select something plainly
visible on screen.

The collecting half never had that limit: it compares rects in overlay space and
never clipped to the frame, so those elements have always been selectable once
the band could begin. Only the start gate had to go.

A press in the grey that never travels still commits an empty selection, which is
the deselect it used to be, so the old behaviour of clicking out there to clear
is unchanged.

* refactor(studio): keep the selection files under the size cap

The selection work above pushed four files past the 600-line gate. Same
split the branch made later, landed with the changes that caused it.

* fix(studio): preserve selector groups in share URLs

* fix(studio): close multi-selection review gaps

* fix(studio): stabilize selection store reads

* fix(studio): preserve canvas-only group anchors

* fix(studio): stop a group drag from jumping one element back

Dragging several elements at once and dropping them made one of them snap
back to where it started for a frame or two, then jump forward again.

Each member of the group is written separately, and every write patched the
live GSAP tween in place and then seeked the player. A seek re-renders the
WHOLE timeline, not the tween that changed, so the members still queued
behind that write got repainted from their un-patched tweens: back to their
pre-drag position, where they sat until their own write landed. Only members
whose tween actually renders at the playhead showed it, which is why a group
of three flashed one element and left the others still.

The group commit now defers the seek for every member but the last, so the
queued members keep the transform the gesture left on them and the whole
group repaints once, from the fully patched timeline.

* perf(studio): commit a group drag in one request

Dragging N elements cost N writes and 9 reads for a three-element group: each
member fetched the composition's parse to preflight, fetched it again to
resolve its tween, then wrote the file on its own round trip. Every one of
those writes re-read, re-parsed and re-serialized the whole composition.

Three changes, same behaviour:

- The parse endpoint shares an in-flight request per file, so callers asking
  for the same composition at the same moment get one request. Only
  overlapping calls share — the entry is dropped as soon as it settles, so a
  read after a write still gets a fresh parse.
- The group preflight runs its members together instead of one at a time. A
  preflight writes nothing, so there is nothing to order.
- Members' mutations are queued and sent as one batch write. Anything that
  re-reads the file flushes the queue first, so a member resolving a shared or
  stale tween never reads a composition missing writes it is about to build
  on. The batch carries each member's runtime patch, and only the last one
  re-renders.

A three-element group drag now issues 2 reads and 1 write, down from 9 and 3.

* fix(studio): harden batched drag commits

* fix(studio): carry deferred preview fallbacks

* chore(studio): name whoever puts the pre-resize size back

Resizing the card commits correctly — the source and a fresh load both read
273x181 — but 200ms after the drop, mid-commit, the element renders at 395x261
with the studio size vars still holding 273x181. Something writes the
pre-gesture size back inline while the reload is still in flight, and every
writer of that size was silent.

Both are traced now under the existing hf-resize-debug flag, each with the size
going in, the size being replaced, and a short stack. Restoring the pre-gesture
size is right on a cancel and wrong after a successful commit, and the function
doing it cannot tell the two apart from the inside — so the caller has to be
named before this can be fixed at the right end.

* fix(studio): hold a resized element's size while the timeline is rebuilt

Your log caught it across two resizes. The first commits 305x202 and the element
is 305x202 at the drop; 200ms later it renders 395x261, its stylesheet size,
while --hf-studio-width still reads 305. The second gesture then starts with
`actual` at 305 against a live box of 395, and its very first move — a pointer
delta of 0.1px — snaps the element back to 305. That snap is the jump.

The gap belongs to the soft reload: it reverts the old timeline before building
the new one, and GSAP hands back each tween's recorded starting width on the way
out. Nothing held the size in between, because the seek reapply that exists for
exactly this stands aside for elements GSAP animates.

Standing aside is right for the offset — those channels compose, and applying
both doubles the move — and wrong for size, where both channels write width and
height so the later write simply wins on the same committed number. It applies
now. Only an element mid-edit carries the vars, so nothing else is touched.

A test seeks an element whose size GSAP owns after the revert put the stylesheet
size back, and fails with the skip restored.

* refactor(studio): keep the resize files under the size cap

* docs(studio): fold the resize note into the size-reapply comment

* fix(studio): rotate the child outlines with the element they outline

Selecting a rotated element drew upright dashed boxes across its children:
the chrome co-rotated with the element and the child outlines did not, so a
text layer inside a rotated card got a square outline lying across the
rotated glyphs.

The chrome already measures an oriented box; the child outlines were still
measured axis-aligned. They now use the same oriented measurement and render
with the same rotation. An unrotated element measures identically to before,
since the oriented rect returns the plain bounding box at angle 0.
This commit is contained in:
Miguel Ángel
2026-08-09 16:58:34 -07:00
committed by GitHub
parent bea32b8aae
commit 17ac986bfe
48 changed files with 2370 additions and 367 deletions
@@ -14,7 +14,10 @@ import {
resolveDomEditRotationGesture,
} from "./DomEditOverlay";
import type { DomEditSelection } from "./domEditing";
import { resolveResizeCenterAnchorOffset } from "./domEditOverlayGestures";
import {
hoverCacheDescribesPoint,
resolveResizeCenterAnchorOffset,
} from "./domEditOverlayGestures";
// React 19 warns unless the test environment opts into act().
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
@@ -278,7 +281,9 @@ describe("DomEditOverlay", () => {
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
const iframeRef = { current: document.createElement("iframe") as HTMLIFrameElement | null };
const iframeRef: { current: HTMLIFrameElement | null } = {
current: document.createElement("iframe"),
};
const onCanvasMouseDown = vi.fn();
const onMarqueeSelect = vi.fn();
@@ -323,6 +328,44 @@ describe("DomEditOverlay", () => {
host.remove();
});
it("starts a marquee from outside the composition frame", async () => {
const restoreRect = stubViewportRect();
const originalPointerCapture = HTMLDivElement.prototype.setPointerCapture;
const setPointerCapture = vi.fn();
HTMLDivElement.prototype.setPointerCapture = setPointerCapture;
const host = document.createElement("div");
document.body.append(host);
const root = createRoot(host);
const iframeRef: { current: HTMLIFrameElement | null } = {
current: document.createElement("iframe"),
};
act(() => {
root.render(
React.createElement(DomEditOverlay, {
...createOverlayProps({
iframeRef,
selection: null,
hoverSelection: null,
onSelectionChange: () => {},
}),
onMarqueeSelect: vi.fn(),
}),
);
});
await flushOverlayRaf();
// Negative x is outside the 0..800 composition frame but still reaches the
// overlay in a real pointer event when the user starts in the grey margin.
dispatchOverlayPointerDown(getOverlay(host), -40, 100);
expect(setPointerCapture).toHaveBeenCalledTimes(1);
act(() => root.unmount());
HTMLDivElement.prototype.setPointerCapture = originalPointerCapture;
restoreRect();
host.remove();
});
it("does not start a drag from a stale hover target on canvas pointer-down", () => {
const host = document.createElement("div");
document.body.append(host);
@@ -628,6 +671,50 @@ describe("resolveDomEditRotationGesture", () => {
});
});
/**
* Shift-click reads the hover cache instead of hit-testing, and the cache is
* filled asynchronously as the pointer moves. Pass over one element on the way to
* another and the cache still names the one you left, so the shift-click added
* THAT element and the click looked like it selected something at random. The
* guard is what makes the cache usable only when it is about the point clicked.
*/
describe("hoverCacheDescribesPoint", () => {
const doc = new Window().document;
it("rejects a cache left behind by an element the pointer passed over", () => {
const passedOver = doc.createElement("div");
const clicked = doc.createElement("div");
doc.body.append(passedOver, clicked);
expect(hoverCacheDescribesPoint(passedOver, clicked)).toBe(false);
});
it("accepts the cache when it names the element at the point", () => {
const clicked = doc.createElement("div");
doc.body.append(clicked);
expect(hoverCacheDescribesPoint(clicked, clicked)).toBe(true);
});
// The resolver is allowed to hand back a clip ancestor of the raw target, which
// still describes the same click — rejecting it would drop the fast path on
// every element that has children.
it("accepts an ancestor of the element at the point", () => {
const clip = doc.createElement("div");
const child = doc.createElement("span");
clip.append(child);
doc.body.append(clip);
expect(hoverCacheDescribesPoint(clip, child)).toBe(true);
});
it("rejects a missing cache or an empty point", () => {
const el = doc.createElement("div");
expect(hoverCacheDescribesPoint(null, el)).toBe(false);
expect(hoverCacheDescribesPoint(el, null)).toBe(false);
});
});
// resolveResizeCenterAnchorOffset is the UNROTATED (AABB) fallback used only when
// the element's real transformed corners can't be measured. Center-anchored: a
// width/height change grows the box from its top-left, drifting the center by half
@@ -13,6 +13,7 @@ import {
type GestureState,
type GroupGestureState,
focusDomEditOverlayElement,
resolveShiftClickCandidate,
} from "./domEditOverlayGestures";
import { useDomEditOverlayRects } from "./useDomEditOverlayRects";
import { OffCanvasIndicators, type OffCanvasRect } from "./OffCanvasIndicators";
@@ -31,6 +32,7 @@ import { startOffCanvasIndicatorRefresh } from "./offCanvasIndicatorRefresh";
import { CanvasContextMenu } from "./CanvasContextMenu";
import type { ZOrderAction, ZOrderPatch } from "./canvasContextMenuZOrder";
import { getPreviewTargetFromPointer } from "../../utils/studioPreviewHelpers";
import { logSelect } from "../../utils/selectDebug";
// Re-exports for external consumers — preserving existing import paths.
export {
@@ -318,6 +320,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
const handleOverlayMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {
if (!allowCanvasMovement) return;
if (suppressNextOverlayMouseDownRef.current) {
logSelect("mousedown-suppressed", { shift: event.shiftKey });
suppressNextOverlayMouseDownRef.current = false;
suppressNextBoxMouseDownRef.current = false;
suppressNextBoxClickRef.current = false;
@@ -326,7 +329,9 @@ export const DomEditOverlay = memo(function DomEditOverlay({
return;
}
const target = event.target as HTMLElement | null;
if (target?.closest('[data-dom-edit-selection-box="true"]')) return;
const onBox = Boolean(target?.closest('[data-dom-edit-selection-box="true"]'));
logSelect("mousedown", { shift: event.shiftKey, onBox });
if (onBox) return;
// Allow clicks anywhere on the overlay — GSAP-translated elements can
// extend beyond the composition rect into the gray zone, and users need
// to select/deselect them by clicking there.
@@ -341,8 +346,20 @@ export const DomEditOverlay = memo(function DomEditOverlay({
const handleOverlayPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
if (!allowCanvasMovement || event.button !== 0) return;
if (event.shiftKey) {
// Use the already-updated hover selection rather than re-resolving async
const candidate = hoverSelectionRef.current;
const shiftIframe = iframeRef.current;
const candidate = resolveShiftClickCandidate({
cached: hoverSelectionRef.current,
elementAtPoint: shiftIframe
? getPreviewTargetFromPointer(
shiftIframe,
event.clientX,
event.clientY,
activeCompositionPathRef.current,
)
: null,
});
// Not confident: fall through untouched — no preventDefault, no suppression —
// so the mousedown path resolves this point instead of guessing here.
if (!candidate) return;
event.preventDefault();
event.stopPropagation();
@@ -376,28 +393,27 @@ export const DomEditOverlay = memo(function DomEditOverlay({
const overlayEl = overlayRef.current;
if (overlayEl) {
const oRect = overlayEl.getBoundingClientRect();
// Anywhere empty on the overlay starts one, not just inside the frame.
// An element dragged past the edge sits OUT there in the grey, and a
// rubber band that refuses to start there cannot reach it — which left
// the timeline as the only way to select something you can plainly see.
// The hit test collects in overlay space and never clipped to the frame,
// so those elements were always selectable once the band could begin.
event.preventDefault();
event.stopPropagation();
suppressNextOverlayMouseDownRef.current = true;
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
const cx = event.clientX - oRect.left;
const cy = event.clientY - oRect.top;
const inComp =
cx >= compRect.left &&
cx <= compRect.left + compRect.width &&
cy >= compRect.top &&
cy <= compRect.top + compRect.height;
if (inComp) {
event.preventDefault();
event.stopPropagation();
suppressNextOverlayMouseDownRef.current = true;
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
marquee.marqueeRef.current = {
startX: cx,
startY: cy,
currentX: cx,
currentY: cy,
pointerId: event.pointerId,
pastThreshold: false,
};
return;
}
marquee.marqueeRef.current = {
startX: cx,
startY: cy,
currentX: cx,
currentY: cy,
pointerId: event.pointerId,
pastThreshold: false,
};
return;
}
}
};
@@ -503,6 +519,7 @@ export const DomEditOverlay = memo(function DomEditOverlay({
top: cr.top,
width: cr.width,
height: cr.height,
transform: cr.angle ? `rotate(${cr.angle}deg)` : undefined,
}}
/>
))}
@@ -5,6 +5,7 @@ import {
orientedGroupAwareOverlayRect,
overlayCornersCentroid,
selectionCacheKey,
orientedVisibleOverlayRect,
} from "./domEditOverlayGeometry";
describe("overlayCornersCentroid", () => {
@@ -67,6 +68,17 @@ describe("orientedOverlayRect — rotation gate (perf fix, V15 18a/18b)", () =>
number,
];
}
/** `this` applied outside `other`, the way an ancestor composes over a child. */
multiply(other: { a: number; b: number; c: number; d: number; e: number; f: number }) {
const out = new (this.constructor as new (init?: string) => this)();
out.a = this.a * other.a + this.c * other.b;
out.b = this.b * other.a + this.d * other.b;
out.c = this.a * other.c + this.c * other.d;
out.d = this.b * other.c + this.d * other.d;
out.e = this.a * other.e + this.c * other.f + this.e;
out.f = this.b * other.e + this.d * other.f + this.f;
return out;
}
transformPoint(pt: { x: number; y: number }) {
return {
x: this.a * pt.x + this.c * pt.y + this.e,
@@ -148,6 +160,30 @@ describe("orientedOverlayRect — rotation gate (perf fix, V15 18a/18b)", () =>
expect(rect!.angle ?? 0).toBe(0);
});
/**
* A child outline is drawn ON the child, not around it. Measured axis-aligned,
* a text layer inside a rotated card got an upright dashed box sitting across
* the rotated glyphs — the parent's chrome rotated and its children's did not.
*/
it("child outlines carry the element's angle, so they can co-rotate with it", () => {
const { overlayEl, iframe, el } = buildHarness();
el.style.transform = ROTATE_30DEG_MATRIX;
const rect = orientedVisibleOverlayRect(overlayEl, iframe, el);
expect(rect).not.toBeNull();
expect(rect!.angle).toBeCloseTo(30, 3);
});
it("an unrotated child outline is unchanged — no angle, same box as before", () => {
const { overlayEl, iframe, el } = buildHarness();
const rect = orientedVisibleOverlayRect(overlayEl, iframe, el);
expect(rect).not.toBeNull();
expect(rect!.angle ?? 0).toBe(0);
expect(rect!.left).toBeCloseTo(400, 5);
expect(rect!.top).toBeCloseTo(450, 5);
expect(rect!.width).toBeCloseTo(200, 5);
expect(rect!.height).toBeCloseTo(100, 5);
});
it("rotated element takes the corner-geometry path — reports the live angle", () => {
const { overlayEl, iframe, el } = buildHarness();
el.style.transform = ROTATE_30DEG_MATRIX;
@@ -156,6 +192,64 @@ describe("orientedOverlayRect — rotation gate (perf fix, V15 18a/18b)", () =>
expect(rect!.angle).toBeCloseTo(30, 3);
});
/**
* The selection box is drawn at the size the element PAINTS, which is the
* product of every transform between it and the composition root.
*
* A text layer inside a card carrying `scale(1.2)` was drawn at 1/1.2 of the
* text: the top-left was right, because the caller anchors that to the real
* bounding rect, and the right and bottom edges fell short. The same read
* decides whether to draw the box rotated, so an element inside a rotated
* parent got an upright box.
*/
const SCALE_1_2_MATRIX = "matrix(1.2, 0, 0, 1.2, 0, 0)";
const MIRROR_X_MATRIX = "matrix(-1, 0, 0, 1, 0, 0)";
it("sizes the box by the accumulated transform, not the element's own", () => {
const { overlayEl, iframe, el } = buildHarness();
// The element carries no transform; its parent scales it by 1.2, so it
// paints at 240x120 and its bounding rect says so.
el.parentElement!.style.transform = SCALE_1_2_MATRIX;
el.style.transform = ROTATE_30DEG_MATRIX;
stubRect(el, { left: 400, top: 450, width: 240, height: 120 });
const rect = orientedOverlayRect(overlayEl, iframe, el);
expect(rect).not.toBeNull();
// 200x100 local, scaled by the ancestor, then rotated: the oriented box is
// the scaled local box, and the AABB it is anchored to is wider again.
expect(rect!.width).toBeCloseTo(240, 3);
expect(rect!.height).toBeCloseTo(120, 3);
expect(rect!.angle).toBeCloseTo(30, 3);
});
it("takes the rotated path when only an ANCESTOR is rotated", () => {
const { overlayEl, iframe, el } = buildHarness();
el.parentElement!.style.transform = ROTATE_30DEG_MATRIX;
const rect = orientedOverlayRect(overlayEl, iframe, el);
expect(rect!.angle).toBeCloseTo(30, 3);
});
it("does not misread a mirrored ancestor as a 180-degree rotation", () => {
const { overlayEl, iframe, el } = buildHarness();
el.parentElement!.style.transform = MIRROR_X_MATRIX;
const rect = orientedOverlayRect(overlayEl, iframe, el);
expect(rect?.angle ?? 0).toBe(0);
});
it("stops transform composition at the composition root", () => {
const { overlayEl, iframe, el } = buildHarness();
iframe.contentDocument!.body.style.transform = ROTATE_30DEG_MATRIX;
const rect = orientedOverlayRect(overlayEl, iframe, el);
expect(rect?.angle ?? 0).toBe(0);
});
it("preserves an ordinary element's rotation through the group-aware entry point", () => {
const { overlayEl, iframe, el } = buildHarness();
el.style.transform = ROTATE_30DEG_MATRIX;
@@ -117,6 +117,28 @@ interface ElementTransformSnapshot {
cs: CSSStyleDeclaration;
}
/**
* The transform from the element's own box to the composition's, ACCUMULATED
* over its ancestors rather than read from the element alone.
*
* What the user sees is the product of every transform between the element and
* the composition root, and an element is routinely a child of something
* scaled or rotated. Reading only its own transform drew the selection box at
* the element's untransformed size: a text layer inside a card carrying
* `scale(1.2)` got a box at 1/1.2 of the text, with the top-left correct (the
* caller anchors that to the real bounding rect) and the right and bottom
* edges falling short. The same read decides whether to draw the box rotated,
* so an element inside a rotated parent got an upright box too.
*
* Only the linear part matters here. Each transform's origin contributes
* translation, and the caller discards translation by matching the corners'
* bounding box to the element's real one, so composing the matrices alone is
* enough and there is no per-ancestor origin to unpick.
*
* The walk stops at the composition document's root. The canvas zoom lives on
* the iframe element in Studio's own document and is applied separately by
* `computeOverlayRootScale`; including it here would count it twice.
*/
function readElementTransformSnapshot(
win: Window,
element: HTMLElement,
@@ -125,7 +147,15 @@ function readElementTransformSnapshot(
if (!DOMMatrixCtor) return null;
const cs = win.getComputedStyle(element);
try {
const matrix = new DOMMatrixCtor(cs.transform === "none" ? "" : cs.transform);
let matrix = new DOMMatrixCtor();
for (let node: HTMLElement | null = element; node; node = node.parentElement) {
const transform = node === element ? cs.transform : win.getComputedStyle(node).transform;
if (transform && transform !== "none") {
// An ancestor applies outside, so it multiplies on the left.
matrix = new DOMMatrixCtor(transform).multiply(matrix);
}
if (node.hasAttribute("data-composition-id")) break;
}
return { matrix, cs };
} catch {
return null;
@@ -141,7 +171,16 @@ function readElementTransformSnapshot(
function rotationDegreesFromMatrix(matrix: DOMMatrix): number {
const a = Number.isFinite(matrix.a) ? matrix.a : 1;
const b = Number.isFinite(matrix.b) ? matrix.b : 0;
const deg = (Math.atan2(b, a) * 180) / Math.PI;
const c = Number.isFinite(matrix.c) ? matrix.c : 0;
const d = Number.isFinite(matrix.d) ? matrix.d : 1;
const fromX = (Math.atan2(b, a) * 180) / Math.PI;
const determinant = a * d - b * c;
// A reflection makes one basis direction read 180° away from the authored
// rotation. For cursor/handle orientation those directions are equivalent;
// choose the representative nearest zero instead of drawing a pure mirror's
// rotate handle on the opposite side of the element.
const fromY = (Math.atan2(-c, d) * 180) / Math.PI;
const deg = determinant < 0 && Math.abs(fromY) < Math.abs(fromX) ? fromY : fromX;
return Number.isFinite(deg) ? deg : 0;
}
@@ -391,6 +430,24 @@ export function orientedOverlayRect(
};
}
/**
* `toVisibleOverlayRect`'s oriented twin: the element's crop-hugged box plus its
* live rotation, for chrome that has to sit on a rotated element rather than
* around it. Rendering the result with `transform: rotate(angle)` about its
* centre lands it on the element's real corners.
*
* At angle 0 `orientedOverlayRect` returns the plain AABB, so an unrotated
* element measures exactly as it did before.
*/
export function orientedVisibleOverlayRect(
overlayEl: HTMLDivElement,
iframe: HTMLIFrameElement,
element: HTMLElement,
): OverlayRect | null {
const rect = orientedOverlayRect(overlayEl, iframe, element);
return rect ? { ...rect, ...hugRectForElement(rect, element) } : null;
}
const OVERLAY_RECT_EPSILON_PX = 0.5;
const OVERLAY_RECT_ANGLE_EPSILON_DEG = 0.1;
@@ -10,6 +10,7 @@ import type { GroupOverlayItem, OverlayRect } from "./domEditOverlayGeometry";
import type { SnapContext } from "./snapTargetCollection";
import type { SnapGuidesState } from "./SnapGuideOverlay";
import type { PreviewMouseDownOptions } from "../../hooks/usePreviewInteraction";
import { logSelect } from "../../utils/selectDebug";
export type GestureKind = "drag" | "resize" | "rotate";
@@ -112,6 +113,47 @@ export function focusDomEditOverlayElement(element: FocusableDomEditOverlay | nu
element?.focus({ preventScroll: true });
}
/**
* Whether the hover cache may stand in for a hit-test at this point.
*
* The cache is filled asynchronously as the pointer moves, so it can describe an
* element the pointer has already left. That is harmless for drawing a hover
* outline and wrong for a shift-click, which would add the stale element to the
* selection instead of the one under the pointer. True only when the cached
* element IS the element at the point, or contains it — the resolver is allowed
* to hand back a clip ancestor of the raw target, and that still describes the
* same click.
*/
export function hoverCacheDescribesPoint(
cachedElement: Element | null | undefined,
elementAtPoint: Element | null | undefined,
): boolean {
if (!cachedElement || !elementAtPoint) return false;
return cachedElement === elementAtPoint || cachedElement.contains(elementAtPoint);
}
/**
* The element a shift-click should add, or null to let the slower path resolve it.
*
* Reading the hover cache without checking is safe for a hover outline and wrong
* for a shift-click: the click silently adds whatever the pointer last passed
* over instead of the element under it, which reads as multi-select picking
* things at random. Returning null means "not confident", and the caller must
* then fall through untouched so the mousedown path resolves the point properly.
*/
export function resolveShiftClickCandidate<T extends { element: Element }>(input: {
cached: T | null;
elementAtPoint: Element | null;
}): T | null {
const describes = hoverCacheDescribesPoint(input.cached?.element, input.elementAtPoint);
logSelect("shift-pointerdown", {
candidate: input.cached ? ((input.cached as { selector?: string }).selector ?? null) : null,
pointTarget: input.elementAtPoint?.id ?? input.elementAtPoint?.tagName ?? null,
cacheIsAboutThisPoint: describes,
});
return describes ? input.cached : null;
}
/**
* Overlay-px translation that keeps the element's CENTER fixed while a corner
* resizes: a CSS width/height change grows the layout box from its top-left, so
@@ -33,6 +33,7 @@ import {
} from "./domEditOverlayGestures";
import { collectSnapContext, buildExcludeElements } from "./snapTargetCollection";
import { logResize, resetResizeMoveLog } from "../../utils/resizeDebug";
import { logDrag, readDragPositions, resetDragMoveLog } from "../../utils/dragDebug";
export function startGroupDrag(
e: React.PointerEvent<HTMLElement>,
@@ -70,6 +71,22 @@ export function startGroupDrag(
}
members.push(result.member);
}
resetDragMoveLog();
logDrag("group-start", {
// A member whose mapping differs from its neighbours travels a different
// distance for the same pointer delta, which is the group coming apart.
members: Object.fromEntries(
members.map((member) => [
member.key,
{
map: `${member.screenToOffset.a.toFixed(3)},${member.screenToOffset.d.toFixed(3)}`,
base: `${Math.round(member.baseGsap.x)},${Math.round(member.baseGsap.y)}`,
offset: `${Math.round(member.initialOffset.x)},${Math.round(member.initialOffset.y)}`,
},
]),
),
at: readDragPositions(members),
});
const overlayEl = opts.overlayRef.current;
const iframe = opts.iframeRef.current;
@@ -0,0 +1,110 @@
import { resolveDomEditGroupOverlayRect } from "./domEditOverlayGeometry";
import {
resolveEquidistanceGuides,
resolveSnapAdjustment,
snapEngagedForTravel,
SNAP_THRESHOLD_PX,
} from "./snapEngine";
import { applyManualOffsetDragDraft } from "./manualOffsetDrag";
import type { GroupGestureState, UseDomEditOverlayGesturesOptions } from "./domEditOverlayGestures";
import type { GroupOverlayItem } from "./domEditOverlayGeometry";
import {
findNonRigidMembers,
logDrag,
logDragMove,
readDragPositions,
} from "../../utils/dragDebug";
/**
* One frame of a group drag, kept out of onPointerMove which already handles
* four gesture kinds and reads better without this one's snapping arithmetic.
* The previous frame's positions live in the closure so the rigidity check below
* compares against the frame before, not against whatever was last sampled.
*/
export function createGroupDragMover(
opts: UseDomEditOverlayGesturesOptions,
setDraftGroupOverlayItems: (items: GroupOverlayItem[]) => void,
) {
let lastGroupPositions: Record<string, string> = {};
let lastGesture: GroupGestureState | null = null;
/** Snap the group's delta to nearby edges, publishing the guides drawn for it. */
// fallow-ignore-next-line complexity
const snapGroupDelta = (
groupG: GroupGestureState,
e: React.PointerEvent<HTMLDivElement>,
proposed: { dx: number; dy: number },
) => {
const sc = groupG.snapContext;
if (!sc?.snapEnabled || sc.targets.length === 0) return proposed;
if (!snapEngagedForTravel(proposed.dx, proposed.dy)) {
opts.snapGuidesRef.current = null;
return proposed;
}
const groupBounds = resolveDomEditGroupOverlayRect(groupG.originItems.map((i) => i.rect));
if (!groupBounds) return proposed;
const allTargets = sc.compositionTarget ? [...sc.targets, sc.compositionTarget] : sc.targets;
const snap = resolveSnapAdjustment({
movingRect: groupBounds,
proposedDx: proposed.dx,
proposedDy: proposed.dy,
targets: allTargets,
gridEdges: sc.gridEdges ?? undefined,
threshold: SNAP_THRESHOLD_PX,
disabled: e.altKey,
});
const movingRect = {
...groupBounds,
left: groupBounds.left + snap.dx,
top: groupBounds.top + snap.dy,
};
const spacingGuides = e.altKey
? []
: resolveEquidistanceGuides({
movingRect,
targets: allTargets,
threshold: SNAP_THRESHOLD_PX,
});
opts.snapGuidesRef.current = { guides: snap.guides, spacingGuides };
return { dx: snap.dx, dy: snap.dy };
};
/** One frame of a group drag: snap the delta, redraw the boxes, move every member. */
const moveGroupDrag = (groupG: GroupGestureState, e: React.PointerEvent<HTMLDivElement>) => {
if (groupG !== lastGesture) {
lastGesture = groupG;
lastGroupPositions = {};
}
const { dx, dy } = snapGroupDelta(groupG, e, {
dx: e.clientX - groupG.startX,
dy: e.clientY - groupG.startY,
});
groupG.lastSnappedDx = dx;
groupG.lastSnappedDy = dy;
setDraftGroupOverlayItems(
groupG.originItems.map((i) => ({
...i,
rect: { ...i.rect, left: i.rect.left + dx, top: i.rect.top + dy },
})),
);
const offsets: Record<string, string> = {};
for (const m of groupG.members) {
const n = applyManualOffsetDragDraft(m, dx, dy);
offsets[m.key] = `${Math.round(n.x)},${Math.round(n.y)}`;
}
const at = readDragPositions(groupG.members);
const px = Math.round(e.clientX - groupG.startX);
const py = Math.round(e.clientY - groupG.startY);
// A member breaking away IS the fault, so it reports on the frame it happens;
// the throttled line below would step over it. A gap between pointer and
// applied there is snapping pulling the group off the cursor.
const trace = { pointer: `${px},${py}`, applied: `${Math.round(dx)},${Math.round(dy)}`, at };
const drift = findNonRigidMembers(lastGroupPositions, at);
if (drift.length > 0) logDrag("drift", { ...trace, drift });
lastGroupPositions = at;
logDragMove({ ...trace, offsets });
};
return moveGroupDrag;
}
@@ -0,0 +1,70 @@
// @vitest-environment happy-dom
import { describe, expect, it, vi } from "vitest";
import { createDomEditOverlayGestureHandlers } from "./useDomEditOverlayGestures";
import type { GroupGestureState } from "./domEditOverlayGestures";
/**
* A group drag ended by deselecting the group it had just moved.
*
* Every pointerup trails a click. The gesture ref is cleared before the commit,
* so by the time that click arrives the box no longer looks busy and it reaches
* the canvas as an ordinary click landing in the gap between the members,
* resolving to nothing, and clearing the selection. Captured live as a
* `[hf-select] clear` with `hadGroup: 3` two milliseconds after the drop.
*
* The under-threshold path already ate that click; the committed path has to as
* well, and the flag is set before the two diverge so neither can forget.
*/
describe("dropping a dragged group eats the click that follows", () => {
function harness(travel: { dx: number; dy: number }) {
const suppressNextBoxClickRef = { current: false };
const groupGestureRef = {
current: {
startX: 0,
startY: 0,
originItems: [],
members: [],
} as unknown as GroupGestureState,
};
const handlers = createDomEditOverlayGestureHandlers({
overlayRef: { current: null },
iframeRef: { current: null },
boxRef: { current: null },
selectionRef: { current: null },
hoverSelectionRef: { current: null },
overlayRectRef: { current: null },
groupOverlayItemsRef: { current: [] },
gestureRef: { current: null },
groupGestureRef,
blockedMoveRef: { current: null },
rafPausedRef: { current: false },
suppressNextBoxClickRef,
setOverlayRect: vi.fn(),
setGroupOverlayItems: vi.fn(),
onBlockedMoveRef: { current: vi.fn() },
onManualDragStartRef: { current: vi.fn() },
onPathOffsetCommitRef: { current: vi.fn() },
onGroupPathOffsetCommitRef: { current: vi.fn() },
onBoxSizeCommitRef: { current: vi.fn() },
onRotationCommitRef: { current: vi.fn() },
onCanvasPointerMoveRef: { current: vi.fn() },
onCanvasMouseDown: vi.fn(),
snapGuidesRef: { current: null },
} as never);
handlers.onPointerUp({
clientX: travel.dx,
clientY: travel.dy,
currentTarget: { releasePointerCapture: vi.fn() },
} as never);
return suppressNextBoxClickRef;
}
it("eats the click after a drag that moved", () => {
expect(harness({ dx: 120, dy: 60 }).current).toBe(true);
});
it("still eats it after a press that never travelled", () => {
expect(harness({ dx: 1, dy: 0 }).current).toBe(true);
});
});
@@ -221,6 +221,7 @@ function isIdentityAfterTranslateStrip(m: DOMMatrix): boolean {
return m.is2D && m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1;
}
// fallow-ignore-next-line complexity
function stripGsapTranslateFromTransform(element: HTMLElement): void {
if (element.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR)) return;
const transform = element.style.getPropertyValue("transform");
@@ -256,6 +257,7 @@ function stripGsapTranslateFromTransform(element: HTMLElement): void {
// and push the offset straight into GSAP's x/y via gsap.set; the var() offset is
// still persisted (buildPathOffsetPatches), and GSAP re-reads it at init on
// reload. Returns true when handled as GSAP (caller must skip the CSS path).
// fallow-ignore-next-line complexity
function applyStudioPathOffsetViaGsap(
element: HTMLElement,
offset: { x: number; y: number },
@@ -553,26 +555,26 @@ function queryStudioElements(doc: Document, attr: string): HTMLElement[] {
function reapplyPathOffsets(doc: Document): void {
for (const el of queryStudioElements(doc, STUDIO_PATH_OFFSET_ATTR)) {
const gsapSkip = gsapAnimatesProperty(el, "x", "y");
// Unlike size below, the offset channels COMPOSE — applying both doubles the move.
if (gsapAnimatesProperty(el, "x", "y")) continue;
const x = el.style.getPropertyValue(STUDIO_OFFSET_X_PROP);
const y = el.style.getPropertyValue(STUDIO_OFFSET_Y_PROP);
if (gsapSkip) continue;
if (x || y) {
applyStudioPathOffset(
el,
{
x: Number.parseFloat(x) || 0,
y: Number.parseFloat(y) || 0,
},
{ updateBase: false },
);
}
if (!x && !y) continue;
const offset = { x: Number.parseFloat(x) || 0, y: Number.parseFloat(y) || 0 };
applyStudioPathOffset(el, offset, { updateBase: false });
}
}
/**
* Put the studio's committed size back after a seek, GSAP-sized elements included.
* Size does not compose the way the offset above does: both channels write width
* and height, so the later write wins on the same number. Standing aside meant
* nothing held the size while a soft reload reverted the old timeline (GSAP hands
* back each tween's recorded starting width), so the element sat at its stylesheet
* size until the new one rendered the jump after a resize.
*/
function reapplyBoxSizes(doc: Document): void {
for (const el of queryStudioElements(doc, STUDIO_BOX_SIZE_ATTR)) {
if (gsapAnimatesProperty(el, "width", "height")) continue;
const w = Number.parseFloat(el.style.getPropertyValue(STUDIO_WIDTH_PROP));
const h = Number.parseFloat(el.style.getPropertyValue(STUDIO_HEIGHT_PROP));
if (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {
@@ -88,6 +88,41 @@ describe("measureManualOffsetDragScreenToOffsetMatrix", () => {
expect(element.style.getPropertyValue("translate")).toBe("");
});
/**
* The element that has never been offset is the common case, and it used to skip
* the measurement and assume the canvas zoom was the whole story. Any transform
* above the element makes that assumption wrong: the mirrored parent here sends a
* rightward drag left, so the overlay followed the pointer while the element went
* the other way, and only on drop did the overlay jump to where the element really
* was. The fixture mirrors x and scales both axes by 1.2, as a `rotationY: 180`
* card at `scale: 1.2` does.
*/
it("measures a mirrored parent even when the element carries no offset yet", () => {
const window = new Window();
const element = window.document.createElement("div");
window.document.body.append(element);
element.getBoundingClientRect = () => {
const offsetX = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_X_PROP)) || 0;
const offsetY = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)) || 0;
return new window.DOMRect(100 - 1.2 * offsetX, 200 + 1.2 * offsetY, 40, 20);
};
const measured = measureManualOffsetDragScreenToOffsetMatrix(element, { x: 0, y: 0 });
if (!measured.ok) throw new Error(measured.reason);
// Dragging one screen px right must move the element one screen px right, which
// on a mirrored parent means writing a NEGATIVE offset.
const offset = resolveManualOffsetForPointerDelta({
initialOffset: { x: 0, y: 0 },
screenToOffset: measured.matrix,
dx: 60,
dy: 60,
});
expect(offset.x).toBeCloseTo(-50, 6);
expect(offset.y).toBeCloseTo(50, 6);
});
it("measures movement in parent viewport pixels when the element is inside a scaled iframe", () => {
const window = new Window();
const iframe = window.document.createElement("iframe");
@@ -133,7 +168,12 @@ describe("measureManualOffsetDragScreenToOffsetMatrix", () => {
expect(nextOffset).toEqual({ x: 100, y: 50 });
});
it("returns identity matrix for non-path-offset elements with zero initial offset", () => {
// Carrying no path offset used to be taken as permission to assume the response
// instead of measuring it. It is not a signal about the transforms above the
// element, so it no longer changes the answer: an element that does not move is
// unmeasurable either way, and the caller falls back rather than being handed a
// matrix that was never checked.
it("does not treat a missing path offset as a measurable response", () => {
const window = new Window();
const element = window.document.createElement("div");
window.document.body.append(element);
@@ -141,10 +181,7 @@ describe("measureManualOffsetDragScreenToOffsetMatrix", () => {
const measured = measureManualOffsetDragScreenToOffsetMatrix(element, { x: 0, y: 0 });
expect(measured.ok).toBe(true);
if (measured.ok) {
expectMatrixClose(measured.matrix, { a: 1, b: 0, c: 0, d: 1 });
}
expect(measured.ok).toBe(false);
});
it("rejects path-offset elements whose movement response cannot be measured", () => {
@@ -160,6 +197,56 @@ describe("measureManualOffsetDragScreenToOffsetMatrix", () => {
});
});
/**
* A group drag is rigid: every member is handed the SAME pointer delta and must
* travel the same distance on screen, or the group visibly comes apart mid-drag.
* Members do not share a mapping though each measures its own, because each can
* sit under different ancestor transforms. A member whose movement cannot be
* measured falls back to a guess, and this pins what that guess costs the group.
*/
describe("group drag stays rigid", () => {
function member(key: string, response: number, measurable: boolean) {
const window = new Window();
const element = window.document.createElement("div");
window.document.body.append(element);
element.getBoundingClientRect = () => {
const ox = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_X_PROP)) || 0;
const oy = Number.parseFloat(element.style.getPropertyValue(STUDIO_OFFSET_Y_PROP)) || 0;
const move = measurable ? response : 0;
return new window.DOMRect(100 + move * ox, 200 + move * oy, 40, 20);
};
const result = createManualOffsetDragMember({
key,
selection: { element } as never,
element,
rect: { left: 100, top: 200, width: 40, height: 20, editScaleX: 1, editScaleY: 1 },
});
if (!result.ok) throw new Error(result.reason);
return { member: result.member, response };
}
/** Screen distance this member travels for a pointer delta of `d`. */
function screenTravel(entry: ReturnType<typeof member>, d: number): number {
const offset = resolveManualOffsetForPointerDelta({
initialOffset: entry.member.initialOffset,
screenToOffset: entry.member.screenToOffset,
dx: d,
dy: 0,
});
return offset.x * entry.response;
}
it("moves every measurable member the same distance for one pointer delta", () => {
// Two members under different ancestor scales: one 1:1, one inside a half-scale
// parent. Different offsets, identical screen travel — that is what rigid means.
const a = member("a", 1, true);
const b = member("b", 0.5, true);
expect(screenTravel(a, 60)).toBeCloseTo(60, 6);
expect(screenTravel(b, 60)).toBeCloseTo(60, 6);
});
});
describe("createManualOffsetDragMember uses raw CSS var offset", () => {
it("ignores GSAP transform — initialOffset comes from CSS vars only", () => {
const window = new Window();
@@ -213,9 +213,9 @@ export function applyManualOffsetDragMatrix(matrix: ManualOffsetDragMatrix, poin
* The perspective w-divisor (matrix3d m44) of the element's current transform.
* For a plain `translateZ(z)` under `perspective(p)`, m44 = (p - z) / p, so the
* element renders 1/m44× larger and a translate of `d` composition px moves
* `d / m44` px on screen. Returns 1 for 2D transforms (no foreshortening). Used
* to keep the drag offset screen-movement mapping correct for depth elements,
* which the flat-scale fast path below would otherwise get wrong by 1/m44.
* `d / m44` px on screen. Returns 1 for 2D transforms (no foreshortening). Only
* the unmeasurable-element fallback needs this the measured path reads the
* foreshortening off the element's real movement along with everything else.
*/
function readTransformWDivisor(element: HTMLElement): number {
const t = element.ownerDocument.defaultView?.getComputedStyle(element).transform;
@@ -225,25 +225,25 @@ function readTransformWDivisor(element: HTMLElement): number {
return Number.isFinite(w) && w > 0 ? w : 1;
}
/**
* How far the element actually moves on screen per unit of drag offset, measured
* rather than assumed.
*
* The offset is written on the element, but what reaches the screen is that offset
* put through every transform above it. A parent carrying a rotation, a mirror, a
* scale or a perspective changes both the direction and the distance a card at
* `rotationY: 180` sends a rightward drag left. Guessing this from the canvas zoom
* alone was wrong for every such element: the overlay tracked the pointer while the
* element went somewhere else, and the overlay only jumped to the truth on drop,
* when it re-measured. Moving the element and watching where it lands costs three
* layout reads once per gesture and is right for any transform, including ones no
* closed-form fast path would cover.
*/
export function measureManualOffsetDragScreenToOffsetMatrix(
element: HTMLElement,
initialOffset: { x: number; y: number },
options: { probeSize?: number; scaleX?: number; scaleY?: number } = {},
): { ok: true; matrix: ManualOffsetDragMatrix } | { ok: false; reason: string } {
if (
!element.hasAttribute("data-hf-studio-path-offset") &&
initialOffset.x === 0 &&
initialOffset.y === 0
) {
const sx = options.scaleX || 1;
const sy = options.scaleY || 1;
// Fold in the perspective foreshortening: a depth element (z≠0) moves
// 1/m44× faster on screen than its flat scale implies, so the screen→offset
// matrix must scale by m44 or the element outruns the pointer/overlay.
const w = readTransformWDivisor(element);
return { ok: true, matrix: { a: w / sx, b: 0, c: 0, d: w / sy } };
}
const probeSize = options.probeSize ?? DEFAULT_OFFSET_PROBE_PX;
if (!Number.isFinite(probeSize) || probeSize <= 0) {
return { ok: false, reason: "Invalid movement probe size." };
@@ -325,6 +325,8 @@ export function resolveManualOffsetForPointerDelta(input: {
};
}
// Pre-existing complexity — surfaced by this branch touching the file, not by new logic.
// fallow-ignore-next-line complexity
export function createManualOffsetDragMember(input: {
key: string;
selection: DomEditSelection;
@@ -515,6 +517,7 @@ function restoreManualOffsetDragMember(member: ManualOffsetDragMember): void {
endStudioManualEditGesture(member.element, member.gestureToken);
}
/** Roll back a FAILED drag to the exact gesture-start state. */
export function restoreManualOffsetDragMembers(members: ManualOffsetDragMember[]): void {
for (const member of members) {
restoreManualOffsetDragMember(member);
@@ -522,6 +525,7 @@ export function restoreManualOffsetDragMembers(members: ManualOffsetDragMember[]
}
}
/** Teardown after a COMMITTED drag. */
export function endManualOffsetDragMembers(members: ManualOffsetDragMember[]): void {
for (const member of members) {
endStudioManualEditGesture(member.element, member.gestureToken);
@@ -550,6 +554,7 @@ export function endManualOffsetDragMembers(members: ManualOffsetDragMember[]): v
}
}
/** Shared timeline teardown for either the committed or restored path. */
export function resumeGsapTimelines(element: HTMLElement): void {
const ids = element.getAttribute("data-hf-drag-paused-timelines");
element.removeAttribute("data-hf-drag-paused-timelines");
@@ -0,0 +1,64 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from "vitest";
import { reapplyPositionEditsAfterSeek } from "./manualEditsDom";
import { STUDIO_BOX_SIZE_ATTR, STUDIO_HEIGHT_PROP, STUDIO_WIDTH_PROP } from "./manualEditsTypes";
/**
* A resize commit hands the size to a GSAP tween, and a soft reload reverts the
* old timeline before the new one renders GSAP restores each tween's recorded
* starting width on the way out. Nothing else held the size across that window,
* so the element sat at its stylesheet size for a few hundred milliseconds: the
* jump after a resize. Worse, the next gesture then started from a box that
* disagreed with the studio's own vars and snapped on its first move.
*
* The seek reapply is what closes the window, and it used to stand aside for
* exactly the elements that need it the ones GSAP sizes.
*/
describe("box size survives a seek while GSAP owns the size", () => {
afterEach(() => {
document.body.innerHTML = "";
Reflect.deleteProperty(window, "__timelines");
});
function cardSizedByGsap(): HTMLElement {
const el = document.createElement("div");
el.id = "card";
el.setAttribute(STUDIO_BOX_SIZE_ATTR, "true");
el.style.setProperty(STUDIO_WIDTH_PROP, "305px");
el.style.setProperty(STUDIO_HEIGHT_PROP, "202px");
document.body.append(el);
// A timeline that animates this element's width/height, as the committed
// resize leaves behind.
Object.assign(window, {
__timelines: {
main: {
getChildren: () => [{ targets: () => [el], vars: { width: 305, height: 202 } }],
},
},
});
return el;
}
it("re-applies the committed size after the timeline gave it back", () => {
const el = cardSizedByGsap();
// The revert: GSAP puts the tween's recorded starting size back.
el.style.width = "395px";
el.style.height = "261px";
reapplyPositionEditsAfterSeek(document);
expect(el.style.width).toBe("305px");
expect(el.style.height).toBe("202px");
});
it("leaves an element alone once its studio size is cleared", () => {
const el = cardSizedByGsap();
el.style.removeProperty(STUDIO_WIDTH_PROP);
el.style.removeProperty(STUDIO_HEIGHT_PROP);
el.style.width = "395px";
reapplyPositionEditsAfterSeek(document);
expect(el.style.width).toBe("395px");
});
});
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import {
resolveSnapAdjustment,
snapEngagedForTravel,
SNAP_THRESHOLD_PX,
type SnapTarget,
} from "./snapEngine";
/**
* Picking a selection up used to move it. An element resting within the snap
* threshold of a guide is already snappable, so the snap computed on the first
* frame of a drag displaced it by up to the threshold while the pointer had not
* moved at all captured live as `pointer "0,0"` against `applied "4,-3"`, with
* every member of the group jumping 12,-8 composition px before the drag had
* started. Snapping pulls toward a guide as you drag; it has nothing to say about
* a gesture that has not moved.
*/
describe("snapping waits for the drag to travel", () => {
// Moving box's right edge is at 150; the target's left edge is at 154, so the
// pair is 4px apart — inside the threshold, and snappable the moment it is asked.
const movingRect = { left: 100, top: 50, width: 50, height: 40 };
const target: SnapTarget = {
left: 154,
top: 50,
right: 254,
bottom: 90,
centerX: 204,
centerY: 70,
id: "neighbour",
};
const snapAt = (dx: number, dy: number) =>
resolveSnapAdjustment({
movingRect,
proposedDx: dx,
proposedDy: dy,
targets: [target],
threshold: SNAP_THRESHOLD_PX,
disabled: false,
disabledForTravel: !snapEngagedForTravel(dx, dy),
});
it("does not move a selection that has not been dragged yet", () => {
expect(snapAt(0, 0)).toMatchObject({ dx: 0, dy: 0 });
});
it("leaves a sub-threshold twitch alone", () => {
expect(snapAt(1, -1)).toMatchObject({ dx: 1, dy: -1 });
});
it("still snaps once the drag is a real one", () => {
expect(snapEngagedForTravel(0, 0)).toBe(false);
expect(snapEngagedForTravel(10, 0)).toBe(true);
// Without the travel gate the same delta snaps, which is the behaviour to keep.
const engaged = resolveSnapAdjustment({
movingRect,
proposedDx: 0,
proposedDy: 0,
targets: [target],
threshold: SNAP_THRESHOLD_PX,
disabled: false,
});
expect(engaged.dx).toBe(4);
});
});
@@ -3,6 +3,24 @@
// All position values are in overlay-space (screen) pixels.
export const SNAP_THRESHOLD_PX = 6;
/**
* Pointer travel a MOVE must reach before snapping is allowed to touch it.
*
* An element resting within the threshold of a guide is already "snappable", so
* a snap computed on the very first frame displaces it by up to the threshold
* while the pointer has moved nothing pick a selection up and the whole thing
* teleports before you have dragged at all. Snapping is meant to pull toward a
* guide as the user drags, so it does not participate until the drag is real.
* The value matches the distance a drag must cover to count as a drag rather
* than a click, so nothing below it moves anything.
*/
const SNAP_ENGAGE_TRAVEL_PX = 4;
/** Whether a move of this size has travelled far enough for snapping to apply. */
export function snapEngagedForTravel(dx: number, dy: number): boolean {
return Math.hypot(dx, dy) >= SNAP_ENGAGE_TRAVEL_PX;
}
const EQUIDISTANCE_TOLERANCE_PX = 1;
// ---------------------------------------------------------------------------
@@ -359,8 +377,10 @@ export function resolveSnapAdjustment(input: {
gridEdges?: { x: SnapEdge[]; y: SnapEdge[] };
threshold: number;
disabled: boolean;
/** Set when the gesture has not travelled far enough for snapping yet. */
disabledForTravel?: boolean;
}): SnapResult {
if (input.disabled || input.threshold <= 0) {
if (input.disabled || input.disabledForTravel || input.threshold <= 0) {
return DISABLED_RESULT(input.proposedDx, input.proposedDy);
}
@@ -30,7 +30,6 @@ import {
type GroupOverlayItem,
type OverlayRect,
orientedOverlayRect,
resolveDomEditGroupOverlayRect,
} from "./domEditOverlayGeometry";
import {
BLOCKED_MOVE_THRESHOLD_PX,
@@ -50,8 +49,15 @@ import {
startGroupDrag as _startGroupDrag,
} from "./domEditOverlayStartGesture";
import { hugRectForElement } from "./domEditOverlayCrop";
import { resolveSnapAdjustment, resolveEquidistanceGuides, SNAP_THRESHOLD_PX } from "./snapEngine";
import {
resolveSnapAdjustment,
resolveEquidistanceGuides,
snapEngagedForTravel,
SNAP_THRESHOLD_PX,
} from "./snapEngine";
import { logResize, logResizeMove, logResizeSettle } from "../../utils/resizeDebug";
import { logDrag, logDragSettle, readDragPositions } from "../../utils/dragDebug";
import { createGroupDragMover } from "./groupDragMove";
export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGesturesOptions) {
const setDraftOverlayRect = (next: OverlayRect) => {
@@ -91,6 +97,8 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
},
) => _startGesture(kind, e, opts, options);
const moveGroupDrag = createGroupDragMover(opts, setDraftGroupOverlayItems);
// fallow-ignore-next-line complexity
const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
const g = opts.gestureRef.current;
@@ -114,55 +122,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
}
if (groupG) {
let dx = e.clientX - groupG.startX;
let dy = e.clientY - groupG.startY;
const sc = groupG.snapContext;
if (sc?.snapEnabled && sc.targets.length > 0) {
const groupBounds = resolveDomEditGroupOverlayRect(
groupG.originItems.map((item) => item.rect),
);
if (groupBounds) {
const allTargets = sc.compositionTarget
? [...sc.targets, sc.compositionTarget]
: sc.targets;
const snap = resolveSnapAdjustment({
movingRect: groupBounds,
proposedDx: dx,
proposedDy: dy,
targets: allTargets,
gridEdges: sc.gridEdges ?? undefined,
threshold: SNAP_THRESHOLD_PX,
disabled: e.altKey,
});
dx = snap.dx;
dy = snap.dy;
const movedRect = {
left: groupBounds.left + dx,
top: groupBounds.top + dy,
width: groupBounds.width,
height: groupBounds.height,
};
const spacingGuides = e.altKey
? []
: resolveEquidistanceGuides({
movingRect: movedRect,
targets: allTargets,
threshold: SNAP_THRESHOLD_PX,
});
opts.snapGuidesRef.current = { guides: snap.guides, spacingGuides };
}
}
groupG.lastSnappedDx = dx;
groupG.lastSnappedDy = dy;
setDraftGroupOverlayItems(
groupG.originItems.map((item) => ({
...item,
rect: { ...item.rect, left: item.rect.left + dx, top: item.rect.top + dy },
})),
);
for (const member of groupG.members) applyManualOffsetDragDraft(member, dx, dy);
moveGroupDrag(groupG, e);
return;
}
@@ -215,6 +175,9 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
movingRect,
proposedDx: dx,
proposedDy: dy,
// Same reason as the group path: a snap on a drag that has not travelled
// yet moves the element while the pointer is still.
disabledForTravel: !snapEngagedForTravel(dx, dy),
targets: allTargets,
gridEdges: sc.gridEdges ?? undefined,
threshold: SNAP_THRESHOLD_PX,
@@ -319,9 +282,14 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
opts.rafPausedRef.current = false;
const rawDx = e.clientX - groupG.startX;
const rawDy = e.clientY - groupG.startY;
// The click that trails every pointerup has to be eaten either way. The
// gesture ref is already cleared above, so by the time it arrives the box
// no longer looks busy, and handleBoxClick hands it to the canvas as an
// ordinary click — which lands between the members, resolves to nothing,
// and deselects the group the drag just moved.
opts.suppressNextBoxClickRef.current = true;
if (Math.hypot(rawDx, rawDy) < BLOCKED_MOVE_THRESHOLD_PX) {
restoreGroupPathOffsets(groupG);
opts.suppressNextBoxClickRef.current = true;
return;
}
const dx = groupG.lastSnappedDx ?? rawDx;
@@ -336,6 +304,17 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
selection: member.selection,
next: applyManualOffsetDragCommit(member, dx, dy),
}));
logDrag("drop", {
pointer: `${Math.round(rawDx)},${Math.round(rawDy)}`,
applied: `${Math.round(dx)},${Math.round(dy)}`,
committed: Object.fromEntries(
updates.map((update, index) => [
groupG.members[index]?.key ?? String(index),
`${Math.round(update.next.x)},${Math.round(update.next.y)}`,
]),
),
at: readDragPositions(groupG.members),
});
void Promise.resolve(opts.onGroupPathOffsetCommitRef.current(updates))
.catch(() => {
for (const member of groupG.members) {
@@ -346,7 +325,15 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
restoreStudioPathOffset(member.element, member.initialPathOffset);
}
})
.finally(() => endManualOffsetDragMembers(groupG.members));
.finally(() => {
logDrag("committed", { at: readDragPositions(groupG.members) });
endManualOffsetDragMembers(groupG.members);
// The gesture teardown resumes the paused timelines and re-seeks the
// player, which re-renders from whatever the preview currently holds.
// If the reloaded source has not landed yet that is the OLD position,
// so this is where a snap-back would show.
logDragSettle("settle", groupG.members);
});
return;
}
@@ -17,7 +17,7 @@ import {
rectsEqual,
resolveElementForOverlay,
selectionCacheKey,
toVisibleOverlayRect,
orientedVisibleOverlayRect,
} from "./domEditOverlayGeometry";
function childRectsEqual(a: OverlayRect[], b: OverlayRect[]): boolean {
@@ -172,7 +172,9 @@ export function useDomEditOverlayRects({
for (let i = 0; i < descendants.length; i++) {
const child = descendants[i] as HTMLElement;
if (!child.getBoundingClientRect) continue;
const r = toVisibleOverlayRect(overlayEl, iframe, child);
// Oriented, not axis-aligned: a child of a rotated element drew its
// outline square around the rotated glyphs instead of on them.
const r = orientedVisibleOverlayRect(overlayEl, iframe, child);
if (r && r.width > 2 && r.height > 2) nextChildRects.push(r);
}
if (!childRectsEqual(childRectsRef.current, nextChildRects)) {