From da25881be5ebaad1f50053f9a2291a7608b91563 Mon Sep 17 00:00:00 2001 From: tfukaza Date: Fri, 11 Sep 2026 10:01:56 -0700 Subject: [PATCH 01/10] feat(snapsort): add direct and keyboard drag controllers Snapshot of in-flight SnapSort work, committed before the core geometry refactor so its diff reviews on its own: - keyboard-controller, drag/direct-controller, drag/direct-candidates and drag/pointer-controller for direct (non-pointer) drags - drag session, algorithm, and item updates to support them - core EventCallback exposes installed input/global callbacks - snapsort_keyboard demo route and e2e spec - docs and design plan updates; drop the docs-framework-code e2e spec Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01DsiHfSvTGUzy6iNEkoWiG3 --- assets/snapsort/AGENTS.md | 36 +- assets/snapsort/README.md | 65 +- assets/snapsort/src/algorithm.ts | 188 +- assets/snapsort/src/container.ts | 2 +- assets/snapsort/src/drag/direct-candidates.ts | 583 ++++ assets/snapsort/src/drag/direct-controller.ts | 609 ++++ assets/snapsort/src/drag/group.ts | 36 +- assets/snapsort/src/drag/insertion-marker.ts | 60 +- assets/snapsort/src/drag/lifecycle.ts | 4 +- .../snapsort/src/drag/pointer-controller.ts | 139 + assets/snapsort/src/drag/pointer-preview.ts | 28 +- assets/snapsort/src/drag/session-store.ts | 8 +- assets/snapsort/src/drag/session.ts | 570 ++-- assets/snapsort/src/drag/swap.ts | 60 +- assets/snapsort/src/event-builders.ts | 8 +- assets/snapsort/src/index.ts | 11 +- assets/snapsort/src/item.ts | 131 +- assets/snapsort/src/keyboard-controller.ts | 220 ++ assets/snapsort/src/mutation.ts | 10 +- assets/snapsort/src/react/Handle.tsx | 26 +- assets/snapsort/src/snapshot.ts | 32 - assets/snapsort/src/svelte/Handle.svelte | 23 +- demo/svelte/main.ts | 1 - demo/svelte/src/DemoRouter.svelte | 9 + .../DirectResizeFixture.svelte | 165 + .../SnapSortKeyboardDemo.svelte | 408 +++ .../03_sessions/04_commit-and-cleanup.mdx | 2 +- docs/snapsort/04_reference/01_index.mdx | 2 +- .../04_reference/02_svelte/03_ghost.mdx | 2 +- .../04_reference/03_react/04_ghost.mdx | 2 +- .../snapsort/04_reference/04_drag-session.mdx | 79 +- .../design/direct-drag-accessibility-plan.md | 372 ++- src/object.ts | 38 +- .../docs-framework-code.playwright.config.ts | 1 - tests/e2e/docs-framework-code.spec.ts | 2913 ----------------- tests/e2e/snapsort-callback-ledger.spec.ts | 133 +- tests/e2e/snapsort-drag-snapshot.spec.ts | 448 +-- tests/e2e/snapsort-keyboard-demo.spec.ts | 189 ++ tests/e2e/snapsort.playwright.config.ts | 22 +- tests/types/snapsort-api-contract.ts | 77 +- tests/ut/snapsort-render-tree.spec.ts | 2 +- tests/ut/snapsort-state.spec.ts | 339 +- 42 files changed, 3977 insertions(+), 4076 deletions(-) create mode 100644 assets/snapsort/src/drag/direct-candidates.ts create mode 100644 assets/snapsort/src/drag/direct-controller.ts create mode 100644 assets/snapsort/src/drag/pointer-controller.ts create mode 100644 assets/snapsort/src/keyboard-controller.ts create mode 100644 demo/svelte/src/demo/snapsort_keyboard/DirectResizeFixture.svelte create mode 100644 demo/svelte/src/demo/snapsort_keyboard/SnapSortKeyboardDemo.svelte delete mode 100644 tests/e2e/docs-framework-code.spec.ts create mode 100644 tests/e2e/snapsort-keyboard-demo.spec.ts diff --git a/assets/snapsort/AGENTS.md b/assets/snapsort/AGENTS.md index fb037419..c27c23c5 100644 --- a/assets/snapsort/AGENTS.md +++ b/assets/snapsort/AGENTS.md @@ -15,7 +15,7 @@ A single `Container`/`Item` class pair (per framework) whose drag/drop behavior - `Container` - The only container class. `new Container(engine, parent, { itemId, mode, ... })`. - `defaultAnimations` - Opt-in standard reorder, drop, and programmatic move/removal animation preset. - `Item` - The only ordinary item class. `new Item(engine, parent, { itemId })`; identity is required and construction-only. Ghosts/markers are created internally. -- `DragSession` - Type-only public handle for one gesture. Callback events and `root.dragSession` expose the same stable handle; lifecycle/controller state remains internal. +- `DragSession` - Type-only public view of the per-gesture controller. Callback events and `root.dragSession` expose the same controller object; pointer/direct state lives on its discriminated `input` controller. - Event types: `ItemInsertEvent`, `ItemRemoveEvent`, `ItemMoveEvent`, `ItemSwapEvent`, `GhostCreateEvent`, `GhostInsertEvent`, `GhostMoveEvent`, `GhostRemoveEvent`, `DragStartEvent`, `DragEndEvent`, `DropTargetChangeEvent`, `DropPriorityEvent`, `VisualGeometryInvalidationEvent`, `DragLocation`. - `DROP_REJECT_PRIORITY` - the effective `-1` destination rejection value. - Drag presentation types: `DragVisual` (`"item" | "preview" | "none"`) and `DropEffect` (`"move" | "none"`). @@ -111,23 +111,23 @@ public configuration surface is the built-in `SortMode` union. ### DragSession `DragSessionController` is created on `dragStart` and kept in the internal -root-keyed session store. Lifecycle strategies receive that controller, which -owns pointer/offset/start state, ghosts, targets, the resolved strategy, and -animation bookkeeping. Public callbacks and `root.dragSession` receive only -its stable `DragSession` handle. Nested containers report `null`. - -The handle exposes read-only `root`, `pointerId`, `items`, `sources`, -`pressedItem`, `primaryItem`, `start`, `pointer`, and `status`, plus the -phase-checked `dragVisual` and `dropEffect` controls. Its arrays, locations, and -coordinate objects are immutable. `DragSession` is a type-only root export and -cannot be constructed by consumers. Internal code that needs lifecycle state -must resolve the controller through `drag/session-store.ts`; never widen the -public handle to expose controller fields. - -`handoff(replacements)` is deprecated. It predates the move-and-backfill copy -recipe, has no first-party use case, and remains temporarily only so it can be -removed in a future release if no concrete use case emerges. Do not add new -call sites or present it as a supported application recipe. +root-keyed session store. It owns the shared transaction, ghosts, targets, +resolved strategy, visual coordinates, and animation bookkeeping. Its +`input` is either a `PointerDragController` or `DirectDragController`, which +owns input-specific state and commands. Public callbacks and +`root.dragSession` receive the same controller object through the narrower +`DragSession` type; nested containers report `null`. + +Direct movement retains one destination rectangle per dragged participant and +animates the active visual from its current rectangle to those projected +rectangles with the destination Container's `animation.reorder` channel. +Position, width, and height share one progress value. A queued drop waits for +that transition; cancel and teardown stop it. + +The public type exposes read-only root, participant, source, status, and input +state plus the phase-checked `dragVisual` and `dropEffect` controls. Its arrays, +locations, and coordinate objects are immutable. `DragSession` remains a +type-only root export and cannot be constructed by consumers. ### Mutator (`mutation.ts`) diff --git a/assets/snapsort/README.md b/assets/snapsort/README.md index 2d792e8a..96a5f732 100644 --- a/assets/snapsort/README.md +++ b/assets/snapsort/README.md @@ -21,7 +21,7 @@ their bindings from `@snap-engine/snapsort/svelte` or - `Container` - `Item` -- `DragSession` - read-only public handle type for the active gesture +- `DragSession` - public view of the active gesture controller - `DragVisual` - `"item"`, `"preview"`, or `"none"` pointer representation - `DropEffect` - `"move"` or `"none"` persistent mutation choice - `defaultAnimations` - opt-in 100ms reorder, drop, and programmatic-move animation preset @@ -238,14 +238,13 @@ const callbacks = { }; ``` -`DragSession` is exported as a type, not a constructor. The same stable handle -is exposed through callback events and `root.dragSession`; nested containers -return `null`. Its read-only observations are `root`, `pointerId`, `items`, -`sources`, `pressedItem`, `primaryItem`, `start`, `pointer`, and `status`. -`items`, `sources`, their locations, and the coordinate objects are immutable. -The supported mutable controls are `dragVisual` while pending and `dropEffect` -while pending or active. Lifecycle methods, placement strategies, target -state, ghosts, and animation bookkeeping remain internal. +`DragSession` is exported as a type, not a constructor. Callback events and +`root.dragSession` expose the same controller object; nested containers return +`null`. Shared read-only observations include `root`, `items`, `sources`, +`pressedItem`, `primaryItem`, `status`, and the discriminated `input` +controller. Pointer coordinates live on pointer input, while direct +navigation state lives on direct input. The supported shared mutable controls +are `dragVisual` while pending and `dropEffect` while pending or active. A preview is one root-owned `GhostState` with `type: "pointer-preview"` and an overlay location. It can coexist with insertion's destination-owned @@ -438,6 +437,49 @@ the root exports `SortStrategy`, `DropTargetStrategy`, and `DragLifecycleStrategy` are also removed; select a built-in behavior through `ContainerConfig.mode` and the exported `SortMode` type. +## Keyboard dragging + +`KeyboardDragController` adds optional linear keyboard controls to one root +Container without changing Item markup or focus order: + +```ts +import { Container, KeyboardDragController } from "@snap-engine/snapsort"; + +const root = new Container(engine, null, { itemId: "tasks" }); +const keyboard = new KeyboardDragController(root); + +// Enter lifts or drops, Escape cancels, and arrow keys follow the current +// Container's row or column direction. + +keyboard.destroy(); +``` + +Items must already use a native focusable element or provide `tabIndex`. +When an Item has a Svelte or React `Handle`, keyboard commands are accepted +only from that exact Handle. Custom bindings replace individual defaults: + +```ts +const keyboard = new KeyboardDragController(root, { + bindings: { + liftDrop: ["Enter", " "], + previous: { row: ["ArrowLeft", "h"] }, + next: { row: ["ArrowRight", "l"] }, + }, +}); +``` + +For board navigation or other spatial behavior, call +`item.beginDirectDrag()` and use the narrowed direct controller's `moveTo()`, +`drop()`, and `cancel()` methods from an application-owned key handler. + +Accepted direct moves animate with the destination Container's +`animation.reorder` settings. The dragged visual interpolates its exact +position and size to the projected candidate geometry, including per-member +geometry for a selected group. Omit `animation`, set it to `null`, or disable +the reorder channel for an immediate move. A drop requested during a direct +transition is queued until that transition settles; cancellation interrupts +it immediately. + ## DOM ownership contract SnapSort core is designed to work identically across Vanilla JS, Svelte, React, @@ -452,8 +494,9 @@ never fight over the same DOM nodes. The contract: exists only behind `createVanillaAdapter`; framework bindings never inherit it as a parallel mutation path. 2. **Core writes only non-structural properties on the dragged element** — - `transform`, `position`/`z-index` styles. Every framework tolerates that; - none diffs inline styles it didn't set. + `transform`, temporary `position`/`z-index`, and temporary `width`/`height` + styles. Every framework tolerates that; none diffs inline styles it didn't + set. 3. **Framework mutations commit synchronously.** Core runs structural commands inside `SnapSortAdapter.commit(mutation)`. React and Svelte adapters provide this transaction automatically, committing state and DOM before diff --git a/assets/snapsort/src/algorithm.ts b/assets/snapsort/src/algorithm.ts index 37949392..dd81cf47 100644 --- a/assets/snapsort/src/algorithm.ts +++ b/assets/snapsort/src/algorithm.ts @@ -233,11 +233,13 @@ function createResolutionContext( item: ItemBase, session: DragSession | null, pointer: { x: number; y: number }, + dragRect?: Rect, ): ResolutionContext { const items = session?.items ?? [item]; const run = buildItemRunEvent(items); const sources = session?.sources ?? items.map(buildItemLocation); const box = requireDragSnapshotBox(item); + return Object.freeze({ session, item, @@ -248,13 +250,18 @@ function createResolutionContext( itemsMetadata: Object.freeze([...run.itemsMetadata]), source: sources[0] ?? null, sources: Object.freeze([...sources]), - pointer: Object.freeze({ x: pointer.x, y: pointer.y }), - dragRect: frozenRect({ - x: item.dragPositionX, - y: item.dragPositionY, - width: box.width, - height: box.height, + pointer: Object.freeze({ + x: pointer.x, + y: pointer.y, }), + dragRect: frozenRect( + dragRect ?? { + x: item.dragPositionX, + y: item.dragPositionY, + width: box.width, + height: box.height, + }, + ), containers: new Map(), }); } @@ -330,7 +337,7 @@ function resolveItemHitbox( if (!callback) return { shape: "rect", rect: defaultRect }; const hitbox = callback({ - session: session.handle, + session, item: draggedItem, itemId: draggedItem.itemId, itemMetadata: draggedItem.metadata, @@ -1390,6 +1397,102 @@ function collectInsertionCandidates( return candidates; } +/** @internal Build the canonical insertion marker for one direct slot. */ +export function createDirectInsertionTarget( + session: DragSession, + container: Container, + logicalIndex: number, +): ResolvedDropTarget & { + readonly insertion: InsertionMarkerPresentation; +} { + const containerSnapshot = requireDragSnapshot(container); + const rawChildren = containerSnapshot.children.filter( + (child) => !child.value.isGhost, + ); + + const retainedIndices = rawChildren.flatMap( + (child, rawIndex) => + session.itemSet.has(child.value) + ? [] + : [rawIndex], + ); + + if ( + !Number.isInteger(logicalIndex) || + logicalIndex < 0 || + logicalIndex > retainedIndices.length + ) { + throw new RangeError( + "SnapSort: direct insertion index is outside the retained item slots.", + ); + } + + const boundary = + retainedIndices[logicalIndex] ?? + rawChildren.length; + + const previousSnapshot = + rawChildren[boundary - 1] ?? null; + const nextSnapshot = + rawChildren[boundary] ?? null; + + const visualLines = inferSnapshotVisualLines( + containerSnapshot, + flowAxesForDirection(containerSnapshot.direction), + ); + + const lineBySnapshot = new Map< + ItemSnapshot, + SnapshotVisualLine + >(); + + for (const line of visualLines) { + for (const snapshot of line.snapshots) { + lineBySnapshot.set(snapshot, line); + } + } + + const useVisualLineBand = + containerSnapshot.layoutModel === "slots" + ? visualLines.length > 1 + : flowLayoutCanWrap( + containerSnapshot, + flowAxesForDirection( + containerSnapshot.direction, + ), + visualLines.length, + ); + + const gap = insertionGapSegment( + containerSnapshot, + previousSnapshot, + nextSnapshot, + lineBySnapshot, + useVisualLineBand, + ); + + const projection = projectItemRunMove( + container, + boundary, + session.activeSources, + ); + + const insertion = Object.freeze({ + gap, + previous: insertionMarkerNeighbor( + previousSnapshot, + ), + next: insertionMarkerNeighbor(nextSnapshot), + isCurrentPlacement: projection.isCurrentPlacement, + }) satisfies InsertionMarkerPresentation; + + return Object.freeze({ + container, + index: logicalIndex, + insertion, + }); +} + function chooseInsertionCandidate( candidates: InsertionCandidate[], ): InsertionCandidate | null { @@ -1446,7 +1549,7 @@ function dropPolicyEvent( const base = containerResolutionBase(context, candidate.target.container); return { - session: context.session?.handle ?? null, + session: context.session, item: context.item, itemId: context.itemId, itemMetadata: context.itemMetadata, @@ -1467,6 +1570,59 @@ function dropPolicyEvent( }; } +function effectiveDropPriority( + candidate: { target: ResolvedDropTarget }, + getContext: () => ResolutionContext, +): number { + const container = candidate.target.container; + const staticPriority = + configuredDropPriority(container); + const callback = container.callbacks?.getDropPriority; + + if (!callback) { + return staticPriority; + } + + const override = callback( + dropPolicyEvent( + candidate, + getContext(), + staticPriority, + ), + ); + + if (override !== undefined) { + validateDropPriority( + container, + override, + "getDropPriority", + ); + } + + return override ?? staticPriority; +} + +export function evaluateDropTargetPriority( + item: ItemBase, + session: DragSession, + target: ResolvedDropTarget, + geometry: Readonly<{ + pointer: Readonly<{ x: number; y: number }>; + dragRect: Readonly; + }>, +): number { + return effectiveDropPriority( + { target }, + () => + createResolutionContext( + item, + session, + geometry.pointer, + geometry.dragRect, + ), + ); +} + /** * Apply destination-owned drop policy once per distinct container. Effective * priority -1 rejects a destination; only candidates tied at the highest @@ -1488,17 +1644,11 @@ function applyDropPolicy( } const eligible: Array<{ candidate: T; priority: number }> = []; - for (const [container, directCandidates] of byContainer) { - const callbacks = container.callbacks; - const staticPriority = configuredDropPriority(container); - const override = callbacks?.getDropPriority - ? callbacks.getDropPriority( - dropPolicyEvent(directCandidates[0], getContext(), staticPriority), - ) - : undefined; - if (override !== undefined) - validateDropPriority(container, override, "getDropPriority"); - const priority = override ?? staticPriority; + for (const [_, directCandidates] of byContainer) { + const priority = effectiveDropPriority( + directCandidates[0], + getContext, + ); if (priority === DROP_REJECT_PRIORITY) continue; for (const candidate of directCandidates) { eligible.push({ candidate, priority }); diff --git a/assets/snapsort/src/container.ts b/assets/snapsort/src/container.ts index e7e63bfd..a531b9ee 100644 --- a/assets/snapsort/src/container.ts +++ b/assets/snapsort/src/container.ts @@ -105,7 +105,7 @@ export class Container extends Item { #visualInvalidationItems = new Set(); #visualInvalidationReasons = new Set(); - /** The read-only public handle for this tree's in-progress drag, or null. Only meaningful on the root container. */ + /** The public view of this tree's in-progress drag controller, or null. Only meaningful on the root container. */ get dragSession(): DragSession | null { return this.rootContainer === this ? getDragSession(this) : null; } diff --git a/assets/snapsort/src/drag/direct-candidates.ts b/assets/snapsort/src/drag/direct-candidates.ts new file mode 100644 index 00000000..96717996 --- /dev/null +++ b/assets/snapsort/src/drag/direct-candidates.ts @@ -0,0 +1,583 @@ +import type { CollisionRect } from "@snap-engine/core/collision"; +import { + createDirectInsertionTarget, + type ResolvedDropTarget, +} from "../algorithm"; +import type { DragLocation, InsertionMarkerPresentation } from "../events"; +import type { ItemId, ItemSnapshot } from "../snapshot"; +import { Container } from "../container"; +import type { Item } from "../item"; +import { buildDragLocation } from "../event-builders"; + +import { + contentBoxOrigin, + virtualEntrySizeFor, + createLayoutResolutionPlan, + type VirtualInsertion, + type LayoutResolutionPlan, +} from "../layout"; +import type { DragSessionController } from "./session"; + +interface DirectLayoutSnapshot { + readonly root: ItemSnapshot; + readonly byItem: ReadonlyMap>; +} + +interface DirectCandidateBase { + readonly target: Readonly; + /** Projected world-space border boxes, ordered to parallel session.items. */ + readonly memberRects: readonly Readonly[]; +} + +export interface DirectFlowCandidate extends DirectCandidateBase { + readonly kind: "flow"; +} + +export interface DirectInsertionCandidate extends DirectCandidateBase { + readonly kind: "insertion"; + readonly target: Readonly & { + readonly insertion: InsertionMarkerPresentation; + }; +} + +export interface DirectSwapCandidate extends DirectCandidateBase { + readonly kind: "swap"; + readonly targetItemId: ItemId; +} + +export interface DirectCandidateGeometry { + readonly pointer: Readonly<{ + x: number; + y: number; + }>; + readonly dragRect: Readonly; + readonly memberRects: readonly Readonly[]; +} + +export type DirectCandidate = + | DirectFlowCandidate + | DirectInsertionCandidate + | DirectSwapCandidate; + +function createDirectLayoutSnapshot(root: Container): DirectLayoutSnapshot { + const rootSnapshot = root.dragSnapshot; + + if (!rootSnapshot) { + throw new Error( + "SnapSort: direct candidates require an active drag snapshot.", + ); + } + + const byItem = new Map>(); + + const visit = (snapshot: ItemSnapshot): void => { + byItem.set(snapshot.value, snapshot); + + for (const child of snapshot.children) { + visit(child); + } + }; + + visit(rootSnapshot); + + return { + root: rootSnapshot, + byItem, + }; +} + +// TODO: feels like we have a lot of repeated code to +// traverse item trees, we should make a common utility. +function collectDirectSlotTargets( + session: DragSessionController, + rootSnapshot: ItemSnapshot, +): readonly ResolvedDropTarget[] { + const targets: ResolvedDropTarget[] = []; + + const visit = (containerSnapshot: ItemSnapshot): void => { + const container = containerSnapshot.value; + + if (!(container instanceof Container)) { + throw new Error( + "SnapSort: direct candidate traversal expected a container.", + ); + } + + const retainedChildren = containerSnapshot.children.filter( + (child) => !session.itemSet.has(child.value), + ); + + targets.push({ + container, + index: 0, + }); + + retainedChildren.forEach((child, index) => { + if (child.value instanceof Container) { + visit(child); + } + + targets.push({ + container, + index: index + 1, + }); + }); + }; + + visit(rootSnapshot); + + return targets; +} + +export function createDirectFlowCandidates( + session: DragSessionController, +): readonly DirectCandidate[] { + const snapshot = createDirectLayoutSnapshot(session.root); + const targets = collectDirectSlotTargets(session, snapshot.root); + + const candidates = targets.map( + (target): DirectFlowCandidate => ({ + kind: "flow", + target: { + container: target.container, + index: target.index, + }, + memberRects: projectDirectRects(session, snapshot, target), + }), + ); + + return freezeDirectCandidates(candidates); +} + +export function createDirectInsertionCandidates( + session: DragSessionController, +): readonly DirectCandidate[] { + const snapshot = createDirectLayoutSnapshot(session.root); + + const slots = collectDirectSlotTargets(session, snapshot.root); + + const candidates = slots.map( + ({ container, index }): DirectInsertionCandidate => { + const target = createDirectInsertionTarget(session, container, index); + + return { + kind: "insertion", + target, + memberRects: projectDirectRects(session, snapshot, target), + }; + }, + ); + + return freezeDirectCandidates(candidates); +} + +function createDirectInsertionRun( + session: DragSessionController, + containerSnapshot: ItemSnapshot, + index: number, +): readonly VirtualInsertion[] { + return Object.freeze( + session.items.map((item, offset) => { + const box = session.dragBoxFor(item); + const size = virtualEntrySizeFor(containerSnapshot, box); + + return Object.freeze({ + container: containerSnapshot, + index: index + offset, + entry: Object.freeze({ + width: size.width, + height: size.height, + margin: box.margin, + }), + }); + }), + ); +} + +export function createDirectSwapCandidates( + session: DragSessionController, + initiatingItemId: ItemId, +): readonly DirectCandidate[] { + const snapshot = createDirectLayoutSnapshot(session.root); + + const homeItem = + session.items.find((item) => item.itemId === initiatingItemId) ?? + session.pressedItem; + + const candidates: DirectSwapCandidate[] = []; + + const visit = (containerSnapshot: ItemSnapshot): void => { + const container = containerSnapshot.value; + + if (!(container instanceof Container)) { + throw new Error("SnapSort: direct swap traversal expected a container."); + } + + containerSnapshot.children.forEach((child, index) => { + const item = child.value; + + if (item.isGhost) { + return; + } + + if (session.itemSet.has(item)) { + if (item === homeItem) { + candidates.push({ + kind: "swap", + target: { + container, + index, + }, + targetItemId: item.itemId, + memberRects: projectRectsIntoTarget(session, child.box), + }); + } + + // Never descend into a dragged Container. + return; + } + + candidates.push({ + kind: "swap", + target: { + container, + index, + }, + targetItemId: item.itemId, + memberRects: projectRectsIntoTarget(session, child.box), + }); + + if (item instanceof Container) { + visit(child); + } + }); + }; + + visit(snapshot.root); + + return freezeDirectCandidates(candidates); +} + +export function createDirectCandidates( + session: DragSessionController, + initiatingItemId: ItemId, +): readonly DirectCandidate[] { + switch (session.strategy.mode) { + case "euclidean": + case "progressive": + return createDirectFlowCandidates(session); + + case "insertion": + return createDirectInsertionCandidates(session); + + case "swap": + return createDirectSwapCandidates(session, initiatingItemId); + } +} + +function snapshotPathTo( + root: ItemSnapshot, + target: ItemSnapshot, +): readonly ItemSnapshot[] { + if (root === target) { + return [root]; + } + + for (const child of root.children) { + const childPath = snapshotPathTo(child, target); + + if (childPath.length > 0) { + return [root, ...childPath]; + } + } + + return []; +} + +function freezeRect(rect: CollisionRect): Readonly { + return Object.freeze({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }); +} + +function sourceMemberRects( + session: DragSessionController, +): readonly Readonly[] { + return Object.freeze( + session.items.map((item) => { + const start = session.dragVisualStart.get(item); + + if (!start) { + throw new Error( + "SnapSort: direct candidate geometry requires captured visual positions.", + ); + } + + const box = session.dragBoxFor(item); + return freezeRect({ + x: start.x, + y: start.y, + width: box.width, + height: box.height, + }); + }), + ); +} + +// TODO: Eventually, these functions +// should be provided as part of a layout engine +function boundingRect( + rects: readonly Readonly[], +): CollisionRect { + if (rects.length === 0) { + throw new Error( + "SnapSort: cannot calculate a direct candidate without projected items.", + ); + } + + let left = rects[0].x; + let top = rects[0].y; + let right = rects[0].x + rects[0].width; + let bottom = rects[0].y + rects[0].height; + + for (const rect of rects.slice(1)) { + left = Math.min(left, rect.x); + top = Math.min(top, rect.y); + right = Math.max(right, rect.x + rect.width); + bottom = Math.max(bottom, rect.y + rect.height); + } + + return { + x: left, + y: top, + width: right - left, + height: bottom - top, + }; +} + +function projectRectsIntoTarget( + session: DragSessionController, + target: Readonly, +): readonly Readonly[] { + const sourceRects = sourceMemberRects(session); + const sourceGroup = boundingRect(sourceRects); + const scaleX = sourceGroup.width > 0 ? target.width / sourceGroup.width : 1; + const scaleY = + sourceGroup.height > 0 ? target.height / sourceGroup.height : 1; + + return Object.freeze( + sourceRects.map((rect) => + freezeRect({ + x: target.x + (rect.x - sourceGroup.x) * scaleX, + y: target.y + (rect.y - sourceGroup.y) * scaleY, + width: rect.width * scaleX, + height: rect.height * scaleY, + }), + ), + ); +} + +export function directCandidateGeometry( + session: DragSessionController, + candidate: DirectCandidate, +): DirectCandidateGeometry { + const sourceRects = sourceMemberRects(session); + const pressedIndex = session.items.indexOf(session.pressedItem); + const primaryIndex = session.items.indexOf(session.primaryItem); + const pressedStart = sourceRects[pressedIndex]; + const pressedTarget = candidate.memberRects[pressedIndex]; + const primaryTarget = candidate.memberRects[primaryIndex]; + + if ( + candidate.memberRects.length !== session.items.length || + !pressedStart || + !pressedTarget || + !primaryTarget + ) { + throw new Error( + "SnapSort: direct candidate geometry requires one projected rectangle per participant.", + ); + } + + const delta = { + x: pressedTarget.x - pressedStart.x, + y: pressedTarget.y - pressedStart.y, + }; + + return Object.freeze({ + pointer: Object.freeze({ + x: session.visualStart.x + delta.x, + y: session.visualStart.y + delta.y, + }), + dragRect: primaryTarget, + memberRects: candidate.memberRects, + }); +} + +function projectedContentOrigin( + layoutPlan: LayoutResolutionPlan, + path: readonly ItemSnapshot[], +): Readonly<{ x: number; y: number }> { + const rootSnapshot = path[0]; + + if (!rootSnapshot) { + throw new Error( + "SnapSort: direct candidate target is outside the drag snapshot.", + ); + } + + let origin = contentBoxOrigin(rootSnapshot.box); + + for (let index = 1; index < path.length; index += 1) { + const parent = path[index - 1]; + const child = path[index]; + + const parentLayout = layoutPlan.layoutPositions(parent, origin.x, origin.y); + + const childPosition = parentLayout.itemPositions.get(child); + + if (!childPosition) { + throw new Error( + "SnapSort: layout did not project a direct candidate container.", + ); + } + + origin = { + x: childPosition.x + child.box.border.left + child.box.padding.left, + y: childPosition.y + child.box.border.top + child.box.padding.top, + }; + } + + return Object.freeze(origin); +} + +function projectDirectRects( + session: DragSessionController, + snapshot: DirectLayoutSnapshot, + target: ResolvedDropTarget, +): readonly Readonly[] { + const targetSnapshot = snapshot.byItem.get(target.container); + + if (!targetSnapshot) { + throw new Error( + "SnapSort: direct candidate target is outside the drag snapshot.", + ); + } + + const insertionRun = createDirectInsertionRun( + session, + targetSnapshot, + target.index, + ); + + const layoutPlan = createLayoutResolutionPlan(snapshot.root, { + filter: { + excludeValues: session.itemSet, + }, + insertions: insertionRun, + }); + + const path = snapshotPathTo(snapshot.root, targetSnapshot); + const targetOrigin = projectedContentOrigin(layoutPlan, path); + + const result = layoutPlan.layoutPositions( + targetSnapshot, + targetOrigin.x, + targetOrigin.y, + insertionRun, + ); + + const memberRects = insertionRun.map((insertion) => { + const rect = result.virtualRects.get(insertion); + + if (!rect) { + throw new Error( + "SnapSort: layout did not project a direct candidate item.", + ); + } + + return rect; + }); + + return Object.freeze(memberRects.map(freezeRect)); +} + +function freezeInsertion( + insertion: InsertionMarkerPresentation, +): InsertionMarkerPresentation { + const freezeNeighbor = (neighbor: InsertionMarkerPresentation["previous"]) => + neighbor + ? Object.freeze({ + ...neighbor, + rect: freezeRect(neighbor.rect), + }) + : null; + + return Object.freeze({ + gap: Object.freeze({ ...insertion.gap }), + previous: freezeNeighbor(insertion.previous), + next: freezeNeighbor(insertion.next), + isCurrentPlacement: insertion.isCurrentPlacement, + }); +} + +export function freezeDirectCandidate( + candidate: DirectCandidate, +): DirectCandidate { + const memberRects = Object.freeze(candidate.memberRects.map(freezeRect)); + + switch (candidate.kind) { + case "flow": + return Object.freeze({ + kind: candidate.kind, + target: Object.freeze({ + container: candidate.target.container, + index: candidate.target.index, + }), + memberRects, + }); + + case "insertion": + return Object.freeze({ + kind: candidate.kind, + target: Object.freeze({ + container: candidate.target.container, + index: candidate.target.index, + insertion: freezeInsertion(candidate.target.insertion), + }), + memberRects, + }); + + case "swap": + return Object.freeze({ + kind: candidate.kind, + target: Object.freeze({ + container: candidate.target.container, + index: candidate.target.index, + }), + targetItemId: candidate.targetItemId, + memberRects, + }); + } +} + +export function freezeDirectCandidates( + candidates: readonly DirectCandidate[], +): readonly DirectCandidate[] { + return Object.freeze(candidates.map(freezeDirectCandidate)); +} + +export function directCandidateLocations( + candidates: readonly DirectCandidate[], +): readonly DragLocation[] { + return Object.freeze( + candidates.map((candidate) => + Object.freeze( + buildDragLocation(candidate.target.container, candidate.target.index), + ), + ), + ); +} diff --git a/assets/snapsort/src/drag/direct-controller.ts b/assets/snapsort/src/drag/direct-controller.ts new file mode 100644 index 00000000..bf324cd2 --- /dev/null +++ b/assets/snapsort/src/drag/direct-controller.ts @@ -0,0 +1,609 @@ +import { AnimationObject } from "@snap-engine/core/animation"; +import type { CollisionRect } from "@snap-engine/core/collision"; +import { evaluateDropTargetPriority } from "../algorithm"; +import { animationConfigFor } from "../internal/flip-animation"; +import { DROP_REJECT_PRIORITY, type DragLocation } from "../events"; +import type { ItemId } from "../snapshot"; +import { + createDirectCandidates, + directCandidateGeometry, + directCandidateLocations, + type DirectCandidate, + type DirectCandidateGeometry, +} from "./direct-candidates"; +import type { DragSessionController } from "./session"; +import type { Container } from "../container"; +import { settleMutation } from "../mutation"; +import { getDragSessionController } from "./session-store"; + +let directDragGeneration = 0; +const directAnimationCancellation = new WeakMap< + DirectDragController, + () => void +>(); + +/** @internal Stop direct-input motion while preserving its last rendered rect. */ +export function cancelDirectMoveAnimation( + controller: DirectDragController, +): void { + directAnimationCancellation.get(controller)?.(); +} + +const DIRECT_MOVE_DEFAULT_DURATION = 160; +const DIRECT_MOVE_DEFAULT_EASING = "ease-out"; + +function freezeRect(rect: Readonly): Readonly { + return Object.freeze({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }); +} + +function freezeRects( + rects: readonly Readonly[], +): readonly Readonly[] { + return Object.freeze(rects.map(freezeRect)); +} + +function interpolateRect( + from: Readonly, + to: Readonly, + progress: number, +): CollisionRect { + return { + x: from.x + (to.x - from.x) * progress, + y: from.y + (to.y - from.y) * progress, + width: from.width + (to.width - from.width) * progress, + height: from.height + (to.height - from.height) * progress, + }; +} + +function boundingRect( + rects: readonly Readonly[], +): Readonly { + const first = rects[0]; + if (!first) { + throw new Error("DirectDragController: visual geometry cannot be empty."); + } + + let left = first.x; + let top = first.y; + let right = first.x + first.width; + let bottom = first.y + first.height; + + for (const rect of rects.slice(1)) { + left = Math.min(left, rect.x); + top = Math.min(top, rect.y); + right = Math.max(right, rect.x + rect.width); + bottom = Math.max(bottom, rect.y + rect.height); + } + + return freezeRect({ + x: left, + y: top, + width: right - left, + height: bottom - top, + }); +} + +export class DirectDragController { + readonly inputType = "direct" as const; + readonly initiatingItemId: ItemId; + readonly #session: DragSessionController; + readonly #participantIndexById: ReadonlyMap; + readonly #queueIdPrefix = `direct-drag-${++directDragGeneration}`; + + #candidates: readonly DirectCandidate[] = Object.freeze([]); + #candidateLocations: readonly DragLocation[] = Object.freeze([]); + #activated = false; + #moveSettling = false; + #dropRequested = false; + #restoreFocus = true; + #visualRects: readonly Readonly[] = Object.freeze([]); + #moveAnimation: AnimationObject | null = null; + + #currentCandidateIndex: number | null = null; + #homeCandidateIndex: number | null = null; + + constructor(session: DragSessionController, initiatingItemId: ItemId) { + this.#session = session; + this.initiatingItemId = initiatingItemId; + this.#participantIndexById = new Map( + session.items.map((item, index) => [item.itemId, index]), + ); + directAnimationCancellation.set(this, () => this.#cancelMoveAnimation()); + Object.freeze(this); + } + + /** @internal Capture this session's direct candidates after drag geometry exists. */ + activate(): void { + if (this.#activated) { + throw new Error("DirectDragController: input is already active."); + } + + const candidates = createDirectCandidates( + this.#session, + this.initiatingItemId, + ); + this.#candidates = candidates; + this.#candidateLocations = directCandidateLocations(candidates); + const homeCandidateIndex = this.#resolveSourceCandidateIndex(); + + this.#homeCandidateIndex = homeCandidateIndex; + this.#currentCandidateIndex = homeCandidateIndex; + this.#visualRects = freezeRects( + this.#session.items.map((item) => { + const start = this.#session.dragVisualStart.get(item); + if (!start) { + throw new Error( + "DirectDragController: participant visual geometry is missing.", + ); + } + const box = this.#session.dragBoxFor(item); + return { + x: start.x, + y: start.y, + width: box.width, + height: box.height, + }; + }), + ); + this.#activated = true; + } + + /** @internal Restore focus after terminal callbacks and framework reconciliation. */ + scheduleFocusRestoration(): void { + if (!this.#restoreFocus) return; + + const root = this.#session.root; + const initiatingItemId = this.initiatingItemId; + + root.schedule( + async () => { + await settleMutation(); + + if (root.isDeleteRequested || getDragSessionController(root)) return; + const item = root.findItemById(initiatingItemId); + const inputElement = item?.inputElement; + + if (!item || item.isDeleteRequested || !inputElement?.isConnected) { + return; + } + + inputElement.focus({ preventScroll: true }); + }, + { + stage: "WRITE_3", + queueId: `${this.#queueIdPrefix}-focus`, + }, + ); + } + + /** @internal Let native focus navigation proceed after cancelling this drag. */ + suppressFocusRestoration(): void { + this.#restoreFocus = false; + } + + /** @internal Exact candidates used for placement and visuals. */ + get directCandidates(): readonly DirectCandidate[] { + return this.#candidates; + } + + /** Public logical destinations available to direct input. */ + get candidates(): readonly DragLocation[] { + return this.#candidateLocations; + } + + get currentCandidate(): DirectCandidate | null { + if (this.#currentCandidateIndex === null) { + return null; + } + + return this.#candidates[this.#currentCandidateIndex] ?? null; + } + + get currentTarget(): DragLocation | null { + if (this.#currentCandidateIndex === null) { + return null; + } + + return this.#candidateLocations[this.#currentCandidateIndex] ?? null; + } + + /** @internal Current animated world-space border box for one participant. */ + visualRectFor(itemId: ItemId): Readonly | null { + const index = this.#participantIndexById.get(itemId); + return index === undefined ? null : this.#visualRects[index] ?? null; + } + + /** @internal Current animated bounding box for the complete drag visual. */ + get visualGroupRect(): Readonly | null { + return this.#visualRects.length > 0 + ? boundingRect(this.#visualRects) + : null; + } + + get #canMove(): boolean { + return ( + this.#activated && !this.#moveSettling && this.#session.phase === "active" + ); + } + + #writeVisualGeometry( + rects: readonly Readonly[], + pointer: Readonly<{ x: number; y: number }>, + ): void { + if (rects.length !== this.#session.items.length) { + throw new Error( + "DirectDragController: visual geometry must parallel the dragged participants.", + ); + } + + this.#visualRects = freezeRects(rects); + this.#session.visualPointer = pointer; + this.#session.strategy.lifecycle.dragMove(this.#session); + } + + #completeMove(): void { + this.#moveAnimation = null; + this.#moveSettling = false; + + if (this.#dropRequested && this.#session.phase === "active") { + this.#session.beginDrop(); + } + } + + #cancelMoveAnimation(): void { + const animation = this.#moveAnimation; + this.#moveAnimation = null; + animation?.cancel(); + this.#moveSettling = false; + } + + #startMoveAnimation( + candidate: DirectCandidate, + geometry: DirectCandidateGeometry, + ): void { + const session = this.#session; + const targetRects = freezeRects(geometry.memberRects); + const targetPointer = geometry.pointer; + const config = animationConfigFor(candidate.target.container, "reorder"); + const duration = config?.duration ?? DIRECT_MOVE_DEFAULT_DURATION; + + if (!config || duration <= 0 || session.dragVisual === "none") { + this.#writeVisualGeometry(targetRects, targetPointer); + this.#completeMove(); + return; + } + + const sourceRects = this.#visualRects; + const sourcePointer = session.visualPointer; + let animation: AnimationObject; + + const fail = () => { + if (this.#moveAnimation !== animation) return; + this.#cancelMoveAnimation(); + session.scheduleErrorFinalizer(); + }; + + animation = new AnimationObject( + null, + { $progress: [0, 1] }, + { + duration, + easing: config.timing_function ?? DIRECT_MOVE_DEFAULT_EASING, + tick: ({ $progress }) => { + if (this.#moveAnimation !== animation || session.phase !== "active") { + return; + } + + try { + this.#writeVisualGeometry( + sourceRects.map((source, index) => { + const target = targetRects[index]; + if (!target) { + throw new Error( + "DirectDragController: target visual geometry is missing.", + ); + } + return interpolateRect(source, target, $progress); + }), + { + x: + sourcePointer.x + + (targetPointer.x - sourcePointer.x) * $progress, + y: + sourcePointer.y + + (targetPointer.y - sourcePointer.y) * $progress, + }, + ); + } catch { + fail(); + } + }, + finish: () => { + if (this.#moveAnimation !== animation) return; + + try { + this.#writeVisualGeometry(targetRects, targetPointer); + } catch { + fail(); + return; + } + + this.#completeMove(); + }, + }, + ); + + this.#moveAnimation = animation; + session.root.addAnimation(animation, { replaceExisting: false }); + animation.play(); + } + + #scheduleMove( + candidateIndex: number, + candidate: DirectCandidate, + geometry: DirectCandidateGeometry, + ): void { + const session = this.#session; + const item = session.primaryItem; + const queueId = `${this.#queueIdPrefix}-move-${item.id}`; + + const placementTarget = + candidate.kind === "swap" && candidateIndex === this.#homeCandidateIndex + ? null + : candidate.target; + + this.#moveSettling = true; + + item.schedule( + () => { + if (session.phase !== "active") { + return; + } + + let completed = false; + + try { + session.prepareTarget(placementTarget); + completed = true; + } finally { + if (!completed) { + this.#moveSettling = false; + session.scheduleErrorFinalizer(); + } + } + }, + { + stage: "READ_1", + queueId: `${queueId}-read`, + }, + ); + + item.schedule( + async () => { + if (session.phase !== "active") { + this.#moveSettling = false; + return; + } + + let completed = false; + + try { + await session.applyTarget(placementTarget, false); + if (session.phase !== "active") { + this.#moveSettling = false; + completed = true; + return; + } + this.#startMoveAnimation(candidate, geometry); + completed = true; + } finally { + if (!completed) { + this.#cancelMoveAnimation(); + session.scheduleErrorFinalizer(); + } + } + }, + { + stage: "WRITE_1", + queueId, + }, + ); + + session.root.queueReadTree("READ_2", queueId); + } + + #acceptCandidate( + candidateIndex: number, + candidate: DirectCandidate, + geometry: DirectCandidateGeometry, + ): boolean { + this.#currentCandidateIndex = candidateIndex; + this.#scheduleMove(candidateIndex, candidate, geometry); + return true; + } + + moveTo(container: Container, index: number): boolean { + if (!this.#canMove) { + return false; + } + + const candidateIndex = this.#candidateIndexFor(container, index); + + if (candidateIndex === this.#currentCandidateIndex) { + return false; + } + + const candidate = this.#candidates[candidateIndex]; + + if (!candidate) { + throw new Error("DirectDragController: resolved candidate is missing."); + } + + const geometry = directCandidateGeometry(this.#session, candidate); + + const priority = evaluateDropTargetPriority( + this.#session.primaryItem, + this.#session, + candidate.target, + geometry, + ); + + if (priority === DROP_REJECT_PRIORITY) { + return false; + } + + return this.#acceptCandidate(candidateIndex, candidate, geometry); + } + + moveNext(): boolean { + return this.#moveBy(1); + } + + movePrevious(): boolean { + return this.#moveBy(-1); + } + + drop(): boolean { + if ( + !this.#activated || + this.#dropRequested || + this.#session.phase !== "active" + ) { + return false; + } + + this.#dropRequested = true; + + if (!this.#moveSettling) { + this.#session.beginDrop(); + } + + return true; + } + + cancel(): boolean { + if (!this.#activated || this.#session.phase !== "active") { + return false; + } + + this.#dropRequested = false; + this.#cancelMoveAnimation(); + this.#session.cancel(); + return true; + } + + #moveBy(direction: 1 | -1): boolean { + if (!this.#canMove || this.#currentCandidateIndex === null) { + return false; + } + + const rejectedContainers = new Set(); + + for ( + let candidateIndex = this.#currentCandidateIndex + direction; + candidateIndex >= 0 && candidateIndex < this.#candidates.length; + candidateIndex += direction + ) { + const candidate = this.#candidates[candidateIndex]; + + if (!candidate) { + continue; + } + + const container = candidate.target.container; + + if (rejectedContainers.has(container)) { + continue; + } + + const geometry = directCandidateGeometry(this.#session, candidate); + + const priority = evaluateDropTargetPriority( + this.#session.primaryItem, + this.#session, + candidate.target, + geometry, + ); + + if (priority === DROP_REJECT_PRIORITY) { + rejectedContainers.add(container); + continue; + } + + return this.#acceptCandidate(candidateIndex, candidate, geometry); + } + + return false; + } + + #candidateIndexFor(container: Container, index: number): number { + if (!Number.isInteger(index) || index < 0) { + throw new RangeError( + "DirectDragController: candidate index must be a nonnegative integer.", + ); + } + + if ( + container.isDeleteRequested || + container.rootContainer !== this.#session.root + ) { + throw new Error( + "DirectDragController: candidate container must be live and belong to the session root.", + ); + } + + const candidateIndex = this.#candidateLocations.findIndex( + (location) => + location.container === container && location.index === index, + ); + + if (candidateIndex === -1) { + throw new RangeError( + "DirectDragController: the requested location is not a direct-drag candidate.", + ); + } + + return candidateIndex; + } + + #resolveSourceCandidateIndex(): number { + let participantIndex = this.#session.items.findIndex( + (item) => item.itemId === this.initiatingItemId, + ); + + // A selected ancestor may be the actual dragged participant. + if (participantIndex === -1) { + participantIndex = this.#session.items.indexOf(this.#session.pressedItem); + } + + if (participantIndex === -1) { + throw new Error( + "DirectDragController: initiating participant is missing from the session.", + ); + } + + const source = this.#session.sources[participantIndex]; + + const removedBefore = this.#session.sources.reduce( + (count, candidateSource, sourceIndex) => + sourceIndex !== participantIndex && + candidateSource.container === source.container && + candidateSource.index < source.index + ? count + 1 + : count, + 0, + ); + + const homeIndex = + this.#session.strategy.mode === "swap" + ? source.index + : source.index - removedBefore; + + return this.#candidateIndexFor(source.container, homeIndex); + } +} diff --git a/assets/snapsort/src/drag/group.ts b/assets/snapsort/src/drag/group.ts index 5e55a9fb..fac8cdc3 100644 --- a/assets/snapsort/src/drag/group.ts +++ b/assets/snapsort/src/drag/group.ts @@ -1,10 +1,9 @@ import type { BaseObject, dragStartProp } from "@snap-engine/core"; -import type { Container } from "../container"; import { buildDragLocation } from "../event-builders"; import type { DragLocation } from "../events"; import type { Item } from "../item"; import { resolveSortStrategy } from "./drop-strategy"; -import { DragSessionController } from "./session"; +import { DragSessionController, type DragInputStart } from "./session"; import { installDragSession } from "./session-store"; /** @internal Gather the consumer-selected drag run in logical document order. */ @@ -42,27 +41,46 @@ function sourceFor(item: Item): DragLocation { if (!container) throw new Error("Item has no parent container"); return buildDragLocation(container, index); } - -/** @internal Build, install, and begin a DragSession for an Item gesture. */ -export function beginItemDrag( +function beginDragSession( item: Item, - prop: dragStartProp, + start: DragInputStart, ): DragSessionController { item.takeRootSnapshot(); + const root = item.rootContainer; const group = collectSelectedDragGroup(root as unknown as Item, item); const pressedItem = findGroupAnchor(group, item); const strategy = resolveSortStrategy(root.config.mode); const sources = group.map(sourceFor); + const session = new DragSessionController( - root as Container, + root, group, sources, strategy, - prop, + start, pressedItem, ); + installDragSession(root, session); - session.begin(prop); + session.begin(); + return session; } +/** @internal Build, install, and begin a DragSession for an Item gesture. */ +export function beginItemDrag( + item: Item, + prop: dragStartProp, +): DragSessionController { + return beginDragSession(item, { + inputType: "pointer", + prop, + }); +} + +export function beginDirectItemDrag(item: Item): DragSessionController { + return beginDragSession(item, { + inputType: "direct", + initiatingItemId: item.itemId, + }); +} diff --git a/assets/snapsort/src/drag/insertion-marker.ts b/assets/snapsort/src/drag/insertion-marker.ts index 41d4c6a9..c6702827 100644 --- a/assets/snapsort/src/drag/insertion-marker.ts +++ b/assets/snapsort/src/drag/insertion-marker.ts @@ -261,6 +261,52 @@ function drop(session: DragSession): void { ); } +function directInsertionSnapshotIndex( + session: DragSession, + container: Container, + logicalIndex: number, +): number { + const snapshot = container.dragSnapshot; + + if (!snapshot) { + throw new Error( + "SnapSort: direct insertion requires a captured destination snapshot.", + ); + } + + const rawChildren = snapshot.children.filter((child) => !child.value.isGhost); + + const retainedChildren = rawChildren.filter( + (child) => !session.itemSet.has(child.value), + ); + + if ( + !Number.isInteger(logicalIndex) || + logicalIndex < 0 || + logicalIndex > retainedChildren.length + ) { + throw new RangeError( + "SnapSort: direct insertion index is outside the retained item slots.", + ); + } + + const nextRetained = retainedChildren[logicalIndex] ?? null; + + if (!nextRetained) { + return rawChildren.length; + } + + const snapshotIndex = rawChildren.indexOf(nextRetained); + + if (snapshotIndex === -1) { + throw new Error( + "SnapSort: retained insertion neighbor is missing from its snapshot.", + ); + } + + return snapshotIndex; +} + export class InsertionMarkerLifecycle implements DragLifecycleStrategy { readonly placementOccupiesFlowSlots = false; @@ -278,7 +324,7 @@ export class InsertionMarkerLifecycle implements DragLifecycleStrategy { async dragStart(session: DragSession): Promise { await startDragVisual(session); - await session.updateDropTarget(); + await session.initializeTarget(); } dragMove(session: DragSession): void { @@ -293,8 +339,16 @@ export class InsertionMarkerLifecycle implements DragLifecycleStrategy { return { container: pending.container, index: pending.index }; } - placementIndexFor(_session: DragSession, target: ResolvedDropTarget): number { - return target.index; + placementIndexFor(session: DragSession, target: ResolvedDropTarget): number { + if (session.input.inputType === "pointer") { + return target.index; + } + + return directInsertionSnapshotIndex( + session, + target.container, + target.index, + ); } async syncPlacement( diff --git a/assets/snapsort/src/drag/lifecycle.ts b/assets/snapsort/src/drag/lifecycle.ts index a355389e..dc0c7152 100644 --- a/assets/snapsort/src/drag/lifecycle.ts +++ b/assets/snapsort/src/drag/lifecycle.ts @@ -28,8 +28,8 @@ export interface DragLifecycleStrategy { * (ghost creation, detaching the item, styling). */ dragStart(session: DragSession): void | Promise; - /** WRITE_1 work specific to a pointer move. */ - dragMove(session: DragSession): void | Promise; + /** Synchronous visual work for one pointer or direct-input movement frame. */ + dragMove(session: DragSession): void; /** Current container/index the ghost logically occupies, * or null when there is none yet. */ diff --git a/assets/snapsort/src/drag/pointer-controller.ts b/assets/snapsort/src/drag/pointer-controller.ts new file mode 100644 index 00000000..bd15b951 --- /dev/null +++ b/assets/snapsort/src/drag/pointer-controller.ts @@ -0,0 +1,139 @@ +import type { + dragEndProp, + dragProp, + dragStartProp, +} from "@snap-engine/core"; +import type { ResolvedDropTarget } from "../algorithm"; +import type { DragSessionController } from "./session"; + +function freezePoint(point: { + x: number; + y: number; +}): Readonly<{ x: number; y: number }> { + return Object.freeze({ + x: point.x, + y: point.y, + }); +} + +export class PointerDragController { + readonly inputType = "pointer" as const; + readonly pointerId: number; + readonly start: Readonly<{ x: number; y: number }>; + readonly #session: DragSessionController; + + #pointer: Readonly<{ x: number; y: number }>; + #preparedTarget: ResolvedDropTarget | null = null; + #applyingScheduledMove = false; + + constructor( + session: DragSessionController, + prop: dragStartProp, + ) { + this.#session = session; + this.pointerId = prop.pointerId; + this.start = freezePoint(prop.start); + this.#pointer = this.start; + Object.freeze(this); + } + + get pointer(): Readonly<{ x: number; y: number }> { + return this.#pointer; + } + + /** @internal True while the scheduled final pointer move owns placement. */ + get applyingScheduledMove(): boolean { + return this.#applyingScheduledMove; + } + + ownsPointer(pointerId: number): boolean { + return pointerId === this.pointerId; + } + + updatePointer(prop: dragProp): boolean { + if (!this.ownsPointer(prop.pointerId)) { + return false; + } + + this.#pointer = freezePoint(prop.position); + return true; + } + + move(prop: dragProp): void { + if (!this.ownsPointer(prop.pointerId)) return; + + const session = this.#session; + const item = session.primaryItem; + const queueId = `drag-${item.id}`; + + item.schedule( + () => { + if (!this.#acceptsScheduledMove) return; + let completed = false; + try { + this.updatePointer(prop); + session.visualPointer = this.pointer; + if (session.strategy.lifecycle.placementOccupiesFlowSlots) { + this.#preparedTarget = session.resolvePointerTarget(); + session.prepareTarget(this.#preparedTarget); + } else { + session.stageTargetVisual(); + } + completed = true; + } finally { + if (!completed) session.scheduleErrorFinalizer(); + } + }, + { stage: "READ_1", queueId: `${queueId}-read` }, + ); + + item.schedule( + async () => { + if (!this.#acceptsScheduledMove) return; + let completed = false; + try { + this.updatePointer(prop); + session.visualPointer = this.pointer; + this.#applyingScheduledMove = true; + try { + const target = session.strategy.lifecycle + .placementOccupiesFlowSlots + ? this.#preparedTarget + : session.resolvePointerTarget(); + await session.applyTarget(target, true); + session.strategy.lifecycle.dragMove(session); + } finally { + this.#applyingScheduledMove = false; + } + completed = true; + } finally { + if (!completed) session.scheduleErrorFinalizer(); + } + }, + { stage: "WRITE_1", queueId }, + ); + + session.root.queueReadTree("READ_2", queueId); + } + + end(prop: dragEndProp): void { + if (!this.ownsPointer(prop.pointerId)) return; + + const session = this.#session; + if (prop.cancelled || session.phase === "pending") { + session.cancel(); + return; + } + if (session.phase !== "active") return; + + session.beginDrop(); + } + + get #acceptsScheduledMove(): boolean { + const session = this.#session; + return ( + session.phase === "active" || + (session.phase === "dropping" && !session.cancelled) + ); + } +} diff --git a/assets/snapsort/src/drag/pointer-preview.ts b/assets/snapsort/src/drag/pointer-preview.ts index 465356ca..6546ecb6 100644 --- a/assets/snapsort/src/drag/pointer-preview.ts +++ b/assets/snapsort/src/drag/pointer-preview.ts @@ -47,10 +47,22 @@ function frozenGroupGeometry(session: DragSession): GroupGeometry { /** @internal Current world-space rectangle of the single group preview. */ export function pointerPreviewRect(session: DragSession): GhostRect { + if (session.input.inputType === "direct") { + const directRect = session.input.visualGroupRect; + if (directRect) { + return { + x: directRect.x, + y: directRect.y, + width: directRect.width, + height: directRect.height, + }; + } + } + const group = frozenGroupGeometry(session); return { - x: group.x + session.pointer.x - session.start.x, - y: group.y + session.pointer.y - session.start.y, + x: group.x + session.visualPointer.x - session.visualStart.x, + y: group.y + session.visualPointer.y - session.visualStart.y, width: group.width, height: group.height, }; @@ -142,12 +154,18 @@ export function pointerPreviewMemberRects( const preview = previewItem ? readVisualRect(previewItem) : null; if (!preview) return session.items.map(() => null); - const group = frozenGroupGeometry(session); + const directGroup = + session.input.inputType === "direct" ? session.input.visualGroupRect : null; + const group = directGroup ?? frozenGroupGeometry(session); const scaleX = group.width > 0 ? preview.width / group.width : 1; const scaleY = group.height > 0 ? preview.height / group.height : 1; return session.items.map((item) => { - const box = session.dragBoxFor(item); - const start = session.dragVisualStart.get(item); + const directRect = + session.input.inputType === "direct" + ? session.input.visualRectFor(item.itemId) + : null; + const box = directRect ?? session.dragBoxFor(item); + const start = directRect ?? session.dragVisualStart.get(item); if (!start) { throw new Error( `SnapSort: participant "${item.itemId}" has no captured visual start.`, diff --git a/assets/snapsort/src/drag/session-store.ts b/assets/snapsort/src/drag/session-store.ts index 93c7a0e3..402d1b85 100644 --- a/assets/snapsort/src/drag/session-store.ts +++ b/assets/snapsort/src/drag/session-store.ts @@ -12,14 +12,18 @@ export function getDragSessionController( /** @internal */ export function getDragSession(root: Container): DragSession | null { - return getDragSessionController(root)?.handle ?? null; + return getDragSessionController(root); } -/** @internal */ +/** @internal Install the only active drag session for this root. */ export function installDragSession( root: Container, controller: DragSessionController, ): void { + if (controllers.has(root)) { + throw new Error("SnapSort: this root already has an active drag session."); + } + controllers.set(root, controller); } diff --git a/assets/snapsort/src/drag/session.ts b/assets/snapsort/src/drag/session.ts index 942712f5..c6e8711c 100644 --- a/assets/snapsort/src/drag/session.ts +++ b/assets/snapsort/src/drag/session.ts @@ -1,10 +1,5 @@ import type { AnimationObject } from "@snap-engine/core/animation"; -import type { - DomProperty, - GestureHandoffControl, - dragStartProp, - dragProp, -} from "@snap-engine/core"; +import type { DomProperty, dragStartProp } from "@snap-engine/core"; import type { Container } from "../container"; import type { Item } from "../item"; import { reconcileRootTreeState, rootHasItemId } from "../internal/tree-state"; @@ -41,29 +36,38 @@ import { import type { SortStrategy } from "./drop-strategy"; import { resetItemVisual, restoreActiveItems } from "./item-visual"; import { clearDragSession } from "./session-store"; +import { PointerDragController } from "./pointer-controller"; +import { + cancelDirectMoveAnimation, + DirectDragController, +} from "./direct-controller"; export type DragSessionStatus = "pending" | "active" | "dropping" | "ended"; export type GhostChannel = "target" | "source" | "pointer"; +export type DragInputController = PointerDragController | DirectDragController; + +/** @internal Input-specific information needed to start one shared session. */ +export type DragInputStart = + | { + readonly inputType: "pointer"; + readonly prop: dragStartProp; + } + | { + readonly inputType: "direct"; + readonly initiatingItemId: ItemId; + }; + export interface DragSession { readonly root: Container; - readonly pointerId: number; + readonly input: DragInputController; readonly items: readonly Item[]; readonly sources: readonly DragLocation[]; readonly pressedItem: Item; readonly primaryItem: Item; - readonly start: Readonly<{ x: number; y: number }>; - readonly pointer: Readonly<{ x: number; y: number }>; readonly status: DragSessionStatus; dragVisual: DragVisual; dropEffect: DropEffect; - /** - * @deprecated This escape hatch predates the recommended move-and-backfill - * copying recipe. SnapSort retains it temporarily for compatibility, but it - * has no supported first-party use case and may be removed in a future - * release. - */ - handoff(replacements: readonly Item[]): void; } /** @internal Placement the active lifecycle is currently targeting. */ @@ -93,8 +97,14 @@ interface DropTargetUpdate { readonly shouldClear: boolean; } -function freezePoint(point: { x: number; y: number }) { - return Object.freeze({ x: point.x, y: point.y }); +function freezePoint(point: { + x: number; + y: number; +}): Readonly<{ x: number; y: number }> { + return Object.freeze({ + x: point.x, + y: point.y, + }); } function freezeLocation(location: DragLocation): DragLocation { @@ -109,68 +119,14 @@ function freezePlacement( return Object.freeze({ container, index, insertion }); } -class PublicDragSession implements DragSession { - readonly #controller: DragSessionController; - - constructor(controller: DragSessionController) { - this.#controller = controller; - Object.freeze(this); - } - - get root() { - return this.#controller.root; - } - get pointerId() { - return this.#controller.pointerId; - } - get items() { - return this.#controller.items; - } - get sources() { - return this.#controller.sources; - } - get pressedItem() { - return this.#controller.pressedItem; - } - get primaryItem() { - return this.#controller.primaryItem; - } - get start() { - return this.#controller.start; - } - get pointer() { - return this.#controller.pointer; - } - get status() { - return this.#controller.publicStatus; - } - get dragVisual() { - return this.#controller.dragVisual; - } - set dragVisual(value: DragVisual) { - this.#controller.dragVisual = value; - } - get dropEffect() { - return this.#controller.dropEffect; - } - set dropEffect(value: DropEffect) { - this.#controller.dropEffect = value; - } - handoff(replacements: readonly Item[]): void { - this.#controller.handoff(replacements); - } -} - /** - * @internal Runtime controller for one drag gesture. Its `handle` is the only - * session object exposed through public callbacks and `root.dragSession`. + * @internal Runtime controller maintaining drag events and states, + * newly created for every drag gesture. */ -export class DragSessionController { - readonly handle: DragSession; +export class DragSessionController implements DragSession { readonly root: Container; - /** Pointer id driving this drag (from `dragStartProp`). */ - readonly pointerId: number; - readonly #handoffTo: GestureHandoffControl["handoffTo"]; + /** Input-specific controller created and owned by this session. */ + readonly input: DragInputController; /** * The items currently receiving this drag. Stable except across `handoff`. * Ordered by the original run's document order (lowest first). @@ -191,20 +147,57 @@ export class DragSessionController { /** Per-item constant visual offset (relative to `pressedItem`) so companions preview the collapsed run while hoisted. */ readonly groupVisualOffsets: Map = new Map(); readonly strategy: SortStrategy; - status: DragSessionStatus = "pending"; + phase: DragSessionStatus = "pending"; /** @internal True when a lifecycle is dropping only to unwind a failed drag. */ cancelled = false; - #runningScheduledPointerMove = false; - #preparedFlowDropTargetUpdate: DropTargetUpdate | null = null; #preparedFlowReorderAnimation: PreparedReorderAnimation | null = null; - /** Status exposed through the public handle during a logically pre-drop move. */ - get publicStatus(): DragSessionStatus { - return this.#runningScheduledPointerMove && - this.status === "dropping" && + /** Status exposed during a logically pre-drop move. */ + get status(): DragSessionStatus { + return this.pointerInput?.applyingScheduledMove === true && + this.phase === "dropping" && !this.cancelled ? "active" - : this.status; + : this.phase; + } + + /** @internal Active pointer input, or null for a direct session. */ + get pointerInput(): PointerDragController | null { + return this.input.inputType === "pointer" ? this.input : null; + } + + get pointerId(): number { + const input = this.pointerInput; + + if (!input) { + throw new Error("DragSession: a direct drag has no pointer id."); + } + + return input.pointerId; + } + + get start(): Readonly<{ x: number; y: number }> { + const input = this.pointerInput; + + if (!input) { + throw new Error( + "DragSession: a direct drag has no public pointer start.", + ); + } + + return input.start; + } + + get pointer(): Readonly<{ x: number; y: number }> { + const input = this.pointerInput; + + if (!input) { + throw new Error( + "DragSession: a direct drag has no public pointer position.", + ); + } + + return input.pointer; } /** @@ -218,7 +211,7 @@ export class DragSessionController { } set dropEffect(value: DropEffect) { - if (this.publicStatus !== "pending" && this.publicStatus !== "active") { + if (this.status !== "pending" && this.status !== "active") { throw new Error( "DragSession.dropEffect can only be changed before dropping begins.", ); @@ -242,7 +235,7 @@ export class DragSessionController { } set dragVisual(value: DragVisual) { - if (this.status !== "pending") { + if (this.phase !== "pending") { throw new Error( "DragSession.dragVisual can only be changed during onDragStart.", ); @@ -255,9 +248,24 @@ export class DragSessionController { this.#dragVisual = value; } - start: Readonly<{ x: number; y: number }>; - pointer: Readonly<{ x: number; y: number }>; - offset: { x: number; y: number } = { x: 0, y: 0 }; + #visualStart: Readonly<{ x: number; y: number }>; + #visualPointer: Readonly<{ x: number; y: number }>; + visualOffset: { x: number; y: number } = { + x: 0, + y: 0, + }; + + get visualStart(): Readonly<{ x: number; y: number }> { + return this.#visualStart; + } + + get visualPointer(): Readonly<{ x: number; y: number }> { + return this.#visualPointer; + } + + set visualPointer(value: Readonly<{ x: number; y: number }>) { + this.#visualPointer = freezePoint(value); + } /** * Ghosts currently live for this drag, keyed by role. Most lifecycles only @@ -317,10 +325,9 @@ export class DragSessionController { items: Item[], sources: DragLocation[], strategy: SortStrategy, - prop: dragStartProp, + start: DragInputStart, pressedItem: Item = items[0], ) { - this.handle = new PublicDragSession(this); this.root = root; this.sources = Object.freeze(sources.map(freezeLocation)); this.snapshotItemSet = new Set(items); @@ -332,10 +339,18 @@ export class DragSessionController { : strategy.mode === "swap" ? "preview" : "item"; - this.pointerId = prop.pointerId; - this.#handoffTo = prop.handoffTo; - this.start = freezePoint(prop.start); - this.pointer = freezePoint(prop.start); + + if (start.inputType === "pointer") { + const input = new PointerDragController(this, start.prop); + this.input = input; + this.#visualStart = input.start; + this.#visualPointer = input.pointer; + } else { + const initialVisualPoint = freezePoint({ x: 0, y: 0 }); + this.input = new DirectDragController(this, start.initiatingItemId); + this.#visualStart = initialVisualPoint; + this.#visualPointer = initialVisualPoint; + } } #setParticipants( @@ -362,101 +377,6 @@ export class DragSessionController { for (const item of items) this.#touchedItems.add(item); } - /** - * Transfer this gesture to an already-mounted parallel run. Handoff changes - * input/session ownership only: it never creates, destroys, inserts, removes, - * or otherwise manages application state for either run. Public `sources` - * continue to describe where the gesture began. Call it synchronously from - * `onDragStart`, before the selected drag visual is activated. - * - * Validation and native input transfer complete before session fields are - * changed, so a rejected handoff leaves the current participants unchanged. - */ - handoff(replacements: readonly Item[]): void { - if (this.status !== "pending") { - throw new Error( - "DragSession.handoff can only be called during onDragStart.", - ); - } - if (replacements.length !== this.items.length) { - throw new Error( - "DragSession.handoff: replacements must be parallel to the dragged items.", - ); - } - - const origins = this.items; - const unique = new Set(replacements); - if (unique.size !== replacements.length) { - throw new Error("DragSession.handoff: replacements must be unique."); - } - if (replacements.some((replacement) => this.itemSet.has(replacement))) { - throw new Error( - "DragSession.handoff: replacements must not include the current dragged items.", - ); - } - - const replacementSources = replacements.map((replacement) => { - if ( - replacement.engine !== this.root.engine || - replacement.isDeleteRequested - ) { - throw new Error( - "DragSession.handoff: every replacement must be live in the session engine.", - ); - } - if (replacement.isGhost) { - throw new Error( - "DragSession.handoff: pointer previews and other Ghosts cannot receive an Item handoff.", - ); - } - if (replacement.rootContainer !== this.root) { - throw new Error( - "DragSession.handoff: every replacement must belong to the session root.", - ); - } - const { container, index } = replacement.getIndexAndContainer(); - if (!container || index < 0) { - throw new Error( - "DragSession.handoff: every replacement must be attached to a container.", - ); - } - const element = replacement.element; - if ( - !element?.isConnected || - !container.element || - element.parentElement !== container.element - ) { - throw new Error( - "DragSession.handoff: every replacement must have a connected element directly inside its container.", - ); - } - return buildDragLocation(container, index); - }); - - const pressedIndex = origins.indexOf(this.pressedItem); - const nextPressedItem = - replacements[pressedIndex === -1 ? 0 : pressedIndex]; - - // Native capture can reject a stale destination. Transfer before changing - // SnapSort bookkeeping so that failure is atomic from the session's side. - this.#handoffTo(nextPressedItem); - - replacements.forEach((replacement, i) => { - replacement.adoptDragSnapshotFrom(origins[i]); - const visualStart = this.dragVisualStart.get(origins[i]); - if (visualStart) { - this.dragVisualStart.set(replacement, { ...visualStart }); - } - const groupOffset = this.groupVisualOffsets.get(origins[i]); - if (groupOffset) { - this.groupVisualOffsets.set(replacement, { ...groupOffset }); - } - this.#touchedItems.add(replacement); - }); - - this.#setParticipants(replacements, replacementSources, nextPressedItem); - } - /** The run head — lowest original index, first element of `items`. Used as the singular `item` in backwards-compatible event fields. */ get primaryItem(): Item { return this.items[0]; @@ -513,15 +433,13 @@ export class DragSessionController { } /** Schedules the READ_1/WRITE_1 work for starting a drag; see FlowGhostLifecycle/InsertionMarkerLifecycle for the mode-specific WRITE_1 continuation. */ - begin(prop: dragStartProp): void { + begin(): void { const item = this.pressedItem; const root = this.root; item.schedule( () => { if (this.#isEnded()) return; - this.pointer = freezePoint(prop.start); - this.start = freezePoint(prop.start); for (const member of this.items) { const visual = member.readDom({ unapplyTransform: false }); this.dragVisualStart.set(member, { x: visual.x, y: visual.y }); @@ -530,13 +448,23 @@ export class DragSessionController { x: item.worldTransform.x, y: item.worldTransform.y, }; - this.offset = { - x: prop.start.x - itemVisualStart.x, - y: prop.start.y - itemVisualStart.y, - }; + const pointerInput = this.pointerInput; + if (pointerInput) { + this.visualOffset = { + x: pointerInput.start.x - itemVisualStart.x, + y: pointerInput.start.y - itemVisualStart.y, + }; + } else { + this.#visualStart = freezePoint(itemVisualStart); + this.#visualPointer = this.#visualStart; + this.visualOffset = { x: 0, y: 0 }; + } root.readDragSnapshotTree(); root.captureDragSnapshotTree(); this.groupDims = this.#computeGroupDims(); + if (this.input.inputType === "direct") { + this.input.activate(); + } }, { stage: "READ_1", queueId: `drag-start-offset-${item.id}` }, ); @@ -555,7 +483,7 @@ export class DragSessionController { } this.strategy.lifecycle.validateStart(this); - this.status = "active"; + this.phase = "active"; await this.strategy.lifecycle.dragStart(this); if (this.#isEnded()) { this.#clearSessionState(); @@ -576,76 +504,51 @@ export class DragSessionController { ); } - pointerMove(prop: dragProp): void { - const item = this.primaryItem; - item.schedule( - () => { - if (!this.#acceptsScheduledPointerMove()) return; - let completed = false; - try { - this.pointer = freezePoint(prop.position); - const ghostItem = this.ghostsByChannel.get("target"); - if (ghostItem) stageVisualRectBeforeMutation(ghostItem); - if (this.strategy.lifecycle.placementOccupiesFlowSlots) { - this.#prepareFlowDropTargetUpdate(); - } - completed = true; - } finally { - if (!completed) this.scheduleErrorFinalizer(); - } - }, - { stage: "READ_1", queueId: `drag-read-${item.id}` }, - ); - item.schedule( - async () => { - if (!this.#acceptsScheduledPointerMove()) return; - let completed = false; - try { - this.pointer = freezePoint(prop.position); - this.#runningScheduledPointerMove = true; - try { - if (this.strategy.lifecycle.placementOccupiesFlowSlots) { - await this.#applyPreparedFlowDropTargetUpdate(); - } else { - await this.updateDropTarget(); - } - await this.strategy.lifecycle.dragMove(this); - } finally { - this.#runningScheduledPointerMove = false; - } - completed = true; - } finally { - if (!completed) this.scheduleErrorFinalizer(); - } - }, - { stage: "WRITE_1", queueId: `drag-${item.id}` }, - ); - this.root.queueReadTree("READ_2", `drag-${item.id}`); + #isEnded(): boolean { + return this.phase === "ended"; } - #acceptsScheduledPointerMove(): boolean { - // A normal pointerup queues drop work after the final move in the same - // frame; cancellation must still suppress any queued move immediately. - return ( - this.status === "active" || - (this.status === "dropping" && !this.cancelled) - ); + #cancelInputAnimation(): void { + if (this.input.inputType === "direct") { + cancelDirectMoveAnimation(this.input); + } } - #isEnded(): boolean { - return this.status === "ended"; + /** @internal Begin a successful drop exactly once. */ + beginDrop(): boolean { + if (this.phase !== "active") { + return false; + } + + this.#cancelInputAnimation(); + this.phase = "dropping"; + this.dragTransformSyncAnimation?.cancel(); + this.dragTransformSyncAnimation = null; + + let completed = false; + + try { + this.strategy.lifecycle.drop(this); + completed = true; + return true; + } finally { + if (!completed) { + this.scheduleErrorFinalizer(); + } + } } /** @internal Unwinds an input-cancelled drag without committing a drop. */ cancel(): void { - if (this.status === "dropping" || this.status === "ended") return; + if (this.phase === "dropping" || this.phase === "ended") return; + this.#cancelInputAnimation(); this.cancelled = true; - if (this.status === "pending") { + if (this.phase === "pending") { this.#clearSessionState(); return; } - this.status = "dropping"; + this.phase = "dropping"; this.dragTransformSyncAnimation?.cancel(); this.dragTransformSyncAnimation = null; this.#dropEffect = "none"; @@ -666,32 +569,33 @@ export class DragSessionController { /** @internal Mark a failed task and defer cleanup to the engine's error boundary. */ scheduleErrorFinalizer(): void { - if (this.status === "ended") return; - const shouldFireDragEnd = this.status !== "pending"; + if (this.phase === "ended") return; + const shouldFireDragEnd = this.phase !== "pending"; this.#markFailedDrop(); this.#scheduleFailureFinalizer(shouldFireDragEnd); } #markFailedDrop(): void { if (this.#isEnded()) return; + this.#cancelInputAnimation(); this.cancelled = true; - this.status = "dropping"; + this.phase = "dropping"; this.#dropEffect = "none"; this.dragTransformSyncAnimation?.cancel(); this.dragTransformSyncAnimation = null; } #clearSessionState(): void { + this.#cancelInputAnimation(); this.dragTransformSyncAnimation?.cancel(); this.dragTransformSyncAnimation = null; - this.status = "ended"; + this.phase = "ended"; clearDragSession(this.root, this); this.dragCoordinateParent.clear(); this.dragLayoutPosition.clear(); this.dragVisualStart.clear(); this.groupVisualOffsets.clear(); this.groupDims = null; - this.#preparedFlowDropTargetUpdate = null; this.#preparedFlowReorderAnimation = null; this.pendingPlacement = null; this.resolvedDropTarget = null; @@ -718,11 +622,19 @@ export class DragSessionController { } finally { this.#clearSessionState(); } + this.#fireDragEnd(destination); + } + + #fireDragEnd(destination: DragLocation | null): void { fireOptionalMutation( this.root, this.root.callbacks?.onDragEnd, buildDragEndEvent(this, destination), ); + + if (this.input.inputType === "direct") { + this.input.scheduleFocusRestoration(); + } } #scheduleFailureFinalizer(shouldFireDragEnd: boolean): void { @@ -756,39 +668,85 @@ export class DragSessionController { if (!shouldFireDragEnd) return; finalizer.addCallback(() => { if (!finalized) return; - fireOptionalMutation( - this.root, - this.root.callbacks?.onDragEnd, - buildDragEndEvent(this, null), - ); + this.#fireDragEnd(null); }); } - /** - * Compute the current drop target and move the ghost when the target changes. - * Mode-specific translation/comparison is delegated to the lifecycle strategy; - * this method owns the shared "did the target change" bookkeeping and the - * `onDropTargetChange` callback. - */ - async updateDropTarget(): Promise { - const update = this.#resolveDropTargetUpdate(); - if (!update) return; - await this.#applyDropTargetUpdate(update); + /** @internal Initialize placement feedback for the active input method. */ + async initializeTarget(): Promise { + if (this.input.inputType === "pointer") { + await this.applyTarget(this.resolvePointerTarget(), true); + return; + } + + // The direct swap home candidate represents no prospective swap. + if (this.strategy.mode === "swap") { + return; + } + + await this.applyTarget(this.input.currentCandidate?.target ?? null, false); } - #resolveDropTargetUpdate(): DropTargetUpdate | null { + /** @internal Resolve the current real pointer through the active strategy. */ + resolvePointerTarget(): ResolvedDropTarget | null { const item = this.primaryItem; - const root = this.root; - // Defensive guard for a drag-start/drag race: the deeper fix should live in - // the engine scheduler as built-in debounce/coalescing support for input - // updates that depend on earlier READ/WRITE phases. - if (!root.hasDragSnapshotTree() || !item.dragSnapshot) { - return null; + if (!this.root.hasDragSnapshotTree() || !item.dragSnapshot) return null; + return this.strategy.dropTarget.resolve(item, this.root, this); + } + + /** @internal Stage an existing target visual before structural mutation. */ + stageTargetVisual(): void { + const ghost = this.ghostsByChannel.get("target"); + if (ghost) stageVisualRectBeforeMutation(ghost); + } + + /** @internal Capture pre-mutation animation geometry for an exact target. */ + prepareTarget(target: ResolvedDropTarget | null): void { + this.stageTargetVisual(); + + this.#preparedFlowReorderAnimation = null; + + if (!this.strategy.lifecycle.placementOccupiesFlowSlots) { + return; } + const update = this.#dropTargetUpdateFor(target); + + if (!update.logicalChanged) { + return; + } + + const animationContainer = + update.placement?.container ?? + update.previousPlacement?.container ?? + null; + + if (!animationContainer) { + return; + } + + this.#preparedFlowReorderAnimation = prepareReorderAnimation( + this.primaryItem, + animationContainer, + this.items, + ); + } + + /** @internal Apply one already-selected target through the shared lifecycle. */ + async applyTarget( + target: ResolvedDropTarget | null, + updatePointerHover: boolean, + ): Promise { + await this.#applyDropTargetUpdate( + this.#dropTargetUpdateFor(target), + updatePointerHover, + ); + } + + #dropTargetUpdateFor(target: ResolvedDropTarget | null): DropTargetUpdate { const lifecycle = this.strategy.lifecycle; - const target = this.strategy.dropTarget.resolve(item, root, this); const previousPlacement = lifecycle.currentPlacement(this); + if (!target) { return { target: null, @@ -810,7 +768,9 @@ export class DragSessionController { !previousPlacement || placement.container !== previousPlacement.container || placement.index !== previousPlacement.index; + const previousInsertion = this.pendingPlacement?.insertion ?? null; + const presentationChanged = previousInsertion === null || placement.insertion === null ? previousInsertion !== placement.insertion @@ -828,8 +788,10 @@ export class DragSessionController { shouldClear: false, }; } - - async #applyDropTargetUpdate(update: DropTargetUpdate): Promise { + async #applyDropTargetUpdate( + update: DropTargetUpdate, + updatePointerHover = true, + ): Promise { const lifecycle = this.strategy.lifecycle; const { previousPlacement, placement } = update; if (!placement) { @@ -846,12 +808,16 @@ export class DragSessionController { ); this.#fireDropTargetChange(previousPlacement, null); } - this.#updateHoveredItem(null); + if (updatePointerHover) { + this.#updateHoveredItem(null); + } return; } this.resolvedDropTarget = update.target; - this.#updateHoveredItem(placement.container); + if (updatePointerHover) { + this.#updateHoveredItem(placement.container); + } if (update.logicalChanged || update.presentationChanged) { await lifecycle.syncPlacement(this, placement); this.#invalidateVisualGeometry( @@ -870,34 +836,6 @@ export class DragSessionController { lifecycle.afterPlacementSync(this); } - #prepareFlowDropTargetUpdate(): void { - this.#preparedFlowDropTargetUpdate = null; - this.#preparedFlowReorderAnimation = null; - - const update = this.#resolveDropTargetUpdate(); - if (!update) return; - this.#preparedFlowDropTargetUpdate = update; - if (!update.logicalChanged) return; - - const animationContainer = - update.placement?.container ?? - update.previousPlacement?.container ?? - null; - if (!animationContainer) return; - this.#preparedFlowReorderAnimation = prepareReorderAnimation( - this.primaryItem, - animationContainer, - this.items, - ); - } - - async #applyPreparedFlowDropTargetUpdate(): Promise { - const update = this.#preparedFlowDropTargetUpdate; - this.#preparedFlowDropTargetUpdate = null; - if (!update) return; - await this.#applyDropTargetUpdate(update); - } - /** @internal Consume the READ_1 FLIP capture for this flow mutation. */ consumePreparedFlowReorderAnimation(): PreparedReorderAnimation | null { const prepared = this.#preparedFlowReorderAnimation; diff --git a/assets/snapsort/src/drag/swap.ts b/assets/snapsort/src/drag/swap.ts index b639c776..0aece795 100644 --- a/assets/snapsort/src/drag/swap.ts +++ b/assets/snapsort/src/drag/swap.ts @@ -69,14 +69,45 @@ function drop(session: DragSession): void { } | null = null; const resolveDropTarget = () => { - if (session.cancelled) return null; + if (session.cancelled) { + return null; + } + + if (session.input.inputType === "direct") { + const candidate = session.input.currentCandidate; + + if (!candidate || candidate.kind !== "swap") { + return null; + } + + const targetItem = root.findItemById(candidate.targetItemId); + + if (!targetItem || targetItem.isDeleteRequested) { + return null; + } + + const location = targetItem.getIndexAndContainer(); + + if (!location.container || location.container.rootContainer !== root) { + return null; + } + + return { + container: location.container, + index: location.index, + item: targetItem, + }; + } + const pending = session.pendingPlacement; const container = pending?.container ?? null; const index = pending?.index ?? -1; + const targetItem = container && index >= 0 && index < container.itemOrderedList.length ? container.itemOrderedList[index] : null; + return container && targetItem ? { container, index, item: targetItem } : null; @@ -87,7 +118,9 @@ function drop(session: DragSession): void { draggedAnimation.first = captureDropOriginRects(session)[0] ?? null; dropTarget = resolveDropTarget(); - if (!dropTarget || dropTarget.item === item) return; + if (!dropTarget || dropTarget.item.itemId === draggedItemId) { + return; + } displacedAnimation.item = dropTarget.item; displacedAnimation.itemId = dropTarget.item.itemId; displacedAnimation.first = readVisualRect(dropTarget.item); @@ -113,13 +146,19 @@ function drop(session: DragSession): void { const bContainer = targetLocation?.container ?? null; const bIndex = targetLocation?.index ?? -1; - let destination: DragLocation | null = null; + const source = session.sources[0] ?? null; + + let destination: DragLocation | null = + session.cancelled || !source + ? null + : buildDragLocation(source.container, source.index); + draggedAnimation.config = animationConfigFor( bContainer ?? aLocation.container, "drop", ); - if (bContainer && targetItem && targetItem !== item) { + if (bContainer && targetItem && targetItem.itemId !== draggedItemId) { destination = buildDragLocation(bContainer, bIndex); } @@ -127,7 +166,7 @@ function drop(session: DragSession): void { aLocation.container && bContainer && targetItem && - targetItem !== item && + targetItem.itemId !== draggedItemId && session.dropEffect === "move" ) { const aContainer = aLocation.container; @@ -213,8 +252,7 @@ function drop(session: DragSession): void { if (!displacedAnimation.item || !displacedAnimation.itemId) return; const currentDisplacedItem = - root.findItemById(displacedAnimation.itemId) ?? - displacedAnimation.item; + root.findItemById(displacedAnimation.itemId) ?? displacedAnimation.item; displacedAnimation.element = currentDisplacedItem.element?.isConnected ? currentDisplacedItem.element : null; @@ -260,8 +298,12 @@ export class SwapLifecycle implements DragLifecycleStrategy { async dragStart(session: DragSession): Promise { await startDragVisual(session); - if (session.dragVisual === "preview") updateDragVisual(session); - await session.updateDropTarget(); + + if (session.dragVisual === "preview") { + updateDragVisual(session); + } + + await session.initializeTarget(); } dragMove(session: DragSession): void { diff --git a/assets/snapsort/src/event-builders.ts b/assets/snapsort/src/event-builders.ts index da9ec9c8..d979740b 100644 --- a/assets/snapsort/src/event-builders.ts +++ b/assets/snapsort/src/event-builders.ts @@ -101,7 +101,7 @@ export function buildGhostState( ghostItem: Item, ): GhostState { const base: GhostStateBase = { - session: session.handle, + session, original, originalItemId: original.itemId, originalMetadata: original.metadata, @@ -318,7 +318,7 @@ export function buildGhostRemoveEvent(state: GhostState): GhostRemoveEvent { export function buildDragStartEvent(session: DragSession): DragStartEvent { return { - session: session.handle, + session, ...buildItemRunEvent(session.items), element: session.primaryItem.element, source: session.sources[0], @@ -331,7 +331,7 @@ export function buildDragEndEvent( destination: DragLocation | null, ): DragEndEvent { return { - session: session.handle, + session, ...buildItemRunEvent(session.items), element: session.primaryItem.element, source: session.sources[0], @@ -346,7 +346,7 @@ export function buildDropTargetChangeEvent( current: DragLocation | null, ): DropTargetChangeEvent { return { - session: session.handle, + session, ...buildItemRunEvent(session.items), previous, current, diff --git a/assets/snapsort/src/index.ts b/assets/snapsort/src/index.ts index 214e3f6a..07cbf8f7 100644 --- a/assets/snapsort/src/index.ts +++ b/assets/snapsort/src/index.ts @@ -69,5 +69,14 @@ export type { LayoutMainAxisAlign } from "./layout"; export { Item } from "./item"; export type { ItemOptions } from "./item"; export type { ItemId, ItemMetadata, ItemSnapshot } from "./snapshot"; -export type { DragSession, DragSessionStatus } from "./drag/session"; +export type { + DragInputController, + DragSession, + DragSessionStatus, +} from "./drag/session"; export type { SortMode } from "./drag/drop-strategy"; +export { KeyboardDragController } from "./keyboard-controller"; +export type { + KeyboardDragBindings, + KeyboardDragControllerOptions, +} from "./keyboard-controller"; diff --git a/assets/snapsort/src/item.ts b/assets/snapsort/src/item.ts index 5337ed03..8086e1dd 100644 --- a/assets/snapsort/src/item.ts +++ b/assets/snapsort/src/item.ts @@ -40,9 +40,12 @@ import { fireItemMove, fireItemRemove, } from "./mutation"; -import type { DragSessionController as DragSession } from "./drag/session"; +import type { + DragSession as PublicDragSession, + DragSessionController as DragSession, +} from "./drag/session"; import { getDragSessionController } from "./drag/session-store"; -import { beginItemDrag } from "./drag/group"; +import { beginDirectItemDrag, beginItemDrag } from "./drag/group"; import { assertCanPlaceItems, detachItem, @@ -379,7 +382,10 @@ export class Item extends ElementObject { get dragPointerPosition(): { x: number; y: number } | null { const session = getDragSessionController(this.rootContainer); if (!session || !this.#dragSnapshot) return null; - return { x: session.pointer.x, y: session.pointer.y }; + return { + x: session.pointer.x, + y: session.pointer.y, + }; } /** @@ -389,11 +395,16 @@ export class Item extends ElementObject { get dragPositionX(): number { const session = getDragSessionController(this.rootContainer); if (!session || !this.#dragSnapshot) return this.worldTransform.x; + if (session.input.inputType === "direct") { + return ( + session.input.visualRectFor(this.#itemId)?.x ?? this.worldTransform.x + ); + } const visualStart = session.dragVisualStart.get(this); return ( (visualStart?.x ?? this.#dragSnapshot.box.x) + - session.pointer.x - - session.start.x + session.visualPointer.x - + session.visualStart.x ); } @@ -404,11 +415,16 @@ export class Item extends ElementObject { get dragPositionY(): number { const session = getDragSessionController(this.rootContainer); if (!session || !this.#dragSnapshot) return this.worldTransform.y; + if (session.input.inputType === "direct") { + return ( + session.input.visualRectFor(this.#itemId)?.y ?? this.worldTransform.y + ); + } const visualStart = session.dragVisualStart.get(this); return ( (visualStart?.y ?? this.#dragSnapshot.box.y) + - session.pointer.y - - session.start.y + session.visualPointer.y - + session.visualStart.y ); } @@ -572,32 +588,6 @@ export class Item extends ElementObject { return snapshot; } - /** - * Give this item a frozen drag snapshot copied from another item's, keyed to - * this item. Used by `DragSession.handoff` so a replacement preserves the - * active gesture's drop prediction and pointer-follow geometry. - * - * @param source Item whose drag snapshot geometry to adopt. - * @internal - */ - adoptDragSnapshotFrom(source: Item): void { - const src = source.#dragSnapshot; - if (!src) return; - this.#dragSnapshot = { - value: this, - itemId: this.itemId, - metadata: Object.freeze({ ...this.#metadata }), - direction: src.direction, - mainAxisAlign: src.mainAxisAlign, - layoutModel: src.layoutModel, - wrap: src.wrap, - stretchItems: src.stretchItems, - locked: this.#locked, - box: cloneDomProperty(src.box), - children: [], - }; - } - /** * Clear frozen drag snapshots from this subtree after drag end. * @@ -745,14 +735,14 @@ export class Item extends ElementObject { */ scheduleWriteDrag() { const session = getDragSessionController(this.rootContainer); - if (!session || session.status !== "active") return; + if (!session || session.phase !== "active") return; const parentItem = session.dragCoordinateParent.get(this) ?? null; this.schedule( async () => { if ( getDragSessionController(this.rootContainer) !== session || - session.status !== "active" + session.phase !== "active" ) { return; } @@ -784,7 +774,7 @@ export class Item extends ElementObject { const session = getDragSessionController(this.rootContainer); if ( !session || - session.status !== "active" || + session.phase !== "active" || (expectedSession && session !== expectedSession) ) { return; @@ -800,21 +790,42 @@ export class Item extends ElementObject { // Account for offsets if the container is being animated. const ancestorOffset = ancestorVisualOffset(parentItem); + const directRect = + session.input.inputType === "direct" + ? session.input.visualRectFor(this.#itemId) + : null; + + if (directRect) { + this.style = { + width: `${directRect.width}px`, + height: `${directRect.height}px`, + }; + this.worldTransform.x = + directRect.x - layoutPosition.x - ancestorOffset.x; + this.worldTransform.y = + directRect.y - layoutPosition.y - ancestorOffset.y; + this.writeDom(); + this.writeTransform(); + this.rootContainer.invalidateVisualGeometry([this], "drag"); + return; + } + const groupOffset = session.groupVisualOffsets.get(this) ?? { x: 0, y: 0, }; this.worldTransform.x = - session.pointer.x - + session.visualPointer.x - layoutPosition.x - ancestorOffset.x - - session.offset.x + + session.visualOffset.x + groupOffset.x; + this.worldTransform.y = - session.pointer.y - + session.visualPointer.y - layoutPosition.y - ancestorOffset.y - - session.offset.y + + session.visualOffset.y + groupOffset.y; this.writeTransform(); @@ -1087,6 +1098,32 @@ export class Item extends ElementObject { } } + /** + * Begin a direct drag without creating a pointer gesture. + * + * Returns null when this item cannot safely start a drag. + */ + beginDirectDrag(): PublicDragSession | null { + const location = this.getIndexAndContainer(); + const container = location.container; + + if (!container || this.#locked || this.#isGhost || this.isDeleteRequested) { + return null; + } + + const rootContainer = container.rootContainer; + const root = rootContainer as unknown as Item; + + if ( + getDragSessionController(rootContainer) || + root.#hasPendingProgrammaticMutation() + ) { + return null; + } + + return beginDirectItemDrag(this); + } + /** * Called when a drag operation starts. * @param prop @@ -1113,8 +1150,8 @@ export class Item extends ElementObject { drag(prop: dragProp) { if (prop.objectId !== this.id) return; const session = getDragSessionController(this.rootContainer); - if (!session || session.status !== "active") return; - session.pointerMove(prop); + if (!session || session.phase !== "active") return; + session.pointerInput?.move(prop); } dragEnd(prop: dragEndProp) { @@ -1127,15 +1164,7 @@ export class Item extends ElementObject { if (this.element) delete this.element.dataset.snapsortDragging; return; } - if (prop.cancelled || session.status === "pending") { - session.cancel(); - return; - } - if (session.status !== "active") return; - session.status = "dropping"; - session.dragTransformSyncAnimation?.cancel(); - session.dragTransformSyncAnimation = null; - session.strategy.lifecycle.drop(session); + session.pointerInput?.end(prop); } destroy(removeElement: boolean = true) { diff --git a/assets/snapsort/src/keyboard-controller.ts b/assets/snapsort/src/keyboard-controller.ts new file mode 100644 index 00000000..814a56ca --- /dev/null +++ b/assets/snapsort/src/keyboard-controller.ts @@ -0,0 +1,220 @@ +import type { keyDownProp } from "@snap-engine/core"; +import type { Container } from "./container"; +import { Item } from "./item"; +import type { DragSessionController } from "./drag/session"; +import type { DirectDragController } from "./drag/direct-controller"; +import { getDragSessionController } from "./drag/session-store"; + +export interface KeyboardDragBindings { + readonly liftDrop?: readonly string[]; + readonly cancel?: readonly string[]; + readonly previous?: Readonly<{ + column?: readonly string[]; + row?: readonly string[]; + }>; + readonly next?: Readonly<{ + column?: readonly string[]; + row?: readonly string[]; + }>; +} + +export interface KeyboardDragControllerOptions { + readonly bindings?: KeyboardDragBindings; +} + +interface ResolvedKeyboardDragBindings { + readonly liftDrop: ReadonlySet; + readonly cancel: ReadonlySet; + readonly previous: Readonly<{ + column: ReadonlySet; + row: ReadonlySet; + }>; + readonly next: Readonly<{ + column: ReadonlySet; + row: ReadonlySet; + }>; +} + +const defaultBindings = Object.freeze({ + liftDrop: Object.freeze(["Enter"]), + cancel: Object.freeze(["Escape"]), + previous: Object.freeze({ + column: Object.freeze(["ArrowUp"]), + row: Object.freeze(["ArrowLeft"]), + }), + next: Object.freeze({ + column: Object.freeze(["ArrowDown"]), + row: Object.freeze(["ArrowRight"]), + }), +}); + +function resolveBindings( + bindings: KeyboardDragBindings | undefined, +): ResolvedKeyboardDragBindings { + return Object.freeze({ + liftDrop: new Set(bindings?.liftDrop ?? defaultBindings.liftDrop), + cancel: new Set(bindings?.cancel ?? defaultBindings.cancel), + previous: Object.freeze({ + column: new Set( + bindings?.previous?.column ?? defaultBindings.previous.column, + ), + row: new Set(bindings?.previous?.row ?? defaultBindings.previous.row), + }), + next: Object.freeze({ + column: new Set(bindings?.next?.column ?? defaultBindings.next.column), + row: new Set(bindings?.next?.row ?? defaultBindings.next.row), + }), + }); +} + +function hasCommandModifier(event: KeyboardEvent): boolean { + return event.altKey || event.ctrlKey || event.metaKey || event.shiftKey; +} + +/** Adds conventional keyboard operation to direct SnapSort drag sessions. */ +export class KeyboardDragController { + readonly root: Container; + readonly #bindings: ResolvedKeyboardDragBindings; + + #installedCallback: ((prop: keyDownProp) => void) | null = null; + #startedSession: DragSessionController | null = null; + #destroyed = false; + + constructor(root: Container, options: KeyboardDragControllerOptions = {}) { + if (root.rootContainer !== root || root.isDeleteRequested) { + throw new Error( + "KeyboardDragController: root must be a live SnapSort root container.", + ); + } + if (root.event.hasGlobalCallback("keyDown")) { + throw new Error( + "KeyboardDragController: the root keyDown callback is already in use.", + ); + } + + this.root = root; + this.#bindings = resolveBindings(options.bindings); + root.event.global.keyDown = this.#onKeyDown; + this.#installedCallback = root.event.globalCallback("keyDown"); + } + + destroy(): void { + if (this.#destroyed) return; + this.#destroyed = true; + + const session = getDragSessionController(this.root); + if ( + session && + session === this.#startedSession && + session.input.inputType === "direct" && + session.phase !== "ended" + ) { + if (session.phase === "pending") { + session.cancel(); + } else { + session.input.cancel(); + } + } + + if ( + this.#installedCallback && + this.root.event.globalCallback("keyDown") === this.#installedCallback + ) { + this.root.event.global.keyDown = null; + } + + this.#installedCallback = null; + this.#startedSession = null; + } + + #focusedItem(prop: keyDownProp): Item | null { + const focusedObject = prop.focusedObject; + + if ( + !(focusedObject instanceof Item) || + focusedObject.rootContainer !== this.root || + prop.event.target !== focusedObject.inputElement + ) { + return null; + } + + return focusedObject; + } + + #onKeyDown = (prop: keyDownProp): void => { + if ( + this.#destroyed || + prop.event.defaultPrevented || + prop.event.isComposing + ) { + return; + } + + const session = getDragSessionController(this.root); + + if (prop.event.key === "Tab" && session?.input.inputType === "direct") { + session.input.suppressFocusRestoration(); + if (session.phase === "pending") { + session.cancel(); + } else { + session.input.cancel(); + } + return; + } + + if (hasCommandModifier(prop.event)) return; + + const focusedItem = this.#focusedItem(prop); + if (!focusedItem) return; + + if (session) { + if (session.input.inputType !== "direct") return; + this.#handleActiveDirectSession(prop.event, session.input); + return; + } + + if ( + prop.event.repeat || + !this.#bindings.liftDrop.has(prop.event.key) || + focusedItem.locked + ) { + return; + } + + const publicSession = focusedItem.beginDirectDrag(); + const startedSession = getDragSessionController(this.root); + + if (!publicSession || !startedSession) return; + this.#startedSession = startedSession; + prop.event.preventDefault(); + }; + + #handleActiveDirectSession( + event: KeyboardEvent, + input: DirectDragController, + ): void { + if (this.#bindings.liftDrop.has(event.key)) { + if (!event.repeat && input.drop()) event.preventDefault(); + return; + } + + if (this.#bindings.cancel.has(event.key)) { + if (!event.repeat && input.cancel()) event.preventDefault(); + return; + } + + const direction = input.currentTarget?.container.direction; + if (!direction) return; + + if (this.#bindings.previous[direction].has(event.key)) { + input.movePrevious(); + event.preventDefault(); + return; + } + + if (this.#bindings.next[direction].has(event.key)) { + input.moveNext(); + event.preventDefault(); + } + } +} diff --git a/assets/snapsort/src/mutation.ts b/assets/snapsort/src/mutation.ts index f836189a..17e22d7d 100644 --- a/assets/snapsort/src/mutation.ts +++ b/assets/snapsort/src/mutation.ts @@ -184,7 +184,7 @@ export function fireItemInsert( ): void { const onInsert = requireMutationCallback(container, "onItemInsert"); const event: ItemInsertEvent = { - session: session?.handle ?? null, + session, ...buildItemRunEvent(items), container, containerMetadata: container.metadata, @@ -201,7 +201,7 @@ export function fireItemRemove( ): void { const onRemove = requireMutationCallback(container, "onItemRemove"); const event: ItemRemoveEvent = { - session: session?.handle ?? null, + session, ...buildItemRunEvent(items), container, containerMetadata: container.metadata, @@ -230,7 +230,7 @@ export function fireItemMove( } if (resolved.operation === "move") { const event: ItemMoveEvent = { - session: session?.handle ?? null, + session, ...buildItemRunEvent(items), from: froms[0], to, @@ -256,7 +256,7 @@ export function fireItemSwap( ): void { const onSwap = requireMutationCallback(a.container, "onItemSwap"); const event: ItemSwapEvent = { - session: session?.handle ?? null, + session, a: { item: a.item, itemId: a.item.itemId, @@ -284,7 +284,7 @@ function buildDragItemHoverEvent( container: Container, ): DragItemHoverEvent { return { - session: session.handle, + session, item, itemId: item.itemId, itemMetadata: item.metadata, diff --git a/assets/snapsort/src/react/Handle.tsx b/assets/snapsort/src/react/Handle.tsx index e38fab91..eaa34298 100644 --- a/assets/snapsort/src/react/Handle.tsx +++ b/assets/snapsort/src/react/Handle.tsx @@ -1,8 +1,7 @@ import { forwardRef, + useCallback, useContext, - useEffect, - useImperativeHandle, useRef, type HTMLAttributes, type ReactNode, @@ -21,23 +20,24 @@ export const Handle = forwardRef(function Handle( ) { const item = useContext(ItemObjectContext); const handleRef = useRef(null); + const setHandleElement = useCallback( + (handleElement: HTMLDivElement | null) => { + const previousElement = handleRef.current; + if (item && previousElement) item.removeInputAlias(previousElement); - useImperativeHandle(ref, () => handleRef.current as HTMLDivElement, []); + handleRef.current = handleElement; + if (item && handleElement) item.addInputAlias(handleElement); - useEffect(() => { - const handleElement = handleRef.current; - if (!item || !handleElement) return; - - item.addInputAlias(handleElement); - return () => { - item.removeInputAlias(handleElement); - }; - }, [item]); + if (typeof ref === "function") ref(handleElement); + else if (ref) ref.current = handleElement; + }, + [item, ref], + ); return (
diff --git a/assets/snapsort/src/snapshot.ts b/assets/snapsort/src/snapshot.ts index cb4cd7fb..762f1ac5 100644 --- a/assets/snapsort/src/snapshot.ts +++ b/assets/snapsort/src/snapshot.ts @@ -3,33 +3,9 @@ import type { DomProperty } from "@snap-engine/core"; export type ItemId = string; export type LayoutDirection = "column" | "row"; export type LayoutMainAxisAlign = "start" | "center"; -/** - * How a container arranges its children, and therefore how the drop - * simulation predicts positions: - * - * - `"flow"` (default): flexbox-like — children take their own measured - * size and wrap when the accumulated main-axis extent exceeds capacity. - * - `"slots"`: CSS-grid-like — position is a function of *index*. The - * pristine snapshot's measured child boxes are the slots; a simulated - * entry adopts the geometry of the slot at its index. Requires the - * main-axis track geometry to be independent of which items occupy it - * (fixed/fr/percent templates); see `slotLayoutPositions` for the full - * contract. - */ export type LayoutModel = "flow" | "slots"; -/** - * Whether a flow container's lines may wrap: - * - * - `"auto"` (default): inferred from measurements — row containers may - * wrap; column containers wrap only when the measured layout already - * shows multiple lines. - * - `"nowrap"`: the list never wraps and simply keeps growing along its - * main axis (todo lists, file explorers). Declaring it makes zero-slack - * lists immune to spurious wrap flips from measurement noise. - */ export type LayoutWrap = "auto" | "nowrap"; -/** Read-only application data associated with an item. */ export type ItemMetadata = Readonly>; export interface ItemSnapshot { @@ -40,14 +16,6 @@ export interface ItemSnapshot { mainAxisAlign: LayoutMainAxisAlign; layoutModel: LayoutModel; wrap: LayoutWrap; - /** - * Entries in this container fill its cross axis (width in column lists, - * height in row lists) up to the content box minus the entry's own - * margins — the CSS `align-items: stretch` analogy. The drop simulation - * re-sizes an inserted entry to the *destination* container, so ghost - * rects and center points stay correct when dragging between containers - * of different sizes (e.g. into a narrower nested list). - */ stretchItems: boolean; locked: boolean; box: DomProperty; diff --git a/assets/snapsort/src/svelte/Handle.svelte b/assets/snapsort/src/svelte/Handle.svelte index b5ee43a8..4d95f2e6 100644 --- a/assets/snapsort/src/svelte/Handle.svelte +++ b/assets/snapsort/src/svelte/Handle.svelte @@ -1,5 +1,6 @@
{@render children()} diff --git a/demo/svelte/main.ts b/demo/svelte/main.ts index b23583cd..68499b5c 100644 --- a/demo/svelte/main.ts +++ b/demo/svelte/main.ts @@ -1,5 +1,4 @@ import "../../css/snapdesign.scss"; -import "../../website/src/lib/landing/snapdesign/style.dev.scss"; import App from "./src/App.svelte"; import { mount } from "svelte"; diff --git a/demo/svelte/src/DemoRouter.svelte b/demo/svelte/src/DemoRouter.svelte index 165a8bf8..f8eb1f63 100644 --- a/demo/svelte/src/DemoRouter.svelte +++ b/demo/svelte/src/DemoRouter.svelte @@ -12,6 +12,7 @@ import SnapSortComponentsPage from "./demo/snapsort_components/SnapSortComponentsDemo.svelte"; import SnapSortFileExplorerPage from "./demo/snapsort_file_explorer/SnapSortFileExplorerDemo.svelte"; import SnapSortInsertionPage from "./demo/snapsort_insertion/SnapSortInsertionDemo.svelte"; + import SnapSortKeyboardPage from "./demo/snapsort_keyboard/SnapSortKeyboardDemo.svelte"; import SnapSortWebsiteCorePage from "./demo/snapsort_website_core/SnapSortWebsiteCoreDemo.svelte"; import CollisionPage from "./demo/collision/CollisionDemo.svelte"; import CollisionStressPage from "./demo/collision/CollisionStressDemo.svelte"; @@ -106,6 +107,12 @@ legacyDemoValues: ["snapsort_insertion"], usesDevNav: true, }, + { + label: "SnapSort Keyboard", + path: "/snapsort-keyboard", + legacyDemoValues: ["snapsort_keyboard"], + usesDevNav: true, + }, { label: "SnapSort Website Core", path: "/snapsort-website-core", @@ -302,6 +309,8 @@ {:else if selectedPath === "/snapsort-insertion"} + {:else if selectedPath === "/snapsort-keyboard"} + {:else if selectedPath === "/snapsort-website-core"} {:else if selectedPath === "/snapsort-file-explorer"} diff --git a/demo/svelte/src/demo/snapsort_keyboard/DirectResizeFixture.svelte b/demo/svelte/src/demo/snapsort_keyboard/DirectResizeFixture.svelte new file mode 100644 index 00000000..6c3130f0 --- /dev/null +++ b/demo/svelte/src/demo/snapsort_keyboard/DirectResizeFixture.svelte @@ -0,0 +1,165 @@ + + +
+ + + + {#each cards.entries as entry (entry.itemId)} + {#if entry.isGhost} + + {:else if entry.childTree} + + {:else if entry.itemId === "resize-dragged"} + + {entry.value.label} + + {:else} + + {entry.value.label} + + {/if} + {/each} + + +
+ + diff --git a/demo/svelte/src/demo/snapsort_keyboard/SnapSortKeyboardDemo.svelte b/demo/svelte/src/demo/snapsort_keyboard/SnapSortKeyboardDemo.svelte new file mode 100644 index 00000000..9e2c2a6f --- /dev/null +++ b/demo/svelte/src/demo/snapsort_keyboard/SnapSortKeyboardDemo.svelte @@ -0,0 +1,408 @@ + + +{#if showResizeFixture} + +{:else} +
+
+

DIRECT DRAG

+

Keyboard sorting

+

+ Focus a card, press Enter to lift it, then use Up and Down to choose a + position. Press Enter again to drop or Escape to cancel. +

+
+ +
+
+
+
+

TASKS

+

Release checklist

+
+ {tasks.entries.filter((entry) => !entry.isGhost).length} +
+ + + + {#each tasks.entries as entry (entry.itemId)} + {#if entry.isGhost} + + + + {:else} + + + + + {entry.value.label} + {entry.value.detail} + + + + + {/if} + {/each} + + + +

+ {status} +

+
+ + +
+
+{/if} + + diff --git a/docs/snapsort/02_guides/03_sessions/04_commit-and-cleanup.mdx b/docs/snapsort/02_guides/03_sessions/04_commit-and-cleanup.mdx index e85c14cd..4d553ebc 100644 --- a/docs/snapsort/02_guides/03_sessions/04_commit-and-cleanup.mdx +++ b/docs/snapsort/02_guides/03_sessions/04_commit-and-cleanup.mdx @@ -60,7 +60,7 @@ interface DragEndEvent { `destination` is the final resolved direct Container and index. It may equal `source`; it is `null` when the lifecycle ends without a resolved destination. -The session handle has status `"ended"` by the time `onDragEnd` runs, and +The session has status `"ended"` by the time `onDragEnd` runs, and `root.dragSession` has been cleared. ## Cancellation and Failed Drops diff --git a/docs/snapsort/04_reference/01_index.mdx b/docs/snapsort/04_reference/01_index.mdx index f1a3264d..df67a45c 100644 --- a/docs/snapsort/04_reference/01_index.mdx +++ b/docs/snapsort/04_reference/01_index.mdx @@ -17,7 +17,7 @@ hidden: true | React | [Container](/docs/snapsort/reference/react/container) | [Item](/docs/snapsort/reference/react/item) | [Ghost](/docs/snapsort/reference/react/ghost) | The framework-neutral [DragSession](/docs/snapsort/reference/drag-session) -reference documents the stable handle exposed during a gesture, including its +reference documents the session controller exposed during a gesture, including its read-only state and mutable controls. [Standard Callbacks](/docs/snapsort/reference/callbacks) documents the reusable diff --git a/docs/snapsort/04_reference/02_svelte/03_ghost.mdx b/docs/snapsort/04_reference/02_svelte/03_ghost.mdx index 8f927974..8ebda1a9 100644 --- a/docs/snapsort/04_reference/02_svelte/03_ghost.mdx +++ b/docs/snapsort/04_reference/02_svelte/03_ghost.mdx @@ -129,7 +129,7 @@ Identifies the role and narrows the union: **Type:** `DragSession` · **Read-only** -The stable session handle that owns this ghost. All ghost roles created during +The session controller that owns this ghost. All ghost roles created during one gesture refer to the same handle. ```ts diff --git a/docs/snapsort/04_reference/03_react/04_ghost.mdx b/docs/snapsort/04_reference/03_react/04_ghost.mdx index 9e13ae18..335a0a22 100644 --- a/docs/snapsort/04_reference/03_react/04_ghost.mdx +++ b/docs/snapsort/04_reference/03_react/04_ghost.mdx @@ -132,7 +132,7 @@ Identifies the role and narrows the union: **Type:** `DragSession` · **Read-only** -The stable session handle that owns this ghost. All ghost roles created during +The session controller that owns this ghost. All ghost roles created during one gesture refer to the same handle. ```ts diff --git a/docs/snapsort/04_reference/04_drag-session.mdx b/docs/snapsort/04_reference/04_drag-session.mdx index 5db7dabb..fefdc2f5 100644 --- a/docs/snapsort/04_reference/04_drag-session.mdx +++ b/docs/snapsort/04_reference/04_drag-session.mdx @@ -8,9 +8,10 @@ sectionTitle: Reference sectionOrder: 3 --- -`DragSession` is the stable public handle for one drag gesture. It is a -TypeScript interface, not a constructor; SnapSort supplies it through drag -events and the root Container's `dragSession` property. +`DragSession` is the public view of the one controller created for a drag +gesture. It is a TypeScript interface, not a constructor; SnapSort supplies +the same controller object through drag events and the root Container's +`dragSession` property. ```ts import type { DragSession, DragStartEvent } from "@snap-engine/snapsort"; @@ -26,18 +27,14 @@ function onDragStart(event: DragStartEvent) { ```ts interface DragSession { readonly root: Container; - readonly pointerId: number; + readonly input: PointerDragController | DirectDragController; readonly items: readonly Item[]; readonly sources: readonly DragLocation[]; readonly pressedItem: Item; readonly primaryItem: Item; - readonly start: Readonly<{ x: number; y: number }>; - readonly pointer: Readonly<{ x: number; y: number }>; readonly status: DragSessionStatus; dragVisual: DragVisual; dropEffect: DropEffect; - /** @deprecated */ - handoff(replacements: readonly Item[]): void; } ``` @@ -48,24 +45,28 @@ interface DragSession { **Type:** `Container` · **Read-only** The independent root Container that owns the gesture. It receives root -lifecycle callbacks and exposes this handle as `root.dragSession` while the +lifecycle callbacks and exposes this controller as `root.dragSession` while the session is active. ```ts const activeSession = event.session.root.dragSession; ``` -### `pointerId` +### `input` -**Type:** `number` · **Read-only** +**Type:** `PointerDragController | DirectDragController` · **Read-only** -The browser pointer identifier captured from the gesture that started the -drag. Use it when correlating the session with application-level pointer -state. +The input-specific controller contained by this drag transaction. Narrow its +`inputType` discriminant before reading pointer state or issuing direct +navigation commands. ```ts -if (event.pointerId === session.pointerId) { - // Both refer to the pointer driving this drag. +if (session.input.inputType === "pointer") { + console.log(session.input.pointerId); + console.log(session.input.start, session.input.pointer); +} else { + console.log(session.input.candidateLocations); + console.log(session.input.currentTarget); } ``` @@ -88,8 +89,7 @@ The array is frozen. Do not add, remove, or reorder its entries. **Type:** `readonly DragLocation[]` · **Read-only** The gesture-origin locations parallel to `items`: `sources[i]` describes -`items[i]`. They remain the original locations when the prospective target -changes and after a deprecated handoff. +`items[i]`. They remain the original locations when the prospective target changes. ```ts const origins = session.items.map((item, index) => ({ @@ -124,30 +124,6 @@ const isSingleDrag = session.items.length === 1 && session.primaryItem === session.pressedItem; ``` -### `start` - -**Type:** `Readonly<{ x: number; y: number }>` · **Read-only** - -Frozen world-space pointer coordinates captured when the drag began. - -```ts -const distanceX = session.pointer.x - session.start.x; -``` - -### `pointer` - -**Type:** `Readonly<{ x: number; y: number }>` · **Read-only** - -The latest world-space pointer coordinates processed by SnapSort. Each value -is an immutable snapshot. Read it inside callbacks; do not use it as a -continuous framework render signal. - -```ts -function onDropTargetChange(event: DropTargetChangeEvent) { - console.log(event.session.pointer); -} -``` - ### `status` **Type:** `DragSessionStatus` · **Read-only** @@ -242,25 +218,6 @@ const source: DragLocation = session.sources[0]; console.log(source.container.name, source.index); ``` -## Methods - -### Deprecated `handoff` - -```ts -/** @deprecated */ -session.handoff(replacements: readonly Item[]): void; -``` - -Transfers a pending gesture to an already-mounted parallel run of replacement -Items. It may only run synchronously during `onDragStart`. Replacements must -be a unique, equally sized run of non-ghost Items attached to the same root -and engine, and must not include the current participants. Invalid input or a -call after the pending phase throws without changing the current participants. - -This escape hatch predates the supported move-and-backfill copying recipe and -has no recommended first-party use case. Do not add new integrations that use -it; it may be removed in a future release. - ## Appendix ### Obtaining and Retaining the Session diff --git a/docs/snapsort/design/direct-drag-accessibility-plan.md b/docs/snapsort/design/direct-drag-accessibility-plan.md index ae12775f..618890e6 100644 --- a/docs/snapsort/design/direct-drag-accessibility-plan.md +++ b/docs/snapsort/design/direct-drag-accessibility-plan.md @@ -8,6 +8,13 @@ gesture through `moveNext()`, `movePrevious()`, `moveTo()`, `drop()`, and preserving SnapSort's existing lifecycle, policy checks, callbacks, visuals, adapters, and final mutations. +Direct movement is target-first. A command selects an exact logical candidate, +SnapSort synchronizes its prospective placement, and only then derives private +presentation coordinates from the candidate geometry to reuse the existing +item/preview animation path. The derived coordinates never participate in +candidate selection. Application data and final DOM order change only when the +session drops. + Ship an optional `KeyboardDragController` supporting only lift/drop, cancel, and linear previous/next navigation. Kanban movement, spatial navigation, selection controls, and other gestures remain the responsibility of custom @@ -36,29 +43,26 @@ interface keyDownProp { ### Drag sessions ```ts -type DragSession = PointerDragSession | DirectDragSession; - -interface BaseDragSession { - readonly inputType: "pointer" | "direct"; +interface DragSession { readonly root: Container; + readonly input: PointerDragController | DirectDragController; readonly items: readonly Item[]; readonly sources: readonly DragLocation[]; readonly pressedItem: Item; readonly primaryItem: Item; - readonly start: Readonly<{ x: number; y: number }>; - readonly pointer: Readonly<{ x: number; y: number }>; readonly status: DragSessionStatus; dragVisual: DragVisual; dropEffect: DropEffect; } -interface PointerDragSession extends BaseDragSession { +class PointerDragController { readonly inputType: "pointer"; readonly pointerId: number; - handoff(replacements: readonly Item[]): void; + readonly start: Readonly<{ x: number; y: number }>; + readonly pointer: Readonly<{ x: number; y: number }>; } -interface DirectDragSession extends BaseDragSession { +class DirectDragController { readonly inputType: "direct"; readonly candidates: readonly DragLocation[]; readonly currentTarget: DragLocation | null; @@ -74,12 +78,22 @@ interface DirectDragSession extends BaseDragSession { Add: ```ts -Item.beginDirectDrag(): DirectDragSession | null; +Item.beginDirectDrag(): DragSession | null; ``` -- This is intentionally a clean discriminated union. Existing callers must - narrow on `inputType` before using `pointerId` or `handoff()`. -- `root.dragSession` and callback session fields expose the union. +- `DragSessionController` is the one runtime session object. `root.dragSession` + and callback session fields expose that same object through the narrower + `DragSession` interface; there is no separate handle or wrapper class. +- Callers narrow `session.input.inputType` before using pointer coordinates or + direct navigation commands. +- The shared session transaction retains private `visualStart`, + `visualPointer`, and `visualOffset` coordinates solely as an adapter for the + existing visual transform code. Pointer input copies real coordinates into + them; direct input derives them from the accepted candidate. They are not + public direct-session state, and `Item.dragPointerPosition` returns `null` + for a direct session. +- `dragVisual` remains input-agnostic. Direct sessions preserve all existing + `"item"`, `"preview"`, and `"none"` behavior. - `beginDirectDrag()` returns `null` for expected refusal: locked or unattached initiator, pending programmatic mutation, or an existing root session. Invalid or destroyed programmer state throws. @@ -91,14 +105,191 @@ Item.beginDirectDrag(): DirectDragSession | null; - Existing `getIndexAndContainer()` and cached geometry remain the ordinary Item/Container position APIs; do not add another global position index. +### Controller ownership + +Keep one drag transaction and contain its input-specific behavior through +composition: + +```ts +type DragInputController = PointerDragController | DirectDragController; + +type DragInputStart = + | { + readonly inputType: "pointer"; + readonly prop: dragStartProp; + } + | { + readonly inputType: "direct"; + readonly initiatingItemId: ItemId; + }; + +class DragSessionController { + readonly input: DragInputController; + + constructor( + root: Container, + items: readonly Item[], + sources: readonly DragLocation[], + strategy: SortStrategy, + start: DragInputStart, + pressedItem?: Item, + ); +} +``` + +- `DragSessionController` owns the shared drag transaction: root and + participants, snapshots and group geometry, strategy/lifecycle state, + drag-visual and drop-effect configuration, ghosts and pending placement, + exact-target application, commit/cancel/error cleanup, and the internal + visual coordinates used by existing animation code. +- `PointerDragController` owns `pointerId`, real start/current coordinates, + pointer move/end entry points, pointer hit-testing and candidate ranking, + hovered-Item state, and pointer-only enter/move/leave callbacks. +- `DirectDragController` owns the frozen rich candidates, their public + `DragLocation` projection, current candidate index, navigation and policy + scanning, move-settling and queued-terminal state, initiating Item identity, + and focus restoration. +- Do not add public wrapper classes or an inheritance hierarchy. + `DragSessionController` implements the public `DragSession` shape directly, + while its contained input controller owns the pointer- or direct-only API. +- A pointer gesture and a direct/key gesture both construct the same + `DragSessionController`. The constructor receives a discriminated + `DragInputStart`, initializes all shared transaction state, and then creates + the matching contained controller. Callers never construct an input + controller separately and never attach one to an existing session. +- Each input controller may retain a private, non-owning reference to its + session so its commands can request shared placement, visual, drop, and + cancellation work. The session remains the sole owner of the controller and + of the drag transaction. +- Refactor pointer resolution to receive the real pointer from + `PointerDragController`; it must not read the shared visual adapter as input. + Direct input updates `visualPointer` only after choosing an authoritative + candidate and never invokes pointer resolution. +- Do not add `fromPointer()`/`fromDirect()` factories or expose a separate + candidate-initialization step. Root session storage, callbacks, and + `root.dragSession` all reference the same `DragSessionController` instance. + +### Session initialization lifecycle + +The session owns initialization from the initial event through activation: + +1. Pointer drag start or `Item.beginDirectDrag()` gathers the participants, + sources, strategy, and a `DragInputStart` description. +2. `new DragSessionController(...)` initializes shared state and constructs + either `PointerDragController` or `DirectDragController` itself. +3. The caller installs that complete session in the root and calls + `session.begin()` with no second copy of the pointer-start property. +4. During the existing `READ_1` start stage, the session captures drag + snapshots and computes group geometry. +5. If the contained controller is direct, the session invokes one internal + controller activation method. That method builds and freezes candidates + from the now-available drag snapshot. +6. During `WRITE_1`, normal validation, callbacks, lifecycle startup, and the + transition to `"active"` continue for either input method. + +The direct controller exists from session construction onward but accepts no +navigation or terminal command until candidate activation completes. Calls +made while the session is `"pending"` return `false`. Candidate activation is +an internal phase of `session.begin()`, not public object assembly; it runs +exactly once and throws if the session attempts to activate it twice. + ## Direct-session implementation ### Frozen candidates and indices -Build a pure structural candidate snapshot when direct drag begins, using the -reconciled tree and cached geometry. The public array remains frozen for the -session and includes structurally valid candidates even when current drop -policy rejects them. +Build a pure structural candidate snapshot during the direct session's +`READ_1` activation, after the session has captured its drag snapshot and group +geometry. The public array remains frozen for the active session and includes +structurally valid candidates even when current drop policy rejects them. + +Each private candidate keeps its exact resolved target and the frozen geometry +needed to present that target. Do not store a pointer anchor. The target is the +single source of truth; the public `DragLocation` is derived from it. + +```ts +type DirectCandidate = + | { + readonly kind: "flow"; + readonly target: ResolvedDropTarget; + readonly memberRects: readonly Readonly[]; + } + | { + readonly kind: "insertion"; + readonly target: ResolvedDropTarget & { + readonly insertion: InsertionMarkerPresentation; + }; + readonly memberRects: readonly Readonly[]; + } + | { + readonly kind: "swap"; + readonly target: ResolvedDropTarget; + readonly targetItemId: ItemId; + readonly memberRects: readonly Readonly[]; + }; +``` + +- Flow candidates reuse the layout engine's projected group placement rect. +- Insertion candidates retain both the canonical zero-thickness marker + presentation and a separate projected group rect for the drag visual. +- Swap candidates retain the target Item identity and its frozen rect. +- Candidate collection and geometry generation must not require a pointer. + Refactor pointer-distance scoring into a later selection step so pointer and + direct modes can share geometry without sharing resolution. + +### Layout projection for flow candidates + +Use the layout engine's existing virtual-insertion model instead of building or +splicing a second Item-order representation outside the layout module. A +`VirtualInsertion` is the dragged member's stand-in in the hypothetical final +order, and `FlowPositionResult.virtualRects` is the authoritative projected +geometry. + +For each candidate: + +1. Start from the frozen root drag snapshot. +2. Exclude every dragged participant through + `filter.excludeValues = session.itemSet`. Candidate indices therefore use + the final post-removal coordinate system. +3. Create one `VirtualInsertion` per dragged member at consecutive indices + beginning at the candidate index. Size every entry with + `virtualEntrySizeFor(targetSnapshot, memberBox)` so destination stretching, + margins, wrapping, and measured-slot layouts remain layout-engine owned. +4. Register that insertion run when creating the candidate's layout resolution + plan. This lets a nested destination's projected dimensions propagate + through its ancestors. +5. Materialize positions recursively from the root content-box origin to the + destination, passing each Container its local insertion entries. +6. Read every inserted member's rect from `virtualRects` and freeze the full + array as `candidate.memberRects`, ordered to parallel `session.items`. + +The essential local call is: + +```ts +const result = layoutPlan.layoutPositions( + targetSnapshot, + targetOrigin.x, + targetOrigin.y, + insertionRun, +); + +const memberRects = insertionRun.map((insertion) => { + const rect = result.virtualRects.get(insertion); + if (!rect) { + throw new Error("SnapSort: layout did not project a direct candidate."); + } + return rect; +}); +``` + +The layout module's `materializeEntries()` remains the sole owner of the +hypothetical order: it starts with the filtered children and inserts the +virtual entries at their requested indices. Direct-candidate code must not +manually clone, splice, or lay out an Item list. + +Single-item dragging is the degenerate one-entry run. A multi-item run retains +every member's destination position and size; its bounding union is derived +from the current interpolated member rects only when a combined preview needs +one group rectangle. For `euclidean`, `progressive`, and `insertion`: @@ -122,16 +313,22 @@ boundary immediately before the next retained child, or the end boundary. For swap mode: -- Traverse non-participant Items, including nested Containers-as-Items, in - depth-first preorder. +- Traverse Items, including nested Containers-as-Items, in depth-first + preorder. Include the initiating participant's home position as one no-op + candidate; prune the remaining dragged participants and their subtrees. - A candidate location identifies the target Item at its frozen parent/index; empty Containers provide no target. - Retain the target Item identity internally and re-resolve it before commit. -- Passing the dragged Item's own swap position is a no-op returning `false`. +- Selecting the already-current home candidate returns `false`; returning to + it from another candidate is accepted and clears the prospective swap. +- Dropping on the home candidate performs no mutation. -Before the first accepted movement, `currentTarget` is `null`. Maintain a -private cursor at the initiating Item's projected source slot; if a selected -ancestor is the actual participant, anchor at that nearest participant instead. +During direct activation, initialize the single current candidate to the +initiating Item's projected source/home slot. If a selected ancestor is the +actual participant, use that nearest participant's source instead. Once active, +`currentTarget` is always `candidates[currentCandidateIndex]`; there is no +separate navigation cursor. It may be `null` only while the session is pending +and candidate geometry has not yet been captured. ### Movement and policy @@ -148,15 +345,16 @@ ancestor is the actual participant, anchor at that nearest participant instead. but never prunes descendants. A later command reevaluates policy. - An already accepted target is authoritative and is not revalidated by `drop()`. -- A successful move immediately updates `currentTarget` and the virtual - `pointer`, then schedules lifecycle synchronization. +- A successful move immediately makes the selected target authoritative and + updates `currentTarget`, then schedules prospective placement and visual + synchronization. The shared `visualPointer` is derived from that target; it + never determines or revalidates it. - Return `false` at traversal boundaries, for the same destination, policy rejection, an inactive or terminal session, or while another move is settling. -- A move called while start is pending is accepted immediately using the frozen - cached layout, updates `currentTarget`, and is applied after activation. If - the later scheduled `onDragStart` vetoes the session, discard that command - and end normally. +- A move called while start is pending returns `false`; candidate geometry and + the initial source target become available together during `READ_1` + activation. ### Shared lifecycle and visual state @@ -167,29 +365,62 @@ separate: shared placement method. - Direct sessions pass their exact logical target to that method without invoking pointer algorithms. -- The shared path remains responsible for placement conversion, hover state, - ghosts, markers, `onDropTargetChange`, visual invalidation, and mode - lifecycle callbacks. - -Use the existing candidate-layout geometry to derive the direct virtual -pointer: +- The shared path remains responsible for placement conversion, ghosts, + markers, `onDropTargetChange`, visual invalidation, and mode lifecycle + callbacks. Pointer-hover state and `onDragItemEnter`/`Move`/`Leave` remain + pointer-input-only. + +Apply an accepted direct candidate in this order: + +1. Construct the shared placement update from the candidate's exact target. +2. Synchronize its prospective flow ghost, insertion marker, or swap target. +3. Capture the currently rendered rect of every dragged member as the motion + origin. For a second command this is the previous candidate's settled + geometry, not the gesture's original source geometry. +4. Animate each member rect to its corresponding `candidate.memberRects` + entry, interpolating `x`, `y`, `width`, and `height` together. +5. Derive the compatibility `visualPointer` from the initiating member's + source-to-current delta and run the existing mode lifecycle's drag-visual + update on every tick. + +The initiating member keeps the legacy pointer adapter coherent without +making it authoritative: -- Flow modes use the exact candidate's projected placement anchor. -- Insertion uses the canonical marker/gap midpoint. -- Swap uses the target Item's frozen center. - -Initialize `start` at the pressed/group-anchor Item's visual center. Moving the -virtual pointer must move an Item or preview visual exactly as the equivalent -resolved pointer placement would. +```ts +const visualPointer = { + x: visualStart.x + currentPressedRect.x - pressedSourceRect.x, + y: visualStart.y + currentPressedRect.y - pressedSourceRect.y, +}; +``` -Flow modes create their source spacer during activation. Insertion and swap -show no pending marker or highlight before the first accepted move. +Do not use candidate centers: differently sized source and destination Items +would produce an incorrect grab offset. Never feed the derived visual pointer +back through `DropTargetStrategy.resolve()`. Item visuals consume their exact +interpolated member rect; pointer previews derive their group rect and member +drop origins from the same current geometry. + +Direct motion uses the accepted destination Container's `animation.reorder` +duration and easing. As with other SnapSort animations, an omitted animation +config, `animation: null`, a nonpositive duration, or `dragVisual: "none"` +settles immediately at the exact destination geometry. Only one direct move +animation runs at a time. Cancel, teardown, and error cleanup stop it; a drop +requested while it runs begins only after the animation reaches its exact +endpoint. + +Flow modes create their source spacer during activation. Insertion synchronizes +its source marker as the initial placement. Swap initializes its logical home +candidate without highlighting or attempting to swap the Item with itself. + +Prospective placement does not fire Item mutation callbacks. The ghost/marker +occupies the target visually while the framework-owned collection remains the +source of truth. `drop()` commits once; `cancel()` removes transient state and +requires no application rollback. ### Scheduling, terminal commands, and cleanup - Permit one accepted move at a time. Keep the session busy until its callbacks, - adapter reconciliation, and transient visual synchronization settle; later - requests return `false` and are not queued. + adapter reconciliation, transient visual synchronization, and direct-motion + animation settle; later requests return `false` and are not queued. - `drop()` during a busy move queues one terminal request and returns `true`. Repeated terminal requests return `false`. - Keep public status pending or active until queued drop work actually begins. @@ -210,8 +441,8 @@ show no pending marker or highlight before the first accepted move. Make the root session store exclusive: - Neither pointer nor direct start may overwrite an existing session. -- Pointer move/end handlers require `inputType === "pointer"` and the matching - `pointerId`. +- Pointer move/end handlers require `input.inputType === "pointer"` and the + matching `pointerId`. - Pointer gestures in the same root cannot move, drop, or cancel a direct session; unrelated engine input and other roots remain usable. @@ -260,8 +491,10 @@ A supplied action/direction list replaces that default; an empty list disables it. - The constructor requires a live root Container and an unused - `root.event.input.keyDown` slot, then installs its callback. It throws on - conflicts. + `root.event.global.keyDown` slot, then installs its callback. Root-scoped + dispatch keeps commands active while a dragged Item is temporarily outside + the logical ancestor chain; exact `focusedObject` and `inputElement` + filtering still limits ownership to this root. It throws on conflicts. - Do not add a controller property to Container. - `destroy()` is idempotent and removes the callback only if it still owns the slot. @@ -275,8 +508,8 @@ it. - Inactive Enter starts any focused, unlocked Item; selection only controls participant grouping. - During any active direct session on the root, Enter drops and Escape cancels. -- Previous/next use the initiating source Container's direction before the - first move and `currentTarget.container.direction` afterward. +- Previous/next use `currentTarget.container.direction`; every active direct + session already has its source/home candidate as `currentTarget`. - There is no wrapping, spatial navigation, board-switch action, or `moveTo` resolver in the standard controller. - Handle a command only when the native event target is exactly an Item's @@ -290,7 +523,9 @@ it. - Prevent default for a successful lift and accepted drop/cancel. A refused inactive lift remains native. - Tab and Shift+Tab always cancel an active direct drag immediately but remain - unprevented so browser focus navigation continues. + unprevented so browser focus navigation continues. This controller-driven + cancellation suppresses the usual initiating-Item focus restoration; the + browser's newly focused element remains authoritative. - Ignore pointer sessions. ### Focus restoration @@ -310,14 +545,27 @@ it. - The library does not alter `tabIndex`; consumers must use a native focusable control or configure `tabIndex` on the Item/Handle. +### Ghost and screen-reader feedback + +- Ghosts are physical layout markers, not duplicate accessible Items. Built-in + adapters render them as presentational/`aria-hidden` content. +- During a direct drag, the focused real Item remains the accessibility anchor. +- Applications own screen-reader announcements. They may use + `onDropTargetChange`, `onDragEnd`, and their own polite live region to + describe prospective position, drop, and cancellation. +- The standard `KeyboardDragController` does not create a live region or infer + an accessible Item name. +- After drop, framework state reconciliation produces the final DOM order so + reading order, focus order, and visual order agree. + ## Verification and documentation - Core input tests: composed-path owner resolution, input aliases, ancestor/global dispatch, `focusedObject === null`, error isolation, and listener cleanup. -- Type tests: discriminated narrowing, pointer-only members, direct-only - commands, `beginDirectDrag()` return type, controller bindings, and - union-valued callback/root sessions. +- Type tests: discriminated narrowing, pointer-only `pointerId`/`start`/ + `pointer`, direct-only commands, `beginDirectDrag()` return type, controller + bindings, and union-valued callback/root sessions. - Candidate tests: exact nested DFS order, empty Containers, dragged-subtree pruning, final post-removal indices, all locked-adjacent slots, canonical insertion gaps, swap identities, and frozen candidates after live-tree @@ -328,9 +576,13 @@ it. - Scheduling tests: immediate pending move, one in-flight move, repeated key requests, drop-after-settle, cancellation superseding queued drop, stale generation suppression, and start veto. -- Mode integration tests: all four modes use the shared placement lifecycle, - produce equivalent callbacks/ghosts/markers/previews, avoid mutation before - drop, and preserve zero-move behavior. +- Mode integration tests: all four modes use exact direct targets with no + pointer resolution; produce equivalent callbacks/ghosts/markers/previews; + derive one shared visual translation from the selected candidate; avoid + mutation before drop; and preserve zero-move behavior. +- Target-first regression tests: widely different Item sizes retain the grab + offset, insertion preview geometry is independent of its marker, and the + derived pointer cannot change `currentTarget`. - Input-exclusion tests: direct start versus active pointer session, pointer start during direct drag, mismatched pointer move/end, separate roots, destruction, and failed-target cleanup. @@ -350,5 +602,5 @@ it. - Built-in multidirectional or Kanban semantics. - Selection UX. - Scrolling candidates into view. -- Announcements and live regions. +- Built-in announcements and live regions. - Deprecated ARIA drag-state attributes. diff --git a/src/object.ts b/src/object.ts index 3c83dc1d..78d2e80c 100755 --- a/src/object.ts +++ b/src/object.ts @@ -89,13 +89,16 @@ class EventCallback { prop, this.#object.id, ); + Object.assign(this.#global, { [prop]: null }); } else { + const callback = (value as any).bind(this.#object); this.#object.engine?.input.subscribeGlobalCursorEvent( prop, this.#object.id, - (value as any).bind(this.#object), + callback, this.#object.engine, ); + Object.assign(this.#global, { [prop]: callback }); } return true; }, @@ -124,6 +127,30 @@ class EventCallback { }; this.dom = EventProxyFactory(this.#object, this.#dom); } + + /** @internal Whether this object already owns a callback for an input event. */ + hasInputCallback(event: keyof InputEventCallback): boolean { + return this.#input[event] !== null; + } + + /** @internal Whether this object owns a root-scoped callback for an input event. */ + hasGlobalCallback(event: keyof InputEventCallback): boolean { + return this.#global[event] !== null; + } + + /** @internal The bound callback currently installed for an input event. */ + inputCallback( + event: Event, + ): InputEventCallback[Event] { + return this.#input[event]; + } + + /** @internal The bound root-scoped callback installed for an input event. */ + globalCallback( + event: Event, + ): InputEventCallback[Event] { + return this.#global[event]; + } } export class ObjectTransform { @@ -1033,6 +1060,15 @@ export class ElementObject< this.event.dom.onAssignDom?.(); } + /** + * Element currently representing this object for input and focus. + * + * An explicit input alias takes precedence over the object's visual element. + */ + get inputElement(): DomElement | null { + return this.#inputAlias ?? this.#element; + } + addInputAlias(element: DomElement): void { if (this.#inputAlias === element) { return; diff --git a/tests/e2e/docs-framework-code.playwright.config.ts b/tests/e2e/docs-framework-code.playwright.config.ts index 971e53c4..c7a823a1 100644 --- a/tests/e2e/docs-framework-code.playwright.config.ts +++ b/tests/e2e/docs-framework-code.playwright.config.ts @@ -8,7 +8,6 @@ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); export default defineConfig({ testDir: ".", testMatch: [ - "docs-framework-code.spec.ts", "material-surface-ssr.spec.ts", "snapdesign-gallery-virtual-pointer.spec.ts", "snapdesign-control-matrix.spec.ts", diff --git a/tests/e2e/docs-framework-code.spec.ts b/tests/e2e/docs-framework-code.spec.ts deleted file mode 100644 index 6b5720ee..00000000 --- a/tests/e2e/docs-framework-code.spec.ts +++ /dev/null @@ -1,2913 +0,0 @@ -import { expect, test, type Locator, type Page } from "@playwright/test"; -import { insertionTreeMarkerOptions } from "../../website/src/lib/components/docs/placement-modes/insertionTreeMarker"; - -async function dragBetween( - page: Page, - source: Locator, - target: Locator, - options: { beforeDrop?: () => Promise } = {}, -) { - await source.scrollIntoViewIfNeeded(); - const [sourceBox, targetBox] = await Promise.all([ - source.boundingBox(), - target.boundingBox(), - ]); - if (!sourceBox || !targetBox) - throw new Error("Drag target has no layout box."); - - const sourcePoint = { - x: sourceBox.x + sourceBox.width / 2, - y: sourceBox.y + sourceBox.height / 2, - }; - const targetPoint = { - x: targetBox.x + targetBox.width / 2, - y: targetBox.y + targetBox.height / 2, - }; - - await page.mouse.move(sourcePoint.x, sourcePoint.y); - await page.mouse.down(); - await page.mouse.move(sourcePoint.x + 7, sourcePoint.y + 7); - await page.waitForTimeout(60); - await page.mouse.move(targetPoint.x, targetPoint.y, { steps: 12 }); - await page.waitForTimeout(120); - await options.beforeDrop?.(); - await page.mouse.up(); - await page.waitForTimeout(150); -} - -test("tree insertion marker options follow adjacent item geometry", () => { - expect( - insertionTreeMarkerOptions({ - gap: { orientation: "horizontal", x: 10, y: 40, length: 100 }, - previous: { rect: { x: 20, y: 10, width: 70, height: 30 } }, - next: null, - }), - ).toEqual({ thickness: 3, startInset: 10, endInset: 20 }); - - expect( - insertionTreeMarkerOptions({ - gap: { orientation: "horizontal", x: 10, y: 40, length: 100 }, - previous: null, - next: { rect: { x: 0, y: 40, width: 80, height: 30 } }, - }), - ).toEqual({ thickness: 3, startInset: 0, endInset: 30 }); - - expect( - insertionTreeMarkerOptions({ - gap: { orientation: "horizontal", x: 10, y: 40, length: 100 }, - previous: { rect: { x: 15, y: 10, width: 90, height: 30 } }, - next: { rect: { x: 25, y: 40, width: 60, height: 30 } }, - }), - ).toEqual({ thickness: 3, startInset: 15, endInset: 25 }); - - expect( - insertionTreeMarkerOptions({ - gap: { orientation: "vertical", x: 40, y: 20, length: 120 }, - previous: { rect: { x: 10, y: 35, width: 30, height: 80 } }, - next: null, - }), - ).toEqual({ thickness: 3, startInset: 15, endInset: 25 }); - - expect( - insertionTreeMarkerOptions({ - gap: { orientation: "horizontal", x: 10, y: 40, length: 100 }, - previous: null, - next: null, - }), - ).toEqual({ thickness: 3, startInset: 0, endInset: 0 }); - - expect( - insertionTreeMarkerOptions({ - gap: { orientation: "horizontal", x: 10, y: 40, length: 100 }, - previous: { rect: { x: 0, y: 10, width: 5, height: 30 } }, - next: { rect: { x: 120, y: 40, width: 20, height: 30 } }, - }), - ).toEqual({ thickness: 3, startInset: 0, endInset: 0 }); -}); - -test("core components demo reduces ghost teardown through the framework tree", async ({ - page, -}) => { - const pageErrors: Error[] = []; - page.on("pageerror", (error) => pageErrors.push(error)); - const response = await page.goto("/docs/snapsort/guides/core-components"); - expect(response?.status()).toBe(200); - - const diagram = page.locator(".snapsort-concepts-diagram"); - const items = diagram.locator(".snapsort-concepts-item"); - await expect(items).toHaveCount(4); - await dragBetween(page, items.first(), items.nth(1)); - - await expect(diagram.locator(".snapsort-concepts-ghost")).toHaveCount(0); - expect(pageErrors).toEqual([]); -}); - -test("Drags and Ghosts guide demonstrates all four transient roles and cleanup", async ({ - page, -}) => { - const pageErrors: Error[] = []; - page.on("pageerror", (error) => pageErrors.push(error)); - const response = await page.goto( - "/docs/snapsort/guides/sessions/ghosts?framework=svelte", - { waitUntil: "networkidle" }, - ); - expect(response?.status()).toBe(200); - - const flow = page.locator('[data-ghost-demo="flow-lifecycle"]'); - await dragBetween( - page, - flow.locator('[data-demo-item="ghost-flow-outline"]'), - flow.locator('[data-demo-item="ghost-flow-review"]'), - { - beforeDrop: async () => { - await expect( - flow.locator('[data-snapsort-ghost-entry="target-spacer"]'), - ).toHaveCount(1); - await expect( - flow.locator('[data-snapsort-ghost-entry="pointer-preview"]'), - ).toHaveCount(1); - }, - }, - ); - await expect(flow.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); - await expect(flow.locator('[data-ghost-event="insert"]')).not.toHaveCount(0); - await expect(flow.locator('[data-ghost-event="remove"]')).not.toHaveCount(0); - - const overlay = page.locator('[data-ghost-demo="overlay-channels"]'); - await dragBetween( - page, - overlay.locator('[data-demo-item="ghost-overlay-alpha"]'), - overlay.locator('[data-demo-item="ghost-overlay-charlie"]'), - { - beforeDrop: async () => { - await expect( - overlay.locator('[data-snapsort-ghost-entry="source-spacer"]'), - ).toHaveCount(1); - await expect( - overlay.locator('[data-snapsort-ghost-entry="insertion-marker"]'), - ).toHaveCount(1); - }, - }, - ); - await expect(overlay.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); - await expect( - overlay.locator('[data-ghost-type="insertion-marker"]'), - ).not.toHaveCount(0); - await expect( - overlay.locator('[data-ghost-type="source-spacer"]'), - ).not.toHaveCount(0); - expect(pageErrors).toEqual([]); -}); - -test("SnapSort guide routes use the new session hierarchy without legacy fallbacks", async ({ - request, -}) => { - const currentSlugs = [ - "snapsort/guides/core-components", - "snapsort/guides/placement-modes", - "snapsort/guides/sessions/drag-start", - "snapsort/guides/sessions/ghosts", - "snapsort/guides/sessions/commit-and-cleanup", - "snapsort/guides/sessions/drop-policies", - "snapsort/examples", - "snapsort/examples/basics", - "snapsort/examples/containers", - "snapsort/examples/items", - "snapsort/examples/complete-interfaces", - "snapsort/examples/advanced-settings-and-callbacks", - ]; - const removedSlugs = [ - "snapsort/introduction/01_core_concepts", - "snapsort/introduction/01_setup", - "snapsort/guides/01_core_concepts", - "snapsort/guides/02_placement_modes", - "snapsort/guides/03_ghosts", - "snapsort/guides/03_session_lifecycle", - "snapsort/guides/04_drop_policies", - "snapsort/guides/sessions/placement-modes", - "snapsort/guides/sessions/advanced-settings-and-callbacks", - ]; - - for (const slug of currentSlugs) { - for (const suffix of ["", ".md"]) { - const path = `/docs/${slug}${suffix}`; - const response = await request.get(path, { maxRedirects: 0 }); - expect(response.status(), path).toBe(200); - } - } - - for (const slug of removedSlugs) { - for (const suffix of ["", ".md"]) { - const path = `/docs/${slug}${suffix}`; - const response = await request.get(path, { maxRedirects: 0 }); - expect(response.status(), path).toBe(404); - } - } - - const retiredGallery = await request.get("/snapsort/gallery", { - maxRedirects: 0, - }); - expect(retiredGallery.status()).toBe(404); - - const knownSource = await request.get( - "/docs/snapsort/examples/source/todo-list", - ); - expect(knownSource.status()).toBe(200); - expect(knownSource.headers()["content-type"]).toContain("text/html"); - expect(await knownSource.text()).toContain('
 {
-  for (const [path, destination] of [
-    [
-      "/docs/snapsort/guides/sessions",
-      "/docs/snapsort/guides/sessions/drag-start",
-    ],
-    [
-      "/docs/snapsort/guides/sessions.md",
-      "/docs/snapsort/guides/sessions/drag-start.md",
-    ],
-    [
-      "/docs/snapsort/guides/sessions?framework=react",
-      "/docs/snapsort/guides/sessions/drag-start?framework=react",
-    ],
-    [
-      "/docs/snapsort/guides/sessions.md?framework=react",
-      "/docs/snapsort/guides/sessions/drag-start.md?framework=react",
-    ],
-  ]) {
-    const redirectResponse = await request.get(path, { maxRedirects: 0 });
-    expect(redirectResponse.status()).toBe(308);
-    expect(redirectResponse.headers().location).toBe(destination);
-  }
-
-  const sitemapResponse = await request.get("/sitemap.xml");
-  expect(sitemapResponse.ok()).toBe(true);
-  const sitemap = await sitemapResponse.text();
-  expect(sitemap).toContain(
-    "https://snapengine.dev/docs/snapsort/guides/sessions/drag-start",
-  );
-  expect(sitemap).not.toContain(
-    "https://snapengine.dev/docs/snapsort/guides/sessions",
-  );
-
-  await page.setViewportSize({ width: 1280, height: 900 });
-  await page.goto("/docs/snapsort/guides/sessions/drag-start?framework=svelte");
-  await expect(page.locator(".doc-article > p").first()).toContainText(
-    "DragSession",
-  );
-  const applicationBoundaryHeading = page.getByRole("heading", {
-    name: "Application Boundary",
-    level: 2,
-  });
-  const dragStartHeading = page.getByRole("heading", {
-    name: "onDragStart",
-    level: 2,
-  });
-  await expect(applicationBoundaryHeading).toBeVisible();
-  await expect(dragStartHeading).toBeVisible();
-  const [applicationBoundaryBox, dragStartBox] = await Promise.all([
-    applicationBoundaryHeading.boundingBox(),
-    dragStartHeading.boundingBox(),
-  ]);
-  expect(applicationBoundaryBox).not.toBeNull();
-  expect(dragStartBox).not.toBeNull();
-  expect(applicationBoundaryBox!.y).toBeLessThan(dragStartBox!.y);
-  await expect(
-    page.locator(".pagination-link.prev .pagination-title"),
-  ).toHaveText("Placement Modes");
-  await expect(
-    page.locator(".pagination-link.next .pagination-title"),
-  ).toHaveText("Drags and Ghosts");
-
-  const response = await page.goto(
-    "/docs/snapsort/guides/sessions/ghosts?framework=svelte",
-    { waitUntil: "networkidle" },
-  );
-  expect(response?.status()).toBe(200);
-
-  const guidesSection = page.locator(".doc-sidebar .sidebar-section", {
-    has: page.locator(".section-title", { hasText: "Guides" }),
-  });
-  const topLevelItems = guidesSection.locator(
-    ":scope > ul > li > :is(a, button)",
-  );
-  await expect(topLevelItems).toHaveText([
-    "Core Components",
-    "Placement Modes",
-    "Drag Sessions",
-    "Examples",
-  ]);
-
-  const sessionsButton = guidesSection.locator(
-    ":scope > ul > li > button.doc-navigation-group",
-    { hasText: "Drag Sessions" },
-  );
-  const sessionsNode = sessionsButton.locator("..");
-  await expect(sessionsButton).toHaveClass(/ancestor/);
-  await expect(sessionsButton).toHaveAttribute("aria-expanded", "true");
-  await expect(sessionsButton).not.toHaveAttribute("href", /./);
-  await expect(sessionsNode.locator(":scope > ul > li > a")).toHaveText([
-    "Drag Start",
-    "Drags and Ghosts",
-    "Commit and Cleanup",
-    "Programmatic Moves",
-  ]);
-  await expect(
-    sessionsNode.locator('a[href="/docs/snapsort/guides/placement-modes"]'),
-  ).toHaveCount(0);
-  await expect(
-    sessionsNode.locator(
-      ':scope > ul > li > a[href="/docs/snapsort/guides/sessions/ghosts"]',
-    ),
-  ).toHaveAttribute("aria-current", "page");
-
-  await sessionsButton.click();
-  await expect(sessionsButton).toHaveAttribute("aria-expanded", "false");
-  await expect(sessionsNode.locator(":scope > ul")).toBeHidden();
-  await sessionsButton.click();
-  await expect(sessionsButton).toHaveAttribute("aria-expanded", "true");
-  await expect(sessionsNode.locator(":scope > ul")).toBeVisible();
-
-  const examplesLink = guidesSection.locator(
-    ':scope > ul > li > a[href="/docs/snapsort/examples"]',
-  );
-  const examplesNode = examplesLink.locator("..");
-  await expect(examplesNode.locator(":scope > ul > li > a")).toHaveText([
-    "Basics",
-    "Container Recipes",
-    "Item Recipes",
-    "Complete Interfaces",
-    "Advanced Session Settings and Callbacks",
-  ]);
-
-  const ghostsBreadcrumb = page.locator(".doc-breadcrumb");
-  await expect(
-    ghostsBreadcrumb.getByRole("link", { name: "Drag Sessions" }),
-  ).toHaveCount(0);
-  await expect(ghostsBreadcrumb).toContainText("Drag Sessions");
-  await expect(ghostsBreadcrumb.locator('[aria-current="page"]')).toHaveText(
-    "Drags and Ghosts",
-  );
-  await expect(
-    page.locator(".pagination-link.prev .pagination-title"),
-  ).toHaveText("Drag Start");
-  await expect(
-    page.locator(".pagination-link.next .pagination-title"),
-  ).toHaveText("Commit and Cleanup");
-
-  await page.goto("/docs/snapsort/guides/placement-modes?framework=svelte");
-  const placementLink = guidesSection.locator(
-    ':scope > ul > li > a[href="/docs/snapsort/guides/placement-modes"]',
-  );
-  await expect(placementLink).toHaveAttribute("aria-current", "page");
-  await expect(sessionsButton).not.toHaveClass(/ancestor/);
-
-  const placementBreadcrumb = page.locator(".doc-breadcrumb");
-  await expect(placementBreadcrumb).toContainText("Guides");
-  await expect(placementBreadcrumb.locator('[aria-current="page"]')).toHaveText(
-    "Placement Modes",
-  );
-  await expect(
-    placementBreadcrumb.getByRole("link", { name: "Drag Sessions" }),
-  ).toHaveCount(0);
-
-  await page.goto("/docs/snapsort/examples/containers?framework=svelte");
-  await expect(examplesLink).toHaveClass(/ancestor/);
-  await expect(
-    examplesNode.locator(
-      ':scope > ul > li > a[href="/docs/snapsort/examples/containers"]',
-    ),
-  ).toHaveAttribute("aria-current", "page");
-  await expect(
-    page.locator(".doc-breadcrumb").getByRole("link", { name: "Examples" }),
-  ).toHaveAttribute("href", "/docs/snapsort/examples");
-
-  await page.setViewportSize({ width: 390, height: 844 });
-  await page.goto("/docs/snapsort/guides/sessions/ghosts?framework=svelte", {
-    waitUntil: "networkidle",
-  });
-  const primaryNav = page.getByRole("navigation", {
-    name: "Primary navigation",
-  });
-  const mobileNavigationTrigger = primaryNav.getByRole("button", {
-    name: "Toggle navigation",
-  });
-  await mobileNavigationTrigger.click();
-  await expect(mobileNavigationTrigger).toHaveAttribute(
-    "aria-expanded",
-    "true",
-  );
-
-  const mobileDocs = primaryNav.locator(".mobile-doc-navigation");
-  await expect(mobileDocs).toBeVisible();
-  await expect(mobileDocs).toContainText("SnapSort docs");
-  const mobileGuides = mobileDocs.locator(".mobile-doc-section", {
-    has: page.locator(".mobile-doc-section-title", {
-      hasText: "Guides",
-    }),
-  });
-  await expect(
-    mobileGuides.locator(":scope > ul > li > :is(a, button)"),
-  ).toHaveText([
-    "Core Components",
-    "Placement Modes",
-    "Drag Sessions",
-    "Examples",
-  ]);
-  const mobileSessionsButton = mobileGuides.locator(
-    ":scope > ul > li > button.mobile-doc-group",
-    { hasText: "Drag Sessions" },
-  );
-  const mobileSessionsNode = mobileSessionsButton.locator("..");
-  await expect(mobileSessionsButton).toHaveAttribute("aria-expanded", "true");
-  await expect(mobileSessionsNode.locator(":scope > ul > li > a")).toHaveText([
-    "Drag Start",
-    "Drags and Ghosts",
-    "Commit and Cleanup",
-    "Programmatic Moves",
-  ]);
-  await expect(
-    mobileSessionsNode.locator(
-      'a[href="/docs/snapsort/guides/placement-modes"]',
-    ),
-  ).toHaveCount(0);
-
-  await mobileSessionsButton.click();
-  await expect(mobileSessionsButton).toHaveAttribute("aria-expanded", "false");
-  await expect(mobileSessionsNode.locator(":scope > ul")).toBeHidden();
-  await expect(mobileNavigationTrigger).toHaveAttribute(
-    "aria-expanded",
-    "true",
-  );
-  await mobileSessionsButton.click();
-  await expect(mobileSessionsButton).toHaveAttribute("aria-expanded", "true");
-  await expect(mobileSessionsNode.locator(":scope > ul")).toBeVisible();
-
-  const mobileExamplesLink = mobileGuides.locator(
-    ':scope > ul > li > a[href="/docs/snapsort/examples"]',
-  );
-  await expect(
-    mobileExamplesLink.locator("..").locator(":scope > ul > li > a"),
-  ).toHaveText([
-    "Basics",
-    "Container Recipes",
-    "Item Recipes",
-    "Complete Interfaces",
-    "Advanced Session Settings and Callbacks",
-  ]);
-});
-
-test("SnapSort example source tabs recover from a failed lazy request", async ({
-  page,
-}) => {
-  let sourceAttempts = 0;
-  await page.route(
-    "**/docs/snapsort/examples/source/container-intro-basic",
-    async (route) => {
-      sourceAttempts += 1;
-      if (sourceAttempts === 1) {
-        await route.fulfill({ status: 503, body: "Unavailable" });
-        return;
-      }
-      await route.continue();
-    },
-  );
-
-  await page.goto("/docs/snapsort/examples/basics", {
-    waitUntil: "networkidle",
-  });
-  expect(sourceAttempts).toBe(0);
-
-  const example = page.locator('[data-demo-code-tabs="container-intro-basic"]');
-  await example.getByRole("tab", { name: "Svelte source" }).click();
-  await expect(example.getByRole("alert")).toContainText(
-    "Could not load the Svelte source.",
-  );
-  await example.getByRole("button", { name: "Retry" }).click();
-  await expect(example.locator("pre.shiki.display")).toHaveCount(1);
-  expect(sourceAttempts).toBe(2);
-});
-
-test("article outlines expose Markdown headings without demo internals", async ({
-  page,
-}) => {
-  await page.setViewportSize({ width: 1280, height: 900 });
-  await page.goto("/docs/snapsort/guides/placement-modes?framework=svelte");
-
-  const rail = page.locator('[data-article-outline="rail"]');
-  const inline = page.locator('[data-article-outline="inline"]');
-  await expect(rail).toBeVisible();
-  await expect(inline).toBeHidden();
-  const desktopOutlineGeometry = await page.evaluate(() => {
-    const content = document.querySelector(".doc-content");
-    const outline = document.querySelector('[data-article-outline="rail"]');
-    if (
-      !(content instanceof HTMLElement) ||
-      !(outline instanceof HTMLElement)
-    ) {
-      throw new Error("Missing desktop documentation outline geometry");
-    }
-
-    const contentRect = content.getBoundingClientRect();
-    const outlineRect = outline.getBoundingClientRect();
-    return {
-      contentRight: contentRect.right,
-      outlineLeft: outlineRect.left,
-    };
-  });
-  expect(desktopOutlineGeometry.outlineLeft).toBeGreaterThanOrEqual(
-    desktopOutlineGeometry.contentRight - 1,
-  );
-  await expect(rail.locator("a")).toHaveText([
-    "Euclidean",
-    "Insertion",
-    "Swap",
-    "Progressive",
-  ]);
-  await expect(rail.locator('[data-outline-depth="2"]')).toHaveCount(4);
-  await expect(rail.locator('[data-outline-depth="3"]')).toHaveCount(0);
-
-  for (const [title, id] of [
-    ["Euclidean", "euclidean"],
-    ["Insertion", "insertion"],
-    ["Swap", "swap"],
-    ["Progressive", "progressive"],
-  ]) {
-    await expect(
-      rail.getByRole("link", { name: title, exact: true }),
-    ).toHaveAttribute("href", `#${id}`);
-    await expect(page.locator(`h2#${id}`)).toHaveCount(1);
-  }
-
-  await rail.getByRole("link", { name: "Insertion", exact: true }).click();
-  await expect(page).toHaveURL(/#insertion$/);
-  await expect(page.locator("h2#insertion")).toBeInViewport();
-  await page.evaluate(() =>
-    window.scrollTo(0, document.documentElement.scrollHeight),
-  );
-  await expect(
-    rail.getByRole("link", { name: "Progressive", exact: true }),
-  ).toHaveAttribute("aria-current", "location");
-  expect(new URL(page.url()).hash).toBe("#insertion");
-
-  await page.goto("/docs/snapsort/guides/sessions/ghosts?framework=svelte");
-  const ghostsRail = page.locator('[data-article-outline="rail"]');
-  await expect(
-    page.getByRole("heading", { name: "Active ghosts", level: 3 }),
-  ).toHaveCount(2);
-  await expect(
-    page.getByRole("heading", { name: "Lifecycle ledger", level: 3 }),
-  ).toHaveCount(2);
-  await expect(
-    ghostsRail.getByRole("link", { name: "Active ghosts" }),
-  ).toHaveCount(0);
-  await expect(
-    ghostsRail.getByRole("link", { name: "Lifecycle ledger" }),
-  ).toHaveCount(0);
-
-  await page.goto("/docs/snapsort/reference/svelte/item?framework=svelte");
-  const itemRail = page.locator('[data-article-outline="rail"]');
-  const childrenLinks = itemRail.getByRole("link", {
-    name: "children",
-    exact: true,
-  });
-  await expect(childrenLinks).toHaveCount(2);
-  await expect(childrenLinks.nth(0)).toHaveAttribute("href", "#children");
-  await expect(childrenLinks.nth(1)).toHaveAttribute("href", "#children-1");
-  await expect(page.locator("h3#children")).toHaveCount(1);
-  await expect(page.locator("h3#children-1")).toHaveCount(1);
-
-  await page.goto(
-    "/docs/snapsort/reference/react/container?framework=react#callbacks",
-  );
-  await expect(page.locator("h2#callbacks")).toBeInViewport();
-
-  await page.goto("/docs/snapsort/introduction");
-  await expect(page.locator("[data-article-outline]")).toHaveCount(0);
-
-  await page.goto("/docs");
-  const docsHomeRail = page.locator('[data-article-outline="rail"]');
-  await expect(page.locator(".doc-sidebar")).toHaveCount(0);
-  await expect(page.locator(".doc-breadcrumb")).toHaveText("Docs");
-  await expect(docsHomeRail).toBeVisible();
-  await expect(docsHomeRail.locator("a")).toHaveText([
-    "SnapEngine Core",
-    "Assets",
-    "SnapSort",
-    "SnapLine",
-    "SnapZap",
-  ]);
-
-  await page.setViewportSize({ width: 390, height: 844 });
-  await page.goto("/docs/snapsort/guides/placement-modes?framework=svelte", {
-    waitUntil: "networkidle",
-  });
-  const mobileRail = page.locator('[data-article-outline="rail"]');
-  const mobileInline = page.locator('[data-article-outline="inline"]');
-  await expect(mobileRail).toBeHidden();
-  await expect(mobileInline).toBeVisible();
-  const outlineSummary = mobileInline.locator("summary");
-  await outlineSummary.focus();
-  await expect(outlineSummary).toBeFocused();
-  await page.keyboard.press("Enter");
-  await expect(mobileInline).toHaveAttribute("open", "");
-  await expect(mobileInline.locator("a")).toHaveText([
-    "Euclidean",
-    "Insertion",
-    "Swap",
-    "Progressive",
-  ]);
-  await mobileInline
-    .getByRole("link", { name: "Insertion", exact: true })
-    .click();
-  await expect(mobileInline).not.toHaveAttribute("open", "");
-  await expect(outlineSummary).toBeFocused();
-  await expect(page.locator("h2#insertion")).toBeInViewport();
-  const mobilePageWidth = await page.locator("html").evaluate((element) => ({
-    clientWidth: element.clientWidth,
-    scrollWidth: element.scrollWidth,
-  }));
-  expect(mobilePageWidth.scrollWidth).toBeLessThanOrEqual(
-    mobilePageWidth.clientWidth,
-  );
-});
-
-test("insertion placement demo moves items through a nested layers tree", async ({
-  page,
-}) => {
-  const pageErrors: Error[] = [];
-  page.on("pageerror", (error) => pageErrors.push(error));
-  await page.goto("/docs/snapsort/guides/placement-modes?framework=svelte", {
-    waitUntil: "networkidle",
-  });
-
-  const demo = page.locator(".insertion-demo-tree");
-  await expect(page.locator(".euclidean-demo-list")).toHaveCount(2);
-  await expect(page.locator(".progressive-demo-list")).toHaveCount(1);
-  await expect(page.locator(".swap-demo-list")).toHaveCount(1);
-  const unaffectedLabels = await Promise.all([
-    page.locator(".euclidean-demo-list").allTextContents(),
-    page.locator(".progressive-demo-list").allTextContents(),
-    page.locator(".swap-demo-list").allTextContents(),
-  ]);
-  await expect(demo.locator(".insertion-tree-row")).toHaveCount(8);
-  await expect(demo.locator(".insertion-tree-label")).toHaveText([
-    "Item 1",
-    "Item 2",
-    "Item 3",
-    "Item 4",
-    "Item 5",
-    "Item 6",
-    "Item 7",
-    "Item 8",
-  ]);
-  await expect(demo.locator(".insertion-tree-group")).toHaveCount(2);
-  await expect(demo.locator(":scope > .insertion-tree-item")).toHaveCount(3);
-  await expect(demo.locator(":scope > .insertion-tree-group")).toHaveCount(1);
-
-  const labelOffsets = await Promise.all(
-    ["one", "four", "seven"].map((itemId) =>
-      demo
-        .locator(
-          `[data-snapsort-item-id="${itemId}"] .insertion-tree-label, [data-placement-tree-id="${itemId}"] > .insertion-tree-row .insertion-tree-label`,
-        )
-        .boundingBox(),
-    ),
-  );
-  expect(labelOffsets.every(Boolean)).toBe(true);
-  expect(labelOffsets[1]!.x).toBeGreaterThan(labelOffsets[0]!.x);
-  expect(labelOffsets[2]!.x).toBeGreaterThan(labelOffsets[1]!.x);
-
-  const itemEight = demo.locator('[data-snapsort-item-id="eight"]');
-  const itemFour = demo.locator('[data-snapsort-item-id="four"]');
-  const itemSeven = demo.locator('[data-snapsort-item-id="seven"]');
-  const [initialItemEightBox, initialItemFourBox] = await Promise.all([
-    itemEight.boundingBox(),
-    itemFour.boundingBox(),
-  ]);
-  expect(initialItemEightBox).not.toBeNull();
-  expect(initialItemFourBox).not.toBeNull();
-  const sharedVirtualLeft =
-    initialItemFourBox!.x +
-    initialItemFourBox!.width / 2 -
-    initialItemEightBox!.width / 2;
-  await expect(
-    demo
-      .locator('[data-placement-tree-id="six"]')
-      .locator('[data-snapsort-item-id="seven"]'),
-  ).toHaveCount(1);
-  let firstLevelMarkerBox: Awaited> = null;
-  let firstLevelNeighborBox: Awaited> = null;
-  let firstLevelDotBox: Awaited> = null;
-  await dragBetween(page, itemEight, itemFour, {
-    beforeDrop: async () => {
-      const marker = demo.locator('[data-snapsort-ghost="insertion"]');
-      const dot = marker.locator(".insertion-tree-marker-dot");
-      await expect(marker).toHaveCount(1);
-      await expect(marker).toHaveAttribute("data-tree-marker-hidden", "false");
-      await expect(marker).toHaveCSS("visibility", "visible");
-      await expect(dot).toHaveAttribute("aria-hidden", "true");
-      [firstLevelMarkerBox, firstLevelNeighborBox, firstLevelDotBox] =
-        await Promise.all([
-          marker.boundingBox(),
-          itemFour.boundingBox(),
-          dot.boundingBox(),
-        ]);
-    },
-  });
-
-  await expect(
-    demo
-      .locator('[data-placement-tree-id="three"]')
-      .locator('[data-snapsort-item-id="eight"]'),
-  ).toHaveCount(1);
-  await dragBetween(
-    page,
-    itemEight,
-    demo.locator('[data-snapsort-item-id="two"]'),
-  );
-  await expect(
-    demo.locator(':scope > [data-snapsort-item-id="eight"]'),
-  ).toHaveCount(1);
-
-  const [alternateSourceBox, alternateTargetBox, alternateGroupBox] =
-    await Promise.all([
-      itemEight.boundingBox(),
-      itemFour.boundingBox(),
-      demo.locator('[data-placement-tree-id="three"]').boundingBox(),
-    ]);
-  expect(alternateSourceBox).not.toBeNull();
-  expect(alternateTargetBox).not.toBeNull();
-  expect(alternateGroupBox).not.toBeNull();
-  const alternateGrabOffset = alternateSourceBox!.width - 2;
-  const alternatePointerX = sharedVirtualLeft + alternateGrabOffset;
-  expect(sharedVirtualLeft).toBeGreaterThanOrEqual(alternateGroupBox!.x);
-  expect(alternatePointerX).toBeGreaterThan(
-    alternateGroupBox!.x + alternateGroupBox!.width,
-  );
-  const alternateStart = {
-    x: alternateSourceBox!.x + alternateGrabOffset,
-    y: alternateSourceBox!.y + alternateSourceBox!.height / 2,
-  };
-  await page.mouse.move(alternateStart.x, alternateStart.y);
-  await page.mouse.down();
-  await page.mouse.move(alternateStart.x + 7, alternateStart.y + 7);
-  await page.waitForTimeout(60);
-  await page.mouse.move(
-    alternatePointerX,
-    alternateTargetBox!.y + alternateTargetBox!.height / 2,
-    { steps: 12 },
-  );
-  await page.waitForTimeout(120);
-  const offsetAwareMarker = demo.locator(
-    '[data-placement-tree-id="three"] > [data-snapsort-ghost="insertion"]',
-  );
-  await expect(offsetAwareMarker).toHaveCount(1);
-  const offsetAwareMarkerBox = await offsetAwareMarker.boundingBox();
-  expect(offsetAwareMarkerBox).not.toBeNull();
-  expect(offsetAwareMarkerBox!.x).toBeCloseTo(firstLevelMarkerBox!.x, 0);
-  expect(offsetAwareMarkerBox!.width).toBeCloseTo(
-    firstLevelMarkerBox!.width,
-    0,
-  );
-  await page.mouse.up();
-  await page.waitForTimeout(150);
-  await expect(
-    demo
-      .locator('[data-placement-tree-id="three"]')
-      .locator('[data-snapsort-item-id="eight"]'),
-  ).toHaveCount(1);
-
-  await dragBetween(
-    page,
-    itemEight,
-    demo.locator('[data-snapsort-item-id="two"]'),
-  );
-  await expect(
-    demo.locator(':scope > [data-snapsort-item-id="eight"]'),
-  ).toHaveCount(1);
-
-  let secondLevelMarkerBox: Awaited> = null;
-  let secondLevelNeighborBox: Awaited> =
-    null;
-  await dragBetween(page, itemEight, itemSeven, {
-    beforeDrop: async () => {
-      const marker = demo.locator('[data-snapsort-ghost="insertion"]');
-      await expect(marker).toHaveCount(1);
-      [secondLevelMarkerBox, secondLevelNeighborBox] = await Promise.all([
-        marker.boundingBox(),
-        itemSeven.boundingBox(),
-      ]);
-    },
-  });
-  await expect(
-    demo
-      .locator('[data-placement-tree-id="six"]')
-      .locator('[data-snapsort-item-id="eight"]'),
-  ).toHaveCount(1);
-
-  for (const [markerBox, neighborBox] of [
-    [firstLevelMarkerBox, firstLevelNeighborBox],
-    [secondLevelMarkerBox, secondLevelNeighborBox],
-  ]) {
-    expect(markerBox).not.toBeNull();
-    expect(neighborBox).not.toBeNull();
-    expect(Math.abs(markerBox!.x - neighborBox!.x)).toBeLessThanOrEqual(1);
-    expect(
-      Math.abs(
-        markerBox!.x + markerBox!.width - (neighborBox!.x + neighborBox!.width),
-      ),
-    ).toBeLessThanOrEqual(1);
-  }
-  expect(secondLevelMarkerBox!.x).toBeGreaterThan(firstLevelMarkerBox!.x);
-  expect(secondLevelMarkerBox!.width).toBeLessThan(firstLevelMarkerBox!.width);
-  expect(firstLevelMarkerBox!.height).toBeCloseTo(3, 0);
-  expect(firstLevelDotBox).not.toBeNull();
-  expect(firstLevelDotBox!.width).toBeCloseTo(7, 0);
-  expect(firstLevelDotBox!.height).toBeCloseTo(7, 0);
-  expect(firstLevelDotBox!.x).toBeGreaterThanOrEqual(firstLevelMarkerBox!.x);
-  expect(firstLevelDotBox!.x + firstLevelDotBox!.width).toBeLessThanOrEqual(
-    firstLevelMarkerBox!.x + firstLevelMarkerBox!.width,
-  );
-  await expect(demo.locator("[data-snapsort-ghost]")).toHaveCount(0);
-  await expect(page.locator(".euclidean-demo-list")).toHaveText(
-    unaffectedLabels[0],
-  );
-  await expect(page.locator(".progressive-demo-list")).toHaveText(
-    unaffectedLabels[1],
-  );
-  await expect(page.locator(".swap-demo-list")).toHaveText(unaffectedLabels[2]);
-
-  await dragBetween(
-    page,
-    itemEight,
-    demo.locator('[data-snapsort-item-id="two"]'),
-  );
-  await expect(
-    demo.locator(':scope > [data-snapsort-item-id="eight"]'),
-  ).toHaveCount(1);
-
-  const itemThreeRow = demo.locator(
-    '[data-placement-tree-id="three"] > .insertion-tree-group-row',
-  );
-  const itemSixRow = demo.locator(
-    '[data-placement-tree-id="six"] > .insertion-tree-group-row',
-  );
-  const groupThree = demo.locator('[data-placement-tree-id="three"]');
-  const groupSix = demo.locator('[data-placement-tree-id="six"]');
-  const moveHeldPointerTo = async (target: Locator) => {
-    const box = await target.boundingBox();
-    if (!box) throw new Error("Held-drag target has no layout box.");
-    await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, {
-      steps: 8,
-    });
-    await page.waitForTimeout(120);
-  };
-
-  await page.evaluate(() => {
-    document.addEventListener(
-      "pointerdown",
-      (event) => {
-        document.documentElement.dataset.testActivePointerId = String(
-          event.pointerId,
-        );
-      },
-      { capture: true, once: true },
-    );
-  });
-  const [cancelSourceBox, cancelTargetBox] = await Promise.all([
-    itemEight.boundingBox(),
-    itemThreeRow.boundingBox(),
-  ]);
-  expect(cancelSourceBox).not.toBeNull();
-  expect(cancelTargetBox).not.toBeNull();
-  await page.mouse.move(
-    cancelSourceBox!.x + cancelSourceBox!.width / 2,
-    cancelSourceBox!.y + cancelSourceBox!.height / 2,
-  );
-  await page.mouse.down();
-  await page.mouse.move(cancelSourceBox!.x + 7, cancelSourceBox!.y + 7);
-  await moveHeldPointerTo(itemThreeRow);
-  await expect(groupThree).toHaveAttribute(
-    "data-tree-group-highlighted",
-    "true",
-  );
-  await expect(demo.locator('[data-snapsort-ghost="insertion"]')).toHaveCSS(
-    "visibility",
-    "hidden",
-  );
-  await page.evaluate(
-    ({ x, y }) => {
-      const pointerId = Number(
-        document.documentElement.dataset.testActivePointerId,
-      );
-      document.dispatchEvent(
-        new PointerEvent("pointercancel", {
-          bubbles: true,
-          buttons: 0,
-          clientX: x,
-          clientY: y,
-          pointerId,
-          pointerType: "mouse",
-        }),
-      );
-      delete document.documentElement.dataset.testActivePointerId;
-    },
-    {
-      x: cancelTargetBox!.x + cancelTargetBox!.width / 2,
-      y: cancelTargetBox!.y + cancelTargetBox!.height / 2,
-    },
-  );
-  await page.mouse.up();
-  await page.waitForTimeout(150);
-  await expect(groupThree).toHaveAttribute(
-    "data-tree-group-highlighted",
-    "false",
-  );
-  await expect(demo.locator("[data-snapsort-ghost]")).toHaveCount(0);
-  await expect(
-    demo.locator(':scope > [data-snapsort-item-id="eight"]'),
-  ).toHaveCount(1);
-
-  await dragBetween(page, itemEight, itemThreeRow, {
-    beforeDrop: async () => {
-      const marker = demo.locator('[data-snapsort-ghost="insertion"]');
-      await expect(groupThree).toHaveAttribute(
-        "data-tree-group-highlighted",
-        "true",
-      );
-      await expect(marker).toHaveCount(1);
-      await expect(marker).toHaveAttribute("data-tree-marker-hidden", "true");
-      await expect(marker).toHaveCSS("visibility", "hidden");
-      await expect(marker.locator(".insertion-tree-marker-dot")).toHaveCount(1);
-
-      await moveHeldPointerTo(itemFour);
-      await expect(groupThree).toHaveAttribute(
-        "data-tree-group-highlighted",
-        "false",
-      );
-      await expect(marker).toHaveAttribute("data-tree-marker-hidden", "false");
-      await expect(marker).toHaveCSS("visibility", "visible");
-
-      await moveHeldPointerTo(itemThreeRow);
-      await expect(groupThree).toHaveAttribute(
-        "data-tree-group-highlighted",
-        "true",
-      );
-      await expect(marker).toHaveCSS("visibility", "hidden");
-    },
-  });
-  await expect(
-    groupThree.locator('[data-snapsort-item-id="eight"]'),
-  ).toHaveCount(1);
-  await expect(groupThree).toHaveAttribute(
-    "data-tree-group-highlighted",
-    "false",
-  );
-  await expect(demo.locator("[data-snapsort-ghost]")).toHaveCount(0);
-
-  await dragBetween(
-    page,
-    itemEight,
-    demo.locator('[data-snapsort-item-id="two"]'),
-  );
-  await expect(
-    demo.locator(':scope > [data-snapsort-item-id="eight"]'),
-  ).toHaveCount(1);
-
-  await dragBetween(page, itemEight, itemSixRow, {
-    beforeDrop: async () => {
-      const marker = demo.locator('[data-snapsort-ghost="insertion"]');
-      await expect(groupSix).toHaveAttribute(
-        "data-tree-group-highlighted",
-        "true",
-      );
-      await expect(marker).toHaveCount(1);
-      await expect(marker).toHaveAttribute("data-tree-marker-hidden", "true");
-      await expect(marker).toHaveCSS("visibility", "hidden");
-    },
-  });
-  await expect(groupSix.locator('[data-snapsort-item-id="eight"]')).toHaveCount(
-    1,
-  );
-  await expect(groupSix).toHaveAttribute(
-    "data-tree-group-highlighted",
-    "false",
-  );
-  await expect(demo.locator("[data-snapsort-ghost]")).toHaveCount(0);
-
-  await dragBetween(page, itemThreeRow, itemSeven);
-  await expect(
-    demo
-      .locator('[data-placement-tree-id="six"]')
-      .locator('[data-placement-tree-id="three"]'),
-  ).toHaveCount(0);
-  await expect(demo.locator("[data-snapsort-ghost]")).toHaveCount(0);
-  expect(pageErrors).toEqual([]);
-
-  await page.setViewportSize({ width: 390, height: 844 });
-  await page.reload({ waitUntil: "networkidle" });
-  const pageWidth = await page.locator("html").evaluate((element) => ({
-    clientWidth: element.clientWidth,
-    scrollWidth: element.scrollWidth,
-  }));
-  expect(pageWidth.scrollWidth).toBeLessThanOrEqual(pageWidth.clientWidth);
-});
-
-test("SnapSort reference exposes paired Ghost pages and shared policies", async ({
-  page,
-  request,
-}) => {
-  for (const slug of [
-    "snapsort/reference/svelte/ghost",
-    "snapsort/reference/react/ghost",
-    "snapsort/reference/drag-session",
-    "snapsort/reference/callbacks",
-  ]) {
-    for (const suffix of ["", ".md"]) {
-      const response = await request.get(`/docs/${slug}${suffix}`);
-      expect(response.status(), `${slug}${suffix}`).toBe(200);
-    }
-  }
-
-  const referenceOverviewResponse = await request.get(
-    "/docs/snapsort/reference.md",
-  );
-  expect(referenceOverviewResponse.status()).toBe(200);
-  const referenceOverview = await referenceOverviewResponse.text();
-  expect(referenceOverview).toContain("/docs/snapsort/reference/svelte/ghost");
-  expect(referenceOverview).toContain("/docs/snapsort/reference/react/ghost");
-  expect(referenceOverview).toContain("/docs/snapsort/reference/drag-session");
-  expect(referenceOverview).toContain("/docs/snapsort/reference/callbacks");
-
-  const sitemapResponse = await request.get("/sitemap.xml");
-  expect(sitemapResponse.status()).toBe(200);
-  const sitemap = await sitemapResponse.text();
-  for (const slug of [
-    "snapsort/reference/svelte/ghost",
-    "snapsort/reference/react/ghost",
-    "snapsort/reference/drag-session",
-    "snapsort/reference/callbacks",
-  ]) {
-    expect(sitemap).toContain(`https://snapengine.dev/docs/${slug}`);
-  }
-
-  const response = await page.goto(
-    "/docs/snapsort/reference/svelte?framework=svelte",
-  );
-  expect(response?.status()).toBe(200);
-  await expect(page).toHaveURL(
-    /\/docs\/snapsort\/reference\/svelte\/container(?:\?framework=svelte)?$/,
-  );
-
-  const sidebar = page.locator(".doc-sidebar");
-  await expect(sidebar.getByText("SnapSort", { exact: true })).toHaveCount(1);
-  await expect(
-    sidebar.getByRole("link", { name: "Container", exact: true }),
-  ).toHaveCount(1);
-  await expect(
-    sidebar.getByRole("link", { name: "Item", exact: true }),
-  ).toHaveCount(1);
-  await expect(
-    sidebar.getByRole("link", { name: "Ghost", exact: true }),
-  ).toHaveCount(1);
-  await expect(
-    sidebar.getByRole("link", { name: "DragSession", exact: true }),
-  ).toHaveCount(1);
-  await expect(
-    sidebar.getByRole("link", { name: "Standard Callbacks", exact: true }),
-  ).toHaveCount(1);
-  await expect(
-    sidebar.getByRole("link", { name: /Svelte (?:Overview|API)/ }),
-  ).toHaveCount(0);
-
-  const referenceTitle = sidebar.getByText("Reference", { exact: true });
-  const containerLink = sidebar.getByRole("link", {
-    name: "Container",
-    exact: true,
-  });
-  const [titleBox, linkBox] = await Promise.all([
-    referenceTitle.boundingBox(),
-    containerLink.boundingBox(),
-  ]);
-  expect(titleBox).not.toBeNull();
-  expect(linkBox).not.toBeNull();
-  expect(linkBox!.x).toBeCloseTo(titleBox!.x, 0);
-
-  await page.goto("/docs/snapsort/reference/svelte/ghost?framework=svelte", {
-    waitUntil: "networkidle",
-  });
-  await expect(
-    page.getByRole("heading", { name: "Component Properties", level: 2 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "ghost", exact: true, level: 3 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "GhostState", exact: true, level: 2 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "insertionMarkerRect()", level: 3 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "Appendix", level: 2 }),
-  ).toBeVisible();
-  await expect(
-    page.locator(".pagination-link.prev .pagination-title"),
-  ).toHaveText("Item");
-  await expect(
-    page.locator(".pagination-link.next .pagination-title"),
-  ).toHaveText("DragSession");
-
-  await page.locator("#desktop-doc-framework").selectOption("react");
-  await expect(page).toHaveURL(
-    /\/docs\/snapsort\/reference\/react\/ghost\?framework=react$/,
-  );
-  await expect(page.getByRole("article")).toContainText(
-    'import { Ghost } from "@snap-engine/snapsort/react"',
-  );
-  await expect(
-    page
-      .locator(".doc-sidebar")
-      .getByRole("link", { name: "Ghost", exact: true }),
-  ).toHaveAttribute("aria-current", "page");
-
-  await page.goto("/docs/snapsort/reference/drag-session?framework=vanilla", {
-    waitUntil: "networkidle",
-  });
-  const vanillaReference = page.locator(".doc-sidebar .sidebar-section", {
-    has: page.locator(".section-title", { hasText: "Reference" }),
-  });
-  await expect(vanillaReference.locator(":scope > ul > li > a")).toHaveText([
-    "DragSession",
-    "Standard Callbacks",
-  ]);
-  await expect(
-    page.getByRole("heading", { name: "root", exact: true, level: 3 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "status", exact: true, level: 3 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "dragVisual", exact: true, level: 3 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "dropEffect", exact: true, level: 3 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "Appendix", level: 2 }),
-  ).toBeVisible();
-
-  const pairedMarkdownResponse = await request.get(
-    "/docs/snapsort/reference/svelte/ghost.md?framework=react",
-  );
-  expect(pairedMarkdownResponse.status()).toBe(200);
-  const pairedMarkdown = await pairedMarkdownResponse.text();
-  expect(pairedMarkdown).toContain("# Ghost");
-  expect(pairedMarkdown).toContain("@snap-engine/snapsort/react");
-  expect(pairedMarkdown).not.toContain("@snap-engine/snapsort/svelte");
-  expect(pairedMarkdown).toContain("## `GhostState`");
-  expect(pairedMarkdown).toContain("### `ghost`");
-  expect(pairedMarkdown).toContain("### `insertionMarkerRect()`");
-  expect(pairedMarkdown).toContain("`source-spacer`");
-  expect(pairedMarkdown).toContain("`pointer-preview`");
-  expect(pairedMarkdown.indexOf("## `GhostState`")).toBeLessThan(
-    pairedMarkdown.indexOf("## Appendix"),
-  );
-
-  const sessionMarkdownResponse = await request.get(
-    "/docs/snapsort/reference/drag-session.md?framework=react",
-  );
-  expect(sessionMarkdownResponse.status()).toBe(200);
-  const sessionMarkdown = await sessionMarkdownResponse.text();
-  expect(sessionMarkdown).toContain("# DragSession");
-  expect(sessionMarkdown).toContain('type DragSessionStatus = "pending"');
-  expect(sessionMarkdown).toContain("### `dragVisual`");
-  expect(sessionMarkdown).toContain("### `dropEffect`");
-  expect(sessionMarkdown).toContain("### Deprecated `handoff`");
-  expect(sessionMarkdown).toContain("### `DragLocation`");
-  expect(sessionMarkdown.indexOf("## Properties")).toBeLessThan(
-    sessionMarkdown.indexOf("## Appendix"),
-  );
-
-  const callbacksResponse = await page.goto(
-    "/docs/snapsort/reference/callbacks?framework=vanilla",
-  );
-  expect(callbacksResponse?.status()).toBe(200);
-  await expect(
-    page.getByRole("heading", {
-      name: "DropPriorityEvent",
-      exact: true,
-      level: 2,
-    }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", {
-      name: "containerRect",
-      exact: true,
-      level: 3,
-    }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", {
-      name: "prioritizeTreeDepth",
-      exact: true,
-      level: 3,
-    }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "Appendix", level: 2 }),
-  ).toBeVisible();
-  await expect(page.getByRole("article")).toContainText(
-    "@snap-engine/snapsort/callbacks",
-  );
-  await expect(page.getByRole("article")).toContainText("DROP_REJECT_PRIORITY");
-
-  const callbacksMarkdownResponse = await request.get(
-    "/docs/snapsort/reference/callbacks.md?framework=react",
-  );
-  expect(callbacksMarkdownResponse.status()).toBe(200);
-  const callbacksMarkdown = await callbacksMarkdownResponse.text();
-  expect(callbacksMarkdown).toContain("# Standard Callbacks");
-  expect(callbacksMarkdown).toContain("## `DropPriorityEvent`");
-  expect(callbacksMarkdown).toContain("### `containerContentRect`");
-  expect(callbacksMarkdown).toContain("### `prioritizeTreeDepth`");
-  expect(callbacksMarkdown).toContain("x: event.dragRect.x");
-  expect(callbacksMarkdown).toContain("y: event.pointer.y");
-  expect(callbacksMarkdown).toContain("event.depth + 1");
-  expect(callbacksMarkdown).toContain("event.staticPriority");
-  expect(callbacksMarkdown).toContain("DROP_REJECT_PRIORITY");
-  expect(callbacksMarkdown).toContain("1 / (1 + distance)");
-  expect(callbacksMarkdown).not.toContain("canDrop");
-  expect(callbacksMarkdown.indexOf("## Functions")).toBeLessThan(
-    callbacksMarkdown.indexOf("## Appendix"),
-  );
-
-  const guideMarkdownResponse = await request.get(
-    "/docs/snapsort/guides/sessions/ghosts.md",
-  );
-  expect(guideMarkdownResponse.status()).toBe(200);
-  const guideMarkdown = await guideMarkdownResponse.text();
-  expect(guideMarkdown).toContain("[Standard Callbacks reference]");
-  expect(guideMarkdown).toContain(
-    "/docs/snapsort/reference/callbacks.md?framework=svelte",
-  );
-  expect(guideMarkdown).not.toContain("| `prioritizePointerContainer`      |");
-  expect(guideMarkdown).not.toContain("canDrop");
-});
-
-test("SnapSort Container examples move out of Reference and keep accessible source tabs", async ({
-  page,
-}) => {
-  const response = await page.goto(
-    "/docs/snapsort/reference/svelte/container?framework=svelte",
-  );
-  expect(response?.status()).toBe(200);
-
-  await expect(
-    page.getByRole("heading", { name: "Component Properties", level: 2 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", {
-      name: "Direct children and RenderTree entries",
-      level: 3,
-    }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "Appendix", level: 2 }),
-  ).toBeVisible();
-  await expect(page.locator("[data-demo-code-tabs]")).toHaveCount(0);
-  await expect(
-    page.getByRole("link", { name: "Container basics" }),
-  ).toHaveAttribute("href", "/docs/snapsort/examples/basics#basic-container");
-  await expect(
-    page
-      .getByRole("article")
-      .getByRole("link", { name: "Container Recipes", exact: true }),
-  ).toHaveAttribute("href", "/docs/snapsort/examples/containers");
-  await expect(
-    page.getByRole("heading", {
-      name: "Move Items Between Containers",
-      level: 2,
-    }),
-  ).toHaveCount(0);
-  const exampleSourceRequests: string[] = [];
-  page.on("request", (request) => {
-    if (request.url().includes("/docs/snapsort/examples/source/")) {
-      exampleSourceRequests.push(request.url());
-    }
-  });
-  await page.goto("/docs/snapsort/examples/basics?framework=svelte");
-  await expect(page.locator("[data-demo-code-tabs]")).toHaveCount(4);
-  expect(exampleSourceRequests).toEqual([]);
-
-  const basic = page.locator('[data-demo-code-tabs="container-intro-basic"]');
-  await expect(basic.locator(".snapsort-item")).toHaveCount(2);
-  await basic.getByRole("tab", { name: "Svelte source" }).click();
-  await expect.poll(() => exampleSourceRequests.length).toBe(1);
-  expect(exampleSourceRequests[0]).toContain(
-    "/docs/snapsort/examples/source/container-intro-basic",
-  );
-  await expect(basic.getByRole("tabpanel")).toContainText("{#each");
-  await expect(basic.locator("pre.shiki.display")).toHaveCount(1);
-  await basic.getByRole("tab", { name: "Demo" }).click();
-  await basic.getByRole("tab", { name: "Svelte source" }).click();
-  expect(exampleSourceRequests).toHaveLength(1);
-
-  const sortable = page.locator(
-    '[data-demo-code-tabs="container-intro-sortable"]',
-  );
-  await expect(sortable.locator(".snapsort-item")).toHaveCount(2);
-  await sortable.getByRole("tab", { name: "Svelte source" }).click();
-  await expect(sortable.getByRole("tabpanel")).toContainText(
-    "onGhostInsert: onGhostMove",
-  );
-
-  const mixed = page.locator('[data-demo-code-tabs="container-intro-mixed"]');
-  await expect(mixed.locator(".snapsort-container")).toHaveCount(3);
-  await expect(mixed.getByText("Today", { exact: true })).toBeVisible();
-  await expect(mixed.getByText("Later", { exact: true })).toBeVisible();
-  const today = mixed.getByText("Today", { exact: true }).locator("..");
-  const later = mixed.getByText("Later", { exact: true }).locator("..");
-  await dragBetween(
-    page,
-    today.getByText("Draft update", { exact: true }),
-    later.getByText("Publish update", { exact: true }),
-  );
-  await expect(today.getByText("Draft update", { exact: true })).toHaveCount(0);
-  await expect(later.getByText("Draft update", { exact: true })).toHaveCount(1);
-  await expect(mixed.locator(".snapsort-ghost")).toHaveCount(0);
-
-  await page.goto("/docs/snapsort/examples/containers?framework=svelte");
-  await expect(page.locator("[data-demo-code-tabs]")).toHaveCount(7);
-
-  const collection = page.locator(
-    '[data-demo-code-tabs="container-property-collection"]',
-  );
-  const demoTab = collection.getByRole("tab", { name: "Demo" });
-  const codeTab = collection.getByRole("tab", { name: "Svelte source" });
-  await expect(collection.locator(".property-list")).toBeVisible();
-  await expect(demoTab).toHaveAttribute("aria-selected", "true");
-  await codeTab.click();
-  await expect(codeTab).toHaveAttribute("aria-selected", "true");
-  await expect(collection.getByRole("tabpanel")).toContainText(
-    "createRenderEntries",
-  );
-  await expect(collection.getByRole("tabpanel")).toContainText(
-    "{#each tasks.entries as entry (entry.itemId)}",
-  );
-  await expect(collection.getByRole("tabpanel")).not.toContainText("entry.key");
-  const codePanel = collection.locator(".code-panel");
-  const highlightedCode = codePanel.locator("pre.shiki.display");
-  await expect(highlightedCode).toHaveCount(1);
-  await expect(highlightedCode).toHaveCSS(
-    "background-color",
-    "rgb(255, 255, 255)",
-  );
-  await expect(highlightedCode).toHaveCSS("color", "rgb(31, 35, 40)");
-  await expect(codePanel.locator("pre")).toHaveCount(1);
-  await expect(codePanel).toContainText("@snap-engine/snapsort/svelte");
-  await expect(codePanel).not.toContainText("@snap-engine/snapsort/react");
-  const firstLine = highlightedCode.locator('.line[data-line="1"]');
-  await expect(firstLine).toBeVisible();
-  expect(
-    await firstLine.evaluate(
-      (line) => getComputedStyle(line, "::before").content,
-    ),
-  ).toBe('"1"');
-
-  await codeTab.press("Home");
-  await expect(demoTab).toBeFocused();
-  await expect(demoTab).toHaveAttribute("aria-selected", "true");
-  await demoTab.press("End");
-  await expect(codeTab).toBeFocused();
-  await expect(codeTab).toHaveAttribute("aria-selected", "true");
-  await codeTab.press("ArrowLeft");
-  await expect(demoTab).toBeFocused();
-
-  const config = page.locator(
-    '[data-demo-code-tabs="container-property-config"]',
-  );
-  await config.getByRole("button", { name: "Row" }).click();
-  await expect(config.locator(".config-list")).toHaveCSS(
-    "flex-direction",
-    "row",
-  );
-
-  const beforeAfter = page.locator(
-    '[data-demo-code-tabs="container-property-before-after"]',
-  );
-  await expect(beforeAfter.locator(".before-after-item")).toHaveCount(2);
-  const fixedSequence = beforeAfter.locator(".before-after-list");
-  await dragBetween(
-    page,
-    beforeAfter.locator(".before-after-item").first(),
-    beforeAfter.locator(".before-after-item").last(),
-    {
-      beforeDrop: async () => {
-        const childKinds = await fixedSequence.evaluate((container) =>
-          Array.from(container.children).map((child) => {
-            if (child.matches("header.before-content")) return "header";
-            if (child.matches("footer.after-content")) return "footer";
-            if (child.matches("[data-snapsort-ghost-entry]")) return "ghost";
-            if (child.matches(".before-after-item")) return "item";
-            return "other";
-          }),
-        );
-        expect(childKinds[0]).toBe("header");
-        expect(childKinds.at(-1)).toBe("footer");
-        expect(childKinds.indexOf("ghost")).toBeGreaterThan(0);
-        expect(childKinds.indexOf("ghost")).toBeLessThan(childKinds.length - 1);
-      },
-    },
-  );
-  await expect(fixedSequence.locator(":scope > :first-child")).toHaveClass(
-    /before-content/,
-  );
-  await expect(fixedSequence.locator(":scope > :last-child")).toHaveClass(
-    /after-content/,
-  );
-  await expect(
-    fixedSequence.locator("[data-snapsort-ghost-entry]"),
-  ).toHaveCount(0);
-  await beforeAfter.getByRole("button", { name: "Add task" }).click();
-  await expect(beforeAfter.locator(".before-after-item")).toHaveCount(3);
-
-  const metadata = page.locator(
-    '[data-demo-code-tabs="container-property-metadata"]',
-  );
-  const backlogColumn = metadata
-    .getByRole("heading", { name: "Backlog" })
-    .locator("..");
-  const doneColumn = metadata
-    .getByRole("heading", { name: "Done" })
-    .locator("..");
-  await dragBetween(
-    page,
-    backlogColumn.getByText("Review changes", { exact: true }),
-    doneColumn,
-  );
-  await expect(
-    doneColumn.getByText("Review changes", { exact: true }),
-  ).toHaveCount(1);
-  await expect(metadata.locator(".move-status")).toHaveText(
-    "Review changes moved to Done",
-  );
-  await expect(metadata.locator(".snapsort-ghost")).toHaveCount(0);
-  await metadata.evaluate(() => {
-    const animationState = window as typeof window & {
-      __metadataMoveTransforms?: string[];
-    };
-    animationState.__metadataMoveTransforms = [];
-    const startedAt = performance.now();
-    const sampleTransform = () => {
-      const draftItem = Array.from(
-        document.querySelectorAll(".metadata-item"),
-      ).find((item) => item.textContent?.includes("Draft copy"));
-      if (draftItem) {
-        animationState.__metadataMoveTransforms!.push(
-          getComputedStyle(draftItem).transform,
-        );
-      }
-      if (performance.now() - startedAt < 500) {
-        requestAnimationFrame(sampleTransform);
-      }
-    };
-    requestAnimationFrame(sampleTransform);
-  });
-  await metadata
-    .getByRole("button", { name: "Move Draft copy to Done" })
-    .click();
-  await expect
-    .poll(() =>
-      page.evaluate(() => {
-        const animationState = window as typeof window & {
-          __metadataMoveTransforms?: string[];
-        };
-        return animationState.__metadataMoveTransforms?.some(
-          (transform) => transform !== "none",
-        );
-      }),
-    )
-    .toBe(true);
-  await expect(metadata.getByText("Draft copy", { exact: true })).toHaveCount(
-    1,
-  );
-  await expect(metadata.locator(".move-status")).toHaveText(
-    "Draft copy moved to Done",
-  );
-
-  const nested = page.locator(
-    '[data-demo-code-tabs="container-property-nested"]',
-  );
-  await dragBetween(
-    page,
-    nested.getByText("Ship", { exact: true }),
-    nested.getByText("Design", { exact: true }),
-  );
-  await expect
-    .poll(() =>
-      nested.locator(".nested-card-content > strong").allTextContents(),
-    )
-    .not.toEqual(["Design", "Build", "Ship"]);
-  await expect(nested.locator(".snapsort-ghost")).toHaveCount(0);
-  const shipSelection = nested.getByRole("button", {
-    name: "Select",
-    exact: true,
-  });
-  await shipSelection.click();
-  await expect(nested.getByRole("button", { name: "Selected" })).toHaveCount(3);
-
-  const presentation = page.locator(
-    '[data-demo-code-tabs="container-property-presentation"]',
-  );
-  const styledContainer = presentation.getByLabel("Styled task list");
-  await expect(styledContainer).toHaveAttribute(
-    "data-example-kind",
-    "presentation",
-  );
-  await expect(styledContainer).toHaveClass(/is-emphasized/);
-  await presentation.getByRole("button", { name: "Toggle emphasis" }).click();
-  await expect(styledContainer).not.toHaveClass(/is-emphasized/);
-});
-
-test("SnapSort Item examples move out of Reference and preserve focused behavior", async ({
-  page,
-  request,
-}) => {
-  const response = await page.goto(
-    "/docs/snapsort/reference/svelte/item?framework=svelte",
-  );
-  expect(response?.status()).toBe(200);
-
-  await expect(
-    page.getByRole("heading", { name: "Component Properties", level: 2 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "Handle", level: 2 }),
-  ).toBeVisible();
-  await expect(page.locator("[data-demo-code-tabs]")).toHaveCount(0);
-  await expect(
-    page.getByRole("link", { name: "Basic Item", exact: true }),
-  ).toHaveAttribute("href", "/docs/snapsort/examples/basics#basic-item");
-  await expect(
-    page
-      .getByRole("article")
-      .getByRole("link", { name: "Item Recipes", exact: true }),
-  ).toHaveAttribute("href", "/docs/snapsort/examples/items");
-
-  await page.goto("/docs/snapsort/examples/basics?framework=svelte");
-  await expect(page.locator("[data-demo-code-tabs]")).toHaveCount(4);
-
-  const basic = page.locator('[data-demo-code-tabs="item-example-basic"]');
-  await expect(basic.locator(".item-demo-card")).toHaveCount(3);
-  await basic.getByRole("tab", { name: "Svelte source" }).click();
-  await expect(basic.locator("pre.shiki.display")).toHaveCount(1);
-  await expect(basic.getByRole("tabpanel")).toContainText(
-    "",
-  );
-
-  const handle = page.locator('[data-demo-code-tabs="item-example-handle"]');
-  const initialHandleStatus =
-    "Drag with the grip; the Done buttons remain interactive.";
-  await expect(handle.locator(".handle-status")).toHaveText(
-    initialHandleStatus,
-  );
-
-  await dragBetween(
-    page,
-    handle.locator(".task-label").first(),
-    handle.locator(".task-label").last(),
-  );
-  await expect(handle.locator(".handle-status")).toHaveText(
-    initialHandleStatus,
-  );
-
-  await dragBetween(
-    page,
-    handle.getByLabel("Drag Plan release"),
-    handle.getByLabel("Drag Ship update"),
-  );
-  await expect(handle.locator(".handle-status")).toHaveText(
-    /(?:Dragging Plan release from its handle|Moved Plan release)/,
-  );
-
-  await handle
-    .getByRole("button", { name: /Done|Undo/ })
-    .first()
-    .click();
-  await expect(handle.locator(".handle-status")).toHaveText(
-    /marked (?:done|not done)$/,
-  );
-
-  await page.setViewportSize({ width: 390, height: 844 });
-  await page.goto("/docs/snapsort/examples/items?framework=svelte");
-  await expect(page.locator(".doc-sidebar")).toBeHidden();
-  await expect(page.locator("[data-demo-code-tabs]")).toHaveCount(4);
-  expect(
-    await page.evaluate(() => document.documentElement.scrollWidth),
-  ).toBeLessThanOrEqual(390);
-
-  const markdownResponse = await request.get(
-    "/docs/snapsort/reference/svelte/item.md",
-  );
-  expect(markdownResponse.status()).toBe(200);
-  const markdown = await markdownResponse.text();
-  expect(markdown).toContain("## Component Properties");
-  expect(markdown).toContain("");
-  expect(markdown).toContain("bind:item");
-  expect(markdown).not.toContain("DragSession.handoff");
-  expect(markdown).not.toContain(
-    "This page includes interactive diagrams or demos.",
-  );
-  expect(markdown).not.toContain(" {
-  const lifecycleResponse = await page.goto(
-    "/docs/snapsort/guides/sessions/drag-start?framework=react",
-  );
-  expect(lifecycleResponse?.status()).toBe(200);
-
-  await expect(
-    page.getByRole("heading", { name: "Terms", level: 2 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("heading", { name: "Lifecycle at a Glance", level: 2 }),
-  ).toBeVisible();
-  await expect(
-    page.getByRole("group", {
-      name: /root-owned DragSession initiates target resolution.*Ghosts are passive visual data/i,
-    }),
-  ).toBeVisible();
-
-  const lifecycleDiagram = page.locator(".lifecycle-diagram");
-  await expect(lifecycleDiagram.locator("[data-phase]")).toHaveCount(5);
-  await expect(lifecycleDiagram).toContainText("Ghost");
-  const structuralCallbackSteps = [
-    "1.3a",
-    "1.4a",
-    "1.6a",
-    "2.3a",
-    "3.1a",
-    "3.2a",
-    "3.3a",
-    "5.1b",
-  ];
-  for (const step of structuralCallbackSteps) {
-    await expect(
-      lifecycleDiagram.locator(`[data-step="${step}"]`),
-    ).toHaveAttribute("data-to", "root");
-  }
-  await expect(
-    lifecycleDiagram.locator('[data-step="2.3b"] .detail'),
-  ).toContainText("reduceRenderTree");
-  await expect(lifecycleDiagram).not.toContainText("container reducer");
-  await expect(lifecycleDiagram.locator(".uml-legend")).toHaveCount(0);
-  await expect(lifecycleDiagram.locator(".message-label > code")).toHaveCount(
-    0,
-  );
-  const callbackLabel = lifecycleDiagram.locator(
-    '[data-step="1.3a"] .self-message',
-  );
-  const ordinaryLabel = lifecycleDiagram.locator('[data-step="1.3c"] .message');
-  await expect(callbackLabel).toHaveClass(/invokes-callback/);
-  await expect(ordinaryLabel).not.toHaveClass(/invokes-callback/);
-  await expect(callbackLabel.locator("strong")).toContainText("onGhostInsert");
-  await expect(callbackLabel.locator("strong")).not.toContainText(
-    "Add source ghost",
-  );
-  await expect(
-    callbackLabel.getByRole("link", { name: "onGhostInsert" }),
-  ).toHaveAttribute(
-    "href",
-    "/docs/snapsort/reference/react/container?framework=react#callbacks",
-  );
-  const labelStyles = await lifecycleDiagram.evaluate((diagram) => {
-    const callbackBadge = diagram.querySelector(
-      '[data-step="1.3a"] .step-number',
-    );
-    const ordinaryBadge = diagram.querySelector(
-      '[data-step="1.3c"] .step-number',
-    );
-    const title = diagram.querySelector('[data-step="1.3a"] strong');
-    const lane = diagram.querySelector(".participant");
-    const phase = diagram.querySelector(".phase-heading span");
-    const branch = diagram.querySelector(".branch-label");
-    const detail = diagram.querySelector(".detail");
-    if (
-      !callbackBadge ||
-      !ordinaryBadge ||
-      !title ||
-      !lane ||
-      !phase ||
-      !branch ||
-      !detail
-    ) {
-      throw new Error("Missing lifecycle label styles");
-    }
-    return {
-      callbackColor: getComputedStyle(callbackBadge).backgroundColor,
-      ordinaryColor: getComputedStyle(ordinaryBadge).backgroundColor,
-      titleSize: Number.parseFloat(getComputedStyle(title).fontSize),
-      laneSize: Number.parseFloat(getComputedStyle(lane).fontSize),
-      phaseSize: Number.parseFloat(getComputedStyle(phase).fontSize),
-      branchSize: Number.parseFloat(getComputedStyle(branch).fontSize),
-      detailSize: Number.parseFloat(getComputedStyle(detail).fontSize),
-      titleFamily: getComputedStyle(title).fontFamily,
-      titleWeight: getComputedStyle(title).fontWeight,
-      arrowWidth: getComputedStyle(diagram.querySelector(".uml-line")!)
-        .strokeWidth,
-    };
-  });
-  expect(labelStyles.callbackColor).not.toBe(labelStyles.ordinaryColor);
-  expect(labelStyles.laneSize).toBeGreaterThan(labelStyles.titleSize);
-  expect(labelStyles.titleSize).toBeGreaterThan(labelStyles.phaseSize);
-  expect(labelStyles.phaseSize).toBeGreaterThan(labelStyles.branchSize);
-  expect(labelStyles.detailSize).toBeGreaterThanOrEqual(13);
-  expect(labelStyles.titleFamily).toContain("Geist");
-  expect(labelStyles.titleWeight).toBe("400");
-  expect(Number.parseFloat(labelStyles.arrowWidth)).toBeGreaterThanOrEqual(2);
-
-  const desktopLayout = await page.evaluate(() => {
-    const bounds = (selector: string) => {
-      const element = document.querySelector(selector);
-      if (!(element instanceof HTMLElement)) {
-        throw new Error(`Missing layout element: ${selector}`);
-      }
-      const rect = element.getBoundingClientRect();
-      return { left: rect.left, right: rect.right, width: rect.width };
-    };
-
-    return {
-      viewportWidth: window.innerWidth,
-      sidebar: bounds(".doc-sidebar"),
-      content: bounds(".doc-content"),
-      paragraph: bounds(".doc-article > p"),
-      diagram: bounds(".lifecycle-diagram"),
-    };
-  });
-  expect(desktopLayout.sidebar.left).toBeGreaterThanOrEqual(15);
-  expect(desktopLayout.sidebar.left).toBeLessThanOrEqual(40);
-  expect(desktopLayout.content.width).toBeGreaterThan(700);
-  expect(desktopLayout.paragraph.width).toBeLessThanOrEqual(701);
-  expect(desktopLayout.diagram.width).toBeGreaterThan(700);
-  expect(
-    Math.abs(desktopLayout.content.width - desktopLayout.diagram.width),
-  ).toBeLessThanOrEqual(1);
-  expect(
-    await lifecycleDiagram
-      .locator(".scroll-region")
-      .evaluate((element) => element.scrollWidth > element.clientWidth),
-  ).toBe(true);
-
-  const diagramGeometry = await lifecycleDiagram.evaluate((diagram) => {
-    const laneOrder = [
-      "item",
-      "ghost",
-      "root",
-      "source",
-      "target",
-      "app",
-      "dom",
-    ];
-    const center = (element: Element) => {
-      const rect = element.getBoundingClientRect();
-      return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
-    };
-    const participants = [...diagram.querySelectorAll(".participant")];
-    const lifelines = [...diagram.querySelectorAll(".lifeline")].slice(0, 7);
-    const laneCenterDeltas = participants.map((participant, index) =>
-      Math.abs(center(participant).x - center(lifelines[index]).x),
-    );
-    const routeGeometry = [...diagram.querySelectorAll(".message-row")]
-      .filter((row) => row.querySelector(":scope > .message"))
-      .map((row) => {
-        const label = row.querySelector(".message-label");
-        const route = row.querySelector(".route-svg");
-        const head = row.querySelector(".route-head-svg");
-        if (!label || !route || !head) {
-          throw new Error(`Incomplete route geometry for ${row.dataset.step}`);
-        }
-        const labelRect = label.getBoundingClientRect();
-        const messageRect = row
-          .querySelector(":scope > .message")!
-          .getBoundingClientRect();
-        const routeCenter = center(route);
-        const headCenter = center(head);
-        const from = laneOrder.indexOf(row.dataset.from ?? "");
-        const to = laneOrder.indexOf(row.dataset.to ?? "");
-        const expectedLeft = center(lifelines[Math.min(from, to)]).x;
-        const expectedRight = center(lifelines[Math.max(from, to)]).x;
-        return {
-          step: row.dataset.step,
-          labelGap: routeCenter.y - labelRect.bottom,
-          headDelta: Math.abs(routeCenter.y - headCenter.y),
-          leftDelta: Math.abs(messageRect.left - expectedLeft),
-          rightDelta: Math.abs(messageRect.right - expectedRight),
-        };
-      });
-
-    const selfLoopGeometry = [...diagram.querySelectorAll(".self-route")].map(
-      (route) => {
-        const rect = route.getBoundingClientRect();
-        return { width: rect.width, height: rect.height };
-      },
-    );
-
-    return { laneCenterDeltas, routeGeometry, selfLoopGeometry };
-  });
-  expect(Math.max(...diagramGeometry.laneCenterDeltas)).toBeLessThan(0.1);
-  for (const route of diagramGeometry.routeGeometry) {
-    expect(
-      route.labelGap,
-      `${route.step} label overlaps its arrow`,
-    ).toBeGreaterThanOrEqual(1);
-    expect(route.headDelta, `${route.step} arrowhead is off-axis`).toBeLessThan(
-      0.1,
-    );
-    expect(route.leftDelta, `${route.step} starts off-lifeline`).toBeLessThan(
-      2,
-    );
-    expect(route.rightDelta, `${route.step} ends off-lifeline`).toBeLessThan(2);
-  }
-  for (const loop of diagramGeometry.selfLoopGeometry) {
-    expect(loop.width).toBeLessThanOrEqual(64.1);
-    expect(loop.width / loop.height).toBeCloseTo(64 / 44, 2);
-  }
-
-  await page.setViewportSize({ width: 2200, height: 900 });
-  const wideLaneGeometry = await lifecycleDiagram.evaluate((diagram) => {
-    const sequence = diagram.querySelector(".sequence");
-    if (!(sequence instanceof HTMLElement)) {
-      throw new Error("Missing lifecycle sequence");
-    }
-    const laneWidths = [...diagram.querySelectorAll(".participant")].map(
-      (participant) => participant.getBoundingClientRect().width,
-    );
-    return {
-      diagramWidth: diagram.getBoundingClientRect().width,
-      sequenceWidth: sequence.getBoundingClientRect().width,
-      widestLane: Math.max(...laneWidths),
-    };
-  });
-  expect(wideLaneGeometry.sequenceWidth).toBeLessThanOrEqual(1400.1);
-  expect(wideLaneGeometry.widestLane).toBeLessThanOrEqual(200.1);
-  expect(
-    wideLaneGeometry.diagramWidth - wideLaneGeometry.sequenceWidth,
-  ).toBeLessThanOrEqual(49);
-  await page.setViewportSize({ width: 1280, height: 720 });
-
-  const ghostRelocation = lifecycleDiagram.locator('[data-step="2.3a"]');
-  await expect(ghostRelocation).toHaveAttribute("data-from", "root");
-  await expect(ghostRelocation).toHaveAttribute("data-to", "root");
-  await expect(ghostRelocation).toHaveAttribute("data-kind", "sync");
-  await expect(ghostRelocation).toContainText("onGhostMove");
-
-  const ghostDomRelocation = lifecycleDiagram.locator('[data-step="2.3c"]');
-  await expect(ghostDomRelocation).toHaveAttribute("data-from", "app");
-  await expect(ghostDomRelocation).toHaveAttribute("data-to", "dom");
-  await expect(ghostDomRelocation).toContainText("Commit relocated ghost");
-
-  const ghostDomRelocationReturn =
-    lifecycleDiagram.locator('[data-step="2.3d"]');
-  await expect(ghostDomRelocationReturn).toHaveAttribute("data-from", "dom");
-  await expect(ghostDomRelocationReturn).toHaveAttribute("data-to", "app");
-  await expect(ghostDomRelocationReturn).toHaveAttribute("data-kind", "return");
-  await expect(ghostDomRelocationReturn).toContainText("DOM commit complete");
-
-  const ghostRemovalFlushReturn =
-    lifecycleDiagram.locator('[data-step="2.3e"]');
-  await expect(ghostRemovalFlushReturn).toHaveAttribute("data-from", "app");
-  await expect(ghostRemovalFlushReturn).toHaveAttribute("data-to", "root");
-  await expect(ghostRemovalFlushReturn).toHaveAttribute("data-kind", "return");
-
-  await expect(lifecycleDiagram.locator('[data-step^="2.4"]')).toHaveCount(0);
-
-  for (const step of ["2.5", "2.5r", "4.2", "4.2r"]) {
-    const notification = lifecycleDiagram.locator(`[data-step="${step}"]`);
-    await expect(notification).toHaveAttribute("data-from", "root");
-    await expect(notification).toHaveAttribute("data-to", "root");
-  }
-
-  const phaseLabels = await lifecycleDiagram
-    .locator(".phase-heading span")
-    .all();
-  for (const label of phaseLabels) {
-    expect(
-      await label.evaluate(
-        (element) => getComputedStyle(element).textTransform,
-      ),
-    ).toBe("none");
-  }
-
-  const normalCommitStep = lifecycleDiagram.locator('[data-step="3.2a"]');
-  await expect(lifecycleDiagram.locator('[data-step="3.1a"]')).toContainText(
-    "onGhostRemove",
-  );
-  await expect(normalCommitStep).toContainText("onItemMove");
-  await expect(normalCommitStep).toContainText("onItemInsert");
-  const collectionUpdateStep = lifecycleDiagram.locator('[data-step="3.2b"]');
-  await collectionUpdateStep.locator(".message, .self-message").hover();
-  await expect(collectionUpdateStep.locator(".detail")).toBeVisible();
-  await expect(collectionUpdateStep.locator(".detail")).toContainText(
-    "The source receives no onItemRemove callback.",
-  );
-
-  for (const step of ["3.1d", "3.2d", "3.3d"]) {
-    const domReturn = lifecycleDiagram.locator(`[data-step="${step}"]`);
-    await expect(domReturn).toHaveAttribute("data-from", "dom");
-    await expect(domReturn).toHaveAttribute("data-to", "app");
-    await expect(domReturn).toHaveAttribute("data-kind", "return");
-  }
-  for (const step of ["3.1e", "3.2e", "3.3e"]) {
-    const transactionReturn = lifecycleDiagram.locator(`[data-step="${step}"]`);
-    await expect(transactionReturn).toHaveAttribute("data-from", "app");
-    await expect(transactionReturn).toHaveAttribute("data-to", "root");
-    await expect(transactionReturn).toHaveAttribute("data-kind", "return");
-  }
-
-  await expect(lifecycleDiagram.locator('[data-step="4.4"]')).toHaveAttribute(
-    "data-kind",
-    "return",
-  );
-  await expect(lifecycleDiagram.locator('[data-step="4.5"]')).toHaveAttribute(
-    "data-kind",
-    "async",
-  );
-  await expect(
-    lifecycleDiagram.locator('[data-phase="finish"]'),
-  ).not.toContainText(/WRITE_1|WRITE_2|READ_2/);
-  await expect(lifecycleDiagram.locator('[data-step="5.1b"]')).toContainText(
-    "onItemRemove",
-  );
-  await expect(lifecycleDiagram.locator('[data-step^="5.2"]')).toHaveCount(0);
-  await expect(lifecycleDiagram).not.toContainText(
-    /flow-copy|transient clone/i,
-  );
-  await expect(lifecycleDiagram).toContainText('dragVisual = "item"');
-  await expect(lifecycleDiagram).toContainText('dragVisual = "preview"');
-  await expect(lifecycleDiagram).toContainText('dragVisual = "none"');
-  await expect(lifecycleDiagram).toContainText(
-    "Independent placement feedback",
-  );
-  await expect(
-    lifecycleDiagram.getByRole("link", { name: "adapter" }).first(),
-  ).toBeVisible();
-
-  for (const framework of ["react", "svelte"] as const) {
-    await page.goto(
-      `/docs/snapsort/guides/sessions/drag-start?framework=${framework}`,
-    );
-    await expect(page.locator(".lifecycle-diagram")).not.toContainText(
-      "createGhost",
-    );
-    await expect(
-      page
-        .locator(".lifecycle-diagram")
-        .getByRole("link", { name: "adapter" })
-        .first(),
-    ).toBeVisible();
-  }
-
-  await page.goto(
-    "/docs/snapsort/guides/sessions/drag-start?framework=vanilla",
-  );
-  const vanillaDiagram = page.locator(".lifecycle-diagram");
-  await expect(vanillaDiagram).toContainText("Construct Vanilla element");
-  await expect(vanillaDiagram).toContainText("The Vanilla adapter constructs");
-  await expect(vanillaDiagram).not.toContainText("inside root adapter commit");
-  await expect(vanillaDiagram.locator("[data-phase]")).toHaveCount(5);
-  for (const step of [
-    "1.3d",
-    "1.4d",
-    "1.6d",
-    "2.3a",
-    "3.1a",
-    "3.2a",
-    "3.3a",
-    "5.1b",
-  ]) {
-    await expect(
-      vanillaDiagram.locator(`[data-step="${step}"]`),
-    ).toHaveAttribute("data-to", "root");
-  }
-  for (const [callStep, returnStep] of [
-    ["1.3e", "1.3f"],
-    ["1.4e", "1.4f"],
-    ["1.6e", "1.6f"],
-    ["2.3b", "2.3c"],
-    ["3.1b", "3.1c"],
-    ["3.2b", "3.2c"],
-    ["3.3b", "3.3c"],
-    ["5.1c", "5.1d"],
-  ] as const) {
-    const domCall = vanillaDiagram.locator(`[data-step="${callStep}"]`);
-    await expect(domCall).toHaveAttribute("data-from", "root");
-    await expect(domCall).toHaveAttribute("data-to", "dom");
-    await expect(domCall).toHaveAttribute("data-kind", "sync");
-
-    const domReturn = vanillaDiagram.locator(`[data-step="${returnStep}"]`);
-    await expect(domReturn).toHaveAttribute("data-from", "dom");
-    await expect(domReturn).toHaveAttribute("data-to", "root");
-    await expect(domReturn).toHaveAttribute("data-kind", "return");
-    await expect(domReturn).toContainText(/returned|complete/);
-  }
-
-  await page.setViewportSize({ width: 390, height: 844 });
-  await page.goto("/docs/snapsort/guides/sessions/drag-start?framework=react");
-  await expect(page.locator(".doc-sidebar")).toBeHidden();
-  expect(
-    await page.evaluate(() => document.documentElement.scrollWidth),
-  ).toBeLessThanOrEqual(390);
-  expect(
-    await page
-      .locator(".lifecycle-diagram .scroll-region")
-      .evaluate((element) => element.scrollWidth > element.clientWidth),
-  ).toBe(true);
-
-  await page.setViewportSize({ width: 1280, height: 720 });
-
-  const rootCallbacks = [
-    "onItemMove",
-    "onItemInsert",
-    "onItemRemove",
-    "onItemSwap",
-    "onDragStart",
-    "onDragEnd",
-    "onDropTargetChange",
-    "onVisualGeometryInvalidated",
-    "onGhostInsert",
-    "onGhostMove",
-    "onGhostRemove",
-  ];
-  const localCallbacks = [
-    "getDropPriority",
-    "getItemHitbox",
-    "onDragItemEnter",
-    "onDragItemMove",
-    "onDragItemLeave",
-  ];
-
-  for (const framework of ["svelte", "react"] as const) {
-    const response = await page.goto(
-      `/docs/snapsort/reference/${framework}/container?framework=${framework}`,
-    );
-    expect(response?.status()).toBe(200);
-
-    for (const callbackName of [...rootCallbacks, ...localCallbacks]) {
-      await expect(
-        page.getByRole("heading", {
-          name: callbackName,
-          exact: true,
-          level: 3,
-        }),
-      ).toHaveCount(1);
-    }
-    await expect(
-      page.getByRole("heading", { name: "Appendix", level: 2 }),
-    ).toBeVisible();
-    await expect(page.locator(".doc-article")).toContainText(
-      "insertionMarkerRect",
-    );
-    await expect(page.locator(".doc-article")).toContainText(
-      "isCurrentPlacement",
-    );
-    await expect(page.locator(".doc-article")).not.toContainText(
-      "getInsertionMarkerRect",
-    );
-
-    const callbackSection = page.locator(".doc-article");
-    await expect(callbackSection).toContainText("tree root");
-    await expect(callbackSection).toContainText("per container");
-  }
-
-  const lifecycleMarkdownResponse = await request.get(
-    "/docs/snapsort/guides/sessions/drag-start.md",
-  );
-  expect(lifecycleMarkdownResponse.status()).toBe(200);
-  const lifecycleMarkdown = await lifecycleMarkdownResponse.text();
-  expect(lifecycleMarkdown).toContain("## Terms");
-  expect(lifecycleMarkdown).toContain("## Lifecycle at a Glance");
-
-  for (const framework of ["svelte", "react"] as const) {
-    const markdownResponse = await request.get(
-      `/docs/snapsort/reference/${framework}/container.md?framework=${framework}`,
-    );
-    expect(markdownResponse.status()).toBe(200);
-    const markdown = await markdownResponse.text();
-    expect(markdown).toContain(
-      "Structural and lifecycle callbacks resolve on the **tree root**",
-    );
-    expect(markdown).toContain("remain **per container**");
-    expect(markdown.indexOf("## Callbacks")).toBeLessThan(
-      markdown.indexOf("## Appendix"),
-    );
-    expect(markdown).toContain("### Drag visuals");
-    for (const callbackName of [...rootCallbacks, ...localCallbacks]) {
-      expect(markdown).toContain(`### \`${callbackName}\``);
-    }
-  }
-});
-
-test("SnapSort docs keep application CRUD and destination meaning application-owned", async ({
-  request,
-}) => {
-  const [
-    quickstartResponse,
-    commitResponse,
-    ghostsResponse,
-    placementResponse,
-    programmaticMovesResponse,
-    advancedResponse,
-    svelteContainerResponse,
-    reactContainerResponse,
-  ] = await Promise.all([
-    request.get("/docs/snapsort/introduction/setup.md"),
-    request.get("/docs/snapsort/guides/sessions/commit-and-cleanup.md"),
-    request.get("/docs/snapsort/guides/sessions/ghosts.md"),
-    request.get("/docs/snapsort/guides/placement-modes.md"),
-    request.get("/docs/snapsort/guides/sessions/drop-policies.md"),
-    request.get("/docs/snapsort/examples/advanced-settings-and-callbacks.md"),
-    request.get("/docs/snapsort/reference/svelte/container.md"),
-    request.get("/docs/snapsort/reference/react/container.md"),
-  ]);
-
-  expect(quickstartResponse.status()).toBe(200);
-  expect(commitResponse.status()).toBe(200);
-  expect(ghostsResponse.status()).toBe(200);
-  expect(placementResponse.status()).toBe(200);
-  expect(programmaticMovesResponse.status()).toBe(200);
-  expect(advancedResponse.status()).toBe(200);
-  expect(svelteContainerResponse.status()).toBe(200);
-  expect(reactContainerResponse.status()).toBe(200);
-
-  const [
-    quickstart,
-    commit,
-    ghosts,
-    placement,
-    programmaticMoves,
-    advanced,
-    svelteContainer,
-    reactContainer,
-  ] = await Promise.all([
-    quickstartResponse.text(),
-    commitResponse.text(),
-    ghostsResponse.text(),
-    placementResponse.text(),
-    programmaticMovesResponse.text(),
-    advancedResponse.text(),
-    svelteContainerResponse.text(),
-    reactContainerResponse.text(),
-  ]);
-
-  expect(quickstart).not.toContain("## Who Changes Framework Render State?");
-  expect(quickstart).not.toContain("function addTask(task: Task)");
-  expect(programmaticMoves).toContain("function addTask(task: Task)");
-  expect(programmaticMoves).toContain(
-    "function deleteTasks(itemIds: readonly ItemId[])",
-  );
-  expect(programmaticMoves).toMatch(
-    /application code,\s+not SnapSort\s+exports/,
-  );
-  expect(programmaticMoves).toContain("container.removeItem(itemId)");
-  expect(programmaticMoves).toMatch(
-    /`reduceRenderTree`\s+cannot invent the application value/,
-  );
-
-  expect(programmaticMoves).toContain(
-    "## Application-Owned Collection Changes",
-  );
-  expect(programmaticMoves).toMatch(
-    /Application-originated additions and deletions do not need to round-trip/,
-  );
-  expect(ghosts).toContain("## Explicit Lifecycle Callbacks");
-  expect(ghosts).toContain("onGhostInsert: applyGhostEvent");
-  expect(ghosts).toContain("onGhostMove: applyGhostEvent");
-  expect(ghosts).toContain("onGhostRemove: applyGhostEvent");
-
-  expect(advanced).toContain("## Give a Drop Application Meaning");
-  expect(advanced).toContain(
-    'event.session.dropEffect = isTrash ? "none" : "move"',
-  );
-  expect(advanced).toContain(
-    'event.destination?.containerMetadata.role !== "trash"',
-  );
-  expect(advanced).toContain("new Set(event.itemIds)");
-  expect(advanced).toMatch(
-    /The recursive `removeEntries` function\s+is\s+intentionally application-local/,
-  );
-  expect(advanced).toMatch(
-    /Checking `event.destination` rather\s+than\s+remembered\s+hover\s+state\s+makes cancellation safe/,
-  );
-  expect(advanced).not.toContain("DragSession.handoff");
-  expect(placement).not.toContain("## Three Independent Decisions");
-  expect(placement).not.toContain("## Give a Drop Application Meaning");
-
-  for (const containerReference of [svelteContainer, reactContainer]) {
-    expect(containerReference).toContain("### Application-owned item lifetime");
-    expect(containerReference).toContain("addTaskToTodo");
-    expect(containerReference).toContain("deleteTasksFromTodo");
-    expect(containerReference).toMatch(
-      /These are application functions, not SnapSort\s+helpers/,
-    );
-    expect(containerReference).toMatch(/framework mounting does not emit it/);
-    expect(containerReference).toMatch(
-      /do not expect `onItemRemove` for the source half of a move/,
-    );
-    expect(containerReference).not.toContain("DragSession.handoff");
-    expect(containerReference).not.toContain("entry.key");
-  }
-
-  expect(svelteContainer).toContain(
-    "{#each board.entries as entry (entry.itemId)}",
-  );
-  expect(reactContainer).toContain(
-    " {
-  const response = await page.goto(
-    "/docs/snapsort/introduction/setup?framework=svelte",
-  );
-  expect(response?.status()).toBe(200);
-  await page.waitForFunction(
-    () => localStorage.getItem("preferredCodeFramework") === "svelte",
-  );
-
-  const tabs = page.locator("[data-code-tabs]");
-  await expect(tabs).toHaveCount(1);
-  await expect(tabs.getByRole("tab")).toHaveText([
-    "npm",
-    "pnpm",
-    "Yarn",
-    "Bun",
-  ]);
-  await expect(
-    tabs.getByRole("tab", { name: "npm", exact: true }),
-  ).toHaveAttribute("aria-selected", "true");
-  await expect(tabs.getByRole("tabpanel")).toHaveCount(1);
-  await expect(tabs.getByRole("tabpanel")).toContainText(
-    "npm install @snap-engine/snapsort @snap-engine/asset-base",
-  );
-  await expect(tabs).toHaveCSS("border-top-width", "1px");
-  const codeBlockBorders = await tabs
-    .locator("pre.shiki.display:visible")
-    .evaluate((element) => {
-      const style = getComputedStyle(element);
-      return [
-        style.borderTopWidth,
-        style.borderRightWidth,
-        style.borderBottomWidth,
-        style.borderLeftWidth,
-      ];
-    });
-  expect(codeBlockBorders).toEqual(["0px", "0px", "0px", "0px"]);
-
-  await tabs.getByRole("tab", { name: "pnpm" }).click();
-  await expect(tabs.getByRole("tabpanel")).toContainText(
-    "pnpm add @snap-engine/snapsort @snap-engine/asset-base",
-  );
-  await tabs.getByRole("tab", { name: "pnpm" }).press("ArrowRight");
-  await expect(tabs.getByRole("tab", { name: "Yarn" })).toBeFocused();
-  await expect(tabs.getByRole("tab", { name: "Yarn" })).toHaveAttribute(
-    "aria-selected",
-    "true",
-  );
-  await expect(tabs.getByRole("tabpanel")).toContainText(
-    "yarn add @snap-engine/snapsort @snap-engine/asset-base",
-  );
-  await expect
-    .poll(() =>
-      page.evaluate(() => ({
-        framework: localStorage.getItem("preferredCodeFramework"),
-        packageManager: localStorage.getItem(
-          "preferredCodeTab:npm|pnpm|yarn|bun",
-        ),
-      })),
-    )
-    .toEqual({ framework: "svelte", packageManager: "yarn" });
-
-  await page.reload({ waitUntil: "networkidle" });
-  await expect(tabs.getByRole("tab", { name: "Yarn" })).toHaveAttribute(
-    "aria-selected",
-    "true",
-  );
-  await expect(tabs.getByRole("tabpanel")).toContainText("yarn add");
-
-  await page.locator("#desktop-doc-framework").selectOption("react");
-
-  await expect(page.locator(".doc-article")).toHaveAttribute(
-    "data-framework",
-    "react",
-  );
-  await expect(tabs.getByRole("tab", { name: "Yarn" })).toHaveAttribute(
-    "aria-selected",
-    "true",
-  );
-  const visibleFrameworkBlock = page.locator(".framework-code-block:visible");
-  await expect(visibleFrameworkBlock).toHaveCount(1);
-  await expect(visibleFrameworkBlock).toContainText(
-    'import { useCallback, useState } from "react"',
-  );
-
-  const markdownResponse = await page.request.get(
-    "/docs/snapsort/introduction/setup.md",
-  );
-  expect(markdownResponse.status()).toBe(200);
-  const markdown = await markdownResponse.text();
-  expect(markdown).toContain("npm install @snap-engine/snapsort");
-  expect(markdown).toContain("pnpm add @snap-engine/snapsort");
-  expect(markdown).toContain("yarn add @snap-engine/snapsort");
-  expect(markdown).toContain("bun add @snap-engine/snapsort");
-
-  await page.setViewportSize({ width: 390, height: 844 });
-  const viewport = await page.locator("html").evaluate((element) => ({
-    clientWidth: element.clientWidth,
-    scrollWidth: element.scrollWidth,
-  }));
-  expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth);
-});
-
-test("coding-agent resource links bypass client-side routing", async ({
-  page,
-}) => {
-  await page.goto("/docs/snapsort/introduction");
-
-  const markdownLink = page.getByRole("link", {
-    name: "this page as Markdown",
-  });
-  await expect(markdownLink).toHaveAttribute("data-sveltekit-reload", "");
-  const markdownResponsePromise = page.waitForResponse((response) =>
-    response.url().endsWith("/docs/snapsort/introduction.md"),
-  );
-  await markdownLink.click();
-  expect((await markdownResponsePromise).status()).toBe(200);
-  await expect(page).toHaveURL(/\/docs\/snapsort\/introduction\.md$/);
-
-  await page.goto("/docs/snapsort/introduction");
-  const indexLink = page.locator('a[href="/docs/snapsort/llms.txt"]');
-  await expect(indexLink).toHaveAttribute("data-sveltekit-reload", "");
-  const indexResponsePromise = page.waitForResponse((response) =>
-    response.url().endsWith("/docs/snapsort/llms.txt"),
-  );
-  await indexLink.click();
-  expect((await indexResponsePromise).status()).toBe(200);
-  await expect(page).toHaveURL(/\/docs\/snapsort\/llms\.txt$/);
-});
-
-test("raw Markdown selects one framework without damaging fenced code", async ({
-  request,
-}) => {
-  const svelteResponse = await request.get(
-    "/docs/snapsort/introduction/setup.md",
-  );
-  expect(svelteResponse.status()).toBe(200);
-  expect(svelteResponse.headers()["content-type"]).toContain("text/markdown");
-
-  const svelteMarkdown = await svelteResponse.text();
-  expect(svelteMarkdown).toContain("# Quickstart");
-  expect(svelteMarkdown).toContain('```svelte\n
 
-
+{#snippet graph()}
   
@@ -17,6 +22,20 @@
+{/snippet} + + + {#if withCamera} + + {@render graph()} + + {:else} + {@render graph()} + {/if} diff --git a/docs/snapengine/reference/camera.mdx b/docs/snapengine/reference/camera.mdx index 498332d8..36827b4b 100644 --- a/docs/snapengine/reference/camera.mdx +++ b/docs/snapengine/reference/camera.mdx @@ -52,6 +52,19 @@ const zoom = camera.zoom; canvasElement.style.transform = camera.canvasStyle; ``` +## Coordinate Spaces + +| Space | Origin | Units | +|-------|--------|-------| +| Screen | Browser viewport | Viewport (client) pixels | +| Camera | Camera container's top-left corner | Viewport pixels | +| World | Scene origin | CSS pixels inside the camera layer | + +Inside the camera layer, CSS lengths are world units: a `120px` wide element +is 120 world units wide at any zoom, while its `getBoundingClientRect()` width +is `120 * zoom`. `ElementObject.readDom()` reports world-space boxes and keeps +the viewport rectangle as `box.screen`. + ## Coordinate Methods ```ts @@ -133,6 +146,11 @@ cameraControl.zoomBy(-0.1); cameraControl.zoomBy(0.1, 200, 150); ``` +Camera changes and their painted transform are one commit: CameraControl +writes the transform immediately when a DOM write is allowed, and a +programmatic change requested during a read stage waits for the next write +stage. A DOM read therefore never sees a zoom that is not on screen yet. + ### Edge panning for drag owners Enable programmatic edge panning when composing the camera with a drag system diff --git a/docs/snapengine/reference/objects.mdx b/docs/snapengine/reference/objects.mdx index 33ccab78..c0814ee2 100644 --- a/docs/snapengine/reference/objects.mdx +++ b/docs/snapengine/reference/objects.mdx @@ -109,13 +109,17 @@ object.schedule(() => { | Field | Description | |-------|-------------| -| `x`, `y`, `width`, `height` | The border box. `x` and `y` are world coordinates. | -| `margin`, `padding`, `border` | Computed CSS edge thicknesses. | +| `x`, `y`, `width`, `height` | The border box in world units (CSS pixels inside the camera layer, at any zoom). | +| `margin`, `padding`, `border` | Computed CSS edge thicknesses, also world units. | | `screen` | The transformed viewport rectangle, exactly as `getBoundingClientRect()` reports it. | Every read produces a new frozen snapshot, so a box you keep never changes afterwards. `elementObject.box` always returns the latest one. +`readDom({ unapplyTransform: true })` removes the element's own inline +`translate` and `scale` (honoring its computed `transform-origin`) to report +its untransformed layout box; `screen` still reports what is rendered. + ## Public API | API | Description | diff --git a/package.json b/package.json index 68e40043..0beb215b 100755 --- a/package.json +++ b/package.json @@ -56,6 +56,7 @@ "test:camera-control-react": "playwright test -c tests/e2e/camera-control-react.playwright.config.ts", "test:asset-base-react": "playwright test -c tests/e2e/asset-base-react.playwright.config.ts", "test:core-ut": "playwright test tests/ut/core-*.spec.ts tests/ut/transform.spec.ts tests/ut/frame-controller.spec.ts --project=chromium", + "test:core-zoom": "playwright test -c tests/e2e/core-zoom.playwright.config.ts", "test:snapline-ut": "playwright test tests/ut/snapline-*.spec.ts --project=chromium", "test:snapsort-ut": "playwright test tests/ut/snapsort-*.spec.ts --project=chromium", "test:snapline": "playwright test -c tests/e2e/snapline.playwright.config.ts", diff --git a/src/AGENTS.md b/src/AGENTS.md index a77d612e..8e0ddda8 100644 --- a/src/AGENTS.md +++ b/src/AGENTS.md @@ -128,6 +128,15 @@ Camera and coordinate systems. - Camera (container-relative) - World (scene coordinates) +Inside the camera layer one world unit is one CSS pixel, so computed CSS +lengths (margins, padding, borders, inline `width`/`translate`) are already +world-space. Only values read from `getBoundingClientRect()` are screen-space; +`measureElementBox` maps the client rect's origin and size into world space +and keeps the raw client rect as `ElementBox.screen`. A measurement divides by +the camera's current zoom, so camera state and its painted transform must +change in the same commit (CameraControl paints synchronously when a write is +legal and defers programmatic changes requested during a read stage). + **Features:** - Coordinate conversions diff --git a/src/debug.ts b/src/debug.ts index 44441573..dc2f487d 100644 --- a/src/debug.ts +++ b/src/debug.ts @@ -1,4 +1,6 @@ +import type { Camera } from "./camera"; import type { Engine } from "./engine"; +import type { Rect } from "./geometry"; import { ElementObject } from "./object"; import type { BaseObject, FrameStats } from "./object"; @@ -13,6 +15,22 @@ export interface DebugRendererInterface { updateSize(width: number, height: number): void; } +/** A world-space size in debug-canvas (camera) pixels. */ +function cameraDelta( + camera: Camera | null, + width: number, + height: number, +): [number, number] { + return camera?.getCameraDeltaFromWorldDelta(width, height) ?? [width, height]; +} + +/** A world-space rectangle in debug-canvas (camera) pixels. */ +function cameraRectFromWorldRect(camera: Camera | null, rect: Rect): Rect { + const [x, y] = camera?.getCameraFromWorld(rect.x, rect.y) ?? [0, 0]; + const [width, height] = cameraDelta(camera, rect.width, rect.height); + return { x, y, width, height }; +} + export class DebugRenderer implements DebugRendererInterface { debugWindow: HTMLCanvasElement | null = null; debugCtx: CanvasRenderingContext2D | null = null; @@ -111,7 +129,11 @@ export class DebugRenderer implements DebugRendererInterface { marker.x, marker.y, ) ?? [0, 0]; - // console.debug("Debug Marker", marker.x, marker.y, cameraX, cameraY); + const [cameraWidth, cameraHeight] = cameraDelta( + engine.camera, + marker.width ?? 0, + marker.height ?? 0, + ); if (marker.type == "point") { this.debugCtx.beginPath(); this.debugCtx.fillStyle = marker.color; @@ -121,22 +143,18 @@ export class DebugRenderer implements DebugRendererInterface { this.debugCtx.beginPath(); if (marker.filled !== false) { this.debugCtx.fillStyle = marker.color; - this.debugCtx.rect(cameraX, cameraY, marker.width!, marker.height!); + this.debugCtx.rect(cameraX, cameraY, cameraWidth, cameraHeight); this.debugCtx.fill(); } else { this.debugCtx.strokeStyle = marker.color; this.debugCtx.lineWidth = marker.lineWidth ?? 1; - this.debugCtx.strokeRect( - cameraX, - cameraY, - marker.width!, - marker.height!, - ); + this.debugCtx.strokeRect(cameraX, cameraY, cameraWidth, cameraHeight); } } else if (marker.type == "circle") { this.debugCtx.beginPath(); this.debugCtx.fillStyle = marker.color; - this.debugCtx.arc(cameraX, cameraY, marker.radius!, 0, 2 * Math.PI); + const [radius] = cameraDelta(engine.camera, marker.radius ?? 0, 0); + this.debugCtx.arc(cameraX, cameraY, radius, 0, 2 * Math.PI); this.debugCtx.fill(); } else if (marker.type == "text") { this.debugCtx.fillStyle = marker.color; @@ -222,16 +240,8 @@ export class DebugRenderer implements DebugRendererInterface { this.debugCtx.beginPath(); this.debugCtx.strokeStyle = colors[i]; this.debugCtx.lineWidth = 1; - const [domCameraX, domCameraY] = engine.camera?.getCameraFromWorld( - property.x, - property.y, - ) ?? [0, 0]; - this.debugCtx.rect( - domCameraX, - domCameraY, - property.width, - property.height, - ); + const rect = cameraRectFromWorldRect(engine.camera, property); + this.debugCtx.rect(rect.x, rect.y, rect.width, rect.height); this.debugCtx.stroke(); } @@ -244,12 +254,12 @@ export class DebugRenderer implements DebugRendererInterface { this.debugCtx.beginPath(); this.debugCtx.strokeStyle = "black"; this.debugCtx.lineWidth = 1; - this.debugCtx.rect( - cameraX, - cameraY, + const [width, height] = cameraDelta( + engine.camera, elementObject.box.width, elementObject.box.height, ); + this.debugCtx.rect(cameraX, cameraY, width, height); this.debugCtx.stroke(); } } @@ -273,21 +283,26 @@ export class DebugRenderer implements DebugRendererInterface { : collisionWorld.y, ) ?? [0, 0]; if (collisionObject.type == "circle") { + const [radius] = cameraDelta( + engine.camera, + collisionObject.worldRadius, + 0, + ); this.debugCtx.arc( colliderCameraX, colliderCameraY, - collisionObject.worldRadius, + radius, 0, 2 * Math.PI, ); this.debugCtx.stroke(); } else if (collisionObject.type == "rect") { - this.debugCtx.rect( - colliderCameraX, - colliderCameraY, + const [width, height] = cameraDelta( + engine.camera, collisionObject.worldWidth, collisionObject.worldHeight, ); + this.debugCtx.rect(colliderCameraX, colliderCameraY, width, height); this.debugCtx.stroke(); } else if (collisionObject.type == "point") { this.debugCtx.arc(colliderCameraX, colliderCameraY, 2, 0, 2 * Math.PI); diff --git a/src/layout.ts b/src/layout.ts index 01af2527..721e2f57 100644 --- a/src/layout.ts +++ b/src/layout.ts @@ -174,6 +174,13 @@ export interface LayoutPlanOptions { readonly exclude?: (node: N) => boolean; /** Virtual entries folded into each container's cached dimensions. */ readonly insertions?: readonly VirtualInsertion[]; + /** + * Wrap comparison tolerance, in the tree's units. Defaults to + * `LAYOUT_WRAP_TOLERANCE`, which is calibrated for CSS pixels; for boxes + * measured under a zoomed camera, divide it by the zoom so the tolerance + * stays constant on screen, where browser measurement noise lives. + */ + readonly wrapTolerance?: number; readonly diagnostics?: LayoutPlanDiagnostics; } @@ -438,6 +445,7 @@ interface FlowBackendPlan { readonly kind: "flow"; readonly canWrap: boolean; readonly mainCapacity: number; + readonly wrapTolerance: number; } interface SlotBackendPlan { @@ -692,7 +700,7 @@ function materializeFlowLayout>( metrics.mainGap + entryMainSize + entryTrailingMainMargin > - backend.mainCapacity + LAYOUT_WRAP_TOLERANCE + backend.mainCapacity + backend.wrapTolerance ) { pushCurrentLine(); } @@ -790,6 +798,7 @@ export function createLayoutResolutionPlan>( options: LayoutPlanOptions = {}, ): LayoutResolutionPlan { const exclude = options.exclude; + const wrapTolerance = options.wrapTolerance ?? LAYOUT_WRAP_TOLERANCE; const insertions = Object.freeze([...(options.insertions ?? [])]); const plans = new Map>(); @@ -836,6 +845,7 @@ export function createLayoutResolutionPlan>( contentSize[axes.mainSize], metrics.measuredMainExtent, ), + wrapTolerance, }); const geometry = { diff --git a/src/object.ts b/src/object.ts index 46821a2f..903cd356 100755 --- a/src/object.ts +++ b/src/object.ts @@ -9,6 +9,7 @@ import { EventProxyFactory, generateTransformString, measureElementBox, + parseTransformOrigin, parseTransformString, setDomStyle, } from "./util"; @@ -916,6 +917,39 @@ export function detachAnimationFromOwner(animation: AnimationInterface) { owner.removeAnimationReference(animation); } +/** + * Remove an element's own inline translation and scale from its measured + * box, recovering its untransformed layout box. + * + * A point `p` of the layout box renders at `origin + t + s * (p - origin)`, + * so the layout left edge is `visual - t - origin * (1 - s)`. Translations + * are CSS pixels, which are world units inside the camera layer. The + * `screen` rect and edges stay as measured. + */ +function unapplyInlineTransform( + box: ElementBox, + element: DomElement, + transform: string, +): ElementBox { + const applied = parseTransformString(transform); + const scaleX = applied.scaleX !== 0 ? applied.scaleX : 1; + const scaleY = applied.scaleY !== 0 ? applied.scaleY : 1; + let originX = 0; + let originY = 0; + if (scaleX !== 1 || scaleY !== 1) { + [originX, originY] = parseTransformOrigin( + window.getComputedStyle(element).transformOrigin, + ); + } + return Object.freeze({ + ...box, + x: box.x - applied.x - originX * (1 - scaleX), + y: box.y - applied.y - originY * (1 - scaleY), + width: box.width / scaleX, + height: box.height / scaleY, + }); +} + function stageBoxIndex(stage: FrameReadStages | null): number { if (stage == "READ_1") return 0; if (stage == "READ_2") return 1; @@ -1092,14 +1126,7 @@ export class ElementObject< let box = measureElementBox(this.engine.camera, this.#element, this.#box); const transform = this.#element.style.transform; if (transform && transform != "none" && config.unapplyTransform) { - const applied = parseTransformString(transform); - box = Object.freeze({ - ...box, - x: box.x - applied.x, - y: box.y - applied.y, - width: box.width / applied.scaleX, - height: box.height / applied.scaleY, - }); + box = unapplyInlineTransform(box, this.#element, transform); } this.#box = box; diff --git a/src/util.ts b/src/util.ts index 93acbb3e..a8be14e5 100644 --- a/src/util.ts +++ b/src/util.ts @@ -1,4 +1,4 @@ -import type { ScreenToWorldMapper } from "./camera"; +import { worldRectFromScreenRect, type ScreenToWorldMapper } from "./camera"; import { ZERO_EDGES, type Edges, type ElementBox, type Rect } from "./geometry"; import type { DomElement, TransformProperty } from "./object"; @@ -93,25 +93,23 @@ function readEdges( * Build an element box from a measured client rect and computed CSS edges. * * Pure: performs no DOM reads, so it can be exercised with a stub camera. - * The box origin maps from screen to world space through `camera`; `screen` - * keeps the client rect exactly as measured. + * The border box maps from screen to world space through `camera`: its + * origin through the camera transform and its size by the zoom. Computed + * CSS edges are already world-space for elements inside the camera layer + * (one world unit is one CSS pixel there), so they pass through unchanged. + * `screen` keeps the client rect exactly as measured. */ function elementBoxFromMeasurement( camera: ScreenToWorldMapper | null, clientRect: Rect, edges: MeasuredEdges, ): ElementBox { - let x = clientRect.x; - let y = clientRect.y; - if (camera) { - const [cameraX, cameraY] = camera.getCameraFromScreen(x, y); - [x, y] = camera.getWorldFromCamera(cameraX, cameraY); - } + const world = worldRectFromScreenRect(camera, clientRect); return Object.freeze({ - x, - y, - width: clientRect.width, - height: clientRect.height, + x: world.x, + y: world.y, + width: world.width, + height: world.height, screen: Object.freeze({ x: clientRect.x, y: clientRect.y, @@ -158,20 +156,76 @@ function generateTransformString(transform: TransformProperty) { return string; } +const TRANSFORM_FUNCTION = /([a-zA-Z0-9]+)\(([^)]*)\)/g; + +/** A pixel length (`12px`, `-3.5px`, or a bare `0`), else `null`. */ +function parsePixelLength(value: string | undefined): number | null { + if (value === undefined) return null; + const trimmed = value.trim(); + if (/^-?[\d.]+(e-?\d+)?px$/i.test(trimmed)) return parseFloat(trimmed); + return parseFloat(trimmed) === 0 ? 0 : null; +} + /** - * Parses a CSS transform string to extract position values. + * Parses the translation and scale of a CSS transform string, such as the + * `translate3d(...) scale(...)` strings `generateTransformString` writes. + * + * Functions compose left to right, so a translate after a scale is scaled. + * Supported: `translate`, `translate3d`, `translateX`, `translateY` (pixel + * lengths only) and `scale`, `scaleX`, `scaleY`. Other functions, and + * translations in units other than `px`, are ignored. * * @param transform - A CSS transform string to parse. - * @returns An object with x and y coordinates. + * @returns The composed translation (`x`, `y`, in pixels) and scale. */ -function parseTransformString(transform: string) { - const transformValues = transform.split("(")[1].split(")")[0].split(","); - return { - x: parseFloat(transformValues[0]), - y: parseFloat(transformValues[1]), - scaleX: parseFloat(transformValues[3]) || 1, - scaleY: parseFloat(transformValues[4]) || 1, +function parseTransformString(transform: string): TransformProperty { + let x = 0; + let y = 0; + let scaleX = 1; + let scaleY = 1; + const translate = (dx: number | null, dy: number | null) => { + x += scaleX * (dx ?? 0); + y += scaleY * (dy ?? 0); }; + for (const [, name, rawArgs] of transform.matchAll(TRANSFORM_FUNCTION)) { + const args = rawArgs.split(","); + switch (name) { + case "translate": + case "translate3d": + translate(parsePixelLength(args[0]), parsePixelLength(args[1] ?? "0")); + break; + case "translateX": + translate(parsePixelLength(args[0]), 0); + break; + case "translateY": + translate(0, parsePixelLength(args[0])); + break; + case "scale": { + const sx = parseFloat(args[0]); + const sy = args[1] === undefined ? sx : parseFloat(args[1]); + if (Number.isFinite(sx)) scaleX *= sx; + if (Number.isFinite(sy)) scaleY *= sy; + break; + } + case "scaleX": { + const sx = parseFloat(args[0]); + if (Number.isFinite(sx)) scaleX *= sx; + break; + } + case "scaleY": { + const sy = parseFloat(args[0]); + if (Number.isFinite(sy)) scaleY *= sy; + break; + } + } + } + return { x, y, scaleX, scaleY }; +} + +/** The pixel `transform-origin` offsets of a computed style value. */ +function parseTransformOrigin(origin: string): [number, number] { + const [x, y] = origin.trim().split(/\s+/); + return [parsePixelLength(x) ?? 0, parsePixelLength(y) ?? 0]; } /** @@ -239,5 +293,6 @@ export { elementBoxFromMeasurement, generateTransformString, parseTransformString, + parseTransformOrigin, mergeDefined, }; diff --git a/tests/e2e/core-zoom.playwright.config.ts b/tests/e2e/core-zoom.playwright.config.ts new file mode 100644 index 00000000..d62931ba --- /dev/null +++ b/tests/e2e/core-zoom.playwright.config.ts @@ -0,0 +1,35 @@ +// Core measurement under a real zoomed Camera, across the three engines: each +// quantizes layout differently, and readDom must map every one of them into +// the same world-space box. +// +// Run with: npm run test:core-zoom +import { defineConfig, devices } from "@playwright/test"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const port = Number(process.env.CORE_ZOOM_TEST_PORT ?? 3034); +const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); + +export default defineConfig({ + testDir: ".", + testMatch: "core-zoom.spec.ts", + fullyParallel: false, + workers: 1, + reporter: [["list"]], + use: { + baseURL: `http://127.0.0.1:${port}`, + viewport: { width: 1280, height: 900 }, + }, + projects: [ + { name: "chromium", use: { ...devices["Desktop Chrome"] } }, + { name: "firefox", use: { ...devices["Desktop Firefox"] } }, + { name: "webkit", use: { ...devices["Desktop Safari"] } }, + ], + webServer: { + cwd: repoRoot, + command: `npx vite serve demo/svelte --config demo/svelte/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort`, + url: `http://127.0.0.1:${port}`, + reuseExistingServer: false, + timeout: 30_000, + }, +}); diff --git a/tests/e2e/core-zoom.spec.ts b/tests/e2e/core-zoom.spec.ts new file mode 100644 index 00000000..9bd3e031 --- /dev/null +++ b/tests/e2e/core-zoom.spec.ts @@ -0,0 +1,123 @@ +import { expect, test, type Page } from "@playwright/test"; + +// ElementObject.readDom under a real zoomed Camera: the measured border box is +// world-space (CSS pixels inside the camera layer), computed edges pass +// through, and `screen` is the browser's own client rect. + +interface Measurement { + box: { + x: number; + y: number; + width: number; + height: number; + margin: Record; + padding: Record; + border: Record; + screen: { x: number; y: number; width: number; height: number }; + }; + clientRect: { x: number; y: number; width: number; height: number }; +} + +/** + * Mount a camera at `zoom` over a 600x400 container at (100, 50) and read a + * 120x40 content-box element with margin 8/6, padding 5, and border 3, + * positioned at (40, 30) inside the camera layer. + */ +async function measureAtZoom( + page: Page, + zoom: number, + transform = "", +): Promise { + const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; + return page.evaluate( + async ({ coreImportPath, zoom, transform }) => { + const { Engine, Camera, ElementObject } = await import(coreImportPath); + document.body.replaceChildren(); + document.body.style.margin = "0"; + + const host = document.createElement("div"); + host.style.cssText = + "position:fixed;left:100px;top:50px;width:600px;height:400px;overflow:hidden;"; + const layer = document.createElement("div"); + layer.style.cssText = + "position:absolute;left:0;top:0;width:100%;height:100%;transform-origin:0 0;"; + const target = document.createElement("div"); + target.style.cssText = + "position:absolute;left:40px;top:30px;width:120px;height:40px;" + + "margin:8px 6px;padding:5px;border:3px solid black;box-sizing:content-box;"; + target.style.transform = transform; + layer.append(target); + host.append(layer); + document.body.append(host); + + const engine = new Engine(); + const camera = new Camera(engine, { + enablePan: false, + zoomBounds: { min: 0.2, max: 4 }, + }); + engine.camera = camera; + engine.assignDom(host); + camera.handleScroll(zoom - 1, 0, 0); + layer.style.transform = camera.canvasStyle; + + const object = new ElementObject(engine); + object.element = target; + const box = object.readDom( + { unapplyTransform: transform !== "" }, + "READ_1", + ); + const rect = target.getBoundingClientRect(); + return { + box: JSON.parse(JSON.stringify(box)), + clientRect: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }, + }; + }, + { coreImportPath, zoom, transform }, + ); +} + +test.beforeEach(async ({ page }) => { + await page.goto("/"); +}); + +for (const zoom of [0.5, 1, 2]) { + test(`readDom reports a world-space box at zoom ${zoom}`, async ({ + page, + }) => { + const { box, clientRect } = await measureAtZoom(page, zoom); + + // Border box: 120 + 2*5 + 2*3 = 136 by 40 + 2*5 + 2*3 = 56 CSS pixels, + // placed at left 40 + margin 6, top 30 + margin 8. + expect(box.width).toBeCloseTo(136, 2); + expect(box.height).toBeCloseTo(56, 2); + expect(box.x).toBeCloseTo(46, 2); + expect(box.y).toBeCloseTo(38, 2); + expect(box.margin).toEqual({ top: 8, right: 6, bottom: 8, left: 6 }); + expect(box.padding).toEqual({ top: 5, right: 5, bottom: 5, left: 5 }); + expect(box.border).toEqual({ top: 3, right: 3, bottom: 3, left: 3 }); + + expect(box.screen).toEqual(clientRect); + expect(clientRect.width).toBeCloseTo(136 * zoom, 2); + }); +} + +test("unapplyTransform removes an inline translate and scale", async ({ + page, +}) => { + const { box } = await measureAtZoom( + page, + 2, + "translate3d(20px, 10px, 0px) scale(2, 1.5)", + ); + + // Back to the untransformed layout box, despite the default 50% 50% origin. + expect(box.width).toBeCloseTo(136, 2); + expect(box.height).toBeCloseTo(56, 2); + expect(box.x).toBeCloseTo(46, 2); + expect(box.y).toBeCloseTo(38, 2); +}); diff --git a/tests/e2e/snapline-resize.spec.ts b/tests/e2e/snapline-resize.spec.ts index 03269a60..1d00b18b 100644 --- a/tests/e2e/snapline-resize.spec.ts +++ b/tests/e2e/snapline-resize.spec.ts @@ -419,3 +419,50 @@ test("tl anchor: the origin freezes once the min size is reached", async ({ expect(Math.abs(brAfter.x - brBefore.x)).toBeLessThanOrEqual(4); expect(Math.abs(brAfter.y - brBefore.y)).toBeLessThanOrEqual(4); }); + +// Under a zoomed camera every resize re-measures the node. The measured size +// must be world-space (CSS pixels), or the next resize starts from the +// on-screen size and the node jumps by the zoom factor. +for (const [direction, wheelDeltaY] of [ + ["out", 300], + ["in", -300], +] as const) { + test(`consecutive resizes stay continuous after zooming ${direction}`, async ({ + page, + }) => { + await page.goto("/snapline-resize?camera=1"); + await expect(page.locator("[data-snapline-type='node']")).toHaveCount(3); + const nodeA = page.locator("[data-snapline-type='node']", { + hasText: "Resizable A", + }); + const eastHandle = nodeA.locator(".resize-region[data-handle='e']"); + const cssWidth = () => nodeA.evaluate((node) => node.offsetWidth); + const zoom = async () => + (await nodeA.boundingBox())!.width / (await cssWidth()); + + // Zoom about the container's top-left corner so the nodes stay in view. + const canvas = (await page.locator("#node-ui-resize-canvas").boundingBox())!; + await page.mouse.move(canvas.x + 10, canvas.y + 10); + await page.keyboard.down("Control"); + await page.mouse.wheel(0, wheelDeltaY); + await page.keyboard.up("Control"); + await expect.poll(zoom).not.toBeCloseTo(1, 2); + const scale = await zoom(); + + const resizeEastBy = async (screenDx: number) => { + const from = await centerOf(eastHandle); + await dragFromTo(page, from, { x: from.x + screenDx, y: from.y }); + await waitForAnimationFrame(page); + await waitForAnimationFrame(page); + }; + + const initial = await cssWidth(); + await resizeEastBy(60); + const first = await cssWidth(); + expect(first - initial).toBeCloseTo(60 / scale, -0.5); + + await resizeEastBy(40); + const second = await cssWidth(); + expect(second - first).toBeCloseTo(40 / scale, -0.5); + }); +} diff --git a/tests/e2e/snapsort-camera.spec.ts b/tests/e2e/snapsort-camera.spec.ts new file mode 100644 index 00000000..0318db8e --- /dev/null +++ b/tests/e2e/snapsort-camera.spec.ts @@ -0,0 +1,127 @@ +import { expect, test, type Locator, type Page } from "@playwright/test"; + +// SnapSort inside a zoomed Camera. Drop prediction, the flow spacer, and the +// wrapped-row simulation all run on measured boxes, so they must agree with +// the browser at every zoom. + +async function centerOf(locator: Locator) { + const box = await locator.boundingBox(); + expect(box).not.toBeNull(); + return { x: box!.x + box!.width / 2, y: box!.y + box!.height / 2 }; +} + +function card(page: Page, id: string) { + return page.locator(`[data-card-id="${id}"]`); +} + +async function cardOrder(page: Page): Promise { + return page + .locator(".camera-grid [data-card-id]") + .evaluateAll((cards) => + cards.map((element) => element.getAttribute("data-card-id")!), + ); +} + +/** On-screen scale of the camera layer, measured from a card. */ +async function zoomOf(page: Page): Promise { + const width = (await card(page, "card-2").boundingBox())!.width; + return width / 120; +} + +async function zoomCamera(page: Page, wheelDeltaY: number) { + const canvas = (await page.locator("#snapsort-camera-canvas").boundingBox())!; + await page.mouse.move(canvas.x + 10, canvas.y + 10); + await page.keyboard.down("Control"); + await page.mouse.wheel(0, wheelDeltaY); + await page.keyboard.up("Control"); + await expect.poll(() => zoomOf(page)).not.toBeCloseTo(1, 2); +} + +/** + * Drag card 1 onto card 5's right half. Returns the flow spacer's authored + * width and the grid's row lengths (by screen y) while the drag is held. + */ +async function dragCardOneOntoCardFive(page: Page) { + const from = await centerOf(card(page, "card-1")); + const target = (await card(page, "card-5").boundingBox())!; + const to = { + x: target.x + target.width * 0.75, + y: target.y + target.height / 2, + }; + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x + 12, from.y + 6, { steps: 4 }); + await page.mouse.move(to.x, to.y, { steps: 16 }); + await page.waitForTimeout(250); + + const held = await page.evaluate(() => { + const ghost = document.querySelector(".camera-ghost"); + const entries = [ + ...document.querySelectorAll(".camera-grid > *"), + ].filter( + (element) => + element.classList.contains("camera-ghost") || + getComputedStyle(element).position !== "absolute", + ); + const rows = new Map(); + for (const element of entries) { + const y = Math.round(element.getBoundingClientRect().y); + rows.set(y, (rows.get(y) ?? 0) + 1); + } + return { + spacerWidth: ghost?.style.width ?? null, + rows: [...rows.entries()].sort((a, b) => a[0] - b[0]).map(([, n]) => n), + }; + }); + + await page.mouse.up(); + await expect(page.locator(".camera-ghost")).toHaveCount(0); + return held; +} + +test.beforeEach(async ({ page }) => { + await page.goto("/snapsort-camera"); + await expect(page.locator(".camera-grid [data-card-id]")).toHaveCount(8); +}); + +test("drags reorder the same way at zoom 1", async ({ page }) => { + const held = await dragCardOneOntoCardFive(page); + expect(held.spacerWidth).toBe("120px"); + expect(held.rows).toEqual([3, 3, 2]); + expect(await cardOrder(page)).toEqual([ + "card-2", + "card-3", + "card-4", + "card-5", + "card-1", + "card-6", + "card-7", + "card-8", + ]); +}); + +for (const [direction, wheelDeltaY] of [ + ["out", 300], + ["in", -300], +] as const) { + test(`drags size the spacer and keep rows whole after zooming ${direction}`, async ({ + page, + }) => { + await zoomCamera(page, wheelDeltaY); + const held = await dragCardOneOntoCardFive(page); + + // The spacer is authored in CSS pixels, which are world units here. + expect(held.spacerWidth).toBe("120px"); + expect(held.rows).toEqual([3, 3, 2]); + expect(await cardOrder(page)).toEqual([ + "card-2", + "card-3", + "card-4", + "card-5", + "card-1", + "card-6", + "card-7", + "card-8", + ]); + }); +} diff --git a/tests/e2e/snapsort.playwright.config.ts b/tests/e2e/snapsort.playwright.config.ts index 27c75988..65b9565e 100644 --- a/tests/e2e/snapsort.playwright.config.ts +++ b/tests/e2e/snapsort.playwright.config.ts @@ -21,7 +21,7 @@ const testMatch = [ const keyboardDemoProjects = frameworkBrowserProjects({ frameworks: ["svelte"], browsers: ["chromium"], - testMatch: ["snapsort-keyboard-demo.spec.ts"], + testMatch: ["snapsort-keyboard-demo.spec.ts", "snapsort-camera.spec.ts"], }).map((project) => ({ ...project, name: `${project.name}-keyboard`, diff --git a/tests/helpers/layout-grid.ts b/tests/helpers/layout-grid.ts index afa6a388..c5ec7d3a 100644 --- a/tests/helpers/layout-grid.ts +++ b/tests/helpers/layout-grid.ts @@ -213,6 +213,7 @@ export function rowCounts(ys: number[], rowStep: number): number[] { export interface LayoutRunOptions { exclude?: (node: N) => boolean; insertions?: readonly VirtualInsertion[]; + wrapTolerance?: number; } /** Lay out one container with a throwaway plan and its local insertions. */ @@ -226,6 +227,7 @@ export function flowLayoutPositions>( const plan = createLayoutResolutionPlan(container, { exclude: options.exclude, insertions, + wrapTolerance: options.wrapTolerance, }); return plan.layoutPositions( container, @@ -256,12 +258,14 @@ export function simulatedRowCounts( rowStep: number; insertion?: VirtualInsertion>; exclude?: (node: ItemSnapshot) => boolean; + wrapTolerance?: number; }, ): number[] { const origin = contentRect(container.box); const result = flowLayoutPositions(container, origin.x, origin.y, { exclude: options.exclude, insertions: options.insertion ? [options.insertion] : undefined, + wrapTolerance: options.wrapTolerance, }); const ys: number[] = []; for (const [, position] of result.itemPositions) ys.push(position.y); diff --git a/tests/ut/core-layout.spec.ts b/tests/ut/core-layout.spec.ts index 5babb598..ecdd3525 100644 --- a/tests/ut/core-layout.spec.ts +++ b/tests/ut/core-layout.spec.ts @@ -1,6 +1,7 @@ import { expect, test } from "@playwright/test"; import { contentRect } from "../../src/geometry"; import { + LAYOUT_WRAP_TOLERANCE, createLayoutResolutionPlan, flowAxesForDirection, inferFlowLayoutMetrics, @@ -750,3 +751,113 @@ test.describe("virtualDimensions", () => { expect(dims.height).toBeCloseTo(grid.box.height, 4); }); }); + +test.describe("scale invariance", () => { + /** Every box scaled by `k`, as a zoomed camera reports world units. */ + function scaleTree( + node: ItemSnapshot, + k: number, + ): ItemSnapshot { + const edges = (e: { + top: number; + right: number; + bottom: number; + left: number; + }) => ({ + top: e.top * k, + right: e.right * k, + bottom: e.bottom * k, + left: e.left * k, + }); + return { + ...node, + box: makeBox({ + x: node.box.x * k, + y: node.box.y * k, + width: node.box.width * k, + height: node.box.height * k, + margin: edges(node.box.margin), + padding: edges(node.box.padding), + border: edges(node.box.border), + }), + children: node.children.map((child) => scaleTree(child, k)), + }; + } + + for (const k of [0.5, 2]) { + test(`scaling every box by ${k} scales every position by ${k}`, () => { + const grid = makeGrid({ + rows: 3, + cols: 4, + itemW: 90, + itemH: 60, + gap: 4, + padding: 6, + }); + const scaled = scaleTree(grid, k); + const dragged = grid.children[5]; + const scaledDragged = scaled.children[5]; + + const at = ( + root: ItemSnapshot, + exclude: ItemSnapshot, + ) => { + const origin = contentRect(root.box); + return flowLayoutPositions(root, origin.x, origin.y, { + exclude: (node) => node === exclude, + }); + }; + const base = at(grid, dragged); + const zoomed = at(scaled, scaledDragged); + grid.children.forEach((child, index) => { + if (child === dragged) return; + const position = base.itemPositions.get(child)!; + const scaledPosition = zoomed.itemPositions.get( + scaled.children[index], + )!; + expect(scaledPosition.x).toBeCloseTo(position.x * k, 6); + expect(scaledPosition.y).toBeCloseTo(position.y * k, 6); + }); + }); + } + + test("a zoom-scaled wrap tolerance keeps exact-fill grids whole at zoom 0.2", () => { + // At zoom 0.2 one screen-pixel snap (1/64px) is 5/64 world units, above + // the CSS-pixel default tolerance; scaling the tolerance by the zoom + // keeps it constant on screen. + const zoom = 0.2; + const snap = 1 / 64 / zoom; + let seed = 7; + const rand = () => { + seed = (seed * 1664525 + 1013904223) % 4294967296; + return seed / 4294967296; + }; + for (let round = 0; round < 50; round++) { + const noise = () => (rand() - 0.5) * snap; + const grid = scaleTree( + makeGrid({ + rows: 4, + cols: 4, + itemW: 90.6, + itemH: 90.6, + gap: 4, + jitter: () => ({ w: noise() * zoom, x: noise() * zoom }), + }), + 1 / zoom, + ); + const dragged = grid.children[5]; + expect( + simulatedRowCounts(grid, { + rowStep: 94.6 / zoom, + insertion: ghostInsertion(grid, Math.floor(rand() * 16), { + width: dragged.box.width, + height: dragged.box.height, + }), + exclude: (node) => node === dragged, + wrapTolerance: LAYOUT_WRAP_TOLERANCE / zoom, + }), + `round ${round}`, + ).toEqual([4, 4, 4, 4]); + } + }); +}); diff --git a/tests/ut/core-measure.spec.ts b/tests/ut/core-measure.spec.ts new file mode 100644 index 00000000..af62717d --- /dev/null +++ b/tests/ut/core-measure.spec.ts @@ -0,0 +1,124 @@ +import { expect, test } from "@playwright/test"; +import { + elementBoxFromMeasurement, + generateTransformString, + parseTransformOrigin, + parseTransformString, +} from "../../src/util"; + +/** A camera at `zoom`, its container at (100, 50), looking at world (10, 20). */ +function stubCamera(zoom: number) { + const offset = { x: 100, y: 50 }; + const position = { x: 10, y: 20 }; + return { + getCameraFromScreen: (x: number, y: number): [number, number] => [ + x - offset.x, + y - offset.y, + ], + getWorldFromCamera: (x: number, y: number): [number, number] => [ + x / zoom + position.x, + y / zoom + position.y, + ], + getWorldDeltaFromCameraDelta: (x: number, y: number): [number, number] => [ + x / zoom, + y / zoom, + ], + }; +} + +const edges = { + margin: { top: 1, right: 2, bottom: 3, left: 4 }, + padding: { top: 5, right: 6, bottom: 7, left: 8 }, + border: { top: 1, right: 1, bottom: 1, left: 1 }, +}; + +test.describe("element box measurement", () => { + for (const zoom of [0.5, 1, 2]) { + test(`maps the border box into world space at zoom ${zoom}`, () => { + const clientRect = { x: 180, y: 90, width: 120, height: 60 }; + const box = elementBoxFromMeasurement( + stubCamera(zoom), + clientRect, + edges, + ); + + expect(box.x).toBeCloseTo(80 / zoom + 10, 9); + expect(box.y).toBeCloseTo(40 / zoom + 20, 9); + expect(box.width).toBeCloseTo(120 / zoom, 9); + expect(box.height).toBeCloseTo(60 / zoom, 9); + // Computed CSS edges are already world units inside the camera layer. + expect(box.margin).toBe(edges.margin); + expect(box.padding).toBe(edges.padding); + expect(box.border).toBe(edges.border); + expect(box.screen).toEqual(clientRect); + expect(Object.isFrozen(box)).toBe(true); + expect(Object.isFrozen(box.screen)).toBe(true); + }); + } + + test("without a camera every space is the client rect", () => { + const clientRect = { x: 5, y: 6, width: 7, height: 8 }; + const box = elementBoxFromMeasurement(null, clientRect, edges); + expect([box.x, box.y, box.width, box.height]).toEqual([5, 6, 7, 8]); + expect(box.screen).toEqual(clientRect); + }); +}); + +test.describe("transform parsing", () => { + test("round-trips the strings the engine writes", () => { + for (const transform of [ + { x: 0, y: 0, scaleX: 1, scaleY: 1 }, + { x: 12.5, y: -40, scaleX: 1, scaleY: 1 }, + { x: -3, y: 7, scaleX: 2, scaleY: 0.5 }, + ]) { + expect(parseTransformString(generateTransformString(transform))).toEqual( + transform, + ); + } + }); + + test("reads single-argument scale and two-argument translate", () => { + expect(parseTransformString("scale(2)")).toEqual({ + x: 0, + y: 0, + scaleX: 2, + scaleY: 2, + }); + expect(parseTransformString("translate(5px, 6px)")).toEqual({ + x: 5, + y: 6, + scaleX: 1, + scaleY: 1, + }); + expect(parseTransformString("translateX(4px) translateY(-2px)")).toEqual({ + x: 4, + y: -2, + scaleX: 1, + scaleY: 1, + }); + }); + + test("composes functions left to right", () => { + // A translate written after a scale moves by the scaled distance. + expect(parseTransformString("scale(2) translate(10px, 5px)")).toEqual({ + x: 20, + y: 10, + scaleX: 2, + scaleY: 2, + }); + }); + + test("treats none, empty, and unsupported values as identity", () => { + const identity = { x: 0, y: 0, scaleX: 1, scaleY: 1 }; + expect(parseTransformString("none")).toEqual(identity); + expect(parseTransformString("")).toEqual(identity); + expect(parseTransformString("rotate(30deg) translate(50%, 0)")).toEqual( + identity, + ); + }); + + test("reads pixel transform origins", () => { + expect(parseTransformOrigin("60px 20.5px")).toEqual([60, 20.5]); + expect(parseTransformOrigin("0px 0px 0px")).toEqual([0, 0]); + }); +}); diff --git a/tests/ut/snapsort-state.spec.ts b/tests/ut/snapsort-state.spec.ts index 1af4b932..7f0ea088 100644 --- a/tests/ut/snapsort-state.spec.ts +++ b/tests/ut/snapsort-state.spec.ts @@ -313,7 +313,7 @@ function expectOrderedChildren(container: Container): void { } } -test("visual rectangles are immutable screen-space snapshots and cache reads", () => { +test("visual rectangles are immutable world-space snapshots and cache reads", () => { const harness = createStateHarness(); try { harness.engine.camera = { @@ -347,15 +347,17 @@ test("visual rectangles are immutable screen-space snapshots and cache reads", ( expect(first).toBe(repeated); expect(reads).toBe(1); - expect(first?.coordinateSpace).toBe("screen"); + // The zoom-2 camera halves the viewport rect into world units, so a + // FLIP delta between two such rects is already in CSS pixels. + expect(first?.coordinateSpace).toBe("world"); expect([first?.x, first?.y, first?.width, first?.height]).toEqual([ - 30, 45, 80, 50, + 15, 22.5, 40, 25, ]); expect(Object.isFrozen(first)).toBe(true); setRect(element, { x: 90, y: 100, width: 20, height: 10 }); expect([first?.x, first?.y, first?.width, first?.height]).toEqual([ - 30, 45, 80, 50, + 15, 22.5, 40, 25, ]); } finally { harness.cleanup(); From 5e5e3c5945140aab50c112cf4d278f74c83c0105 Mon Sep 17 00:00:00 2001 From: tfukaza Date: Fri, 11 Sep 2026 11:05:32 -0700 Subject: [PATCH 08/10] refactor(snapsort): use core geometry types and helpers SnapSort no longer declares rectangle types or rect helpers of its own. Public API (hard break): - `GhostRect`, `ContainerLocalRect`, and `DropPriorityRect` are removed; ghost rects, drop-priority rects, and `toContainerLocalRect` / `insertionMarkerRect` results are core `Rect`s, and event pointers are core `Point`s. - `ItemHitbox`'s circle variant carries a core `Circle`: `{ shape: "circle", circle }` instead of `{ center, radius }`. Duplicates removed: - Four freeze-rect copies, three bounding-rect copies, two rect projections, `interpolateRect`, `sameRect`, and `euclidean`, replaced by `freezeRect`, `boundingRect`, `projectRects`, `lerpRect`, `rectsEqual`, `rectArea`, and `Math.hypot`. - Participant start rectangles were rebuilt in three files; they now come from `DragSession.startMemberRects()`. - The margin CSS string written three times (Vanilla adapter, React and Svelte `Ghost`) goes through `edgesToCss`; session.ts's inline edge type is `BoxModel`; the `ResolvedItemHitbox` mirror type is gone. - Candidate-selection tolerances are named. The type contract pins the removed names and the new circle shape. Docs (ghost, container, and callbacks references, README, AGENTS) are updated. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01DsiHfSvTGUzy6iNEkoWiG3 --- assets/snapsort/AGENTS.md | 3 +- assets/snapsort/README.md | 3 +- assets/snapsort/src/adapter.ts | 3 +- assets/snapsort/src/algorithm.ts | 108 +++++++++--------- assets/snapsort/src/drag/direct-candidates.ts | 87 ++------------ assets/snapsort/src/drag/direct-controller.ts | 83 +++----------- assets/snapsort/src/drag/flow-ghost.ts | 8 +- assets/snapsort/src/drag/pointer-preview.ts | 97 +++++----------- assets/snapsort/src/drag/session.ts | 35 +++++- assets/snapsort/src/event-builders.ts | 8 +- assets/snapsort/src/events.ts | 34 ++---- assets/snapsort/src/index.ts | 7 +- assets/snapsort/src/insertion-geometry.ts | 29 ++--- assets/snapsort/src/react/Ghost.tsx | 3 +- assets/snapsort/src/svelte/Ghost.svelte | 3 +- .../04_reference/02_svelte/01_container.mdx | 9 +- .../04_reference/02_svelte/03_ghost.mdx | 17 +-- .../04_reference/03_react/02_container.mdx | 12 +- .../04_reference/03_react/04_ghost.mdx | 17 +-- docs/snapsort/04_reference/05_callbacks.mdx | 23 ++-- tests/e2e/snapsort-drag-snapshot.spec.ts | 3 +- tests/types/snapsort-api-contract.ts | 31 ++++- tests/ut/snapsort-algorithm.spec.ts | 3 +- 23 files changed, 239 insertions(+), 387 deletions(-) diff --git a/assets/snapsort/AGENTS.md b/assets/snapsort/AGENTS.md index be723a4c..8c14cf73 100644 --- a/assets/snapsort/AGENTS.md +++ b/assets/snapsort/AGENTS.md @@ -21,7 +21,8 @@ A single `Container`/`Item` class pair (per framework) whose drag/drop behavior - Drag presentation types: `DragVisual` (`"item" | "preview" | "none"`) and `DropEffect` (`"move" | "none"`). - Ghost/insertion render types: `GhostState`, `InsertionMarkerState`, `InsertionGapSegment`, and `InsertionMarkerNeighbor`. - Render-state types and helpers: `RenderEntry`, `RenderTree`, `RenderTreeEvent`, `createRenderEntry`, `createRenderEntries`, `createRenderTree`, and `reduceRenderTree`. -- Insertion presentation types and helpers: `InsertionMarkerRectOptions`, `ContainerLocalRect`, `insertionMarkerRect`, `toContainerLocalRect`, and `stockInsertionMarkerRectOptions`. +- Insertion presentation types and helpers: `InsertionMarkerRectOptions`, `insertionMarkerRect`, `toContainerLocalRect`, and `stockInsertionMarkerRectOptions`. +- Geometry values use core's `@snap-engine/core/geometry` types (`Rect`, `Circle`, `Point`) and helpers; SnapSort declares no rectangle types of its own. - `createVanillaAdapter` and `CreateVanillaAdapterOptions`. - `ContainerCallbacks`, `ContainerConfig`, and `SortMode`. diff --git a/assets/snapsort/README.md b/assets/snapsort/README.md index 96a5f732..a8045efe 100644 --- a/assets/snapsort/README.md +++ b/assets/snapsort/README.md @@ -29,7 +29,8 @@ their bindings from `@snap-engine/snapsort/svelte` or - `DROP_REJECT_PRIORITY` - the `-1` effective priority that rejects a destination - Ghost and insertion render state: `GhostState`, `InsertionMarkerState`, `InsertionGapSegment`, and `InsertionMarkerNeighbor` - Framework render state: `RenderEntry`, `RenderTree`, `RenderTreeEvent`, `createRenderEntry`, `createRenderEntries`, `createRenderTree`, and `reduceRenderTree` -- Insertion presentation: `InsertionMarkerRectOptions`, `ContainerLocalRect`, `insertionMarkerRect`, `toContainerLocalRect`, and `stockInsertionMarkerRectOptions` +- Insertion presentation: `InsertionMarkerRectOptions`, `insertionMarkerRect`, `toContainerLocalRect`, and `stockInsertionMarkerRectOptions` +- Geometry values (`Rect`, `Circle`, `Point`) use the shared types from `@snap-engine/core/geometry` - `createVanillaAdapter` and `CreateVanillaAdapterOptions` - `ContainerCallbacks`, `ContainerConfig`, `SortMode` diff --git a/assets/snapsort/src/adapter.ts b/assets/snapsort/src/adapter.ts index b47c5d82..b8ab57f0 100644 --- a/assets/snapsort/src/adapter.ts +++ b/assets/snapsort/src/adapter.ts @@ -9,6 +9,7 @@ import type { ItemRemoveEvent, ItemSwapEvent, } from "./events"; +import { edgesToCss } from "@snap-engine/core/geometry"; import type { Container } from "./container"; import { insertionMarkerRect, @@ -117,7 +118,7 @@ function applyGhostState( if (ghost.type === "source-spacer" || ghost.type === "target-spacer") { const box = ghost.original.dragSnapshot?.box ?? ghost.original.box; - element.style.margin = `${box.margin.top}px ${box.margin.right}px ${box.margin.bottom}px ${box.margin.left}px`; + element.style.margin = edgesToCss(box.margin); return; } diff --git a/assets/snapsort/src/algorithm.ts b/assets/snapsort/src/algorithm.ts index 67e52e0f..2c679a62 100644 --- a/assets/snapsort/src/algorithm.ts +++ b/assets/snapsort/src/algorithm.ts @@ -1,9 +1,11 @@ import type { ElementBox } from "@snap-engine/core"; import { - type Circle, contentOffset, contentRect, distanceToRect, + freezeRect, + rectArea, + type Rect, pointIntersectsCircle, pointIntersectsRect, rectsIntersect, @@ -32,6 +34,7 @@ import { type InsertionGapSegment, type InsertionMarkerNeighbor, type InsertionMarkerPresentation, + type ItemHitbox, type ItemHitboxEvent, } from "./events"; import { buildItemLocation, buildItemRunEvent } from "./event-builders"; @@ -42,10 +45,15 @@ const TAG_CANDIDATES = "drop-candidates"; const TAG_LAYOUT = "drop-layout"; const TOP_CANDIDATE_DEBUG_LIMIT = 3; -type Rect = { x: number; y: number; width: number; height: number }; -type ResolvedItemHitbox = - | { shape: "rect"; rect: Rect } - | { shape: "circle"; circle: Circle }; +/** + * Candidate-selection tolerances, in world units. Differences below these are + * measurement noise, so selection falls through to the next tie-breaker. + */ +const EDGE_DISTANCE_TIE_TOLERANCE = 0.5; +const PLACEMENT_DISTANCE_TIE_TOLERANCE = 0.5; +const CROSS_CONTAINER_DISTANCE_TIE_TOLERANCE = 1; +/** Keeps a point exactly on a line boundary on the later line. */ +const LINE_INDEX_ROUNDING_BIAS = 0.001; type Snapshot = ItemSnapshot; @@ -97,10 +105,6 @@ interface SwapCandidate { area: number; } -function euclidean(x1: number, y1: number, x2: number, y2: number): number { - return Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2); -} - /** * Sum of euclidean distances between each dragged member's own tracked drag * position (its original box translated by the shared pointer delta — see @@ -125,7 +129,7 @@ function groupCandidateDistance( const h = box.height; const dcx = only.dragPositionX + w / 2; const dcy = only.dragPositionY + h / 2; - return euclidean(cx, cy, dcx, dcy); + return Math.hypot(cx - dcx, cy - dcy); } let cumulative = 0; @@ -142,11 +146,9 @@ function groupCandidateDistance( : rect.y + rect.height / 2; const memberDragCenterX = member.dragPositionX + w / 2; const memberDragCenterY = member.dragPositionY + h / 2; - sum += euclidean( - slotCenterX, - slotCenterY, - memberDragCenterX, - memberDragCenterY, + sum += Math.hypot( + slotCenterX - memberDragCenterX, + slotCenterY - memberDragCenterY, ); cumulative += isColumn ? h : w; } @@ -197,15 +199,6 @@ function isContainerObject(item: ItemBase): item is Container { ); } -function frozenRect(rect: Rect): Rect { - return Object.freeze({ - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }); -} - interface ContainerResolutionBase { readonly container: Container; readonly containerMetadata: Record; @@ -254,7 +247,7 @@ function createResolutionContext( x: pointer.x, y: pointer.y, }), - dragRect: frozenRect( + dragRect: freezeRect( dragRect ?? { x: item.dragPositionX, y: item.dragPositionY, @@ -275,8 +268,8 @@ function containerResolutionBase( const base = Object.freeze({ container, containerMetadata: container.metadata, - containerRect: frozenRect(requireDragSnapshotBox(container)), - containerContentRect: frozenRect(containerContentRect(container)), + containerRect: freezeRect(requireDragSnapshotBox(container)), + containerContentRect: freezeRect(containerContentRect(container)), depth: container.depth, }); context.containers.set(container, base); @@ -327,12 +320,12 @@ function resolveItemHitbox( item: ItemBase, container: Container, session: DragSession, -): ResolvedItemHitbox { +): ItemHitbox { const box = item.dragSnapshot?.box; if (!box) { throw new Error(`SnapSort Item ${item.id}: missing drag snapshot box.`); } - const defaultRect = frozenRect(box); + const defaultRect = freezeRect(box); const callback = container.callbacks?.getItemHitbox; if (!callback) return { shape: "rect", rect: defaultRect }; @@ -352,21 +345,22 @@ function resolveItemHitbox( if (hitbox?.shape === "rect") { assertRect(hitbox.rect, "getItemHitbox", container); - return { shape: "rect", rect: frozenRect(hitbox.rect) }; + return { shape: "rect", rect: freezeRect(hitbox.rect) }; } + const circle = hitbox?.shape === "circle" ? hitbox.circle : null; if ( - hitbox?.shape === "circle" && - Number.isFinite(hitbox.center?.x) && - Number.isFinite(hitbox.center?.y) && - Number.isFinite(hitbox.radius) && - hitbox.radius >= 0 + circle && + Number.isFinite(circle.x) && + Number.isFinite(circle.y) && + Number.isFinite(circle.radius) && + circle.radius >= 0 ) { return { shape: "circle", circle: Object.freeze({ - x: hitbox.center.x, - y: hitbox.center.y, - radius: hitbox.radius, + x: circle.x, + y: circle.y, + radius: circle.radius, }), }; } @@ -391,7 +385,7 @@ function hoveredItemCandidate( const area = hitbox.shape === "circle" ? Math.PI * hitbox.circle.radius ** 2 - : hitbox.rect.width * hitbox.rect.height; + : rectArea(hitbox.rect); const intersects = hitbox.shape === "circle" ? pointIntersectsCircle(session.pointer, hitbox.circle) @@ -559,7 +553,9 @@ function chooseByContentBox( const aEdge = distanceToNearestContentEdge(aRect, dragCenterX, dragCenterY); const bEdge = distanceToNearestContentEdge(bRect, dragCenterX, dragCenterY); - if (Math.abs(aEdge - bEdge) > 0.5) return aEdge < bEdge ? a : b; + if (Math.abs(aEdge - bEdge) > EDGE_DISTANCE_TIE_TOLERANCE) { + return aEdge < bEdge ? a : b; + } return a.distance <= b.distance ? a : b; } @@ -650,7 +646,12 @@ function virtualLayoutRecursiveFromSnapshot( ); const dragCross = axes.cross === "x" ? dragCenterX : dragCenterY; const lineIndexForCross = (cross: number) => - Math.max(0, Math.floor((cross - lineCrossStart) / lineCrossStep + 0.001)); + Math.max( + 0, + Math.floor( + (cross - lineCrossStart) / lineCrossStep + LINE_INDEX_ROUNDING_BIAS, + ), + ); const dragLineIndex = lineIndexForCross(dragCross); if (debugEnabled) { @@ -728,19 +729,15 @@ function virtualLayoutRecursiveFromSnapshot( target: { container, index }, candidateCenterX, candidateCenterY, - distance: euclidean( - candidateCenterX, - candidateCenterY, - dragCenterX, - dragCenterY, + distance: Math.hypot( + candidateCenterX - dragCenterX, + candidateCenterY - dragCenterY, ), groupDistance: session ? groupCandidateDistance(session, rect, isColumn) - : euclidean( - candidateCenterX, - candidateCenterY, - dragCenterX, - dragCenterY, + : Math.hypot( + candidateCenterX - dragCenterX, + candidateCenterY - dragCenterY, ), lineDistance: Math.abs(lineIndex - dragLineIndex), placementRect, @@ -920,13 +917,14 @@ function chooseProgressiveCandidate( const placementDistanceDelta: number = candidate.placementDistance - best.placementDistance; - if (Math.abs(placementDistanceDelta) > 0.5) { + if (Math.abs(placementDistanceDelta) > PLACEMENT_DISTANCE_TIE_TOLERANCE) { best = placementDistanceDelta < 0 ? candidate : best; continue; } if ( - Math.abs(candidate.distance - best.distance) <= 1 && + Math.abs(candidate.distance - best.distance) <= + CROSS_CONTAINER_DISTANCE_TIE_TOLERANCE && candidate.target.container.id !== best.target.container.id ) { best = chooseByContentBox(best, candidate, dragCenterX, dragCenterY); @@ -1112,7 +1110,7 @@ function insertionMarkerNeighbor( item: snapshot.value, itemId: snapshot.itemId, itemMetadata: snapshot.metadata, - rect: frozenRect(snapshot.box), + rect: freezeRect(snapshot.box), }); } @@ -1752,7 +1750,7 @@ export function determineSwapDropTarget( const box = requireDragSnapshotBox(hovered); candidates.push({ target: { container, index }, - area: box.width * box.height, + area: rectArea(box), }); } diff --git a/assets/snapsort/src/drag/direct-candidates.ts b/assets/snapsort/src/drag/direct-candidates.ts index 80114aa4..f8fd572d 100644 --- a/assets/snapsort/src/drag/direct-candidates.ts +++ b/assets/snapsort/src/drag/direct-candidates.ts @@ -1,6 +1,9 @@ import { + boundingRect, contentOffset, contentRect, + freezeRect, + projectRects, type Rect, } from "@snap-engine/core/geometry"; import { @@ -297,89 +300,19 @@ function snapshotPathTo( return []; } -function freezeRect(rect: Rect): Readonly { - return Object.freeze({ - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }); -} - -function sourceMemberRects( +function projectRectsIntoTarget( session: DragSessionController, + target: Readonly, ): readonly Readonly[] { - return Object.freeze( - session.items.map((item) => { - const start = session.dragVisualStart.get(item); - - if (!start) { - throw new Error( - "SnapSort: direct candidate geometry requires captured visual positions.", - ); - } - - const box = session.dragBoxFor(item); - return freezeRect({ - x: start.x, - y: start.y, - width: box.width, - height: box.height, - }); - }), - ); -} - -// TODO: Eventually, these functions -// should be provided as part of a layout engine -function boundingRect( - rects: readonly Readonly[], -): Rect { - if (rects.length === 0) { + const sourceRects = session.startMemberRects(); + const sourceGroup = boundingRect(sourceRects); + if (!sourceGroup) { throw new Error( "SnapSort: cannot calculate a direct candidate without projected items.", ); } - - let left = rects[0].x; - let top = rects[0].y; - let right = rects[0].x + rects[0].width; - let bottom = rects[0].y + rects[0].height; - - for (const rect of rects.slice(1)) { - left = Math.min(left, rect.x); - top = Math.min(top, rect.y); - right = Math.max(right, rect.x + rect.width); - bottom = Math.max(bottom, rect.y + rect.height); - } - - return { - x: left, - y: top, - width: right - left, - height: bottom - top, - }; -} - -function projectRectsIntoTarget( - session: DragSessionController, - target: Readonly, -): readonly Readonly[] { - const sourceRects = sourceMemberRects(session); - const sourceGroup = boundingRect(sourceRects); - const scaleX = sourceGroup.width > 0 ? target.width / sourceGroup.width : 1; - const scaleY = - sourceGroup.height > 0 ? target.height / sourceGroup.height : 1; - return Object.freeze( - sourceRects.map((rect) => - freezeRect({ - x: target.x + (rect.x - sourceGroup.x) * scaleX, - y: target.y + (rect.y - sourceGroup.y) * scaleY, - width: rect.width * scaleX, - height: rect.height * scaleY, - }), - ), + projectRects(sourceRects, sourceGroup, target).map(freezeRect), ); } @@ -387,7 +320,7 @@ export function directCandidateGeometry( session: DragSessionController, candidate: DirectCandidate, ): DirectCandidateGeometry { - const sourceRects = sourceMemberRects(session); + const sourceRects = session.startMemberRects(); const pressedIndex = session.items.indexOf(session.pressedItem); const primaryIndex = session.items.indexOf(session.primaryItem); const pressedStart = sourceRects[pressedIndex]; diff --git a/assets/snapsort/src/drag/direct-controller.ts b/assets/snapsort/src/drag/direct-controller.ts index c5281d9e..3f4d2dd3 100644 --- a/assets/snapsort/src/drag/direct-controller.ts +++ b/assets/snapsort/src/drag/direct-controller.ts @@ -1,5 +1,10 @@ import { AnimationObject } from "@snap-engine/core/animation"; -import type { Rect } from "@snap-engine/core/geometry"; +import { + boundingRect, + freezeRect, + lerpRect, + type Rect, +} from "@snap-engine/core/geometry"; import { evaluateDropTargetPriority } from "../algorithm"; import { animationConfigFor } from "../internal/flip-animation"; import { DROP_REJECT_PRIORITY, type DragLocation } from "../events"; @@ -32,13 +37,12 @@ export function cancelDirectMoveAnimation( const DIRECT_MOVE_DEFAULT_DURATION = 160; const DIRECT_MOVE_DEFAULT_EASING = "ease-out"; -function freezeRect(rect: Readonly): Readonly { - return Object.freeze({ - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }); +function requireBoundingRect(rects: readonly Readonly[]): Rect { + const bounds = boundingRect(rects); + if (!bounds) { + throw new Error("DirectDragController: visual geometry cannot be empty."); + } + return bounds; } function freezeRects( @@ -47,47 +51,6 @@ function freezeRects( return Object.freeze(rects.map(freezeRect)); } -function interpolateRect( - from: Readonly, - to: Readonly, - progress: number, -): Rect { - return { - x: from.x + (to.x - from.x) * progress, - y: from.y + (to.y - from.y) * progress, - width: from.width + (to.width - from.width) * progress, - height: from.height + (to.height - from.height) * progress, - }; -} - -function boundingRect( - rects: readonly Readonly[], -): Readonly { - const first = rects[0]; - if (!first) { - throw new Error("DirectDragController: visual geometry cannot be empty."); - } - - let left = first.x; - let top = first.y; - let right = first.x + first.width; - let bottom = first.y + first.height; - - for (const rect of rects.slice(1)) { - left = Math.min(left, rect.x); - top = Math.min(top, rect.y); - right = Math.max(right, rect.x + rect.width); - bottom = Math.max(bottom, rect.y + rect.height); - } - - return freezeRect({ - x: left, - y: top, - width: right - left, - height: bottom - top, - }); -} - export class DirectDragController { readonly inputType = "direct" as const; readonly initiatingItemId: ItemId; @@ -133,23 +96,7 @@ export class DirectDragController { this.#homeCandidateIndex = homeCandidateIndex; this.#currentCandidateIndex = homeCandidateIndex; - this.#visualRects = freezeRects( - this.#session.items.map((item) => { - const start = this.#session.dragVisualStart.get(item); - if (!start) { - throw new Error( - "DirectDragController: participant visual geometry is missing.", - ); - } - const box = this.#session.dragBoxFor(item); - return { - x: start.x, - y: start.y, - width: box.width, - height: box.height, - }; - }), - ); + this.#visualRects = this.#session.startMemberRects(); this.#activated = true; } @@ -221,7 +168,7 @@ export class DirectDragController { /** @internal Current animated bounding box for the complete drag visual. */ get visualGroupRect(): Readonly | null { return this.#visualRects.length > 0 - ? boundingRect(this.#visualRects) + ? freezeRect(requireBoundingRect(this.#visualRects)) : null; } @@ -308,7 +255,7 @@ export class DirectDragController { "DirectDragController: target visual geometry is missing.", ); } - return interpolateRect(source, target, $progress); + return lerpRect(source, target, $progress); }), { x: diff --git a/assets/snapsort/src/drag/flow-ghost.ts b/assets/snapsort/src/drag/flow-ghost.ts index 1cffc35f..0e1f122b 100644 --- a/assets/snapsort/src/drag/flow-ghost.ts +++ b/assets/snapsort/src/drag/flow-ghost.ts @@ -8,7 +8,7 @@ import { buildGhostSlotLocation, updateGhostState, } from "../event-builders"; -import type { DragLocation, GhostRect, GhostState } from "../events"; +import type { DragLocation, GhostState } from "../events"; import { virtualEntrySizeFor } from "@snap-engine/core/layout"; import { assertCanFireGhostInsert, @@ -185,7 +185,7 @@ function anchorRectFor( session: DragSession, container: Container, member: Item, -): GhostRect { +): Rect { const box = session.dragBoxFor(member); const containerSnapshot = container.dragSnapshot; if (!containerSnapshot) { @@ -208,7 +208,7 @@ function ensureFlowGhostRun( session: DragSession, container: Container, index: number, - rects: readonly GhostRect[], + rects: readonly Rect[], ): Item[] { const run = session.flowGhostRun; if (run.length !== 0 && run.length !== session.items.length) { @@ -288,7 +288,7 @@ function commitFlowGhostRun( container: Container, index: number, run: readonly Item[], - rects: readonly GhostRect[], + rects: readonly Rect[], ): void { const current = currentFlowPlacement(session); const rawIndex = rawFlowInsertionIndex( diff --git a/assets/snapsort/src/drag/pointer-preview.ts b/assets/snapsort/src/drag/pointer-preview.ts index d71e27c8..37088a44 100644 --- a/assets/snapsort/src/drag/pointer-preview.ts +++ b/assets/snapsort/src/drag/pointer-preview.ts @@ -1,5 +1,10 @@ -import { projectRect, type Rect } from "@snap-engine/core/geometry"; -import type { GhostRect } from "../events"; +import { + boundingRect, + freezeRect, + projectRects, + translateRect, + type Rect, +} from "@snap-engine/core/geometry"; import { buildGhostOverlayLocation, updateGhostState } from "../event-builders"; import { toContainerLocalRect } from "../insertion-geometry"; import { @@ -11,62 +16,30 @@ import { import type { DragSessionController as DragSession } from "./session"; import { readVisualRect } from "../internal/visual-rect"; -interface GroupGeometry { - x: number; - y: number; - width: number; - height: number; -} - -function frozenGroupGeometry(session: DragSession): GroupGeometry { - let left = Infinity; - let top = Infinity; - let right = -Infinity; - let bottom = -Infinity; - - for (const item of session.items) { - const box = session.dragBoxFor(item); - const start = session.dragVisualStart.get(item); - if (!start) { - throw new Error( - `SnapSort: participant "${item.itemId}" has no captured visual start.`, - ); +/** The dragged members' frozen start rectangles, as one bounding rect. */ +function frozenGroupGeometry(session: DragSession): Rect { + return ( + boundingRect(session.startMemberRects()) ?? { + x: 0, + y: 0, + width: 0, + height: 0, } - left = Math.min(left, start.x); - top = Math.min(top, start.y); - right = Math.max(right, start.x + box.width); - bottom = Math.max(bottom, start.y + box.height); - } - - return { - x: left, - y: top, - width: Math.max(0, right - left), - height: Math.max(0, bottom - top), - }; + ); } /** @internal Current world-space rectangle of the single group preview. */ -export function pointerPreviewRect(session: DragSession): GhostRect { +export function pointerPreviewRect(session: DragSession): Rect { if (session.input.inputType === "direct") { const directRect = session.input.visualGroupRect; - if (directRect) { - return { - x: directRect.x, - y: directRect.y, - width: directRect.width, - height: directRect.height, - }; - } + if (directRect) return freezeRect(directRect); } - const group = frozenGroupGeometry(session); - return { - x: group.x + session.visualPointer.x - session.visualStart.x, - y: group.y + session.visualPointer.y - session.visualStart.y, - width: group.width, - height: group.height, - }; + return translateRect( + frozenGroupGeometry(session), + session.visualPointer.x - session.visualStart.x, + session.visualPointer.y - session.visualStart.y, + ); } /** @internal Validate the root-owned pointer-preview adapter contract. */ @@ -158,22 +131,12 @@ export function pointerPreviewMemberRects( const directGroup = session.input.inputType === "direct" ? session.input.visualGroupRect : null; const group = directGroup ?? frozenGroupGeometry(session); - return session.items.map((item) => { - const directRect = - session.input.inputType === "direct" + const startRects = session.startMemberRects(); + const memberRects = session.items.map( + (item, index) => + (session.input.inputType === "direct" ? session.input.visualRectFor(item.itemId) - : null; - const box = directRect ?? session.dragBoxFor(item); - const start = directRect ?? session.dragVisualStart.get(item); - if (!start) { - throw new Error( - `SnapSort: participant "${item.itemId}" has no captured visual start.`, - ); - } - return projectRect( - { x: start.x, y: start.y, width: box.width, height: box.height }, - group, - preview, - ); - }); + : null) ?? startRects[index], + ); + return projectRects(memberRects, group, preview); } diff --git a/assets/snapsort/src/drag/session.ts b/assets/snapsort/src/drag/session.ts index 8addb27c..3cf8af82 100644 --- a/assets/snapsort/src/drag/session.ts +++ b/assets/snapsort/src/drag/session.ts @@ -1,5 +1,10 @@ import type { AnimationObject } from "@snap-engine/core/animation"; import type { ElementBox, dragStartProp } from "@snap-engine/core"; +import { + freezeRect, + type BoxModel, + type Rect, +} from "@snap-engine/core/geometry"; import type { Container } from "../container"; import type { Item } from "../item"; import { reconcileRootTreeState, rootHasItemId } from "../internal/tree-state"; @@ -398,6 +403,30 @@ export class DragSessionController implements DragSession { return box; } + /** + * @internal Each participant's frozen world rectangle at drag start: its + * captured visual start position with its drag-box size, in `items` order. + */ + startMemberRects(): readonly Rect[] { + return Object.freeze( + this.items.map((item) => { + const start = this.dragVisualStart.get(item); + if (!start) { + throw new Error( + `DragSession: participant "${item.itemId}" has no captured visual start.`, + ); + } + const box = this.dragBoxFor(item); + return freezeRect({ + x: start.x, + y: start.y, + width: box.width, + height: box.height, + }); + }), + ); + } + /** * Compute this session's group dimensions from each member's drag * snapshot box. Called once drag snapshots are captured (READ_1 of @@ -410,11 +439,7 @@ export class DragSessionController implements DragSession { let maxH = 0; let sumW = 0; let sumH = 0; - let prevBox: { - width: number; - height: number; - margin: { top: number; bottom: number; left: number; right: number }; - } | null = null; + let prevBox: BoxModel | null = null; for (const member of this.items) { const box = this.dragBoxFor(member); maxW = Math.max(maxW, box.width); diff --git a/assets/snapsort/src/event-builders.ts b/assets/snapsort/src/event-builders.ts index d979740b..1c19b91f 100644 --- a/assets/snapsort/src/event-builders.ts +++ b/assets/snapsort/src/event-builders.ts @@ -1,3 +1,4 @@ +import { freezeRect } from "@snap-engine/core/geometry"; import type { Container } from "./container"; import type { DragSessionController as DragSession } from "./drag/session"; import type { @@ -85,12 +86,7 @@ function freezeInsertionNeighbor( if (neighbor === null) return null; return Object.freeze({ ...neighbor, - rect: Object.freeze({ - x: neighbor.rect.x, - y: neighbor.rect.y, - width: neighbor.rect.width, - height: neighbor.rect.height, - }), + rect: freezeRect(neighbor.rect), }); } diff --git a/assets/snapsort/src/events.ts b/assets/snapsort/src/events.ts index aba55f72..800efd39 100644 --- a/assets/snapsort/src/events.ts +++ b/assets/snapsort/src/events.ts @@ -2,7 +2,7 @@ import type { Container } from "./container"; import type { Item } from "./item"; import type { DragSession } from "./drag/session"; import type { ItemId, ItemMetadata } from "./snapshot"; -import type { Rect } from "@snap-engine/core/geometry"; +import type { Circle, Point, Rect } from "@snap-engine/core/geometry"; /** * A container + index location, used both for drag sources/destinations and @@ -116,13 +116,6 @@ export interface ItemMoveEvent { beforeElement: HTMLElement | null; } -export interface GhostRect { - x: number; - y: number; - width: number; - height: number; -} - /** A zero-thickness insertion boundary in world coordinates. */ export type InsertionGapSegment = | { @@ -144,7 +137,7 @@ export interface InsertionMarkerNeighbor { readonly itemId: ItemId; readonly itemMetadata: ItemMetadata; /** Frozen world-space border box captured for this resolution. */ - readonly rect: Readonly; + readonly rect: Rect; } export interface GhostSlotLocation { @@ -185,7 +178,7 @@ export interface GhostStateBase { } interface RectGhostStateBase extends GhostStateBase { - readonly rect: GhostRect; + readonly rect: Rect; } /** Framework-ready render state for insertion placement feedback. */ @@ -226,7 +219,7 @@ type GhostStatePlacementFor = State extends GhostState State, "type" | "location" | "gap" | "previous" | "next" | "isCurrentPlacement" > - : State extends { readonly rect: GhostRect } + : State extends { readonly rect: Rect } ? Pick : never : never; @@ -329,13 +322,10 @@ export interface DropTargetChangeEvent { /** Effective priority value that rejects every candidate owned by a Container. */ export const DROP_REJECT_PRIORITY = -1; -/** A frozen world-space rectangle captured for the current drag resolution. */ -export type DropPriorityRect = Rect; - /** Complete world-space geometry for one pointer-hover hitbox. */ export type ItemHitbox = - | { shape: "rect"; rect: Rect } - | { shape: "circle"; center: { x: number; y: number }; radius: number }; + | { readonly shape: "rect"; readonly rect: Rect } + | { readonly shape: "circle"; readonly circle: Circle }; /** Geometry supplied to a hovered item's direct owner for hitbox resolution. */ export interface ItemHitboxEvent { @@ -348,7 +338,7 @@ export interface ItemHitboxEvent { overItemMetadata: ItemMetadata; container: Container; containerMetadata: Record; - pointer: { x: number; y: number }; + pointer: Point; /** Frozen world-space border box used when no callback is configured. */ defaultRect: Rect; } @@ -378,16 +368,16 @@ export interface DropPriorityEvent { index: number; /** The container's configured `dropPriority` before this callback overrides it. */ staticPriority: number; - pointer: { x: number; y: number }; + pointer: Point; /** * The primary dragged item's virtual current world-space rectangle. Its * leading edge preserves the pointer-to-item offset captured at drag start. */ - dragRect: DropPriorityRect; + dragRect: Rect; /** The destination's frozen border-box rectangle. */ - containerRect: DropPriorityRect; + containerRect: Rect; /** The destination's frozen content-box rectangle. */ - containerContentRect: DropPriorityRect; + containerContentRect: Rect; depth: number; } @@ -413,7 +403,7 @@ export interface DragItemHoverEvent { overItemMetadata: ItemMetadata; container: Container; containerMetadata: Record; - pointer: { x: number; y: number }; + pointer: Point; } /** diff --git a/assets/snapsort/src/index.ts b/assets/snapsort/src/index.ts index 4e664dc4..f1be3dfa 100644 --- a/assets/snapsort/src/index.ts +++ b/assets/snapsort/src/index.ts @@ -11,7 +11,6 @@ export type { DragLocation, DropEffect, DragVisual, - GhostRect, GhostLocation, GhostSlotLocation, GhostOverlayLocation, @@ -36,17 +35,13 @@ export type { DropTargetChangeEvent, DragItemHoverEvent, DropPriorityEvent, - DropPriorityRect, ItemHitbox, ItemHitboxEvent, VisualGeometryInvalidationEvent, VisualGeometryInvalidationReason, } from "./events"; export { DROP_REJECT_PRIORITY } from "./events"; -export type { - ContainerLocalRect, - InsertionMarkerRectOptions, -} from "./insertion-geometry"; +export type { InsertionMarkerRectOptions } from "./insertion-geometry"; export { insertionMarkerRect, stockInsertionMarkerRectOptions, diff --git a/assets/snapsort/src/insertion-geometry.ts b/assets/snapsort/src/insertion-geometry.ts index c80ba68e..422d69d3 100644 --- a/assets/snapsort/src/insertion-geometry.ts +++ b/assets/snapsort/src/insertion-geometry.ts @@ -1,20 +1,12 @@ +import { rectsEqual, type Rect } from "@snap-engine/core/geometry"; import type { Container } from "./container"; import type { - GhostRect, InsertionGapSegment, InsertionMarkerNeighbor, InsertionMarkerPresentation, InsertionMarkerState, } from "./events"; -/** A rectangle positioned from a Container's padding-box outer edge. */ -export interface ContainerLocalRect { - readonly x: number; - readonly y: number; - readonly width: number; - readonly height: number; -} - /** Explicit presentation choices for turning an insertion gap into a line. */ export interface InsertionMarkerRectOptions { readonly thickness: number; @@ -59,12 +51,6 @@ function insetGap( return { start: startInset, length: gap.length - startInset - endInset }; } -function sameRect(a: Readonly, b: Readonly): boolean { - return ( - a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height - ); -} - function sameInsertionNeighbor( a: InsertionMarkerNeighbor | null, b: InsertionMarkerNeighbor | null, @@ -76,7 +62,7 @@ function sameInsertionNeighbor( a.item === b.item && a.itemId === b.itemId && a.itemMetadata === b.itemMetadata && - sameRect(a.rect, b.rect) + rectsEqual(a.rect, b.rect) ); } @@ -96,11 +82,14 @@ export function sameInsertionMarkerPresentation( ); } -/** Convert a world-space rectangle into a Container's positioned local space. */ +/** + * Convert a world-space rectangle into a Container's positioned local space: + * relative to its padding-box outer edge, including its scroll offset. + */ export function toContainerLocalRect( - worldRect: Readonly, + worldRect: Rect, container: Container, -): ContainerLocalRect { +): Rect { const element = container.element; if (!element) { throw new Error( @@ -133,7 +122,7 @@ export function toContainerLocalRect( export function insertionMarkerRect( marker: InsertionMarkerState, options: InsertionMarkerRectOptions, -): ContainerLocalRect { +): Rect { assertFiniteNonnegative("thickness", options.thickness); assertFiniteNonnegative("startInset", options.startInset); assertFiniteNonnegative("endInset", options.endInset); diff --git a/assets/snapsort/src/react/Ghost.tsx b/assets/snapsort/src/react/Ghost.tsx index 2cc9ea91..48b05344 100644 --- a/assets/snapsort/src/react/Ghost.tsx +++ b/assets/snapsort/src/react/Ghost.tsx @@ -5,6 +5,7 @@ import { useRef, type HTMLAttributes, } from "react"; +import { edgesToCss } from "@snap-engine/core/geometry"; import { insertionMarkerRect, stockInsertionMarkerRectOptions, @@ -93,7 +94,7 @@ export const Ghost = forwardRef(function Ghost( left: overlay ? rect.x : undefined, margin: overlay ? 0 - : `${original.margin.top}px ${original.margin.right}px ${original.margin.bottom}px ${original.margin.left}px`, + : edgesToCss(original.margin), pointerEvents: overlay ? "none" : undefined, position: overlay ? "absolute" : undefined, top: overlay ? rect.y : undefined, diff --git a/assets/snapsort/src/svelte/Ghost.svelte b/assets/snapsort/src/svelte/Ghost.svelte index 18bc393d..1630062f 100644 --- a/assets/snapsort/src/svelte/Ghost.svelte +++ b/assets/snapsort/src/svelte/Ghost.svelte @@ -1,4 +1,5 @@