From 880f0ea4f10f5d1993c2e5e33df1cf87466f390e Mon Sep 17 00:00:00 2001 From: Nayan Date: Fri, 14 Aug 2026 13:22:55 +0530 Subject: [PATCH] feat(overlay): teach the canvas where you are looking and what paints on top MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Groundwork, and the three questions a frame list and a minimap need answered: what is on screen, how do I put something on screen, and what order do frames paint in. `visibleWorldRect` inverse-transforms the viewport box. `centerAt` centres a world point without touching scale. `projectInto` is `fitTo`'s twin with the clamp removed, and the removal is the whole point — `MIN_SCALE` would floor a minimap projection at 0.1 and the minimap would stop shrinking. On the viewport: `visibleSafeRect`, `fitToRect` and `centerOn`, with the safe-area offset pulled into `inSafe()` so `fitInSafe` and `centerOn` cannot drift apart. `frames.reorder` publishes paint order as `z-index` and never re-parents an `iframe`. Re-parenting reloads it, which would make restacking a frame throw away its state. `applyOrder()` republishes on add, remove and both restores. `onFrameReady` is a field now so `destroy()` can clear `window.__airshipOnFrameReady` — but only if it is still its own, or a second manager's handler gets torn down by the first one's teardown. The marquee fixes are the same story from the input end: three ways a press was claimed by the wrong gesture. - `pointerup` moved to capture. The inline `EditGuard` swallowed it at document capture, so the band was drawn and never landed. - A `gestureFrom` latch lets a pan decline the marquee at pointerdown, rather than both starting and one winning by accident. - `suppressNextClick()` fires at pointer*up* after any drag, so the synthesized click cannot wipe the selection the marquee just made. --- packages/overlay/src/canvas/frames.test.ts | 128 ++++++++++++++ packages/overlay/src/canvas/frames.ts | 109 ++++++++++-- packages/overlay/src/canvas/space.test.ts | 158 +++++++++++++++++ packages/overlay/src/canvas/space.ts | 76 ++++++++ packages/overlay/src/canvas/viewport.test.ts | 172 +++++++++++++++++++ packages/overlay/src/canvas/viewport.ts | 84 ++++++++- packages/overlay/src/picker-marquee.test.ts | 131 ++++++++++++++ packages/overlay/src/picker.ts | 40 ++++- 8 files changed, 879 insertions(+), 19 deletions(-) create mode 100644 packages/overlay/src/canvas/space.test.ts create mode 100644 packages/overlay/src/canvas/viewport.test.ts create mode 100644 packages/overlay/src/picker-marquee.test.ts diff --git a/packages/overlay/src/canvas/frames.test.ts b/packages/overlay/src/canvas/frames.test.ts index 198fca0..016eb30 100644 --- a/packages/overlay/src/canvas/frames.test.ts +++ b/packages/overlay/src/canvas/frames.test.ts @@ -38,6 +38,17 @@ function painted(): string[] { ); } +/** Frame ids sorted by the `z-index` they were given — see `applyOrder`. */ +function stacked(): string[] { + return Array.from(world.children) + .map((node) => ({ + id: node.getAttribute("data-frame") ?? "?", + z: Number((node as HTMLElement).style.zIndex), + })) + .sort((a, b) => a.z - b.z) + .map((entry) => entry.id); +} + function add(name: string): Frame { const frame = frames.add({ name }); if (!frame) { @@ -168,3 +179,120 @@ describe("FrameManager.restoreRemoved", () => { expect(order()).toEqual(["f1", "f2", "f3"]); }); }); + +/* + * `reorder` — the frame list's drag-to-restack. + * + * The DOM assertions here are the interesting ones and they are deliberately + * *negative*: reorder must leave the document untouched. Moving an `iframe` + * between parents (or between siblings) tears down its browsing context and + * reloads it, so the obvious implementation — splice the array, then + * `.before()` the element the way `restoreRemoved` does — would reboot the app + * inside any frame you dragged, losing its route and scroll position. Paint + * order is published as `z-index` instead, which is what `stacked()` reads. + */ +describe("FrameManager.destroy", () => { + it("takes its global down with it", () => { + // The hook is a closure over the manager, hung off `window` by the + // constructor. Left behind, it keeps a destroyed manager and every frame it + // ever built reachable — and points the next frame that loads at an array + // that has just been emptied. + const host = window as unknown as { __airshipOnFrameReady?: unknown }; + add("one"); + expect(typeof host.__airshipOnFrameReady).toBe("function"); + + frames.destroy(); + expect(host.__airshipOnFrameReady).toBeUndefined(); + }); + + it("leaves a newer manager's hook alone", () => { + // Construction order is the trap: a second manager has already overwritten + // the global, so a late `destroy` on the first must not take the live one + // down with it. + const host = window as unknown as { __airshipOnFrameReady?: unknown }; + const older = frames; + const newer = manager(); + const live = host.__airshipOnFrameReady; + + older.destroy(); + expect(host.__airshipOnFrameReady).toBe(live); + + frames = newer; + }); +}); + +describe("FrameManager.reorder", () => { + it("moves the frame in the array and restacks without touching the DOM", () => { + add("one"); + add("two"); + add("three"); + + frames.reorder("f3", 0); + + expect(order()).toEqual(["f3", "f1", "f2"]); + // The bug this exists to prevent: no element moved, so no iframe reloaded. + expect(painted()).toEqual(["f1", "f2", "f3"]); + // …and paint order still agrees with the array, via z-index. + expect(stacked()).toEqual(["f3", "f1", "f2"]); + }); + + it("moves a frame later in the list", () => { + add("one"); + add("two"); + add("three"); + + frames.reorder("f1", 2); + + expect(order()).toEqual(["f2", "f3", "f1"]); + expect(stacked()).toEqual(["f2", "f3", "f1"]); + }); + + it("clamps an overshooting drag to the ends of the list", () => { + add("one"); + add("two"); + add("three"); + + frames.reorder("f1", 99); + expect(order()).toEqual(["f2", "f3", "f1"]); + + frames.reorder("f1", -4); + expect(order()).toEqual(["f1", "f2", "f3"]); + }); + + it("does nothing for an unknown id or a move to the same slot", () => { + add("one"); + add("two"); + let changes = 0; + // `onChanged` is what re-renders the canvas and persists the layout; a + // no-op reorder that still fired it would save on every settled drag. + frames = new FrameManager({ + onChanged: () => { + changes += 1; + }, + pathname: "/", + storageKey: "__airship-test:frames", + world, + }); + add("a"); + add("b"); + changes = 0; + + frames.reorder("nope", 0); + frames.reorder(frames.all[0].id, 0); + + expect(changes).toBe(0); + expect(order()).toEqual(["f1", "f2"]); + }); + + it("keeps z-index in step as frames come and go", () => { + add("one"); + add("two"); + add("three"); + const removed = frames.remove("f2"); + + expect(stacked()).toEqual(["f1", "f3"]); + + expect(removed && frames.restoreRemoved(removed)).toBe(true); + expect(stacked()).toEqual(["f1", "f2", "f3"]); + }); +}); diff --git a/packages/overlay/src/canvas/frames.ts b/packages/overlay/src/canvas/frames.ts index 84b9eb2..810208e 100644 --- a/packages/overlay/src/canvas/frames.ts +++ b/packages/overlay/src/canvas/frames.ts @@ -322,27 +322,36 @@ export class FrameManager { private readonly deps: FrameManagerDeps; + /** + * The `window.__airshipOnFrameReady` hook, held rather than written inline. + * + * Frames push their agent here rather than being polled. A frame's realm is + * rebuilt on every HMR full reload, so any handle the shell cached would go + * stale with no event to tell it — pushing makes re-registration automatic. + * + * Which frame is asking is settled by comparing the agent's own `window` + * against each iframe's `contentWindow`: object identity, which survives + * reloads and cannot be confused by a stale or missing name. + * + * A field so `destroy` has something to compare against before clearing the + * global — see there. + */ + private readonly onFrameReady = (agent: FrameAgent): void => { + const frame = this.frames.find((f) => f.win === agent.window); + if (!frame) { + return; + } + frame.agent = agent; + this.deps.onFrameReady?.(frame); + }; + constructor(deps: FrameManagerDeps) { this.deps = deps; - // Frames push their agent here rather than being polled. A frame's realm is - // rebuilt on every HMR full reload, so any handle the shell cached would go - // stale with no event to tell it — pushing makes re-registration automatic. - // - // Which frame is asking is settled by comparing the agent's own `window` - // against each iframe's `contentWindow`: object identity, which survives - // reloads and cannot be confused by a stale or missing name. ( window as unknown as { __airshipOnFrameReady?: (agent: FrameAgent) => void; } - ).__airshipOnFrameReady = (agent) => { - const frame = this.frames.find((f) => f.win === agent.window); - if (!frame) { - return; - } - frame.agent = agent; - this.deps.onFrameReady?.(frame); - }; + ).__airshipOnFrameReady = this.onFrameReady; } get all(): readonly Frame[] { @@ -449,6 +458,7 @@ export class FrameManager { y: at.y, }); this.frames.push(frame); + this.applyOrder(); // A newly added frame is not auto-selected: selection is something the user // does, and the highlight only means anything if it stays that way. this.deps.onChanged?.(); @@ -485,6 +495,7 @@ export class FrameManager { if (this.textFrameId === id) { this.textFrameId = null; } + this.applyOrder(); this.deps.onChanged?.(); return removed; } @@ -517,6 +528,7 @@ export class FrameManager { // restored frame that overlaps a neighbour is selected where it is not // visible. this.frames[at + 1]?.el.before(frame.el); + this.applyOrder(); if (removed.wasActive) { // The field, not `setActive`: the single `onChanged` below already covers // both the new frame and the new selection in one render. @@ -545,6 +557,36 @@ export class FrameManager { }); } + /** + * Move a frame to a new position in paint order. + * + * Deliberately array-only: the DOM is left exactly as it is, and `applyOrder` + * republishes the new order as `z-index` instead. Re-parenting is not an + * option here the way it is in `restoreRemoved` — moving an `iframe` in the + * document tears down and rebuilds its browsing context, so a frame you + * merely dragged up a list would reload the app inside it and lose its route, + * its scroll position and whatever state you had built up. `restoreRemoved` + * can afford `.before()` because the frame it is placing was just built and + * has nothing to lose. + * + * `index` is clamped rather than rejected: a drag that overshoots the end of + * the list means "last", which is what the gesture looked like. + */ + reorder(id: string, index: number): void { + const from = this.frames.findIndex((f) => f.id === id); + if (from === -1) { + return; + } + const to = Math.max(0, Math.min(Math.round(index), this.frames.length - 1)); + if (to === from) { + return; + } + const [frame] = this.frames.splice(from, 1); + this.frames.splice(to, 0, frame); + this.applyOrder(); + this.deps.onChanged?.(); + } + move(id: string, x: number, y: number): void { const frame = this.byId(id); if (!frame) { @@ -801,6 +843,7 @@ export class FrameManager { }); this.frames.push(frame); } + this.applyOrder(); return true; } @@ -809,6 +852,19 @@ export class FrameManager { frame.el.remove(); } this.frames.length = 0; + // The global goes too. It is a closure over `this`, hung off `window` by + // the constructor, so leaving it behind keeps a destroyed manager — and + // every frame it ever built — reachable, and points the next frame that + // loads at a manager whose array has just been emptied. Only the *own* + // hook is cleared: a second manager constructed in the meantime has already + // overwritten it, and dropping that one would leave the live canvas unable + // to hear its frames. + const host = window as unknown as { + __airshipOnFrameReady?: (agent: FrameAgent) => void; + }; + if (host.__airshipOnFrameReady === this.onFrameReady) { + host.__airshipOnFrameReady = undefined; + } } // -- Internals ------------------------------------------------------------- @@ -889,6 +945,29 @@ export class FrameManager { return frame; } + /** + * Republish paint order as `z-index`, so the array is the single authority on + * what paints over what. + * + * Frames were absolutely positioned with no `z-index`, which left the DOM + * with the last word while `frameAt` read the array — an agreement every + * mutation had to maintain by hand (see the note in `restoreRemoved`). That + * held only because every path happened to touch both in step, and it made + * reordering impossible to do cheaply: the one operation whose entire purpose + * is changing paint order was also the one that could not move an `iframe` + * without reloading it. + * + * Writing the index makes it explicit and costs nothing — every path already + * kept the two in the same order, so this changes no existing behaviour. The + * world element carries a transform and is therefore a stacking context, so + * these small integers are contained by it and cannot reach the chrome above. + */ + private applyOrder(): void { + for (const [i, frame] of this.frames.entries()) { + frame.el.style.zIndex = String(i); + } + } + private applyBox(frame: Frame): void { Object.assign(frame.el.style, { height: `${frame.height}px`, diff --git a/packages/overlay/src/canvas/space.test.ts b/packages/overlay/src/canvas/space.test.ts new file mode 100644 index 0000000..8bb8ccd --- /dev/null +++ b/packages/overlay/src/canvas/space.test.ts @@ -0,0 +1,158 @@ +/** + * The coordinate module had no test at all, which is a strange gap for the one + * file the overlay allows to do arithmetic — every outline, handle and drop + * indicator on the canvas is placed by something in here. + * + * The cases below are the ones the minimap forced into the open. `projectInto` + * exists because reaching for `fitTo` instead is a real, silent bug: `fitTo` + * clamps to `MIN_SCALE`, so projecting a wide canvas into a small card returned + * 0.1 and drew frames several times wider than the card holding them, with no + * error anywhere. `visibleWorldRect` is asserted against `worldToScreen` rather + * than against hand-computed numbers, because the property that matters is that + * the two are inverses — a version that agreed with neither the transform nor + * itself would still pass a literal-value test written from the same wrong + * algebra. + */ + +import { describe, expect, it } from "vitest"; +import { + centerAt, + fitTo, + MIN_SCALE, + projectInto, + type Rect, + screenToWorld, + type Viewport, + visibleWorldRect, + worldToScreen, +} from "./space"; + +const ORIGIN: Rect = { height: 800, left: 0, top: 0, width: 1200 }; + +/** A canvas viewport element that does not sit at the window's top-left. */ +const OFFSET: Rect = { height: 800, left: 40, top: 24, width: 1200 }; + +describe("visibleWorldRect", () => { + it("is the inverse of worldToScreen at the viewport's corners", () => { + const vp: Viewport = { scale: 0.35, x: -220, y: 140 }; + const world = visibleWorldRect(vp, OFFSET); + + const topLeft = worldToScreen(vp, OFFSET, { + x: world.left, + y: world.top, + }); + const bottomRight = worldToScreen(vp, OFFSET, { + x: world.left + world.width, + y: world.top + world.height, + }); + + expect(topLeft.x).toBeCloseTo(OFFSET.left, 6); + expect(topLeft.y).toBeCloseTo(OFFSET.top, 6); + expect(bottomRight.x).toBeCloseTo(OFFSET.left + OFFSET.width, 6); + expect(bottomRight.y).toBeCloseTo(OFFSET.top + OFFSET.height, 6); + }); + + it("widens as the zoom goes out", () => { + const near = visibleWorldRect({ scale: 1, x: 0, y: 0 }, ORIGIN); + const far = visibleWorldRect({ scale: 0.25, x: 0, y: 0 }, ORIGIN); + + expect(near.width).toBe(1200); + // A quarter of the zoom shows four times the world. + expect(far.width).toBe(4800); + expect(far.height).toBe(3200); + }); + + it("tracks the pan, in world units", () => { + // Panning the world 300 screen px left at 0.5× moved us 600 world units right. + const vp: Viewport = { scale: 0.5, x: -300, y: -150 }; + const world = visibleWorldRect(vp, ORIGIN); + + expect(world.left).toBe(600); + expect(world.top).toBe(300); + }); +}); + +describe("centerAt", () => { + it("puts the point at the middle of the box", () => { + const vp = centerAt({ x: 900, y: 400 }, ORIGIN, 0.5); + const screen = worldToScreen(vp, ORIGIN, { x: 900, y: 400 }); + + expect(screen.x).toBeCloseTo(ORIGIN.width / 2, 6); + expect(screen.y).toBeCloseTo(ORIGIN.height / 2, 6); + }); + + it("leaves the scale exactly as given", () => { + // The whole point of centre-vs-fit: going somewhere must not change how + // close you are standing. + expect(centerAt({ x: 10, y: 10 }, ORIGIN, 2.5).scale).toBe(2.5); + expect(centerAt({ x: 10, y: 10 }, ORIGIN, 0.13).scale).toBe(0.13); + }); +}); + +describe("projectInto", () => { + const CARD = { height: 132, width: 200 }; + + it("goes below MIN_SCALE, which is why it is not fitTo", () => { + const wide: Rect = { height: 2000, left: 0, top: 0, width: 6000 }; + + const projected = projectInto(wide, CARD, 8); + const fitted = fitTo(wide, CARD, 8); + + expect(projected.scale).toBeLessThan(MIN_SCALE); + // The bug: fitTo floors at 0.1, so the frames would be drawn 6000 * 0.1 = + // 600px wide inside a 200px card. + expect(fitted.scale).toBe(MIN_SCALE); + }); + + it("lands the bounds inside the padded box, centred", () => { + const bounds: Rect = { height: 900, left: -400, top: -200, width: 1800 }; + const pad = 8; + const map = projectInto(bounds, CARD, pad); + + const topLeft = worldToScreen( + map, + { height: CARD.height, left: 0, top: 0, width: CARD.width }, + { x: bounds.left, y: bounds.top } + ); + const size = { + height: bounds.height * map.scale, + width: bounds.width * map.scale, + }; + + expect(topLeft.x).toBeGreaterThanOrEqual(pad - 0.001); + expect(topLeft.y).toBeGreaterThanOrEqual(pad - 0.001); + expect(topLeft.x + size.width).toBeLessThanOrEqual( + CARD.width - pad + 0.001 + ); + expect(topLeft.y + size.height).toBeLessThanOrEqual( + CARD.height - pad + 0.001 + ); + // Centred on the axis that is not the limiting one. + expect(topLeft.x - pad).toBeCloseTo( + CARD.width - pad - topLeft.x - size.width, + 6 + ); + }); + + it("round-trips a press back to the world point under it", () => { + // What a click on the minimap does: local px in, world coordinates out. + const bounds: Rect = { height: 900, left: -400, top: -200, width: 1800 }; + const box = { height: CARD.height, left: 0, top: 0, width: CARD.width }; + const map = projectInto(bounds, CARD, 8); + + const point = { x: 137, y: 44 }; + const world = screenToWorld(map, box, point); + const back = worldToScreen(map, box, world); + + expect(back.x).toBeCloseTo(point.x, 6); + expect(back.y).toBeCloseTo(point.y, 6); + }); + + it("refuses a degenerate box rather than returning a nonsense scale", () => { + const empty: Rect = { height: 0, left: 0, top: 0, width: 0 }; + expect(projectInto(empty, CARD, 8).scale).toBe(1); + // A card smaller than twice its own padding — the collapsed-panel case. + const bounds: Rect = { height: 100, left: 0, top: 0, width: 100 }; + expect(projectInto(bounds, { height: 10, width: 10 }, 8).scale).toBe(1); + }); +}); diff --git a/packages/overlay/src/canvas/space.ts b/packages/overlay/src/canvas/space.ts index 9feb4d4..82876df 100644 --- a/packages/overlay/src/canvas/space.ts +++ b/packages/overlay/src/canvas/space.ts @@ -191,6 +191,27 @@ export function clipTo(box: Rect, bounds: Rect): string { return `inset(${snap(top)}px ${snap(right)}px ${snap(bottom)}px ${snap(left)}px)`; } +/** + * The world-space box `viewportRect` is currently showing. + * + * The inverse of the world→screen transform applied to the viewport's own + * corners, which is why it is four divisions and not a matrix: screen `left` + * maps to world `-x/scale`, and a viewport `width` screen px wide spans + * `width/scale` world units at any zoom. + * + * Needed by anything that has to reason about *where you are looking* rather + * than where one node is — the minimap's indicator, and the bounds it has to + * cover so that indicator cannot leave the map. + */ +export function visibleWorldRect(vp: Viewport, viewportRect: Rect): Rect { + return { + height: viewportRect.height / vp.scale, + left: -vp.x / vp.scale, + top: -vp.y / vp.scale, + width: viewportRect.width / vp.scale, + }; +} + // -- zoom -------------------------------------------------------------------- /** @@ -243,6 +264,61 @@ export function fitTo( }; } +/** + * The viewport that puts world `point` at the centre of `size`, at the scale + * given. + * + * Same contract as `fitTo` — it centres within a box whose origin is `(0, 0)`, + * so a caller aiming at anything other than the whole viewport shifts the + * result by that box's offset. Deliberately does *not* touch the scale: this is + * "take me there", not "take me there and decide how close I stand", which is + * what keeps a jump from the minimap or the frame list from throwing away the + * zoom level you were working at. + */ +export function centerAt( + point: Point, + size: { height: number; width: number }, + scale: number +): Viewport { + return { + scale, + x: size.width / 2 - point.x * scale, + y: size.height / 2 - point.y * scale, + }; +} + +/** + * Project a world box into a box of screen px, with no scale clamp. + * + * The unclamped twin of `fitTo`, and the clamp is the whole reason it exists. + * `fitTo` produces a *zoom level*, so it is bounded by `MIN_SCALE`/`MAX_SCALE` + * — the range a person can usefully work at. This produces a *projection + * ratio* for a second, non-interactive view of the same world, where those + * bounds are meaningless: fitting a 6000px-wide canvas into a 200px minimap + * needs about 0.03, and running that through `clampScale` would floor it at 0.1 + * and draw the frames three times wider than the card holding them. + * + * Returns `IDENTITY` for a degenerate box or a box smaller than its own + * padding, so a caller never has to defend against a zero or negative scale. + */ +export function projectInto( + bounds: Rect, + size: { height: number; width: number }, + padding = 0 +): Viewport { + const width = size.width - padding * 2; + const height = size.height - padding * 2; + if (bounds.width <= 0 || bounds.height <= 0 || width <= 0 || height <= 0) { + return { ...IDENTITY }; + } + const scale = Math.min(width / bounds.width, height / bounds.height); + return { + scale, + x: (size.width - bounds.width * scale) / 2 - bounds.left * scale, + y: (size.height - bounds.height * scale) / 2 - bounds.top * scale, + }; +} + /** The world-space box containing every rect given, or null if there are none. */ export function unionRects(rects: Rect[]): Rect | null { if (rects.length === 0) { diff --git a/packages/overlay/src/canvas/viewport.test.ts b/packages/overlay/src/canvas/viewport.test.ts new file mode 100644 index 0000000..2f6d01c --- /dev/null +++ b/packages/overlay/src/canvas/viewport.test.ts @@ -0,0 +1,172 @@ +/** + * `centerOn` and `fitToRect` — and really the safe-area shift underneath both. + * + * There was no test for `CanvasViewport` at all, which left `inSafe` uncovered: + * the two lines that move an aim computed against the *size* of the uncovered + * canvas onto its *position*. Every "take me there" in the editor goes through + * them — the frame list, the minimap, ⇧1, ⇧2 — and getting them wrong does not + * throw or look broken. It parks what you asked for underneath a dock, which + * reads as the canvas being slightly off rather than as a bug. + * + * So the cases below are all about the inset. `fitTo` and `centerAt` centre + * within a box whose origin is `(0, 0)`; with a 340px panel open, the answer + * has to land in the middle of the 860px that is left, not the middle of the + * 1200px window. The assertions are written as "where does this world point end + * up on screen", through `worldToScreen`, rather than against hand-computed + * transforms — a test written from the same algebra as the code would agree + * with it while both were wrong. + * + * happy-dom does no layout, so the viewport's own rect is stubbed. That is the + * only fake here: the transform arithmetic is the real thing. + */ + +import { beforeEach, describe, expect, it } from "vitest"; +import { MAX_SCALE, MIN_SCALE, type Rect, worldToScreen } from "./space"; +import { CanvasViewport, type SafeInset } from "./viewport"; + +const WIDTH = 1200; +const HEIGHT = 800; + +let viewport: CanvasViewport; +let inset: SafeInset; + +/** Where a world point lands on screen, under the viewport as it stands. */ +function screenOf(x: number, y: number): { x: number; y: number } { + return worldToScreen(viewport.viewport, viewport.rect, { x, y }); +} + +/** The middle of the part no dock is covering. */ +function safeCentre(): { x: number; y: number } { + return { + x: inset.left + (WIDTH - inset.left - inset.right) / 2, + y: HEIGHT / 2, + }; +} + +beforeEach(() => { + document.body.replaceChildren(); + inset = { left: 0, right: 0 }; + viewport = new CanvasViewport({ + getContentRects: () => [], + getSafeInset: () => inset, + getSelectionRect: () => null, + onChange: () => undefined, + storageKey: "__airship-test:viewport", + }); + // The canvas is full-bleed and pinned at the window's origin. + viewport.element.getBoundingClientRect = () => + ({ + bottom: HEIGHT, + height: HEIGHT, + left: 0, + right: WIDTH, + top: 0, + width: WIDTH, + }) as DOMRect; +}); + +describe("centerOn", () => { + it("puts the point in the middle of the canvas when nothing is covering it", () => { + viewport.set({ scale: 0.5, x: 0, y: 0 }); + viewport.centerOn({ x: 4000, y: 1000 }); + + const at = screenOf(4000, 1000); + expect(at.x).toBeCloseTo(WIDTH / 2, 3); + expect(at.y).toBeCloseTo(HEIGHT / 2, 3); + }); + + it("aims at the uncovered canvas, not the window", () => { + // The bug this exists to catch: with the frame list open, a click in it + // would centre the frame under the panel it was clicked from. + inset = { left: 348, right: 0 }; + viewport.set({ scale: 0.5, x: 0, y: 0 }); + viewport.centerOn({ x: 4000, y: 1000 }); + + const at = screenOf(4000, 1000); + expect(at.x).toBeCloseTo(safeCentre().x, 3); + expect(at.x).toBeGreaterThan(inset.left); + }); + + it("keeps the zoom exactly", () => { + // The whole reason this is not a fit: stepping through a list must not + // change how close you are standing. + for (const scale of [0.25, 1, 2.75]) { + viewport.set({ scale, x: 0, y: 0 }); + viewport.centerOn({ x: 10, y: 10 }); + expect(viewport.scale).toBe(scale); + } + }); + + it("is reachable from anywhere, at any zoom", () => { + inset = { left: 348, right: 360 }; + viewport.set({ scale: 4, x: -99_999, y: -99_999 }); + viewport.centerOn({ x: 0, y: 0 }); + + const at = screenOf(0, 0); + expect(at.x).toBeCloseTo(safeCentre().x, 3); + expect(at.y).toBeCloseTo(safeCentre().y, 3); + }); +}); + +describe("fitToRect", () => { + const BOX: Rect = { height: 1024, left: 2000, top: 500, width: 1440 }; + + it("centres the box in the uncovered canvas", () => { + inset = { left: 348, right: 0 }; + viewport.fitToRect(BOX); + + const topLeft = screenOf(BOX.left, BOX.top); + const bottomRight = screenOf(BOX.left + BOX.width, BOX.top + BOX.height); + const mid = (topLeft.x + bottomRight.x) / 2; + + expect(mid).toBeCloseTo(safeCentre().x, 3); + // …and the whole box is inside the part you can see. + expect(topLeft.x).toBeGreaterThanOrEqual(inset.left); + expect(bottomRight.x).toBeLessThanOrEqual(WIDTH); + }); + + it("scales to fit, and stops at 100% by default", () => { + viewport.fitToRect(BOX); + const topLeft = screenOf(BOX.left, BOX.top); + const bottomRight = screenOf(BOX.left + BOX.width, BOX.top + BOX.height); + + expect(bottomRight.x - topLeft.x).toBeLessThanOrEqual(WIDTH); + expect(bottomRight.y - topLeft.y).toBeLessThanOrEqual(HEIGHT); + // A 1440×1024 box does not fit in 1200×800, so this is a genuine shrink. + expect(viewport.scale).toBeLessThan(1); + }); + + it("does not magnify past 100% unless asked", () => { + const tiny: Rect = { height: 24, left: 0, top: 0, width: 24 }; + viewport.fitToRect(tiny); + expect(viewport.scale).toBe(1); + + viewport.fitToRect(tiny, 96, MAX_SCALE); + expect(viewport.scale).toBeGreaterThan(1); + }); + + it("stays inside the zoom bounds", () => { + const vast: Rect = { height: 400_000, left: 0, top: 0, width: 400_000 }; + viewport.fitToRect(vast); + expect(viewport.scale).toBe(MIN_SCALE); + }); + + it("refuses a degenerate box rather than aiming at nothing", () => { + viewport.set({ scale: 1.5, x: 12, y: 34 }); + viewport.fitToRect({ height: 0, left: 0, top: 0, width: 0 }); + + // Untouched — a zero box has no centre, and `fitTo` would answer with the + // identity, which would silently throw away where you were looking. + expect(viewport.viewport).toEqual({ scale: 1.5, x: 12, y: 34 }); + }); + + it("survives both docks covering almost everything", () => { + // `safeRect` floors the uncovered strip at MIN_SAFE_W rather than letting a + // negative width reach `fitTo`, which would produce a nonsense scale. + inset = { left: 700, right: 700 }; + viewport.fitToRect(BOX); + + expect(Number.isFinite(viewport.scale)).toBe(true); + expect(viewport.scale).toBeGreaterThan(0); + }); +}); diff --git a/packages/overlay/src/canvas/viewport.ts b/packages/overlay/src/canvas/viewport.ts index 71706a9..91d7696 100644 --- a/packages/overlay/src/canvas/viewport.ts +++ b/packages/overlay/src/canvas/viewport.ts @@ -3,6 +3,7 @@ import { isOwn } from "../edit-guard"; import { isInsidePopover, isTypingTarget, keys } from "../keys"; import { isFrameChrome } from "./frame-chrome"; import { + centerAt, clampScale, fitTo, MAX_SCALE, @@ -206,6 +207,36 @@ export class CanvasViewport { return { height: r.height, left: r.left + left, top: r.top, width }; } + /** + * The world-space box the *uncovered* canvas is showing. + * + * `visibleWorldRect(vp, rect)` answers the same question for the whole canvas + * and is the wrong one for anything that has to agree with `centerOn`: that + * command aims at `safeRect`, so its centre is the middle of what you can + * see, while the full rect's centre is the middle of what the docks are + * partly covering. The two differ by `(rightInset - leftInset) / 2 / scale`, + * which is a constant offset rather than a rounding error — with the frames + * panel open it is ~140px of world at scale 1, and 1400 at 10%. + * + * The minimap is the caller that cares: it draws an indicator and then hands + * the point you pressed to `centerOn`, so drawing from anything other than + * what `centerOn` targets puts the box somewhere other than where you aimed. + * Derived here rather than by passing `safeRect` to `visibleWorldRect`, + * because that helper assumes the rect it is given starts at the canvas's own + * origin — it would take the safe area's *size* and the full rect's position. + */ + get visibleSafeRect(): Rect { + const r = this.rect; + const safe = this.safeRect; + const { scale, x, y } = this.vp; + return { + height: safe.height / scale, + left: (safe.left - r.left - x) / scale, + top: (safe.top - r.top - y) / scale, + width: safe.width / scale, + }; + } + /** Is a pan gesture in flight? The picker suppresses hover while one is. */ get isPanning(): boolean { return this.panning !== null; @@ -309,6 +340,45 @@ export class CanvasViewport { this.set(this.fitInSafe(bounds, 96, MAX_SCALE)); } + /** + * Fit an arbitrary world-space box — the public form of `fitInSafe`. + * + * `zoomToFit` and `zoomToSelection` both answer a question the viewport can + * work out for itself, from its own deps. This one is for a caller that + * already knows the box and wants the camera moved onto it: the frame list + * flying to a row, the minimap on a double-click. Kept as a command rather + * than exposing `fitInSafe` directly so the safe-area arithmetic stays the + * one thing it is, and every caller lands on `set`. + */ + fitToRect(bounds: Rect, padding?: number, maxScale?: number): void { + if (bounds.width <= 0 || bounds.height <= 0) { + return; + } + this.set(this.fitInSafe(bounds, padding, maxScale)); + } + + /** + * Put a world point at the centre of the visible canvas, at the current zoom. + * + * The other half of "take me there", and deliberately not a fit: dragging the + * minimap has to move the camera *without* changing how close you are + * standing, or every pan would also be a zoom. Same reason a click in the + * frame list centres rather than fits — you keep the working scale you chose + * and only the position changes. + */ + centerOn(point: Point): void { + const safe = this.safeRect; + this.set( + this.inSafe( + centerAt( + point, + { height: safe.height, width: safe.width }, + this.vp.scale + ) + ) + ); + } + /** * Fit a world-space box into the *uncovered* part of the canvas. * @@ -321,9 +391,21 @@ export class CanvasViewport { padding?: number, maxScale?: number ): Viewport { + return this.inSafe(fitTo(bounds, this.safeRect, padding, maxScale)); + } + + /** + * Move a viewport computed against the safe area's *size* onto the safe + * area's *position*. + * + * Both `fitTo` and `centerAt` centre within a box whose origin is `(0, 0)`, + * which is the canvas's own top-left — so without this every aim lands in the + * middle of the window rather than the middle of what is not covered by a + * dock. Shared by the two so a future third command cannot forget the shift. + */ + private inSafe(vp: Viewport): Viewport { const r = this.rect; const safe = this.safeRect; - const vp = fitTo(bounds, safe, padding, maxScale); return { ...vp, x: vp.x + (safe.left - r.left), diff --git a/packages/overlay/src/picker-marquee.test.ts b/packages/overlay/src/picker-marquee.test.ts new file mode 100644 index 0000000..55e63c5 --- /dev/null +++ b/packages/overlay/src/picker-marquee.test.ts @@ -0,0 +1,131 @@ +/** + * The marquee's negotiations with everything else that owns a drag. + * + * Two of these were shipped bugs. A space-drag pan also armed the marquee — + * `stopPropagation` in the viewport cannot decline a sibling listener on the + * same window node — and the trailing `click` a drag leaves behind was never + * suppressed, so a completed marquee's own click promptly wiped (or collapsed + * to one) the selection it had just made. The third is the inline surface: + * `EditGuard` swallows `pointerup` at document capture, which runs after + * window *capture* but before window bubble — the phase the handler used to + * sit in, where it never fired inline at all. + * + * happy-dom does not synthesize a `click` from a pointer pair and reports + * zero-size rects, so these assert on `guard.clickSuppressed` — the picker's + * own click handler consumes exactly that flag — rather than on a selection + * surviving a synthetic click. + */ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { ChromeLayer } from "./chrome-layer"; +import { SelectionController } from "./picker"; +import { InlineResolver } from "./surface"; + +const layer = new ChromeLayer(); + +interface Rig { + controller: SelectionController; + gesturing: { on: boolean }; +} + +function rig(): Rig { + const gesturing = { on: false }; + const controller = new SelectionController( + { onSelect: () => undefined }, + { + isGesturing: () => gesturing.on, + layer, + resolver: new InlineResolver(), + swallowPresses: false, + } + ); + controller.setEditing(true); + return { controller, gesturing }; +} + +function pointer(type: string, x: number, y: number): PointerEvent { + return new PointerEvent(type, { + bubbles: true, + button: 0, + clientX: x, + clientY: y, + }); +} + +beforeEach(() => { + layer.mount(document.body); +}); + +afterEach(() => { + for (const child of Array.from(document.body.children)) { + child.remove(); + } +}); + +describe("marquee vs pan", () => { + it("declines the press and swallows the trailing click of a real pan", () => { + const { controller, gesturing } = rig(); + gesturing.on = true; + document.body.dispatchEvent(pointer("pointerdown", 10, 10)); + // `endPan` has run by pointerup, so `isGesturing` is already false — the + // decline must have been latched at pointerdown or it is unreachable. + gesturing.on = false; + document.body.dispatchEvent(pointer("pointerup", 60, 60)); + expect(controller.guard.clickSuppressed).toBe(true); + controller.setEditing(false); + }); + + it("does not suppress the click of a stationary gesture press", () => { + const { controller, gesturing } = rig(); + gesturing.on = true; + document.body.dispatchEvent(pointer("pointerdown", 10, 10)); + gesturing.on = false; + document.body.dispatchEvent(pointer("pointerup", 11, 11)); + // Below the 4px threshold this was a click, and clicks own their path. + expect(controller.guard.clickSuppressed).toBe(false); + controller.setEditing(false); + }); + + it("suppresses its own trailing click after a completed marquee", () => { + // The latent bug, written down: without this, the click that follows a + // release lands in `onClick` and deselects (empty canvas) or collapses + // the multi-selection to the element under the release point. + const { controller } = rig(); + document.body.dispatchEvent(pointer("pointerdown", 10, 10)); + document.body.dispatchEvent(pointer("pointerup", 60, 60)); + expect(controller.guard.clickSuppressed).toBe(true); + controller.setEditing(false); + }); + + it("clears the latched gesture press on teardown", () => { + const { controller, gesturing } = rig(); + gesturing.on = true; + document.body.dispatchEvent(pointer("pointerdown", 10, 10)); + controller.setEditing(false); + controller.setEditing(true); + gesturing.on = false; + document.body.dispatchEvent(pointer("pointerup", 60, 60)); + // No stale latch: the press this release would pair with was discarded. + expect(controller.guard.clickSuppressed).toBe(false); + controller.setEditing(false); + }); + + it("completes even when a document-capture handler swallows pointerup", () => { + // The inline surface in miniature: EditGuard's press handler swallows + // `pointerup` over app content at document capture. Window capture runs + // first, so the marquee still completes — in the bubble phase it never + // fired inline at all. + const swallow = (e: Event): void => { + e.stopPropagation(); + }; + document.addEventListener("pointerup", swallow, true); + try { + const { controller } = rig(); + document.body.dispatchEvent(pointer("pointerdown", 10, 10)); + document.body.dispatchEvent(pointer("pointerup", 60, 60)); + expect(controller.guard.clickSuppressed).toBe(true); + controller.setEditing(false); + } finally { + document.removeEventListener("pointerup", swallow, true); + } + }); +}); diff --git a/packages/overlay/src/picker.ts b/packages/overlay/src/picker.ts index 15f0ea9..8d67c97 100644 --- a/packages/overlay/src/picker.ts +++ b/packages/overlay/src/picker.ts @@ -317,6 +317,9 @@ export class SelectionController { /** The eight resize grips' dnd-kit entities, torn down with the controller. */ private readonly handleScope = new DndScope(); private marqueeFrom: Point | null = null; + /** The press point of a declined pan gesture, kept only so `onMarqueeUp` + * can swallow the trailing click the pan leaves behind. */ + private gestureFrom: Point | null = null; private readonly hoverBox: HTMLElement; private readonly hoverLabel: HTMLElement; @@ -517,7 +520,12 @@ export class SelectionController { document.addEventListener("dblclick", this.onDblClick, true); window.addEventListener("pointerdown", this.onMarqueeDown, true); window.addEventListener("pointermove", this.onMarqueeMove); - window.addEventListener("pointerup", this.onMarqueeUp); + // Capture, like the down handler — and not only for symmetry. In the + // inline overlay `EditGuard` swallows `pointerup` over app content at + // document capture, which runs after window capture but before any + // window *bubble* listener — so a bubble-phase handler here never fired + // inline: the band stayed painted and the selection never landed. + window.addEventListener("pointerup", this.onMarqueeUp, true); this.unbindKeys = keys.bind({ keys: "escape", label: "Deselect", @@ -542,8 +550,9 @@ export class SelectionController { document.removeEventListener("dblclick", this.onDblClick, true); window.removeEventListener("pointerdown", this.onMarqueeDown, true); window.removeEventListener("pointermove", this.onMarqueeMove); - window.removeEventListener("pointerup", this.onMarqueeUp); + window.removeEventListener("pointerup", this.onMarqueeUp, true); this.marqueeFrom = null; + this.gestureFrom = null; hide(this.marquee); this.unbindKeys?.(); this.unbindKeys = null; @@ -862,6 +871,17 @@ export class SelectionController { ) { return; } + // A pan owns this press — space-drag or the Hand tool. The viewport's + // `stopPropagation` cannot decline it for us: both handlers hang on the + // same window node, and only `stopImmediatePropagation` silences a + // sibling. Checked at pointerdown because the viewport binds first (at + // construction, before the picker binds in mount), so `panning` is + // already set by the time this runs; by pointerup it is gone again, hence + // the latch. + if (this.deps.isGesturing?.()) { + this.gestureFrom = { x: e.clientX, y: e.clientY }; + return; + } if (this.pick({ x: e.clientX, y: e.clientY })) { return; } @@ -883,14 +903,28 @@ export class SelectionController { }; private readonly onMarqueeUp = (e: PointerEvent): void => { - const from = this.marqueeFrom; + const from = this.marqueeFrom ?? this.gestureFrom; + const wasGesture = this.marqueeFrom === null; this.marqueeFrom = null; + this.gestureFrom = null; hide(this.marquee); if (!from) { return; } const box = rectBetween(from, { x: e.clientX, y: e.clientY }); if (box.width < 4 && box.height < 4) { + // A stationary press is a click, and clicks own their own path. + return; + } + // A drag is not a click, whichever kind it was. Without this, the browser + // still synthesizes a `click` at release: after a completed marquee it + // landed in `onClick` and wiped the selection the band had just made (or + // collapsed N elements to the one under the release point); after a pan + // it selected whatever the canvas stopped over. Armed at pointer*up* on + // purpose — `EditGuard.onPress` clears the flag on every pointerdown, so + // arming it at pointerdown would be dead by now. + this.guard.suppressNextClick(); + if (wasGesture) { return; } const hits = this.nodesIn(box);