diff --git a/AGENTS.md b/AGENTS.md index c952be96..446e8c8a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,7 +30,7 @@ SnapEngineJS/ **Package:** `@snap-engine/core` **Purpose:** Core interactivity engine -**Build:** Yes → `dist/` +**Build:** Raw-source package (`exports` → `src/*.ts`); `npm run build` emits `dist/` as a build check See `src/AGENTS.md` for module details. @@ -38,6 +38,8 @@ See `src/AGENTS.md` for module details. - `@snap-engine/core` - Main export - `@snap-engine/core/animation` - Animation system - `@snap-engine/core/collision` - Collision detection +- `@snap-engine/core/geometry` - Shared geometry types and pure helpers +- `@snap-engine/core/layout` - Layout simulation over measured box trees - `@snap-engine/core/debug` - Debug utilities ## Asset Packages (`assets/`) @@ -149,7 +151,9 @@ Each asset package needs path mappings. A unified package at "@snap-engine/core": ["../../src/index.ts"], "@snap-engine/core/animation": ["../../src/animation.ts"], "@snap-engine/core/collision": ["../../src/collision.ts"], - "@snap-engine/core/debug": ["../../src/debug.ts"] + "@snap-engine/core/debug": ["../../src/debug.ts"], + "@snap-engine/core/geometry": ["../../src/geometry.ts"], + "@snap-engine/core/layout": ["../../src/layout.ts"] } } } diff --git a/assets/asset-base/src/camera.ts b/assets/asset-base/src/camera.ts index a346f9fc..660afa8d 100644 --- a/assets/asset-base/src/camera.ts +++ b/assets/asset-base/src/camera.ts @@ -4,11 +4,12 @@ import type { pointerUpProp, mouseWheelProp, pinchProp, - eventPosition, + PointerPosition, EdgePanController, } from "@snap-engine/core"; -import { ElementObject } from "@snap-engine/core"; +import { ElementObject, pointerPositionFromScreen } from "@snap-engine/core"; import { Camera } from "@snap-engine/core"; +import { pointIntersectsRect, type Point } from "@snap-engine/core/geometry"; import type { CameraConfig } from "@snap-engine/core"; /** What the mouse wheel / trackpad two-finger scroll does. */ @@ -148,8 +149,8 @@ class CameraControl extends ElementObject { #pinchAnchor: PinchAnchor | null = null; #edgePanRequest: { pointerId: number; - position: eventPosition; - onFrame: (position: eventPosition) => void; + position: PointerPosition; + onFrame: (position: PointerPosition) => void; } | null = null; #edgePanFrameId: number | null = null; #edgePanTimestamp: number | null = null; @@ -193,8 +194,7 @@ class CameraControl extends ElementObject { */ setCameraConfig(config: CameraConfig) { this.config = { ...this.config, camera: { ...this.config.camera, ...config } }; - this.camera?.setConfig(config); - this.paintCamera(); + this.#commitCamera(() => this.camera?.setConfig(config)); } set element(_element: HTMLElement) { @@ -209,31 +209,61 @@ class CameraControl extends ElementObject { // }); } + /** + * Paint the camera transform. The paint happens in the same commit as the + * camera state change whenever the stage allows a write: a DOM read later + * in the frame must never see the new zoom against the old transform, or + * it would convert the old on-screen size with the new zoom. + */ paintCamera() { - // this.engine.camera?.updateCameraProperty(); this.engine.camera?.updateCamera(); this.style.transform = this.engine.camera?.canvasStyle as string; + if (this.element && this.#canWriteNow()) { + this.writeTransform(); + return; + } this.schedule(() => this.writeTransform(), { stage: "WRITE_2", queueId: `${this.id}-transform`, }); } + #canWriteNow(): boolean { + const stage = this.global.currentStage; + return stage === "IDLE" || stage.startsWith("WRITE"); + } + + /** + * Apply a programmatic camera change and paint it as one commit. Requested + * during a read stage, both wait for the next write stage, so no read in + * this frame observes a camera the DOM does not show yet. + */ + #commitCamera(mutate: (camera: Camera) => void): void { + const commit = () => { + const camera = this.engine.camera; + if (!camera) return; + mutate(camera); + this.paintCamera(); + }; + if (this.#canWriteNow()) { + commit(); + return; + } + this.schedule(commit, { stage: "WRITE_2" }); + } + // Camera Methods updateCameraCenterPosition(x: number = 0, y: number = 0) { - this.engine.camera?.setCameraCenterPosition(x, y); - this.paintCamera(); + this.#commitCamera((camera) => camera.setCameraCenterPosition(x, y)); } setCameraPosition(x: number, y: number) { - this.engine.camera?.setCameraPosition(x, y); - this.paintCamera(); + this.#commitCamera((camera) => camera.setCameraPosition(x, y)); } setCameraCenterPosition(x: number, y: number) { - this.engine.camera?.setCameraCenterPosition(x, y); - this.paintCamera(); + this.#commitCamera((camera) => camera.setCameraCenterPosition(x, y)); } getCameraCenterPosition() { @@ -244,26 +274,19 @@ class CameraControl extends ElementObject { if (this.config.zoomLock) { return; } - const camera = this.engine.camera; - if (!camera) { - return; - } - - const targetX = originX ?? camera.cameraWidth / 2; - const targetY = originY ?? camera.cameraHeight / 2; - - camera.handleScroll(deltaZoom, targetX, targetY); - this.style.transform = camera.canvasStyle as string; - this.schedule(() => this.writeTransform(), { - stage: "WRITE_2", - queueId: `${this.id}-transform`, - }); + this.#commitCamera((camera) => + camera.handleScroll( + deltaZoom, + originX ?? camera.cameraWidth / 2, + originY ?? camera.cameraHeight / 2, + ), + ); } startEdgePan( pointerId: number, - position: eventPosition, - onFrame: (position: eventPosition) => void, + position: PointerPosition, + onFrame: (position: PointerPosition) => void, ): void { if (!this.config.edgePan?.enabled) { return; @@ -273,7 +296,7 @@ class CameraControl extends ElementObject { this.#scheduleEdgePanFrame(); } - updateEdgePan(pointerId: number, position: eventPosition): void { + updateEdgePan(pointerId: number, position: PointerPosition): void { if (!this.config.edgePan?.enabled) { this.stopEdgePan(pointerId); return; @@ -336,9 +359,9 @@ class CameraControl extends ElementObject { return 0; }; const velocityX = - axisSpeed(request.position.screenX, left, right) * maxSpeed; + axisSpeed(request.position.screen.x, left, right) * maxSpeed; const velocityY = - axisSpeed(request.position.screenY, top, bottom) * maxSpeed; + axisSpeed(request.position.screen.y, top, bottom) * maxSpeed; const previousTimestamp = this.#edgePanTimestamp ?? timestamp; const elapsedSeconds = Math.min(32, Math.max(0, timestamp - previousTimestamp)) / 1000; @@ -356,8 +379,8 @@ class CameraControl extends ElementObject { this.paintCamera(); request.onFrame( this.#positionFromScreen( - request.position.screenX, - request.position.screenY, + request.position.screen.x, + request.position.screen.y, ), ); } @@ -365,23 +388,21 @@ class CameraControl extends ElementObject { this.#scheduleEdgePanFrame(); }; - #positionFromScreen(screenX: number, screenY: number): eventPosition { - const camera = this.engine.camera; - if (!camera) { - return { - x: screenX, - y: screenY, - cameraX: screenX, - cameraY: screenY, - screenX, - screenY, - }; - } - const [cameraX, cameraY] = camera.getCameraFromScreen(screenX, screenY); - const [x, y] = camera.getWorldFromCamera(cameraX, cameraY); - return { x, y, cameraX, cameraY, screenX, screenY }; + #positionFromScreen(screenX: number, screenY: number): PointerPosition { + return pointerPositionFromScreen(this.engine.camera, screenX, screenY); } + /** Whether a viewport point lies inside the camera's container. */ + #isWithinCamera(camera: Camera, screen: Point): boolean { + return pointIntersectsRect(screen, { + x: camera.containerOffsetX, + y: camera.containerOffsetY, + width: camera.cameraWidth, + height: camera.cameraHeight, + }); + } + + // Event Handlers onCursorDown(prop: pointerDownProp) { @@ -419,8 +440,8 @@ class CameraControl extends ElementObject { } this.#state = "panning"; this.#panPointerId = prop.event.pointerId; - this.#mouseDownX = prop.position.screenX; - this.#mouseDownY = prop.position.screenY; + this.#mouseDownX = prop.position.screen.x; + this.#mouseDownY = prop.position.screen.y; this.#pinchAnchor = null; this.engine.camera?.handlePanStart(); prop.event.preventDefault(); @@ -438,14 +459,10 @@ class CameraControl extends ElementObject { if (this.global.data.allowCameraControl === false) { return; } - const dx = prop.position.screenX - this.#mouseDownX; - const dy = prop.position.screenY - this.#mouseDownY; + const dx = prop.position.screen.x - this.#mouseDownX; + const dy = prop.position.screen.y - this.#mouseDownY; this.engine.camera?.handlePanDrag(dx, dy); - this.style.transform = this.engine.camera?.canvasStyle as string; - this.schedule(() => this.writeTransform(), { - stage: "WRITE_2", - queueId: `${this.id}-transform`, - }); + this.paintCamera(); } onCursorUp(prop: pointerUpProp) { @@ -459,11 +476,7 @@ class CameraControl extends ElementObject { this.#state = "idle"; this.#panPointerId = null; this.engine.camera?.handlePanEnd(); - this.style.transform = this.engine.camera?.canvasStyle as string; - this.schedule(() => this.writeTransform(), { - stage: "WRITE_2", - queueId: `${this.id}-transform`, - }); + this.paintCamera(); } onZoom(prop: mouseWheelProp) { @@ -484,12 +497,7 @@ class CameraControl extends ElementObject { return; } const camera = this.engine.camera!; - if ( - prop.position.screenX < camera.containerOffsetX || - prop.position.screenX > camera.containerOffsetX + camera.cameraWidth || - prop.position.screenY < camera.containerOffsetY || - prop.position.screenY > camera.containerOffsetY + camera.cameraHeight - ) { + if (!this.#isWithinCamera(camera, prop.position.screen)) { return; } // A trackpad pinch is a ctrl-wheel; Cmd+scroll is a meta-wheel with much larger @@ -500,8 +508,8 @@ class CameraControl extends ElementObject { options.zoomSensitivity * (pinch ? options.pinchZoomGain : 1); this.zoomBy( (-prop.delta * sensitivity) / 2000, - prop.position.cameraX, - prop.position.cameraY, + prop.position.camera.x, + prop.position.camera.y, ); prop.event.preventDefault(); } @@ -519,12 +527,7 @@ class CameraControl extends ElementObject { if (!camera) { return; } - if ( - prop.position.screenX < camera.containerOffsetX || - prop.position.screenX > camera.containerOffsetX + camera.cameraWidth || - prop.position.screenY < camera.containerOffsetY || - prop.position.screenY > camera.containerOffsetY + camera.cameraHeight - ) { + if (!this.#isWithinCamera(camera, prop.position.screen)) { return; } // Wheel deltas are screen pixels in the document-scroll sense (deltaY > 0 = @@ -532,11 +535,7 @@ class CameraControl extends ElementObject { // divides by zoom, giving 1:1 screen-pixel panning like a pointer drag. const event = prop.event as WheelEvent; camera.handlePan(event.deltaX * sensitivity, event.deltaY * sensitivity); - this.style.transform = camera.canvasStyle as string; - this.schedule(() => this.writeTransform(), { - stage: "WRITE_2", - queueId: `${this.id}-transform`, - }); + this.paintCamera(); prop.event.preventDefault(); } @@ -566,8 +565,8 @@ class CameraControl extends ElementObject { } const [pointer0, pointer1] = prop.current.pointerList; const center = { - x: (pointer0.cameraX + pointer1.cameraX) / 2, - y: (pointer0.cameraY + pointer1.cameraY) / 2, + x: (pointer0.camera.x + pointer1.camera.x) / 2, + y: (pointer0.camera.y + pointer1.camera.y) / 2, }; const camera = this.engine.camera; if (!camera) { @@ -600,11 +599,7 @@ class CameraControl extends ElementObject { : center.y, }); - this.style.transform = camera.canvasStyle as string; - this.schedule(() => this.writeTransform(), { - stage: "WRITE_2", - queueId: `${this.id}-transform`, - }); + this.paintCamera(); } onPinchEnd() { @@ -625,14 +620,15 @@ class CameraControl extends ElementObject { super.destroy(removeDom); } - #createPinchAnchor(center: { x: number; y: number }, distance: number) { + #createPinchAnchor(center: Point, distance: number) { const camera = this.engine.camera!; + const [worldX, worldY] = camera.getWorldFromCamera(center.x, center.y); return { centerX: center.x, centerY: center.y, distance, - worldX: camera.cameraPositionX + center.x / camera.zoom, - worldY: camera.cameraPositionY + center.y / camera.zoom, + worldX, + worldY, zoom: camera.zoom, }; } diff --git a/assets/asset-base/tsconfig.json b/assets/asset-base/tsconfig.json index a188dc0f..eff595e3 100644 --- a/assets/asset-base/tsconfig.json +++ b/assets/asset-base/tsconfig.json @@ -8,6 +8,8 @@ "@snap-engine/core/animation": ["../../src/animation.ts"], "@snap-engine/core/collision": ["../../src/collision.ts"], "@snap-engine/core/debug": ["../../src/debug.ts"], + "@snap-engine/core/geometry": ["../../src/geometry.ts"], + "@snap-engine/core/layout": ["../../src/layout.ts"], "@snap-engine/asset-base": ["./src/index.ts"], "@snap-engine/asset-base/*": ["./src/*"], "@snap-engine/asset-base/svelte": ["./src/svelte/index.ts"], diff --git a/assets/snapline/AGENTS.md b/assets/snapline/AGENTS.md index c9f23a17..7c8f80bc 100644 --- a/assets/snapline/AGENTS.md +++ b/assets/snapline/AGENTS.md @@ -145,7 +145,9 @@ snapline/ **Key Methods:** - `addConnectorObject(connector)` - Register connector - `getConnector(name)` - Look up a connector by name -- `remeasureDomGeometry()` - Re-measure the box and re-glue lines +- `remeasureDomGeometry()` - Re-measure the box and re-glue lines. Measured + sizes are world-space (CSS pixels), so the hitbox matches the authored + size at any camera zoom - `setSize(width, height)` / `setSizeState(width, height)` - Drive size ### ConnectorMirror diff --git a/assets/snapline/src/connector.ts b/assets/snapline/src/connector.ts index 4a1f84a7..7eab250c 100644 --- a/assets/snapline/src/connector.ts +++ b/assets/snapline/src/connector.ts @@ -1,13 +1,25 @@ -import { ElementObject, BaseObject, type DomElement } from "@snap-engine/core"; +import { + ElementObject, + BaseObject, + pointerPositionFromWorld, + worldRectFromScreenRect, + type DomElement, + type WorldToScreenMapper, +} from "@snap-engine/core"; import type { dragEndProp, dragProp, dragStartProp, - eventPosition, + PointerPosition, pointerDownProp, pointerUpProp, } from "@snap-engine/core"; import { CircleCollider } from "@snap-engine/core/collision"; +import { + rectCenter, + type Bounds, + type Point, +} from "@snap-engine/core/geometry"; import type { NodeMirror } from "./node"; import { LineMirror, cloneAnchor, type LineMirrorPhase } from "./line"; import { getGraphRegistry } from "./internal/shared-data"; @@ -38,35 +50,16 @@ export type DragEndOutcome = /** The gesture was cancelled (pointer cancel, teardown). */ | "cancelled"; -export interface ConnectorPoint { - x: number; - y: number; -} - -export interface ConnectorNormal { - x: number; - y: number; -} - -export interface ConnectorAnchor extends ConnectorPoint { - normal?: ConnectorNormal; +/** A world-space connection point, with an optional outward normal. */ +export interface ConnectorAnchor extends Point { + normal?: Point; } /** Cached world-space bounds derived from the parent node's collision box. */ -export interface ConnectorGeometrySnapshot { +export interface ConnectorGeometrySnapshot extends Bounds { connector: ConnectorMirror; node: NodeMirror; - x: number; - y: number; - width: number; - height: number; - left: number; - right: number; - top: number; - bottom: number; center: ConnectorAnchor; - scaleX: number; - scaleY: number; } export interface ConnectorHit { @@ -83,7 +76,7 @@ export interface ConnectorCandidate { export interface ConnectorSurfaceHitTestEvent { connector: ConnectorMirror; - position: eventPosition; + position: PointerPosition; geometry: ConnectorGeometrySnapshot; phase: LineMirrorPhase; } @@ -94,7 +87,7 @@ export interface ConnectorAnchorEvent { line: LineMirror; role: ConnectorRole; phase: LineMirrorPhase; - position: ConnectorPoint; + position: Point; geometry: ConnectorGeometrySnapshot; peerGeometry: ConnectorGeometrySnapshot | null; hit: ConnectorHit | null; @@ -177,7 +170,7 @@ export interface ConnectorDisconnectionEvent export interface ConnectorDragEvent { connector: ConnectorMirror; - position: eventPosition; + position: PointerPosition; pointerId: number; } @@ -278,7 +271,7 @@ class ConnectorMirror extends ElementObject { #candidate: ConnectorResolvedHit | null = null; #dragLine: LineMirror | null = null; #edgePanPointerId: number | null = null; - #localCenter: ConnectorPoint; + #localCenter: Point; #hasMeasuredCenter = false; #armed: ArmedConnection | null = null; #gestureOrigin: "new" | "reconnect" | null = null; @@ -414,17 +407,15 @@ class ConnectorMirror extends ElementObject { return { connector: this, node: this.parent, - x: bounds.left, - y: bounds.top, + x: bounds.x, + y: bounds.y, width: bounds.width, height: bounds.height, left: bounds.left, right: bounds.right, top: bounds.top, bottom: bounds.bottom, - center: { x: bounds.centerX, y: bounds.centerY }, - scaleX: bounds.scaleX, - scaleY: bounds.scaleY, + center: { x: bounds.center.x, y: bounds.center.y }, }; } @@ -444,21 +435,9 @@ class ConnectorMirror extends ElementObject { if (!this.element) return this.geometry.center; const rect = this.element.getBoundingClientRect(); - const screenX = rect.left + rect.width / 2; - const screenY = rect.top + rect.height / 2; - if (this.engine?.camera) { - const [cameraX, cameraY] = this.engine.camera.getCameraFromScreen( - screenX, - screenY, - ); - const [worldX, worldY] = this.engine.camera.getWorldFromCamera( - cameraX, - cameraY, - ); - return { x: worldX, y: worldY }; - } - - return { x: screenX, y: screenY }; + return rectCenter( + worldRectFromScreenRect(this.engine?.camera ?? null, rect), + ); } measureLocalCenter( @@ -472,9 +451,9 @@ class ConnectorMirror extends ElementObject { const scaleY = parentTransform.scaleY === 0 ? 1 : parentTransform.scaleY; const localLeft = (prop.x - parentTransform.x) / scaleX; const localTop = (prop.y - parentTransform.y) / scaleY; - const localCenterX = (prop.x + prop.width / 2 - parentTransform.x) / scaleX; - const localCenterY = - (prop.y + prop.height / 2 - parentTransform.y) / scaleY; + const center = rectCenter(prop); + const localCenterX = (center.x - parentTransform.x) / scaleX; + const localCenterY = (center.y - parentTransform.y) / scaleY; this.localTransform = { x: localLeft, y: localTop }; this.#localCenter = { x: localCenterX, y: localCenterY }; @@ -665,12 +644,14 @@ class ConnectorMirror extends ElementObject { } findCandidateAtPoint( - position: ConnectorPoint, + position: Point, phase: "preview-target" | "drop" = "preview-target", ): ConnectorCandidate | null { return ( - this.#resolveTargetAtPoint(asEventPosition(position), phase)?.candidate ?? - null + this.#resolveTargetAtPoint( + asPointerPosition(this.engine?.camera ?? null, position), + phase, + )?.candidate ?? null ); } @@ -766,7 +747,7 @@ class ConnectorMirror extends ElementObject { this.#moveDraggedLine(prop.position); } - #moveDraggedLine(position: eventPosition): void { + #moveDraggedLine(position: PointerPosition): void { if (this.#state !== ConnectorState.DRAGGING || !this.#dragLine) return; const candidate = this.#resolveTargetAtPoint(position, "preview-target"); @@ -1013,7 +994,7 @@ class ConnectorMirror extends ElementObject { role: ConnectorRole; phase: LineMirrorPhase; peer: ConnectorMirror | null; - position: ConnectorPoint; + position: Point; hit: ConnectorHit | null; strategy: ConnectorSurfaceStrategy | null; }): ConnectorAnchor { @@ -1057,7 +1038,7 @@ class ConnectorMirror extends ElementObject { } #resolveTargetAtPoint( - position: eventPosition, + position: PointerPosition, phase: "preview-target" | "drop", ): ConnectorResolvedHit | null { const hits: ConnectorResolvedHit[] = []; @@ -1328,20 +1309,18 @@ function normalizeHit( }; } -function isFinitePoint(point: ConnectorPoint): boolean { +function isFinitePoint(point: Point): boolean { return Number.isFinite(point.x) && Number.isFinite(point.y); } -function asEventPosition(position: ConnectorPoint): eventPosition { - const value = position as Partial; - return { - x: position.x, - y: position.y, - cameraX: value.cameraX ?? position.x, - cameraY: value.cameraY ?? position.y, - screenX: value.screenX ?? position.x, - screenY: value.screenY ?? position.y, - }; +/** A full pointer position for a world point, resolving camera and screen. */ +function asPointerPosition( + camera: WorldToScreenMapper | null, + position: Point, +): PointerPosition { + const value = position as Partial; + if (value.camera && value.screen) return value as PointerPosition; + return pointerPositionFromWorld(camera, position.x, position.y); } function compareResolvedHits( diff --git a/assets/snapline/src/group.ts b/assets/snapline/src/group.ts index 2e91e2c1..1cc24c97 100644 --- a/assets/snapline/src/group.ts +++ b/assets/snapline/src/group.ts @@ -2,8 +2,13 @@ import { mergeDefined, type BaseObject, type Engine, - type eventPosition, + type PointerPosition, } from "@snap-engine/core"; +import { + pointIntersectsRect, + rectArea, + rectContainsRect, +} from "@snap-engine/core/geometry"; import { NodeMirror, type NodeConfig } from "./node"; import { getGraphRegistry } from "./internal/shared-data"; @@ -52,31 +57,13 @@ const DEFAULT_GROUP_CONFIG = { minHeight: 120, } satisfies GroupConfig; -type Bounds = ReturnType; - -function boundsArea(bounds: Bounds): number { - return ( - Math.max(0, bounds.right - bounds.left) * - Math.max(0, bounds.bottom - bounds.top) - ); -} - -function containsBounds(container: Bounds, child: Bounds): boolean { - return ( - child.left >= container.left && - child.right <= container.right && - child.top >= container.top && - child.bottom <= container.bottom - ); -} - function stableGroupOrder( left: GroupNodeMirror, right: GroupNodeMirror, ): number { const areaDelta = - boundsArea(left.hitBox.getWorldBoundsSnapshot()) - - boundsArea(right.hitBox.getWorldBoundsSnapshot()); + rectArea(left.hitBox.getWorldBoundsSnapshot()) - + rectArea(right.hitBox.getWorldBoundsSnapshot()); return areaDelta || String(left.id).localeCompare(String(right.id)); } @@ -296,12 +283,8 @@ class GroupNodeMirror extends NodeMirror { allowsMembership(node: NodeMirror): boolean { const box = this.hitBox.getWorldBoundsSnapshot(); const nodeBounds = node.hitBox.getWorldBoundsSnapshot(); - const centerContained = - nodeBounds.centerX >= box.left && - nodeBounds.centerX <= box.right && - nodeBounds.centerY >= box.top && - nodeBounds.centerY <= box.bottom; - const boundsContained = containsBounds(box, nodeBounds); + const centerContained = pointIntersectsRect(nodeBounds.center, box); + const boundsContained = rectContainsRect(box, nodeBounds); // Ordinary nodes use center containment. A nested group must fit completely // so partially overlapping peers cannot become a parent/child pair. @@ -328,7 +311,7 @@ class GroupNodeMirror extends NodeMirror { this.refreshMembership(true); } - protected override beginSelectionDrag(position: eventPosition): void { + protected override beginSelectionDrag(position: PointerPosition): void { super.beginSelectionDrag(position); this.#carryGroupOrigin = { x: this.worldTransform.x, diff --git a/assets/snapline/src/index.ts b/assets/snapline/src/index.ts index 739875d7..b87ee39b 100644 --- a/assets/snapline/src/index.ts +++ b/assets/snapline/src/index.ts @@ -7,7 +7,6 @@ export type { NodeLinesEvent, NodePointerEvent, NodeGeometry, - ResolvedNodeDragPosition, NodeResizeEvent, NodeSelectionEvent, NodeSelectionModeEvent, @@ -32,9 +31,7 @@ export type { ConnectorDragEvent, ConnectorGeometrySnapshot, ConnectorHit, - ConnectorNormal, ConnectorPairEvent, - ConnectorPoint, ConnectorPointerEvent, ConnectorResolvedHit, ConnectorRole, @@ -79,14 +76,11 @@ export { query } from "./query"; export type { GraphQuery } from "./query"; export { PlacementController } from "./placement"; export type { - PlacementAnchor, PlacementCallbacks, PlacementCancelEvent, PlacementConfig, PlacementEvent, PlacementGeometrySnapshot, - PlacementPoint, - PlacementSize, PlacementSnapshot, } from "./placement"; export { applyLineChange, attachControlledGraph } from "./controlled-graph"; diff --git a/assets/snapline/src/line.ts b/assets/snapline/src/line.ts index 6f9bbd4a..1c74c9f7 100644 --- a/assets/snapline/src/line.ts +++ b/assets/snapline/src/line.ts @@ -1,10 +1,10 @@ import { ElementObject, BaseObject } from "@snap-engine/core"; +import type { Point } from "@snap-engine/core/geometry"; import type { ConnectorAnchor, ConnectorCandidate, ConnectorMirror, ConnectorHit, - ConnectorPoint, ConnectorSurfaceStrategy, } from "./connector"; import type { GeometryInvalidationObserver, GeometryWriter } from "./types"; @@ -27,7 +27,7 @@ export type LineMirrorPhase = export interface LineGeometrySnapshot { readonly start: ConnectorAnchor; readonly end: ConnectorAnchor; - readonly delta: Readonly<{ x: number; y: number }>; + readonly delta: Point; } export interface LineStateSnapshot { @@ -57,7 +57,7 @@ class LineMirror extends ElementObject { #sourceHit: ConnectorHit | null = null; #targetStrategy: ConnectorSurfaceStrategy | null = null; #targetHit: ConnectorHit | null = null; - #previewPosition: ConnectorPoint | null = null; + #previewPosition: Point | null = null; constructor(engine: any, parent: BaseObject, config: { id?: string } = {}) { super(engine, parent); @@ -236,7 +236,7 @@ class LineMirror extends ElementObject { this.#emitStateChange(); } - setPreviewPosition(position: ConnectorPoint): void { + setPreviewPosition(position: Point): void { this.#previewPosition = position; this.updateAnchors(); } diff --git a/assets/snapline/src/node.ts b/assets/snapline/src/node.ts index da21792b..a1f96a59 100644 --- a/assets/snapline/src/node.ts +++ b/assets/snapline/src/node.ts @@ -1,4 +1,5 @@ import { BaseObject, ElementObject, mergeDefined } from "@snap-engine/core"; +import type { Point, Rect } from "@snap-engine/core/geometry"; import { ConnectorMirror } from "./connector"; import { LineMirror } from "./line"; import type { @@ -7,7 +8,7 @@ import type { dragStartProp, dragProp, dragEndProp, - eventPosition, + PointerPosition, } from "@snap-engine/core"; import { RectCollider } from "@snap-engine/core/collision"; import { getGraphRegistry } from "./internal/shared-data"; @@ -54,12 +55,9 @@ const DEFAULT_NODE_CONFIG: ResolvedNodeConfig = { * Node geometry maintained by SnapLine during drag or resize. * After that, this is committed to the frontend framework. */ -export interface NodeGeometry { - node: NodeMirror; - x: number; - y: number; - width: number; - height: number; +/** A node's world-space rectangle. */ +export interface NodeGeometry extends Rect { + readonly node: NodeMirror; } /** Batched geometry observation for group/multi-select drag. */ @@ -70,7 +68,7 @@ export interface GeometryChangeEvent { export interface NodePointerEvent { node: NodeMirror; pointerId: number; - position: eventPosition; + position: PointerPosition; originalEvent?: PointerEvent; } @@ -80,21 +78,13 @@ export interface NodeDragPositionEvent { y: number; startX: number; startY: number; - position: eventPosition; -} - -export interface ResolvedNodeDragPosition { - x: number; - y: number; + position: PointerPosition; } -export interface NodeResizeEvent { - node: NodeMirror; - handle: ResizeHandle | null; - x: number; - y: number; - width: number; - height: number; +/** A node's world-space rectangle during a resize gesture. */ +export interface NodeResizeEvent extends Rect { + readonly node: NodeMirror; + readonly handle: ResizeHandle | null; } export interface NodeSelectionEvent { @@ -128,7 +118,7 @@ export interface NodeCallbacks { /** Allow node position to be overridden during drag, e.g. to implement snap-to-grid. */ resolveDragPosition?: ( event: NodeDragPositionEvent, - ) => ResolvedNodeDragPosition; + ) => Point; /** Override if and how nodes get selected or deselected. */ resolveSelectionMode?: (event: NodeSelectionModeEvent) => SelectionMode; /** Called when selected status of a node changes. */ @@ -180,7 +170,7 @@ class NodeMirror extends ElementObject { #dragPointerId: number | null = null; #dragRoots: NodeMirror[] = []; #dragCommitNodes: NodeMirror[] = []; - #lastDragPosition: eventPosition | null = null; + #lastDragPosition: PointerPosition | null = null; #pointerSelectionMode: SelectionMode = "replace"; #wasSelectedAtPointerDown = false; @@ -371,7 +361,7 @@ class NodeMirror extends ElementObject { } } - geometrySnapshot(): { x: number; y: number; width: number; height: number } { + geometrySnapshot(): Rect { return { x: this.worldTransform.x, y: this.worldTransform.y, @@ -633,7 +623,7 @@ class NodeMirror extends ElementObject { }); } - #moveSelectionToPointer(position: eventPosition): void { + #moveSelectionToPointer(position: PointerPosition): void { this.#lastDragPosition = position; for (const node of this.#dragRoots) { node.setDragPosition({ position } as dragProp); @@ -641,7 +631,7 @@ class NodeMirror extends ElementObject { } /** Hook used to build one deduplicated multi-selection drag session. */ - protected beginSelectionDrag(position: eventPosition): void { + protected beginSelectionDrag(position: PointerPosition): void { this.setStartPositions(); this.#pointerReferenceX = position.x; this.#pointerReferenceY = position.y; diff --git a/assets/snapline/src/placement.ts b/assets/snapline/src/placement.ts index a6f6abf9..be26331a 100644 --- a/assets/snapline/src/placement.ts +++ b/assets/snapline/src/placement.ts @@ -1,47 +1,33 @@ +import type { Point, Size } from "@snap-engine/core/geometry"; import type { GeometryWriter } from "./types"; -export interface PlacementPoint { - x: number; - y: number; -} - -export interface PlacementSize { - width: number; - height: number; -} - -export interface PlacementAnchor { - x: number; - y: number; -} - export interface PlacementSnapshot { active: boolean; payload: T | null; - screen: PlacementPoint | null; - world: PlacementPoint | null; - position: PlacementPoint | null; - size: PlacementSize | null; - anchor: PlacementAnchor; + screen: Point | null; + world: Point | null; + position: Point | null; + size: Size | null; + anchor: Point; allowed: boolean; } export interface PlacementGeometrySnapshot { readonly active: boolean; readonly visible: boolean; - readonly screen: PlacementPoint | null; - readonly world: PlacementPoint | null; - readonly position: PlacementPoint | null; - readonly size: PlacementSize | null; + readonly screen: Point | null; + readonly world: Point | null; + readonly position: Point | null; + readonly size: Size | null; readonly allowed: boolean; } export interface PlacementEvent extends PlacementSnapshot { payload: T; - screen: PlacementPoint; - world: PlacementPoint; - position: PlacementPoint; - size: PlacementSize; + screen: Point; + world: Point; + position: Point; + size: Size; originalEvent?: PointerEvent | KeyboardEvent; } @@ -61,9 +47,9 @@ export interface PlacementCallbacks { } export interface PlacementConfig { - screenToWorld: (screen: PlacementPoint) => PlacementPoint | null; + screenToWorld: (screen: Point) => Point | null; callbacks?: PlacementCallbacks; - anchor?: PlacementAnchor; + anchor?: Point; } /** @@ -121,8 +107,8 @@ export class PlacementController { begin( payload: T, - size: PlacementSize, - options: { anchor?: PlacementAnchor; screen?: PlacementPoint } = {}, + size: Size, + options: { anchor?: Point; screen?: Point } = {}, ): void { this.#snapshot = { active: true, @@ -138,7 +124,7 @@ export class PlacementController { if (options.screen) this.update(options.screen); } - update(screen: PlacementPoint, originalEvent?: PointerEvent): boolean { + update(screen: Point, originalEvent?: PointerEvent): boolean { const current = this.#snapshot; if (!current.active || current.payload == null || current.size == null) { return false; diff --git a/assets/snapline/src/select.ts b/assets/snapline/src/select.ts index 20ec7292..83d577f1 100644 --- a/assets/snapline/src/select.ts +++ b/assets/snapline/src/select.ts @@ -1,3 +1,4 @@ +import type { Rect } from "@snap-engine/core/geometry"; import { BaseObject, ElementObject } from "@snap-engine/core"; import type { pointerDownProp, @@ -10,12 +11,8 @@ import { getGraphRegistry } from "./internal/shared-data"; import type { GeometryWriter } from "./types"; /** World-space rectangle delivered to the registered geometry writer. */ -export interface SelectRect { - x: number; - y: number; - width: number; - height: number; - visible: boolean; +export interface SelectRect extends Rect { + readonly visible: boolean; } export interface SelectStartEvent { diff --git a/assets/snapline/tsconfig.json b/assets/snapline/tsconfig.json index 9926a9ba..9eba18f4 100644 --- a/assets/snapline/tsconfig.json +++ b/assets/snapline/tsconfig.json @@ -8,6 +8,8 @@ "@snap-engine/core/animation": ["../../src/animation.ts"], "@snap-engine/core/collision": ["../../src/collision.ts"], "@snap-engine/core/debug": ["../../src/debug.ts"], + "@snap-engine/core/geometry": ["../../src/geometry.ts"], + "@snap-engine/core/layout": ["../../src/layout.ts"], "@snap-engine/asset-base": ["../asset-base/src/index.ts"], "@snap-engine/asset-base/react": ["../asset-base/src/react/index.ts"], "@snap-engine/snapline": ["./src/index.ts"], diff --git a/assets/snapsort/AGENTS.md b/assets/snapsort/AGENTS.md index fb037419..8c14cf73 100644 --- a/assets/snapsort/AGENTS.md +++ b/assets/snapsort/AGENTS.md @@ -15,13 +15,14 @@ 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"`). - 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`. @@ -66,7 +67,6 @@ snapsort/ ├── insertion-geometry.ts # Marker rectangle and world/local projection helpers ├── algorithm.ts # Candidate generation, drop policy, and placement ├── callbacks.ts # Standard drop-policy callbacks - ├── layout.ts # Pure flow-layout simulation ├── snapshot.ts # ItemSnapshot / ItemMetadata types ├── drag/ │ ├── session.ts @@ -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`) @@ -197,6 +197,12 @@ item/ghost structure. transaction snapshots the root, so a later Container's pass may replace animations started by an earlier pass in the same frame; mutation commits are still preserved in request order within each Container. +- All drag, candidate, and FLIP geometry is world-space (`ElementBox` from + core, CSS pixels inside a Camera layer). FLIP deltas are therefore written + directly as `translate` pixels, spacer/marker sizes as CSS pixels, and the + layout wrap tolerance is scaled by `1 / zoom` (`layoutWrapToleranceFor`) so + it stays constant on screen. Never mix in `box.screen` except to draw + viewport overlays. Copying is an application recipe, not a lifecycle effect. The destination's ordinary `onItemMove` moves the original stable ID to the destination and, in diff --git a/assets/snapsort/README.md b/assets/snapsort/README.md index 2d792e8a..a8045efe 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 @@ -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` @@ -238,14 +239,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 +438,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 +495,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/adapter.ts b/assets/snapsort/src/adapter.ts index a7d59ddf..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, @@ -116,8 +117,8 @@ function applyGhostState( if (ghost.type === "source-spacer" || ghost.type === "target-spacer") { const box = - ghost.original.dragSnapshot?.box ?? ghost.original.currentDomProperty; - element.style.margin = `${box.margin.top}px ${box.margin.right}px ${box.margin.bottom}px ${box.margin.left}px`; + ghost.original.dragSnapshot?.box ?? ghost.original.box; + element.style.margin = edgesToCss(box.margin); return; } diff --git a/assets/snapsort/src/algorithm.ts b/assets/snapsort/src/algorithm.ts index 37949392..2c679a62 100644 --- a/assets/snapsort/src/algorithm.ts +++ b/assets/snapsort/src/algorithm.ts @@ -1,29 +1,31 @@ -import type { DomProperty } from "@snap-engine/core"; +import type { ElementBox } from "@snap-engine/core"; import { - type CollisionCircle, + contentOffset, + contentRect, distanceToRect, + freezeRect, + rectArea, + type Rect, pointIntersectsCircle, pointIntersectsRect, rectsIntersect, -} from "@snap-engine/core/collision"; -import type { Item as ItemBase } from "./item"; -import type { Container } from "./container"; +} from "@snap-engine/core/geometry"; import { + LAYOUT_WRAP_TOLERANCE, childRelativeOffset, - contentBoxOrigin, - contentBoxSize, createLayoutResolutionPlan, flowAxesForDirection, flowLayoutCanWrap, - inferSnapshotVisualLines, + inferVisualLines, virtualEntrySizeFor, pointFromAxes, - virtualDimensions as layoutVirtualDimensions, type LayoutPlanDiagnostics, type LayoutResolutionPlan, - type SnapshotVisualLine, + type VisualLine, type VirtualInsertion, -} from "./layout"; +} from "@snap-engine/core/layout"; +import type { Item as ItemBase } from "./item"; +import type { Container } from "./container"; import type { ItemSnapshot } from "./snapshot"; import type { DragSessionController as DragSession } from "./drag/session"; import { @@ -32,6 +34,7 @@ import { type InsertionGapSegment, type InsertionMarkerNeighbor, type InsertionMarkerPresentation, + type ItemHitbox, type ItemHitboxEvent, } from "./events"; import { buildItemLocation, buildItemRunEvent } from "./event-builders"; @@ -42,21 +45,26 @@ 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: CollisionCircle }; +/** + * 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; -export interface VirtualGhost { - container: Container; - index: number; - width: number; - height: number; -} +type Snapshot = ItemSnapshot; -export interface VirtualDimensions { - width: number; - height: number; +/** + * The layout wrap tolerance for boxes measured under `item`'s camera: the + * CSS-pixel default scaled so it stays constant on screen at any zoom. + * @internal + */ +export function layoutWrapToleranceFor(item: ItemBase): number { + const zoom = item.engine?.camera?.zoom ?? 1; + return zoom > 0 ? LAYOUT_WRAP_TOLERANCE / zoom : LAYOUT_WRAP_TOLERANCE; } export interface ResolvedDropTarget { @@ -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; } @@ -180,7 +182,7 @@ function requireDragSnapshot(item: ItemBase): ItemSnapshot { return snapshot; } -function requireDragSnapshotBox(item: ItemBase): DomProperty { +function requireDragSnapshotBox(item: ItemBase): ElementBox { return requireDragSnapshot(item).box; } @@ -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; @@ -233,11 +226,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 +243,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: freezeRect( + dragRect ?? { + x: item.dragPositionX, + y: item.dragPositionY, + width: box.width, + height: box.height, + }, + ), containers: new Map(), }); } @@ -268,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); @@ -320,17 +320,17 @@ 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 }; const hitbox = callback({ - session: session.handle, + session, item: draggedItem, itemId: draggedItem.itemId, itemMetadata: draggedItem.metadata, @@ -345,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, }), }; } @@ -384,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) @@ -475,30 +476,10 @@ function createLayoutSnapshot(root: ItemBase): { return { root: rootSnapshot, byItem }; } -function layoutInsertionFromGhost( - byItem: Map>, - ghost?: VirtualGhost, -): VirtualInsertion | undefined { - if (!ghost) return undefined; - const container = byItem.get(ghost.container); - if (!container) return undefined; - const margin = requireDragSnapshotBox(ghost.container).margin; - const size = virtualEntrySizeFor(container, { - width: ghost.width, - height: ghost.height, - margin, - }); - return { - container, - index: ghost.index, - entry: { ...size, margin }, - }; -} - function activeFlowInsertionsFromPendingPlacement( byItem: Map>, session: DragSession | null, -): VirtualInsertion[] { +): VirtualInsertion[] { // Insertion and swap lifecycles use absolute marker/pointer ghosts. They do // not occupy a flow slot and must never influence virtual list layout. if (!session || !session.strategy.lifecycle.placementOccupiesFlowSlots) { @@ -529,10 +510,7 @@ function activeFlowInsertionsFromPendingPlacement( } function containerContentRect(container: Container): Rect { - const prop = requireDragSnapshotBox(container); - const origin = contentBoxOrigin(prop); - const size = contentBoxSize(prop); - return { ...origin, ...size }; + return contentRect(requireDragSnapshotBox(container)); } function expandedChildHitRect( @@ -575,25 +553,12 @@ 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; } -export function virtualDimensions( - container: Container, - draggedItem: ItemBase, - ghost?: VirtualGhost, -): VirtualDimensions { - const snapshot = createLayoutSnapshot(container); - const insertions = [layoutInsertionFromGhost(snapshot.byItem, ghost)].filter( - (insertion): insertion is VirtualInsertion => !!insertion, - ); - return layoutVirtualDimensions(snapshot.root, { - filter: { excludeValues: new Set([draggedItem]) }, - insertions, - }); -} - export function virtualLayoutRecursive( container: Container, startX: number, @@ -605,7 +570,7 @@ export function virtualLayoutRecursive( dragCenterY: number, session: DragSession | null = null, debugEnabled = false, - layoutDiagnostics?: LayoutPlanDiagnostics, + layoutDiagnostics?: LayoutPlanDiagnostics, ): { candidates: FlowCandidate[]; endX: number; endY: number } { const snapshot = createLayoutSnapshot(container); const draggedBox = requireDragSnapshotBox(draggedItem); @@ -621,8 +586,9 @@ export function virtualLayoutRecursive( }; const excludeValues = session ? session.itemSet : new Set([draggedItem]); const layoutPlan = createLayoutResolutionPlan(snapshot.root, { - filter: { excludeValues }, + exclude: (node) => excludeValues.has(node.value), insertions: activeInsertions, + wrapTolerance: layoutWrapToleranceFor(container), diagnostics: layoutDiagnostics, }); return virtualLayoutRecursiveFromSnapshot( @@ -647,8 +613,8 @@ function virtualLayoutRecursiveFromSnapshot( containerSnapshot: ItemSnapshot, startX: number, startY: number, - layoutPlan: LayoutResolutionPlan, - draggedBox: DomProperty, + layoutPlan: LayoutResolutionPlan, + draggedBox: ElementBox, dragGhostW: number, dragGhostH: number, dragCenterX: number, @@ -680,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) { @@ -730,7 +701,7 @@ function virtualLayoutRecursiveFromSnapshot( index: number, fallbackPosition: { x: number; y: number }, ): FlowCandidate => { - const insertion: VirtualInsertion = { + const insertion: VirtualInsertion = { container: containerSnapshot, index, entry: { @@ -758,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, @@ -814,14 +781,13 @@ function virtualLayoutRecursiveFromSnapshot( } if (isContainer) { - const childOrigin = { - x: simulatedPosition.x + prop.border.left + prop.padding.left, - y: simulatedPosition.y + prop.border.top + prop.padding.top, - }; - const childContentSize = contentBoxSize(prop); + const childOffset = contentOffset(prop); + const childContent = contentRect(prop); const childContentRect = { - ...childOrigin, - ...childContentSize, + x: simulatedPosition.x + childOffset.x, + y: simulatedPosition.y + childOffset.y, + width: childContent.width, + height: childContent.height, }; const childHitRect = expandedChildHitRect( childContentRect, @@ -840,8 +806,8 @@ function virtualLayoutRecursiveFromSnapshot( const childResult = virtualLayoutRecursiveFromSnapshot( item, itemSnapshot, - childOrigin.x, - childOrigin.y, + childContentRect.x, + childContentRect.y, layoutPlan, draggedBox, dragGhostW, @@ -886,7 +852,7 @@ function collectDropCandidates( const dragGhostH = dragProp.height; const dragCenterX = item.dragPositionX + dragProp.width / 2; const dragCenterY = item.dragPositionY + dragProp.height / 2; - const layoutOrigin = contentBoxOrigin(rootProp); + const layoutOrigin = contentRect(rootProp); const { candidates: virtualCandidates } = virtualLayoutRecursive( root, @@ -951,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); @@ -1143,7 +1110,7 @@ function insertionMarkerNeighbor( item: snapshot.value, itemId: snapshot.itemId, itemMetadata: snapshot.metadata, - rect: frozenRect(snapshot.box), + rect: freezeRect(snapshot.box), }); } @@ -1151,9 +1118,9 @@ function insertionVisualLine( snapshot: ItemSnapshot | null, lineBySnapshot: ReadonlyMap< ItemSnapshot, - SnapshotVisualLine + VisualLine >, -): SnapshotVisualLine | null { +): VisualLine | null { if (!snapshot) return null; const line = lineBySnapshot.get(snapshot); if (!line) { @@ -1168,15 +1135,14 @@ function insertionGapSegment( next: ItemSnapshot | null, lineBySnapshot: ReadonlyMap< ItemSnapshot, - SnapshotVisualLine + VisualLine >, useVisualLineBand: boolean, ): InsertionGapSegment { const axes = flowAxesForDirection(containerSnapshot.direction); - const contentOrigin = contentBoxOrigin(containerSnapshot.box); - const contentSize = contentBoxSize(containerSnapshot.box); - const contentMainStart = contentOrigin[axes.main]; - const contentMainSize = contentSize[axes.mainSize]; + const content = contentRect(containerSnapshot.box); + const contentMainStart = content[axes.main]; + const contentMainSize = content[axes.mainSize]; const previousMainEnd = previous ? previous.box[axes.main] + previous.box[axes.mainSize] : null; @@ -1203,12 +1169,12 @@ function insertionGapSegment( const crossStart = useVisualLineBand && visualLine - ? contentOrigin[axes.cross] + visualLine.crossStart - : contentOrigin[axes.cross]; + ? content[axes.cross] + visualLine.crossStart + : content[axes.cross]; const crossSize = useVisualLineBand && visualLine ? visualLine.crossSize - : contentSize[axes.crossSize]; + : content[axes.crossSize]; if (axes.direction === "column") { return Object.freeze({ @@ -1292,16 +1258,16 @@ function collectInsertionCandidates( const rawChildren = containerSnapshot.children.filter( (child) => !child.value.isGhost, ); - const visualLines = inferSnapshotVisualLines( + const visualLines = inferVisualLines( containerSnapshot, flowAxesForDirection(containerSnapshot.direction), ); const lineBySnapshot = new Map< ItemSnapshot, - SnapshotVisualLine + VisualLine >(); for (const line of visualLines) { - for (const snapshot of line.snapshots) { + for (const snapshot of line.nodes) { lineBySnapshot.set(snapshot, line); } } @@ -1390,6 +1356,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 = inferVisualLines( + containerSnapshot, + flowAxesForDirection(containerSnapshot.direction), + ); + + const lineBySnapshot = new Map< + ItemSnapshot, + VisualLine + >(); + + for (const line of visualLines) { + for (const snapshot of line.nodes) { + 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 +1508,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 +1529,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 +1603,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 }); @@ -1641,7 +1750,7 @@ export function determineSwapDropTarget( const box = requireDragSnapshotBox(hovered); candidates.push({ target: { container, index }, - area: box.width * box.height, + area: rectArea(box), }); } @@ -1671,7 +1780,7 @@ export function debugDropTargetTree(node: Container, draggedItem: ItemBase) { ); for (const item of items) { - const prop = item.dragSnapshot?.box ?? item.currentDomProperty; + const prop = item.dragSnapshot?.box ?? item.box; if (!prop) continue; item.addDebugRect( diff --git a/assets/snapsort/src/callbacks.ts b/assets/snapsort/src/callbacks.ts index 3b67c42e..d071721f 100644 --- a/assets/snapsort/src/callbacks.ts +++ b/assets/snapsort/src/callbacks.ts @@ -2,7 +2,7 @@ import { distanceToRect, pointIntersectsRect, rectsIntersect, -} from "@snap-engine/core/collision"; +} from "@snap-engine/core/geometry"; import { DROP_REJECT_PRIORITY, type DropPriorityEvent } from "./events"; /** Prefer the destination whose frozen border box contains the pointer. */ diff --git a/assets/snapsort/src/container.ts b/assets/snapsort/src/container.ts index e7e63bfd..b906fdd3 100644 --- a/assets/snapsort/src/container.ts +++ b/assets/snapsort/src/container.ts @@ -4,8 +4,10 @@ import type { ContainerCallbacks, VisualGeometryInvalidationReason, } from "./events"; -import type { LayoutMainAxisAlign } from "./layout"; -import type { LayoutWrap } from "./snapshot"; +import type { + LayoutMainAxisAlign, + LayoutWrap, +} from "@snap-engine/core/layout"; import type { SortMode } from "./drag/drop-strategy"; import type { DragSession } from "./drag/session"; import { getDragSession } from "./drag/session-store"; @@ -105,7 +107,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..f8fd572d --- /dev/null +++ b/assets/snapsort/src/drag/direct-candidates.ts @@ -0,0 +1,517 @@ +import { + boundingRect, + contentOffset, + contentRect, + freezeRect, + projectRects, + type Rect, +} from "@snap-engine/core/geometry"; +import { + virtualEntrySizeFor, + createLayoutResolutionPlan, + type VirtualInsertion, + type LayoutResolutionPlan, +} from "@snap-engine/core/layout"; +import { + createDirectInsertionTarget, + layoutWrapToleranceFor, + 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 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 projectRectsIntoTarget( + session: DragSessionController, + target: Readonly, +): readonly Readonly[] { + const sourceRects = session.startMemberRects(); + const sourceGroup = boundingRect(sourceRects); + if (!sourceGroup) { + throw new Error( + "SnapSort: cannot calculate a direct candidate without projected items.", + ); + } + return Object.freeze( + projectRects(sourceRects, sourceGroup, target).map(freezeRect), + ); +} + +export function directCandidateGeometry( + session: DragSessionController, + candidate: DirectCandidate, +): DirectCandidateGeometry { + const sourceRects = session.startMemberRects(); + 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.", + ); + } + + const rootContent = contentRect(rootSnapshot.box); + let origin = { x: rootContent.x, y: rootContent.y }; + + 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.", + ); + } + + const offset = contentOffset(child.box); + origin = { x: childPosition.x + offset.x, y: childPosition.y + offset.y }; + } + + 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, { + exclude: (node) => session.itemSet.has(node.value), + insertions: insertionRun, + wrapTolerance: layoutWrapToleranceFor(target.container), + }); + + 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..3f4d2dd3 --- /dev/null +++ b/assets/snapsort/src/drag/direct-controller.ts @@ -0,0 +1,556 @@ +import { AnimationObject } from "@snap-engine/core/animation"; +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"; +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 requireBoundingRect(rects: readonly Readonly[]): Rect { + const bounds = boundingRect(rects); + if (!bounds) { + throw new Error("DirectDragController: visual geometry cannot be empty."); + } + return bounds; +} + +function freezeRects( + rects: readonly Readonly[], +): readonly Readonly[] { + return Object.freeze(rects.map(freezeRect)); +} + +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 = this.#session.startMemberRects(); + 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 + ? freezeRect(requireBoundingRect(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 lerpRect(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/flow-ghost.ts b/assets/snapsort/src/drag/flow-ghost.ts index 3e4db1eb..0e1f122b 100644 --- a/assets/snapsort/src/drag/flow-ghost.ts +++ b/assets/snapsort/src/drag/flow-ghost.ts @@ -1,3 +1,4 @@ +import type { Rect } from "@snap-engine/core/geometry"; import type { AnimationConfig } from "../container"; import type { Container } from "../container"; import type { Item } from "../item"; @@ -7,8 +8,8 @@ import { buildGhostSlotLocation, updateGhostState, } from "../event-builders"; -import type { DragLocation, GhostRect, GhostState } from "../events"; -import { virtualEntrySizeFor } from "../layout"; +import type { DragLocation, GhostState } from "../events"; +import { virtualEntrySizeFor } from "@snap-engine/core/layout"; import { assertCanFireGhostInsert, assertCanFireGhostMove, @@ -184,7 +185,7 @@ function anchorRectFor( session: DragSession, container: Container, member: Item, -): GhostRect { +): Rect { const box = session.dragBoxFor(member); const containerSnapshot = container.dragSnapshot; if (!containerSnapshot) { @@ -207,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) { @@ -287,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( @@ -430,8 +431,8 @@ function drop(session: DragSession): void { const root = session.root; const dropItemIds = items.map((member) => member.itemId); const dropRects = items.map(() => ({ - first: null as DOMRect | null, - last: null as DOMRect | null, + first: null as Rect | null, + last: null as Rect | null, element: null as HTMLElement | null, })); let dropAnimationConfig: AnimationConfig | null = null; 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..a243acc2 100644 --- a/assets/snapsort/src/drag/insertion-marker.ts +++ b/assets/snapsort/src/drag/insertion-marker.ts @@ -1,3 +1,4 @@ +import type { Rect } from "@snap-engine/core/geometry"; import type { AnimationConfig, Container } from "../container"; import type { ResolvedDropTarget } from "../algorithm"; import { @@ -103,7 +104,7 @@ async function syncInsertionPlacement( const ghostElement = ghostItem.element; if (!ghostElement) return; - let lastRect: DOMRect | null = null; + let lastRect: Rect | null = null; ghostItem.schedule( () => { lastRect = readVisualRect(ghostItem); @@ -150,8 +151,8 @@ function drop(session: DragSession): void { const dropItemIds = items.map((member) => member.itemId); const dropRects = items.map((member) => ({ item: member, - first: null as DOMRect | null, - last: null as DOMRect | null, + first: null as Rect | null, + last: null as Rect | null, element: null as HTMLElement | null, })); let dropAnimationConfig: AnimationConfig | null = null; @@ -261,6 +262,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 +325,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 +340,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/item-visual.ts b/assets/snapsort/src/drag/item-visual.ts index c3efc03a..6b511cce 100644 --- a/assets/snapsort/src/drag/item-visual.ts +++ b/assets/snapsort/src/drag/item-visual.ts @@ -1,3 +1,4 @@ +import type { Rect } from "@snap-engine/core/geometry"; import type { Container } from "../container"; import { buildGhostSlotLocation } from "../event-builders"; import type { Item } from "../item"; @@ -200,7 +201,7 @@ export function updateDragVisual(session: DragSession): void { /** @internal Capture each dragged member's visible origin for drop FLIP. */ export function captureDropOriginRects( session: DragSession, -): Array { +): Array { if (session.dragVisual === "preview") { return pointerPreviewMemberRects(session); } 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..37088a44 100644 --- a/assets/snapsort/src/drag/pointer-preview.ts +++ b/assets/snapsort/src/drag/pointer-preview.ts @@ -1,4 +1,10 @@ -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 { @@ -10,50 +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 { - const group = frozenGroupGeometry(session); - return { - x: group.x + session.pointer.x - session.start.x, - y: group.y + session.pointer.y - session.start.y, - width: group.width, - height: group.height, - }; +export function pointerPreviewRect(session: DragSession): Rect { + if (session.input.inputType === "direct") { + const directRect = session.input.visualGroupRect; + if (directRect) return freezeRect(directRect); + } + + 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. */ @@ -137,27 +123,20 @@ export async function removePointerPreview( */ export function pointerPreviewMemberRects( session: DragSession, -): Array { +): Array { const previewItem = session.ghostsByChannel.get("pointer"); const preview = previewItem ? readVisualRect(previewItem) : null; if (!preview) return session.items.map(() => null); - const group = 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); - if (!start) { - throw new Error( - `SnapSort: participant "${item.itemId}" has no captured visual start.`, - ); - } - return new DOMRect( - preview.left + (start.x - group.x) * scaleX, - preview.top + (start.y - group.y) * scaleY, - box.width * scaleX, - box.height * scaleY, - ); - }); + const directGroup = + session.input.inputType === "direct" ? session.input.visualGroupRect : null; + const group = directGroup ?? frozenGroupGeometry(session); + const startRects = session.startMemberRects(); + const memberRects = session.items.map( + (item, index) => + (session.input.inputType === "direct" + ? session.input.visualRectFor(item.itemId) + : null) ?? startRects[index], + ); + return projectRects(memberRects, group, preview); } 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..3cf8af82 100644 --- a/assets/snapsort/src/drag/session.ts +++ b/assets/snapsort/src/drag/session.ts @@ -1,10 +1,10 @@ import type { AnimationObject } from "@snap-engine/core/animation"; -import type { - DomProperty, - GestureHandoffControl, - dragStartProp, - dragProp, -} from "@snap-engine/core"; +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"; @@ -41,29 +41,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 +102,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 +124,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 +152,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 +216,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 +240,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 +253,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 +330,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 +344,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,108 +382,13 @@ 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]; } /** @internal Return the captured box for one current participant. */ - dragBoxFor(item: Item): DomProperty { + dragBoxFor(item: Item): ElementBox { if (!this.itemSet.has(item)) { throw new Error( "DragSession: drag geometry is only available for current participants.", @@ -478,6 +403,30 @@ export class DragSessionController { 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 @@ -490,11 +439,7 @@ export class DragSessionController { 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); @@ -513,15 +458,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 +473,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 +508,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 +529,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 +594,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 +647,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 +693,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 +793,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 +813,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 +833,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 +861,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..89f4a590 100644 --- a/assets/snapsort/src/drag/swap.ts +++ b/assets/snapsort/src/drag/swap.ts @@ -1,3 +1,4 @@ +import type { Rect } from "@snap-engine/core/geometry"; import type { AnimationConfig, Container } from "../container"; import type { Item } from "../item"; import type { ResolvedDropTarget } from "../algorithm"; @@ -42,16 +43,16 @@ function drop(session: DragSession): void { const root = session.root; const draggedItemId = item.itemId; const draggedAnimation: { - first: DOMRect | null; - last: DOMRect | null; + first: Rect | null; + last: Rect | null; element: HTMLElement | null; config: AnimationConfig | null; } = { first: null, last: null, element: null, config: null }; const displacedAnimation: { item: Item | null; itemId: string | null; - first: DOMRect | null; - last: DOMRect | null; + first: Rect | null; + last: Rect | null; element: HTMLElement | null; config: AnimationConfig | null; } = { @@ -69,14 +70,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 +119,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 +147,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 +167,7 @@ function drop(session: DragSession): void { aLocation.container && bContainer && targetItem && - targetItem !== item && + targetItem.itemId !== draggedItemId && session.dropEffect === "move" ) { const aContainer = aLocation.container; @@ -213,8 +253,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 +299,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..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), }); } @@ -101,7 +97,7 @@ export function buildGhostState( ghostItem: Item, ): GhostState { const base: GhostStateBase = { - session: session.handle, + session, original, originalItemId: original.itemId, originalMetadata: original.metadata, @@ -318,7 +314,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 +327,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 +342,7 @@ export function buildDropTargetChangeEvent( current: DragLocation | null, ): DropTargetChangeEvent { return { - session: session.handle, + session, ...buildItemRunEvent(session.items), previous, current, diff --git a/assets/snapsort/src/events.ts b/assets/snapsort/src/events.ts index 2275439c..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 { CollisionRect } from "@snap-engine/core/collision"; +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 = CollisionRect; - /** Complete world-space geometry for one pointer-hover hitbox. */ export type ItemHitbox = - | { shape: "rect"; rect: CollisionRect } - | { 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,9 +338,9 @@ 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: CollisionRect; + 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 214e3f6a..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, @@ -65,9 +60,17 @@ export { createRenderTree, reduceRenderTree, } from "./render-state"; -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/insertion-geometry.ts b/assets/snapsort/src/insertion-geometry.ts index af4ded43..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( @@ -108,7 +97,7 @@ export function toContainerLocalRect( ); } const containerBox = - container.dragSnapshot?.box ?? container.currentDomProperty; + container.dragSnapshot?.box ?? container.box; return Object.freeze({ x: @@ -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/internal/flip-animation.ts b/assets/snapsort/src/internal/flip-animation.ts index 65bdac68..1b9676d9 100644 --- a/assets/snapsort/src/internal/flip-animation.ts +++ b/assets/snapsort/src/internal/flip-animation.ts @@ -1,3 +1,4 @@ +import type { Rect } from "@snap-engine/core/geometry"; import { AnimationObject } from "@snap-engine/core/animation"; import type { AnimationConfig, Container } from "../container"; import { Item } from "../item"; @@ -20,9 +21,9 @@ interface TransformOffset { export interface ElementRectAnimationOptions { coordinateParent?: Item | null; - firstParent?: DOMRect | null; + firstParent?: Rect | null; firstParentItem?: Item | null; - lastParent?: DOMRect | null; + lastParent?: Rect | null; lastParentItem?: Item | null; subtractAncestorOffset?: boolean; initialOffset?: TransformOffset; @@ -162,8 +163,8 @@ function captureFlipLast( } function rectAnimationDelta( - first: DOMRect, - last: DOMRect, + first: Rect, + last: Rect, options: ElementRectAnimationOptions, ) { const { firstParent, lastParent } = options; @@ -198,8 +199,8 @@ function writeVisualAnimationTransform( export function playElementRectAnimation( item: Item, - first: DOMRect | null, - last: DOMRect | null, + first: Rect | null, + last: Rect | null, targetElement: HTMLElement | null, animationConfig: AnimationConfig | null, animationOwner: Item, @@ -418,8 +419,8 @@ function playFlipAnimations( export function playDropAnimation( item: Item, - first: DOMRect | null, - last: DOMRect | null, + first: Rect | null, + last: Rect | null, targetElement: HTMLElement | null, animationConfig: AnimationConfig | null, animationOwner: Item, diff --git a/assets/snapsort/src/internal/visual-rect.ts b/assets/snapsort/src/internal/visual-rect.ts index edcac346..7ddb99d1 100644 --- a/assets/snapsort/src/internal/visual-rect.ts +++ b/assets/snapsort/src/internal/visual-rect.ts @@ -1,8 +1,13 @@ import type { ElementObject } from "@snap-engine/core"; +import type { Rect } from "@snap-engine/core/geometry"; -/** @internal Immutable transformed rectangle in browser viewport coordinates. */ -export type VisualRectSnapshot = Readonly & { - readonly coordinateSpace: "screen"; +/** + * @internal Immutable transformed rectangle in world coordinates. Inside a + * Camera layer, world units are the CSS pixels a `translate` is written in, + * so deltas between these rects animate correctly at any zoom. + */ +export type VisualRectSnapshot = Rect & { + readonly coordinateSpace: "world"; }; /** @internal Per-read-stage cache for repeated Item and parent measurements. */ @@ -14,10 +19,8 @@ const stagedBeforeMutationRects = new WeakMap< >(); /** - * Read and immediately clone an ElementObject's transformed visual rectangle. - * Position and dimensions are both expressed in screen pixels. `readDom` - * retains the browser rectangle's screen origin and visual dimensions even - * when a Camera maps its world position. + * Read an ElementObject's transformed visual rectangle in world space: the + * element's current `readDom` box with its own transforms left applied. * @internal */ export function readVisualRect( @@ -30,20 +33,14 @@ export function readVisualRect( return null; } - const property = object.readDom({ unapplyTransform: false }); - const rectangle = new DOMRect( - property.screenX, - property.screenY, - property.width, - property.height, - ) as VisualRectSnapshot; - Object.defineProperty(rectangle, "coordinateSpace", { - configurable: false, - enumerable: true, - value: "screen", - writable: false, + const box = object.readDom({ unapplyTransform: false }); + const rectangle: VisualRectSnapshot = Object.freeze({ + x: box.x, + y: box.y, + width: box.width, + height: box.height, + coordinateSpace: "world", }); - Object.freeze(rectangle); cache?.set(object, rectangle); return rectangle; } diff --git a/assets/snapsort/src/item.ts b/assets/snapsort/src/item.ts index 5337ed03..c1d95d5c 100644 --- a/assets/snapsort/src/item.ts +++ b/assets/snapsort/src/item.ts @@ -1,6 +1,6 @@ +import type { Rect } from "@snap-engine/core/geometry"; import { ElementObject, - cloneDomProperty, type BaseObject, type Engine, type dragEndProp, @@ -8,15 +8,13 @@ import { type dragStartProp, } from "@snap-engine/core"; import type { AnimationConfig, Container } from "./container"; +import type { ItemId, ItemSnapshot, ItemMetadata } from "./snapshot"; import type { - ItemId, - ItemSnapshot, - ItemMetadata, LayoutDirection, LayoutMainAxisAlign, LayoutModel, LayoutWrap, -} from "./snapshot"; +} from "@snap-engine/core/layout"; import type { DragLocation, GhostState, @@ -40,9 +38,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 +380,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 +393,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 +413,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 ); } @@ -440,7 +454,7 @@ export class Item extends ElementObject { const color = Item.#colorForContainer(node.id); for (const child of node.children) { if (!(child instanceof Item)) continue; - const prop = child.dragSnapshot?.box ?? child.currentDomProperty; + const prop = child.dragSnapshot?.box ?? child.box; if (prop) { const cx = prop.x + prop.width / 2; const cy = prop.y + prop.height / 2; @@ -497,7 +511,7 @@ export class Item extends ElementObject { ) { this.readDom({ unapplyTransform: config.unapplyTransform }); if (config.saveWorldPosition ?? true) { - const prop = this.currentDomProperty; + const prop = this.box; this.worldTransform = { x: prop.x, y: prop.y }; } for (const child of this.children) { @@ -562,7 +576,7 @@ export class Item extends ElementObject { wrap: this.#snapshotWrap(), stretchItems: this.#snapshotStretchItems(), locked: this.#locked, - box: cloneDomProperty(this.currentDomProperty), + box: this.box, children: [], }; this.#dragSnapshot = snapshot; @@ -572,32 +586,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. * @@ -661,8 +649,8 @@ export class Item extends ElementObject { /** @internal */ playElementRectAnimation( item: Item, - first: DOMRect | null, - last: DOMRect | null, + first: Rect | null, + last: Rect | null, targetElement: HTMLElement | null, animationConfig: AnimationConfig | null, animationOwner: Item, @@ -684,8 +672,8 @@ export class Item extends ElementObject { * @internal */ playDropAnimation( - first: DOMRect | null, - last: DOMRect | null, + first: Rect | null, + last: Rect | null, targetElement: HTMLElement | null, animationConfig: AnimationConfig | null, animationOwner: Item, @@ -745,14 +733,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 +772,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 +788,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 +1096,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 +1148,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 +1162,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/Ghost.tsx b/assets/snapsort/src/react/Ghost.tsx index 1235102e..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, @@ -32,7 +33,7 @@ export const Ghost = forwardRef(function Ghost( ) { const elementRef = useRef(null); const original = - ghost.original.dragSnapshot?.box ?? ghost.original.currentDomProperty; + ghost.original.dragSnapshot?.box ?? ghost.original.box; const ghostItem = ghost.ghostItem; const rect = ghost.type === "insertion-marker" @@ -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/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..d2f25f6c 100644 --- a/assets/snapsort/src/snapshot.ts +++ b/assets/snapsort/src/snapshot.ts @@ -1,38 +1,18 @@ -import type { DomProperty } from "@snap-engine/core"; +import type { ElementBox } from "@snap-engine/core"; +import type { + LayoutDirection, + LayoutMainAxisAlign, + LayoutModel, + LayoutNode, + LayoutWrap, +} from "@snap-engine/core/layout"; 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 { +/** A frozen item's measured box and layout, captured at drag start. */ +export interface ItemSnapshot extends LayoutNode> { value: T; itemId: ItemId; metadata: ItemMetadata; @@ -40,16 +20,8 @@ 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; + box: ElementBox; children: ItemSnapshot[]; } diff --git a/assets/snapsort/src/svelte/Ghost.svelte b/assets/snapsort/src/svelte/Ghost.svelte index e18241c5..1630062f 100644 --- a/assets/snapsort/src/svelte/Ghost.svelte +++ b/assets/snapsort/src/svelte/Ghost.svelte @@ -1,4 +1,5 @@
{@render children()} diff --git a/assets/snapsort/tsconfig.json b/assets/snapsort/tsconfig.json index f5b1a8fc..0546e9b9 100644 --- a/assets/snapsort/tsconfig.json +++ b/assets/snapsort/tsconfig.json @@ -8,6 +8,8 @@ "@snap-engine/core/animation": ["../../src/animation.ts"], "@snap-engine/core/collision": ["../../src/collision.ts"], "@snap-engine/core/debug": ["../../src/debug.ts"], + "@snap-engine/core/geometry": ["../../src/geometry.ts"], + "@snap-engine/core/layout": ["../../src/layout.ts"], "@snap-engine/asset-base": ["../asset-base/src/index.ts"], "@snap-engine/asset-base/react": ["../asset-base/src/react/index.ts"], "@snap-engine/snapsort": ["./src/index.ts"], diff --git a/demo/react/vite.config.mjs b/demo/react/vite.config.mjs index 3c52b924..6c3f952a 100644 --- a/demo/react/vite.config.mjs +++ b/demo/react/vite.config.mjs @@ -14,6 +14,8 @@ export default defineConfig(({ command, mode }) => { "@snap-engine/core/animation": path.resolve(root, "src/animation.ts"), "@snap-engine/core/collision": path.resolve(root, "src/collision.ts"), "@snap-engine/core/debug": path.resolve(root, "src/debug.ts"), + "@snap-engine/core/geometry": path.resolve(root, "src/geometry.ts"), + "@snap-engine/core/layout": path.resolve(root, "src/layout.ts"), "@snap-engine/core": path.resolve(root, "src/index.ts"), "@snap-engine/asset-base/react": path.resolve( root, 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..93c2c580 100644 --- a/demo/svelte/src/DemoRouter.svelte +++ b/demo/svelte/src/DemoRouter.svelte @@ -12,6 +12,8 @@ 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 SnapSortCameraPage from "./demo/snapsort_camera/SnapSortCameraDemo.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 +108,18 @@ legacyDemoValues: ["snapsort_insertion"], usesDevNav: true, }, + { + label: "SnapSort Keyboard", + path: "/snapsort-keyboard", + legacyDemoValues: ["snapsort_keyboard"], + usesDevNav: true, + }, + { + label: "SnapSort Camera", + path: "/snapsort-camera", + legacyDemoValues: [], + usesDevNav: true, + }, { label: "SnapSort Website Core", path: "/snapsort-website-core", @@ -302,6 +316,10 @@ {:else if selectedPath === "/snapsort-insertion"} + {:else if selectedPath === "/snapsort-keyboard"} + + {:else if selectedPath === "/snapsort-camera"} + {:else if selectedPath === "/snapsort-website-core"} {:else if selectedPath === "/snapsort-file-explorer"} diff --git a/demo/svelte/src/demo/input/Mouse.svelte b/demo/svelte/src/demo/input/Mouse.svelte index 62a3d14e..75113c17 100644 --- a/demo/svelte/src/demo/input/Mouse.svelte +++ b/demo/svelte/src/demo/input/Mouse.svelte @@ -4,8 +4,8 @@ // let engine:Engine = getContext("engine"); - // let pointerPosition: any = $state({x: 0, y: 0, screenX: 0, screenY: 0, cameraX: 0, cameraY: 0}); - // let style = $derived(`top: ${pointerPosition.screenY}px; left: ${pointerPosition.screenX}px;`); + // let pointerPosition: any = $state({x: 0, y: 0, screen: {x: 0, y: 0}, camera: {x: 0, y: 0}}); + // let style = $derived(`top: ${pointerPosition.screen.y}px; left: ${pointerPosition.screen.x}px;`); // function updateMousePosition(prop: pointerMoveProp) { // pointerPosition = prop.position; @@ -28,10 +28,10 @@

World Coordinates: {pointerPosition.x}, {pointerPosition.y}

  • -

    Camera Coordinates: {pointerPosition.cameraX}, {pointerPosition.cameraY}

    +

    Camera Coordinates: {pointerPosition.camera.x}, {pointerPosition.camera.y}

  • -

    Screen Coordinates: {pointerPosition.screenX}, {pointerPosition.screenY}

    +

    Screen Coordinates: {pointerPosition.screen.x}, {pointerPosition.screen.y}

  • --> diff --git a/demo/svelte/src/demo/node_ui_resize/NodeUIResizeDemo.svelte b/demo/svelte/src/demo/node_ui_resize/NodeUIResizeDemo.svelte index e919178b..64f2ebd3 100644 --- a/demo/svelte/src/demo/node_ui_resize/NodeUIResizeDemo.svelte +++ b/demo/svelte/src/demo/node_ui_resize/NodeUIResizeDemo.svelte @@ -1,12 +1,17 @@ - +{#snippet graph()}
    @@ -17,6 +22,20 @@
    +{/snippet} + + + {#if withCamera} + + {@render graph()} + + {:else} + {@render graph()} + {/if} 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/demo/svelte/vite.config.mjs b/demo/svelte/vite.config.mjs index 668d8bb2..6fdc282e 100644 --- a/demo/svelte/vite.config.mjs +++ b/demo/svelte/vite.config.mjs @@ -15,6 +15,8 @@ export default defineConfig(({ command, mode }) => { "@snap-engine/core/animation": path.resolve(root, "src/animation.ts"), "@snap-engine/core/collision": path.resolve(root, "src/collision.ts"), "@snap-engine/core/debug": path.resolve(root, "src/debug.ts"), + "@snap-engine/core/geometry": path.resolve(root, "src/geometry.ts"), + "@snap-engine/core/layout": path.resolve(root, "src/layout.ts"), "@snap-engine/core": path.resolve(root, "src/index.ts"), // Asset packages (raw source) "@snap-engine/asset-base/svelte": path.resolve( diff --git a/demo/vanilla/snapengine/object-D-YQDlkD.js b/demo/vanilla/snapengine/object-D-YQDlkD.js deleted file mode 100644 index 0b4b5378..00000000 --- a/demo/vanilla/snapengine/object-D-YQDlkD.js +++ /dev/null @@ -1,1250 +0,0 @@ -var __defProp = Object.defineProperty; -var __typeError = (msg) => { - throw TypeError(msg); -}; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); -var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); -var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); -var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); -var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); -var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); -var _object, _global, _input, _dom, _owner, _parentTransform, _local, _cachedWorld, _cachedWorldEpoch, _ObjectTransform_instances, getCachedWorld_fn, worldToLocal_fn, markLocalChange_fn, _global2, _engine, _transform, _transformParent, _transformChildren, _CoreObject_instances, detachTransformParent_fn, validateNewTransformParent_fn, _id, _parent, _children, _colliderList, _animationList, _globalInput, _BaseObject_instances, validateNewParent_fn, detachFromParent_fn, attachChild_fn, setParent_fn, detachFromPublicParent_fn, _element, _style, _classList, _dataAttribute, _property, _domProperty, _resizeObserver, _mutationObserver, _state, _ElementObject_instances, assignElement_fn; -function getDomProperty(engine, dom) { - const rect = dom.getBoundingClientRect(); - const css = window.getComputedStyle(dom); - const margin_top = parseFloat(css.marginTop) || 0; - const margin_right = parseFloat(css.marginRight) || 0; - const margin_bottom = parseFloat(css.marginBottom) || 0; - const margin_left = parseFloat(css.marginLeft) || 0; - const padding_top = parseFloat(css.paddingTop) || 0; - const padding_right = parseFloat(css.paddingRight) || 0; - const padding_bottom = parseFloat(css.paddingBottom) || 0; - const padding_left = parseFloat(css.paddingLeft) || 0; - const border_top = parseFloat(css.borderTopWidth) || 0; - const border_right = parseFloat(css.borderRightWidth) || 0; - const border_bottom = parseFloat(css.borderBottomWidth) || 0; - const border_left = parseFloat(css.borderLeftWidth) || 0; - if (engine == null || engine.camera == null) { - return { - height: rect.height, - width: rect.width, - x: rect.left, - y: rect.top, - cameraX: rect.left, - cameraY: rect.top, - screenX: rect.left, - screenY: rect.top, - margin: { - top: margin_top, - right: margin_right, - bottom: margin_bottom, - left: margin_left - }, - padding: { - top: padding_top, - right: padding_right, - bottom: padding_bottom, - left: padding_left - }, - border: { - top: border_top, - right: border_right, - bottom: border_bottom, - left: border_left - } - }; - } - const [cameraX, cameraY] = engine.camera.getCameraFromScreen( - rect.left, - rect.top - ); - const [worldX, worldY] = engine.camera.getWorldFromCamera(cameraX, cameraY); - const [cameraWidth, cameraHeight] = engine.camera.getCameraDeltaFromWorldDelta(rect.width, rect.height); - const [worldWidth, worldHeight] = engine.camera.getWorldDeltaFromCameraDelta( - cameraWidth, - cameraHeight - ); - return { - height: worldHeight, - width: worldWidth, - x: worldX, - y: worldY, - cameraX, - cameraY, - screenX: rect.left, - screenY: rect.top, - margin: { - top: margin_top, - right: margin_right, - bottom: margin_bottom, - left: margin_left - }, - padding: { - top: padding_top, - right: padding_right, - bottom: padding_bottom, - left: padding_left - }, - border: { - top: border_top, - right: border_right, - bottom: border_bottom, - left: border_left - } - }; -} -function generateTransformString(transform) { - const string = `translate3d(${transform.x}px, ${transform.y}px, 0px) scale(${transform.scaleX}, ${transform.scaleY}) `; - return string; -} -function parseTransformString(transform) { - 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 setDomStyle(dom, style) { - Object.assign(dom.style, style); -} -function EventProxyFactory(object, dict, secondary = null) { - return new Proxy(dict, { - set: (target, prop, value) => { - if (value == null) { - target[prop] = null; - } else { - target[prop] = value.bind(object); - } - return true; - }, - get: (target, prop) => { - return (...args) => { - var _a, _b; - (_a = target[prop]) == null ? void 0 : _a.call(target, ...args); - (_b = secondary == null ? void 0 : secondary[prop]) == null ? void 0 : _b.call(secondary, ...args); - }; - } - }); -} -function cloneDomProperty(prop) { - return { - x: prop.x, - y: prop.y, - height: prop.height, - width: prop.width, - scaleX: prop.scaleX, - scaleY: prop.scaleY, - screenX: prop.screenX, - screenY: prop.screenY, - margin: { ...prop.margin }, - padding: { ...prop.padding }, - border: { ...prop.border } - }; -} -class EventCallback { - constructor(object) { - __privateAdd(this, _object); - __privateAdd(this, _global); - __privateAdd(this, _input); - __privateAdd(this, _dom); - __publicField(this, "global"); - __publicField(this, "input"); - __publicField(this, "dom"); - __privateSet(this, _object, object); - __privateSet(this, _global, { - pointerDown: null, - pointerMove: null, - pointerUp: null, - mouseWheel: null, - drag: null, - pinch: null, - dragStart: null, - dragEnd: null, - pinchStart: null, - pinchEnd: null - }); - this.global = new Proxy(__privateGet(this, _global), { - set: (_, prop, value) => { - var _a, _b; - if (value == null) { - (_a = __privateGet(this, _object).engine) == null ? void 0 : _a.input.unsubscribeGlobalCursorEvent( - prop, - __privateGet(this, _object).id - ); - } else { - (_b = __privateGet(this, _object).engine) == null ? void 0 : _b.input.subscribeGlobalCursorEvent( - prop, - __privateGet(this, _object).id, - value.bind(__privateGet(this, _object)), - __privateGet(this, _object).engine - ); - } - return true; - } - }); - __privateSet(this, _input, { - pointerDown: null, - pointerMove: null, - pointerUp: null, - mouseWheel: null, - dragStart: null, - drag: null, - dragEnd: null, - pinchStart: null, - pinch: null, - pinchEnd: null - }); - this.input = EventProxyFactory( - __privateGet(this, _object), - __privateGet(this, _input) - ); - __privateSet(this, _dom, { - onAssignDom: null, - onResize: null, - onAfterReadDom: null - }); - this.dom = EventProxyFactory(__privateGet(this, _object), __privateGet(this, _dom)); - } -} -_object = new WeakMap(); -_global = new WeakMap(); -_input = new WeakMap(); -_dom = new WeakMap(); -let transformEpoch = 0; -class ObjectTransform { - // world: TransformView; - // local: TransformView; - constructor(owner) { - __privateAdd(this, _ObjectTransform_instances); - __privateAdd(this, _owner); - __privateAdd(this, _parentTransform, null); - __privateAdd(this, _local, { - x: 0, - y: 0, - scaleX: 1, - scaleY: 1 - }); - __privateAdd(this, _cachedWorld, { - x: 0, - y: 0, - scaleX: 1, - scaleY: 1 - }); - __privateAdd(this, _cachedWorldEpoch, -1); - __privateSet(this, _owner, owner); - } - // get(space: TransformSpace, property: keyof TransformProperty): number { - // if (space === "local") { - // return this.#local[property]; - // } - // return this.#getCachedWorld()[property]; - // } - // set(space: TransformSpace, property: keyof TransformProperty, value: number) { - // const transform = { - // ...(space === "local" ? this.#local : this.#getCachedWorld()), - // [property]: value, - // }; - // if (space === "local") { - // this.setLocal(transform); - // this.#owner.notifyTransformChange(); - // } else { - // this.setWorld(transform); - // } - // } - getWorld() { - return __privateMethod(this, _ObjectTransform_instances, getCachedWorld_fn).call(this); - } - // #getWorld(property: keyof TransformProperty): number { - // return this.#getCachedWorld()[property]; - // } - setWorld(transform) { - __privateSet(this, _local, __privateMethod(this, _ObjectTransform_instances, worldToLocal_fn).call(this, transform)); - __privateMethod(this, _ObjectTransform_instances, markLocalChange_fn).call(this); - __privateGet(this, _owner).notifyTransformChange(); - } - // #setWorld(property: keyof TransformProperty, value: number) { - // const world = this.#getCachedWorld(); - // // Safe to modify the cache since it will be invalidated anyways - // world[property] = value; - // const local = this.#worldToLocal(world); - // this.#localX = local.x; - // this.#localY = local.y; - // this.#localScaleX = local.scaleX; - // this.#localScaleY = local.scaleY; - // this.#markLocalChange(); - // } - getLocal() { - return __privateGet(this, _local); - } - setLocal(transform) { - __privateSet(this, _local, transform); - __privateMethod(this, _ObjectTransform_instances, markLocalChange_fn).call(this); - } - setParentTransform(parent) { - __privateSet(this, _parentTransform, parent ? parent.transform ?? null : null); - __privateMethod(this, _ObjectTransform_instances, markLocalChange_fn).call(this); - } -} -_owner = new WeakMap(); -_parentTransform = new WeakMap(); -_local = new WeakMap(); -_cachedWorld = new WeakMap(); -_cachedWorldEpoch = new WeakMap(); -_ObjectTransform_instances = new WeakSet(); -getCachedWorld_fn = function() { - var _a; - if (__privateGet(this, _cachedWorldEpoch) === transformEpoch) { - return __privateGet(this, _cachedWorld); - } - const parentWorld = __privateGet(this, _parentTransform) ? __privateMethod(_a = __privateGet(this, _parentTransform), _ObjectTransform_instances, getCachedWorld_fn).call(_a) : null; - if (parentWorld) { - __privateGet(this, _cachedWorld).x = parentWorld.x + __privateGet(this, _local).x * parentWorld.scaleX; - __privateGet(this, _cachedWorld).y = parentWorld.y + __privateGet(this, _local).y * parentWorld.scaleY; - __privateGet(this, _cachedWorld).scaleX = parentWorld.scaleX * __privateGet(this, _local).scaleX; - __privateGet(this, _cachedWorld).scaleY = parentWorld.scaleY * __privateGet(this, _local).scaleY; - } else { - __privateGet(this, _cachedWorld).x = __privateGet(this, _local).x; - __privateGet(this, _cachedWorld).y = __privateGet(this, _local).y; - __privateGet(this, _cachedWorld).scaleX = __privateGet(this, _local).scaleX; - __privateGet(this, _cachedWorld).scaleY = __privateGet(this, _local).scaleY; - } - __privateSet(this, _cachedWorldEpoch, transformEpoch); - return __privateGet(this, _cachedWorld); -}; -worldToLocal_fn = function(transform) { - var _a; - const parentTransform = __privateGet(this, _parentTransform) ? __privateMethod(_a = __privateGet(this, _parentTransform), _ObjectTransform_instances, getCachedWorld_fn).call(_a) : null; - if (!parentTransform) { - return { ...transform }; - } - if (parentTransform.scaleX === 0 || parentTransform.scaleY === 0) { - throw new Error("Cannot set world transform under a zero-scale parent."); - } - return { - x: (transform.x - parentTransform.x) / parentTransform.scaleX, - y: (transform.y - parentTransform.y) / parentTransform.scaleY, - scaleX: transform.scaleX / parentTransform.scaleX, - scaleY: transform.scaleY / parentTransform.scaleY - }; -}; -markLocalChange_fn = function() { - transformEpoch++; -}; -class CoreObject { - // worldTransform: TransformView; - // localTransform: TransformView; - constructor(engine) { - __privateAdd(this, _CoreObject_instances); - __privateAdd(this, _global2); - __privateAdd(this, _engine); - __privateAdd(this, _transform); - __privateAdd(this, _transformParent, null); - __privateAdd(this, _transformChildren, []); - const global = engine.global; - if (!global) { - throw new Error("CoreObject requires an active Engine instance."); - } - __privateSet(this, _engine, engine); - __privateSet(this, _global2, global); - __privateSet(this, _transform, new ObjectTransform(this)); - } - get global() { - return __privateGet(this, _global2); - } - set global(global) { - __privateSet(this, _global2, global); - } - get engine() { - return __privateGet(this, _engine); - } - set engine(engine) { - __privateSet(this, _engine, engine); - } - get transformParent() { - return __privateGet(this, _transformParent); - } - get transformChildren() { - return __privateGet(this, _transformChildren); - } - get transform() { - return __privateGet(this, _transform); - } - get worldTransform() { - return __privateGet(this, _transform).getWorld(); - } - set worldTransform(transform) { - __privateGet(this, _transform).setWorld({ - x: transform.x ?? this.worldTransform.x, - y: transform.y ?? this.worldTransform.y, - scaleX: transform.scaleX ?? this.worldTransform.scaleX, - scaleY: transform.scaleY ?? this.worldTransform.scaleY - }); - } - get localTransform() { - return __privateGet(this, _transform).getLocal(); - } - set localTransform(transform) { - __privateGet(this, _transform).setLocal({ - x: transform.x ?? this.localTransform.x, - y: transform.y ?? this.localTransform.y, - scaleX: transform.scaleX ?? this.localTransform.scaleX, - scaleY: transform.scaleY ?? this.localTransform.scaleY - }); - } - // TODO: Factor in camera scaling - get cameraPosition() { - var _a; - const world = this.worldTransform; - return ((_a = this.engine.camera) == null ? void 0 : _a.getCameraFromWorld(world.x, world.y)) ?? [0, 0]; - } - set cameraPosition(position) { - var _a, _b; - const world = ((_b = (_a = this.engine) == null ? void 0 : _a.camera) == null ? void 0 : _b.getWorldFromCamera(...position)) ?? [ - 0, - 0 - ]; - this.worldTransform = { x: world[0], y: world[1] }; - } - get screenPosition() { - var _a; - return ((_a = this.engine.camera) == null ? void 0 : _a.getScreenFromCamera(...this.cameraPosition)) ?? [0, 0]; - } - set screenPosition(position) { - var _a, _b; - this.cameraPosition = ((_b = (_a = this.engine) == null ? void 0 : _a.camera) == null ? void 0 : _b.getCameraFromScreen( - ...position - )) ?? [0, 0]; - } - notifyTransformChange() { - this.onTransformChange(); - } - onTransformChange() { - } - getWorldTransform() { - return __privateGet(this, _transform).getWorld(); - } - getTransformEpoch() { - return transformEpoch; - } - setWorldTransform(transform) { - __privateGet(this, _transform).setWorld(transform); - } - setTransformParent(parent, preserveWorld) { - __privateMethod(this, _CoreObject_instances, validateNewTransformParent_fn).call(this, parent); - if (parent === __privateGet(this, _transformParent)) { - return; - } - const worldTransform = preserveWorld ? __privateGet(this, _transform).getWorld() : null; - __privateMethod(this, _CoreObject_instances, detachTransformParent_fn).call(this, false); - __privateSet(this, _transformParent, parent); - __privateGet(this, _transform).setParentTransform(parent); - if (parent) { - __privateGet(parent, _transformChildren).push(this); - } - if (worldTransform) { - __privateGet(this, _transform).setWorld(worldTransform); - } else { - this.notifyTransformChange(); - } - } - detachTransformParent(preserveWorld) { - __privateMethod(this, _CoreObject_instances, detachTransformParent_fn).call(this, preserveWorld); - } -} -_global2 = new WeakMap(); -_engine = new WeakMap(); -_transform = new WeakMap(); -_transformParent = new WeakMap(); -_transformChildren = new WeakMap(); -_CoreObject_instances = new WeakSet(); -detachTransformParent_fn = function(preserveWorld) { - if (!__privateGet(this, _transformParent)) { - return; - } - const worldTransform = preserveWorld ? __privateGet(this, _transform).getWorld() : null; - const parent = __privateGet(this, _transformParent); - __privateSet(parent, _transformChildren, __privateGet(parent, _transformChildren).filter( - (child) => child !== this - )); - __privateSet(this, _transformParent, null); - __privateGet(this, _transform).setParentTransform(null); - if (worldTransform) { - __privateGet(this, _transform).setWorld(worldTransform); - } else { - this.notifyTransformChange(); - } -}; -validateNewTransformParent_fn = function(parent) { - if (parent === null) { - return; - } - if (parent === this) { - throw new Error("An object cannot be parented to itself."); - } - let ancestor = parent; - while (ancestor) { - if (ancestor === this) { - throw new Error("An object cannot be parented to one of its children."); - } - ancestor = ancestor.transformParent; - } -}; -class FrameTask { - constructor(object, callback, id = null) { - __publicField(this, "id"); - __publicField(this, "object"); - __publicField(this, "callback"); - this.id = id ?? object.global.createId(); - this.object = object; - this.callback = callback ? [callback.bind(object)] : null; - } - addCallback(callback) { - if (this.callback) { - this.callback.push(callback.bind(this.object)); - } else { - this.callback = [callback.bind(this.object)]; - } - } - cancel() { - this.callback = null; - } -} -const animationOwnerMap = /* @__PURE__ */ new WeakMap(); -class BaseObject extends CoreObject { - constructor(engine, parent = null) { - var _a; - super(engine); - __privateAdd(this, _BaseObject_instances); - __privateAdd(this, _id); - __privateAdd(this, _parent, null); - __privateAdd(this, _children, []); - __privateAdd(this, _colliderList, []); - __privateAdd(this, _animationList, []); - __privateAdd(this, _globalInput); - __publicField(this, "event"); - __publicField(this, "globalInput"); - __publicField(this, "isDeleteRequested", false); - __privateSet(this, _id, this.global.createId()); - this.global.registerObject(this); - __privateSet(this, _colliderList, []); - this.event = new EventCallback(this); - __privateSet(this, _globalInput, { - pointerDown: null, - pointerMove: null, - pointerUp: null, - mouseWheel: null, - dragStart: null, - drag: null, - dragEnd: null, - pinchStart: null, - pinch: null, - pinchEnd: null - }); - this.globalInput = new Proxy(__privateGet(this, _globalInput), { - set: (_, prop, value) => { - var _a2, _b; - if (value == null) { - (_a2 = this.engine) == null ? void 0 : _a2.input.unsubscribeGlobalCursorEvent(prop, this.id); - } else { - (_b = this.engine) == null ? void 0 : _b.input.subscribeGlobalCursorEvent( - prop, - this.id, - value.bind(this), - this.engine - ); - } - return true; - } - }); - if (parent) { - __privateMethod(_a = parent, _BaseObject_instances, attachChild_fn).call(_a, this, false); - } - } - get id() { - return __privateGet(this, _id); - } - set id(id) { - __privateSet(this, _id, id); - } - get parent() { - return __privateGet(this, _parent); - } - set parent(parent) { - __privateMethod(this, _BaseObject_instances, setParent_fn).call(this, parent, true); - } - get children() { - return __privateGet(this, _children); - } - set children(children) { - __privateSet(this, _children, children); - } - get colliderList() { - return __privateGet(this, _colliderList); - } - set colliderList(colliderList) { - __privateSet(this, _colliderList, colliderList); - } - get animationList() { - return __privateGet(this, _animationList); - } - set animationList(animationList) { - __privateSet(this, _animationList, animationList); - } - get animation() { - if (this.animationList.length === 0) { - return null; - } - return this.animationList[this.animationList.length - 1]; - } - destroy() { - this.isDeleteRequested = true; - for (const collider of [...this.colliderList]) { - collider.destroy(); - } - this.colliderList = []; - this.cancelAnimations(); - for (const queue of Object.values(this.global.queue)) { - queue.delete(this.id); - } - if (__privateGet(this, _parent)) { - __privateGet(this, _parent).removeChild(this); - } - this.global.unregisterObject(this); - } - appendChild(child) { - __privateMethod(this, _BaseObject_instances, attachChild_fn).call(this, child, true); - } - removeChild(child) { - var _a; - if (__privateGet(child, _parent) !== this) { - return; - } - __privateMethod(_a = child, _BaseObject_instances, detachFromParent_fn).call(_a, true); - } - /** - * Queues an update callback to be executed during a specific stage of the render pipeline. - * @param callback - Optional callback function to execute during the stage - * @param config - Render stage and optional queue identifier - * @returns The queue entry object - */ - schedule(callback, config) { - const request = new FrameTask(this, callback, config.queueId); - const queue = this.global.queue[config.stage]; - if (!queue.get(this.id)) { - queue.set(this.id, /* @__PURE__ */ new Map()); - } - queue.get(this.id).set(request.id, request); - return request; - } - requestDestroy() { - return this.schedule(() => this.destroyDom(), { - stage: "WRITE_2", - queueId: "destroy" - }); - } - /** - * Write all object properties to the DOM. - */ - writeDom() { - } - /** - * Write the CSS transform property of the object. - * Unlike many other properties, the transform property does not trigger a DOM reflow and is thus more performant. - * Whenever possible, use this method to write the transform property. - */ - writeTransform() { - } - /** - * Destroy the DOM element of the object. - */ - destroyDom() { - } - addCollider(collider) { - var _a; - if (collider.parent !== this) { - collider.parent = this; - } - if (!this.colliderList.includes(collider)) { - this.colliderList.push(collider); - } - if (!this.engine) { - return; - } - (_a = this.engine.collisionEngine) == null ? void 0 : _a.addObject(collider); - } - addAnimation(animation, options = {}) { - var _a, _b; - (_a = this.engine) == null ? void 0 : _a.enableAnimationEngine(); - const replaceExisting = options.replaceExisting ?? true; - if (replaceExisting) { - this.cancelAnimations(); - } - this.animationList.push(animation); - animationOwnerMap.set(animation, this); - (_b = this.engine) == null ? void 0 : _b.animationList.push(animation); - return animation; - } - cancelAnimations() { - for (const existingAnimation of [...this.animationList]) { - existingAnimation.requestDelete = true; - existingAnimation.cancel(); - this.removeAnimationReference(existingAnimation); - } - } - removeAnimationReference(animation) { - this.animationList = this.animationList.filter( - (anim) => anim !== animation - ); - animationOwnerMap.delete(animation); - } - /** - * Convenience method to create and add a sequence of animations to this object. - * - * @param animations - Array of AnimationInterface objects to play as a sequence - * @returns The created sequence animation - */ - async animateSequence(animations) { - const { SequenceObject } = await import("./animation.mjs"); - const sequence = new SequenceObject(); - for (const animation of animations) { - sequence.add(animation); - } - return this.addAnimation(sequence, { replaceExisting: true }); - } - getCurrentStats() { - return { - timestamp: Date.now() - }; - } - addDebugPoint(x, y, color = "red", persistent = false, id = "", tag) { - if (!this.engine) return; - this.engine.debugMarkerList[`${this.id}-${id}`] = { - objectId: this.id, - type: "point", - color, - x, - y, - persistent, - id: `${this.id}-${id}`, - tag - }; - } - addDebugRect(x, y, width, height, color = "red", persistent = false, id = "", filled = true, lineWidth = 1, tag) { - if (!this.engine) return; - this.engine.debugMarkerList[`${this.id}-${id}`] = { - objectId: this.id, - type: "rect", - color, - x, - y, - width, - height, - persistent, - id: `${this.id}-${id}`, - filled, - lineWidth, - tag - }; - } - addDebugLine(x1, y1, x2, y2, color = "red", persistent = false, id = "", lineWidth = 2, tag, arrowEnd, arrowStart, arrowSize) { - if (!this.engine) return; - this.engine.debugMarkerList[`${this.id}-${id}`] = { - objectId: this.id, - type: "line", - color, - x: x1, - y: y1, - x2, - y2, - persistent, - id: `${this.id}-${id}`, - lineWidth, - tag, - arrowEnd, - arrowStart, - arrowSize - }; - } - addDebugCircle(x, y, radius, color = "red", persistent = false, id = "", tag) { - if (!this.engine) return; - this.engine.debugMarkerList[`${this.id}-${id}`] = { - objectId: this.id, - type: "circle", - color, - x, - y, - radius, - persistent, - id: `${this.id}-${id}`, - tag - }; - } - addDebugText(x, y, text, color = "red", persistent = false, id = "", tag) { - if (!this.engine) return; - this.engine.debugMarkerList[`${this.id}-${id}`] = { - objectId: this.id, - x, - y, - type: "text", - color, - text, - persistent, - id: `${this.id}-${id}`, - tag - }; - } - clearDebugMarker(id) { - if (!this.engine) return; - delete this.engine.debugMarkerList[`${this.id}-${id}`]; - } - clearAllDebugMarkers() { - if (!this.engine) return; - for (const marker of Object.values(this.engine.debugMarkerList)) { - if (marker.objectId == this.id) { - delete this.engine.debugMarkerList[marker.id]; - } - } - } -} -_id = new WeakMap(); -_parent = new WeakMap(); -_children = new WeakMap(); -_colliderList = new WeakMap(); -_animationList = new WeakMap(); -_globalInput = new WeakMap(); -_BaseObject_instances = new WeakSet(); -validateNewParent_fn = function(parent) { - if (parent === null) { - return; - } - if (parent === this) { - throw new Error("An object cannot be parented to itself."); - } - let ancestor = parent; - while (ancestor) { - if (ancestor === this) { - throw new Error("An object cannot be parented to one of its children."); - } - ancestor = ancestor.parent; - } -}; -detachFromParent_fn = function(preserveWorld) { - if (!__privateGet(this, _parent)) { - return; - } - const parent = __privateGet(this, _parent); - __privateSet(parent, _children, __privateGet(parent, _children).filter((child) => child !== this)); - __privateSet(this, _parent, null); - this.setTransformParent(null, preserveWorld); -}; -attachChild_fn = function(child, preserveWorld) { - var _a, _b; - __privateMethod(_a = child, _BaseObject_instances, validateNewParent_fn).call(_a, this); - if (__privateGet(child, _parent) === this) { - return; - } - __privateMethod(_b = child, _BaseObject_instances, detachFromPublicParent_fn).call(_b); - __privateSet(child, _parent, this); - __privateGet(this, _children).push(child); - child.setTransformParent(this, preserveWorld); -}; -setParent_fn = function(parent, preserveWorld) { - var _a; - __privateMethod(this, _BaseObject_instances, validateNewParent_fn).call(this, parent); - if (parent === __privateGet(this, _parent)) { - return; - } - if (parent) { - __privateMethod(_a = parent, _BaseObject_instances, attachChild_fn).call(_a, this, preserveWorld); - } else { - __privateMethod(this, _BaseObject_instances, detachFromParent_fn).call(this, preserveWorld); - } -}; -detachFromPublicParent_fn = function() { - if (!__privateGet(this, _parent)) { - return; - } - const parent = __privateGet(this, _parent); - __privateSet(parent, _children, __privateGet(parent, _children).filter((child) => child !== this)); - __privateSet(this, _parent, null); -}; -function detachAnimationFromOwner(animation) { - const owner = animationOwnerMap.get(animation); - if (!owner) { - return; - } - owner.removeAnimationReference(animation); -} -function createDomProperty() { - return { - x: 0, - y: 0, - height: 0, - width: 0, - scaleX: 1, - scaleY: 1, - screenX: 0, - screenY: 0, - margin: { - top: 0, - right: 0, - bottom: 0, - left: 0 - }, - padding: { - top: 0, - right: 0, - bottom: 0, - left: 0 - }, - border: { - top: 0, - right: 0, - bottom: 0, - left: 0 - } - }; -} -function copyDomPropertyValue(target, source) { - Object.assign(target, { - ...source, - margin: { ...source.margin }, - padding: { ...source.padding }, - border: { ...source.border } - }); -} -const _ElementObject = class _ElementObject extends BaseObject { - constructor(engine, parent = null) { - super(engine, parent); - __privateAdd(this, _ElementObject_instances); - __privateAdd(this, _element, null); - __privateAdd(this, _style, {}); - __privateAdd(this, _classList, []); - __privateAdd(this, _dataAttribute, {}); - __privateAdd(this, _property); - __privateAdd(this, _domProperty); - __privateAdd(this, _resizeObserver, null); - __privateAdd(this, _mutationObserver, null); - __privateAdd(this, _state, {}); - __publicField(this, "state"); - __publicField(this, "transformMode"); - __publicField(this, "transformOrigin"); - __privateSet(this, _property, createDomProperty()); - __privateSet(this, _domProperty, []); - for (let i = 0; i < 3; i++) { - __privateGet(this, _domProperty).push(createDomProperty()); - } - this.transformMode = "direct"; - this.transformOrigin = null; - this.state = new Proxy(__privateGet(this, _state), { - set: (target, prop, value) => { - target[prop] = value; - return true; - } - }); - } - get currentDomProperty() { - return __privateGet(this, _property); - } - get style() { - return __privateGet(this, _style); - } - set style(style) { - __privateSet(this, _style, Object.assign(__privateGet(this, _style), style)); - } - get classList() { - return __privateGet(this, _classList); - } - set classList(classList) { - __privateSet(this, _classList, classList); - } - get dataAttribute() { - return __privateGet(this, _dataAttribute); - } - set dataAttribute(dataAttribute) { - __privateSet(this, _dataAttribute, Object.assign(__privateGet(this, _dataAttribute), dataAttribute)); - } - get element() { - return __privateGet(this, _element); - } - set element(element) { - var _a, _b; - if (!element) { - return; - } - __privateMethod(this, _ElementObject_instances, assignElement_fn).call(this, element); - (_b = (_a = this.event.dom).onAssignDom) == null ? void 0 : _b.call(_a); - } - destroy() { - this.destroyDom(); - super.destroy(); - } - getDomProperty(stage = null) { - let index = 0; - if (stage == "READ_1") { - index = 0; - } else if (stage == "READ_2") { - index = 1; - } else if (stage == "READ_3" || stage == null) { - index = 2; - } else { - throw new Error(`Invalid stage: ${stage}`); - } - return __privateGet(this, _domProperty)[index]; - } - copyDomProperty(fromStage, toStage) { - copyDomPropertyValue( - this.getDomProperty(toStage), - this.getDomProperty(fromStage) - ); - } - /** - * Save the DOM property to the transform property. - * Currently only saves the x and y properties. - * This function assumes that the element position has already been read from the DOM. - */ - saveDomProperety(stage = null) { - let currentStage = stage ?? this.global.currentStage; - currentStage = currentStage == "IDLE" ? "READ_2" : currentStage; - const property = this.getDomProperty(currentStage); - this.worldTransform = { x: property.x, y: property.y }; - } - readDom(config = {}, stage = null) { - const currentStage = stage ?? this.global.currentStage; - if (!["READ_1", "READ_2", "READ_3", "IDLE"].includes(currentStage)) { - throw new Error( - `Reading DOM during ${currentStage} is prohibited. Only READ_1, READ_2, READ_3, and IDLE are allowed.` - ); - } - if (currentStage === "IDLE") { - console.warn(`Reading DOM during IDLE stage may cause layout thrashing`); - } - if (!__privateGet(this, _element)) { - throw new Error("Element is not set"); - } - const property = getDomProperty(this.engine, __privateGet(this, _element)); - const transform = __privateGet(this, _element).style.transform; - let transformApplied = { - x: 0, - y: 0, - scaleX: 1, - scaleY: 1 - }; - if (transform && transform != "none" && config.unapplyTransform) { - transformApplied = parseTransformString(transform); - } - __privateGet(this, _property).height = property.height / transformApplied.scaleY; - __privateGet(this, _property).width = property.width / transformApplied.scaleX; - __privateGet(this, _property).x = property.x - transformApplied.x; - __privateGet(this, _property).y = property.y - transformApplied.y; - __privateGet(this, _property).screenX = property.screenX; - __privateGet(this, _property).screenY = property.screenY; - __privateGet(this, _property).margin = property.margin; - __privateGet(this, _property).padding = property.padding; - __privateGet(this, _property).border = property.border; - if (["READ_1", "READ_2", "READ_3"].includes(currentStage)) { - copyDomPropertyValue( - this.getDomProperty(currentStage), - __privateGet(this, _property) - ); - } - return __privateGet(this, _property); - } - readDomRecursive(config = {}) { - const stage = this.global.currentStage; - if (!["READ_1", "READ_2", "READ_3"].includes(stage)) { - throw new Error(`Invalid stage: ${stage}`); - } - this.readDom(config); - if (config.saveDomProperety || config.saveWorldPosition) { - this.saveDomProperety(stage); - } - for (const child of this.children) { - if (child instanceof _ElementObject) { - child.readDomRecursive(config); - } - } - } - requestFLIP(writeCallback, transformCallback) { - this.schedule( - () => { - this.readDom({ unapplyTransform: false }); - this.saveDomProperety("READ_1"); - }, - { stage: "READ_1", queueId: "READ_1" } - ); - this.schedule( - async () => { - this.writeDom(); - await writeCallback(); - }, - { stage: "WRITE_1", queueId: "WRITE_1" } - ); - this.schedule( - () => { - this.readDom({ unapplyTransform: false }); - this.saveDomProperety("READ_2"); - }, - { stage: "READ_2", queueId: "READ_2" } - ); - this.schedule(async () => await transformCallback(), { - stage: "WRITE_2", - queueId: "WRITE_2" - }); - } - writeDom() { - const currentStage = this.global.currentStage; - if (!["WRITE_1", "WRITE_2", "WRITE_3", "IDLE"].includes(currentStage)) { - throw new Error( - `Writing DOM during ${currentStage} is prohibited. Only WRITE_1, WRITE_2, WRITE_3, and IDLE are allowed.` - ); - } - if (!__privateGet(this, _element)) { - throw new Error("Element is not set"); - } - setDomStyle(__privateGet(this, _element), __privateGet(this, _style)); - if (__privateGet(this, _classList).length > 0) { - const nextClassList = new Set(__privateGet(this, _classList)); - __privateGet(this, _element).classList.forEach((className) => { - if (!nextClassList.has(className)) { - __privateGet(this, _element).classList.remove(className); - } - }); - for (const className of nextClassList) { - __privateGet(this, _element).classList.add(className); - } - } - for (const [key, value] of Object.entries(__privateGet(this, _dataAttribute))) { - __privateGet(this, _element).setAttribute(`data-${key}`, value); - } - __privateGet(this, _element).setAttribute("data-engine-id", this.id); - super.writeDom(); - } - writeTransform() { - const currentStage = this.global.currentStage; - if (!["WRITE_1", "WRITE_2", "WRITE_3", "IDLE"].includes(currentStage)) { - throw new Error( - `Writing transform during ${currentStage} is prohibited. Only WRITE_1, WRITE_2, WRITE_3, and IDLE are allowed.` - ); - } - if (!__privateGet(this, _element)) { - throw new Error("Element is not set"); - } - let transformStyle = { - transform: "" - }; - if (this.transformMode == "direct") { - transformStyle = { - transform: generateTransformString({ - x: this.worldTransform.x, - y: this.worldTransform.y, - scaleX: this.worldTransform.scaleX, - scaleY: this.worldTransform.scaleY - }) - }; - } else if (this.transformMode == "relative") { - const [newX, newY] = [ - this.worldTransform.x - __privateGet(this, _property).x, - this.worldTransform.y - __privateGet(this, _property).y - ]; - transformStyle = { - transform: generateTransformString({ - x: newX, - y: newY, - scaleX: this.worldTransform.scaleX, - scaleY: this.worldTransform.scaleY - }) - }; - } else if (this.transformMode == "origin") { - const origin = this.transformOrigin ?? this.parent; - if (!origin) { - const [newX, newY] = [ - this.worldTransform.x - __privateGet(this, _property).x, - this.worldTransform.y - __privateGet(this, _property).y - ]; - transformStyle = { - transform: generateTransformString({ - x: newX, - y: newY, - scaleX: this.worldTransform.scaleX, - scaleY: this.worldTransform.scaleY - }) - }; - } else { - if (origin.worldTransform.scaleX === 0 || origin.worldTransform.scaleY === 0) { - throw new Error( - "Cannot write origin transform relative to a zero-scale origin." - ); - } - transformStyle = { - transform: generateTransformString({ - x: (this.worldTransform.x - origin.worldTransform.x) / origin.worldTransform.scaleX, - y: (this.worldTransform.y - origin.worldTransform.y) / origin.worldTransform.scaleY, - scaleX: this.worldTransform.scaleX / origin.worldTransform.scaleX, - scaleY: this.worldTransform.scaleY / origin.worldTransform.scaleY - }) - }; - } - } else if (this.transformMode == "none") { - transformStyle = { - transform: "" - }; - } - if (__privateGet(this, _style)["transform"] != void 0 && __privateGet(this, _style)["transform"] != "" && transformStyle["transform"] != "") { - transformStyle["transform"] = __privateGet(this, _style)["transform"]; - } - setDomStyle(__privateGet(this, _element), { ...__privateGet(this, _style), ...transformStyle }); - super.writeTransform(); - } - destroyDom() { - var _a, _b, _c; - (_a = __privateGet(this, _resizeObserver)) == null ? void 0 : _a.disconnect(); - (_b = __privateGet(this, _mutationObserver)) == null ? void 0 : _b.disconnect(); - if (__privateGet(this, _element)) { - (_c = this.engine) == null ? void 0 : _c.input.unregisterObjectElement(this, __privateGet(this, _element)); - __privateGet(this, _element).remove(); - } - __privateSet(this, _element, null); - super.destroyDom(); - } -}; -_element = new WeakMap(); -_style = new WeakMap(); -_classList = new WeakMap(); -_dataAttribute = new WeakMap(); -_property = new WeakMap(); -_domProperty = new WeakMap(); -_resizeObserver = new WeakMap(); -_mutationObserver = new WeakMap(); -_state = new WeakMap(); -_ElementObject_instances = new WeakSet(); -assignElement_fn = function(element) { - if (__privateGet(this, _element)) { - this.destroyDom(); - } - __privateSet(this, _element, element); - this.engine.input.registerObjectElement(this, element); - __privateSet(this, _resizeObserver, new ResizeObserver(() => { - var _a, _b; - (_b = (_a = this.event.dom).onResize) == null ? void 0 : _b.call(_a); - })); - __privateGet(this, _resizeObserver).observe(element); - __privateSet(this, _mutationObserver, new MutationObserver(() => { - var _a, _b; - (_b = (_a = this.event.dom).onResize) == null ? void 0 : _b.call(_a); - })); -}; -let ElementObject = _ElementObject; -export { - BaseObject as B, - CoreObject as C, - ElementObject as E, - ObjectTransform as O, - EventProxyFactory as a, - cloneDomProperty as c, - detachAnimationFromOwner as d, - getDomProperty as g -}; diff --git a/demo/vanilla/vite.config.mjs b/demo/vanilla/vite.config.mjs index 21d1eb2a..08afbbb0 100644 --- a/demo/vanilla/vite.config.mjs +++ b/demo/vanilla/vite.config.mjs @@ -10,6 +10,8 @@ export default defineConfig(({ command, mode }) => { "@snap-engine/core/animation": path.resolve(root, "src/animation.ts"), "@snap-engine/core/collision": path.resolve(root, "src/collision.ts"), "@snap-engine/core/debug": path.resolve(root, "src/debug.ts"), + "@snap-engine/core/geometry": path.resolve(root, "src/geometry.ts"), + "@snap-engine/core/layout": path.resolve(root, "src/layout.ts"), "@snap-engine/core": path.resolve(root, "src/index.ts"), "@snap-engine/snapsort": path.resolve( root, diff --git a/docs/snapengine/reference/camera.mdx b/docs/snapengine/reference/camera.mdx index a98f03ce..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 @@ -66,6 +79,28 @@ const [cameraWidth, cameraHeight] = camera.getCameraDeltaFromWorldDelta(10, 10); const [worldDeltaX, worldDeltaY] = camera.getWorldDeltaFromCameraDelta(50, 30); ``` +The root package also exports helpers that resolve a point or rectangle in +every space at once. Each accepts `null` for "no camera", in which case all +spaces coincide. + +```ts +import { + pointerPositionFromScreen, + pointerPositionFromWorld, + worldRectFromScreenRect, +} from "@snap-engine/core"; + +const pointer = pointerPositionFromScreen(engine.camera, event.clientX, event.clientY); +pointer.x; // world +pointer.camera.x; // camera +pointer.screen.x; // viewport + +const worldRect = worldRectFromScreenRect( + engine.camera, + element.getBoundingClientRect(), +); +``` + ## CameraControl Setup ```html @@ -111,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 @@ -153,3 +193,6 @@ pan, keeping dragged content anchored while the pointer is stationary. | `camera.handlePanEnd()` | Ends tracked pan movement. | | `new CameraControl(engine, config?)` | Creates interactive pan/zoom controls. | | `cameraControl.zoomBy(deltaZoom, originX?, originY?)` | Programmatically changes zoom. | +| `pointerPositionFromScreen(camera, x, y)` | Resolves a viewport point as a `PointerPosition`. | +| `pointerPositionFromWorld(camera, x, y)` | Resolves a world point as a `PointerPosition`. | +| `worldRectFromScreenRect(camera, rect)` | Maps a viewport rectangle into world space. | diff --git a/docs/snapengine/reference/collision.mdx b/docs/snapengine/reference/collision.mdx index 3e0e3a32..53f36df7 100644 --- a/docs/snapengine/reference/collision.mdx +++ b/docs/snapengine/reference/collision.mdx @@ -91,6 +91,22 @@ collider.event.collider.onEndContact = (self, other) => { | `onCollide` | Called every frame while two colliders overlap. | | `onEndContact` | Called once when two colliders stop touching. | +## World Bounds + +`collider.getWorldBoundsSnapshot()` returns a `ColliderBounds`: a +[`Bounds`](/docs/snapengine/reference/geometry) plus `center` and `radius`. +For every shape, `x`/`y` are the top-left corner and `width`/`height` span +the bounds, so a circle's bounds are its enclosing square. `center` is the +rectangle center or the circle/point position. + +```ts +import { rectsIntersect } from "@snap-engine/core/geometry"; + +const a = colliderA.getWorldBoundsSnapshot(); +const b = colliderB.getWorldBoundsSnapshot(); +rectsIntersect(a, b); +``` + ## Public API | API | Description | @@ -104,7 +120,7 @@ collider.event.collider.onEndContact = (self, other) => { | `new RectCollider(engine, parent, localX, localY, width, height)` | Creates a rectangular collider. | | `new CircleCollider(engine, parent, localX, localY, radius)` | Creates a circular collider. | | `new PointCollider(engine, parent, localX, localY)` | Creates a point collider. | -| `collider.getWorldBoundsSnapshot()` | Returns current world bounds. | +| `collider.getWorldBoundsSnapshot()` | Returns the cached world `ColliderBounds`. | | `collider.isCollidingWith(other)` | Checks whether two colliders are currently touching. | | `collider.currentCollisions` | Current collision set. | | `collider.destroy()` | Removes the collider from its parent and collision engine. | diff --git a/docs/snapengine/reference/engine.mdx b/docs/snapengine/reference/engine.mdx index 06be0e6e..8a5db0a1 100644 --- a/docs/snapengine/reference/engine.mdx +++ b/docs/snapengine/reference/engine.mdx @@ -79,6 +79,10 @@ engine.subscribeEvent("containerResized", "layout", ({ bounds }) => { engine.unsubscribeEvent("containerResized", "layout"); ``` +`bounds` is the container's viewport rectangle as a +[`Bounds`](/docs/snapengine/reference/geometry); `engine.containerBounds` +holds the latest one. + | Event | Description | | ------------------- | --------------------------------------------------------------- | | `containerAssigned` | Fired after the container element is assigned. | diff --git a/docs/snapengine/reference/geometry.mdx b/docs/snapengine/reference/geometry.mdx new file mode 100644 index 00000000..bd024253 --- /dev/null +++ b/docs/snapengine/reference/geometry.mdx @@ -0,0 +1,97 @@ +--- +title: Geometry +order: 10 +project: snapengine +projectTitle: SnapEngine +section: reference +sectionTitle: Reference +sectionOrder: 2 +--- + +## Imports + +```ts +import type { Point, Rect, BoxModel } from "@snap-engine/core/geometry"; +import { contentRect, rectsIntersect } from "@snap-engine/core/geometry"; +``` + +`@snap-engine/core/geometry` is the shared geometry vocabulary for core and +every asset package. It never reads the DOM or depends on a Camera, so its +helpers are safe in any frame stage. Import only what you use; unused +helpers are tree-shaken. + +## Types + +| Type | Fields | Description | +|------|--------|-------------| +| `Point` | `x`, `y` | A 2D point. | +| `Size` | `width`, `height` | A 2D extent. | +| `Rect` | `Point & Size` | An axis-aligned rectangle anchored at its top-left corner. | +| `Circle` | `Point & { radius }` | A circle anchored at its center. | +| `Edges` | `top`, `right`, `bottom`, `left` | Per-side thicknesses, matching CSS `margin`, `padding`, and `border-width`. | +| `Bounds` | `Rect & { left, top, right, bottom }` | A rectangle with precomputed edge coordinates (DOMRect-compatible). | +| `BoxModel` | `Rect & { margin, padding, border }` | A CSS box model. The rectangle is the border box. | +| `ElementBox` | `BoxModel & { screen: Rect }` | A measured element box (see [Objects](/docs/snapengine/reference/objects)). | +| `PointerPosition` | `Point & { camera: Point, screen: Point }` | A pointer resolved in world, camera, and screen space. | +| `Axis` | `"x" \| "y"` | A rectangle axis name. | +| `Dimension` | `"width" \| "height"` | A rectangle dimension name. | + +All fields are `readonly`. Values are plain objects; `Rect` accepts any +object with `x`, `y`, `width`, and `height`, including a `BoxModel` or a +`DOMRect`. + +Types carry no coordinate space. A value's space comes from where it was +produced: an `ElementBox` is world-space except for its `screen` rectangle. + +## Predicates + +| Function | Description | +|----------|-------------| +| `pointIntersectsRect(point, rect)` | Edge-inclusive point containment. | +| `pointIntersectsCircle(point, circle)` | Edge-inclusive point containment. | +| `circlesIntersect(a, b)` | Edge-inclusive tangency counts as intersecting. | +| `rectIntersectsCircle(rect, circle)` | Edge-inclusive tangency counts as intersecting. | +| `rectsIntersect(a, b)` | Requires positive overlap; touching edges do not intersect. | +| `rectContainsRect(outer, inner)` | Whether `inner` lies entirely inside `outer`, edges inclusive. | +| `rectsEqual(a, b, tolerance?)` | Component-wise equality within `tolerance` (default `0`). | + +## Measures + +| Function | Description | +|----------|-------------| +| `distance(a, b)` | Euclidean distance between two points. | +| `distanceToRect(point, rect)` | Distance from a point to a rectangle; `0` inside it. | +| `rectCenter(rect)` | The center point. | +| `rectArea(size)` | `width * height`. | + +## Construction and Mapping + +| Function | Description | +|----------|-------------| +| `freezeRect(rect)` | A frozen copy holding only the rectangle fields. | +| `boundsOf(rect)` | A frozen `Bounds` with edge coordinates precomputed. | +| `boundingRect(rects)` | The smallest rectangle containing every input, or `null` for none. | +| `translateRect(rect, dx, dy)` | The rectangle moved by an offset. | +| `lerpRect(from, to, t)` | Linear interpolation; `t = 0` returns `from`. | +| `projectRect(rect, from, to)` | Maps a rectangle from the `from` frame into the `to` frame by their size ratio. | +| `projectRects(rects, from, to)` | `projectRect` over a list. | + +## Box Model + +```ts +const box: BoxModel = element.box; +const content = contentRect(box); // border box inset by border + padding +const outer = marginRect(box); // border box grown by margin +``` + +| Function | Description | +|----------|-------------| +| `ZERO_EDGES` | Frozen zero-thickness edges. | +| `addEdges(a, b)` | Per-side sum. | +| `insetRect(rect, edges)` | Shrinks a rectangle; the size is clamped at zero. | +| `outsetRect(rect, edges)` | Grows a rectangle. | +| `paddingRect(box)` | The padding box. | +| `contentRect(box)` | The content box. | +| `marginRect(box)` | The margin box. | +| `contentOffset(box)` | Offset of the content box from the border box's top-left corner. | +| `edgesToCss(edges)` | CSS shorthand such as `"1px 2px 3px 4px"`. | diff --git a/docs/snapengine/reference/index.mdx b/docs/snapengine/reference/index.mdx index 08fc4e01..03b24c0f 100644 --- a/docs/snapengine/reference/index.mdx +++ b/docs/snapengine/reference/index.mdx @@ -21,3 +21,5 @@ The Reference section contains setup notes, code examples, method signatures, an - [Collision](/docs/snapengine/reference/collision) - [Animation](/docs/snapengine/reference/animation) - [Debug Renderer](/docs/snapengine/reference/debug_renderer) +- [Geometry](/docs/snapengine/reference/geometry) +- [Layout](/docs/snapengine/reference/layout) diff --git a/docs/snapengine/reference/input_system.mdx b/docs/snapengine/reference/input_system.mdx index d8a39b84..6ef89fca 100644 --- a/docs/snapengine/reference/input_system.mdx +++ b/docs/snapengine/reference/input_system.mdx @@ -21,11 +21,11 @@ object.event.input.pointerDown = (props) => { }; object.event.input.pointerMove = (props) => { - console.log(props.position.cameraX, props.position.cameraY); + console.log(props.position.camera.x, props.position.camera.y); }; object.event.input.pointerUp = (props) => { - console.log(props.position.screenX, props.position.screenY); + console.log(props.position.screen.x, props.position.screen.y); console.log(props.cancelled); }; @@ -64,6 +64,10 @@ object.event.global.mouseWheel = (props) => { }; ``` +Every `position` is a `PointerPosition`: `x`/`y` are world coordinates, +`camera` is the point relative to the camera container, and `screen` is the +viewport (client) point. A drag `delta` has the same shape. + ## Drag Gestures ```ts diff --git a/docs/snapengine/reference/layout.mdx b/docs/snapengine/reference/layout.mdx new file mode 100644 index 00000000..77477163 --- /dev/null +++ b/docs/snapengine/reference/layout.mdx @@ -0,0 +1,100 @@ +--- +title: Layout +order: 11 +project: snapengine +projectTitle: SnapEngine +section: reference +sectionTitle: Reference +sectionOrder: 2 +--- + +## Imports + +```ts +import { + createLayoutResolutionPlan, + type LayoutNode, + type VirtualInsertion, +} from "@snap-engine/core/layout"; +``` + +`@snap-engine/core/layout` simulates CSS layout over a frozen tree of +measured boxes. It never reads the DOM: measure once (for example with +`ElementObject.readDom()` in a READ stage), then ask any number of "what if" +questions — remove these nodes, insert an entry here — without layout +thrash. SnapSort uses it to predict drop positions during a drag. + +## Layout Trees + +A tree is any object graph that satisfies `LayoutNode`: + +```ts +interface LayoutNode> { + readonly box: BoxModel; // measured border box and edges + readonly children: readonly Child[]; + readonly direction: "column" | "row"; + readonly mainAxisAlign: "start" | "center"; + readonly layoutModel: "flow" | "slots"; + readonly wrap: "auto" | "nowrap"; + readonly stretchItems: boolean; +} +``` + +`box` is a [`BoxModel`](/docs/snapengine/reference/geometry), so an +`ElementBox` from `readDom()` can be used directly. + +| Backend | Behavior | +|---------|----------| +| `flow` | Accumulates entries along the main axis and wraps them against the measured capacity (flexbox-style flow). | +| `slots` | Places entries into measured track positions by index — the basis for simulating CSS grid. | + +## Resolution Plans + +```ts +const plan = createLayoutResolutionPlan(root, { + exclude: (node) => node === dragged, +}); + +const origin = contentRect(root.box); +const insertion: VirtualInsertion = { + container: root, + index: 2, + entry: { width: 120, height: 40, margin: ZERO_EDGES }, +}; +const { itemPositions, virtualRects } = plan.layoutPositions( + root, + origin.x, + origin.y, + [insertion], +); +virtualRects.get(insertion); // where the entry would land +``` + +A plan infers each container's metrics once — content-box start offsets, +main/cross gaps, line sizes, and the wrap capacity the browser actually used +— and caches them. `layoutPositions` then materializes positions for any set +of local insertions. + +| Option | Description | +|--------|-------------| +| `exclude(node)` | Leaves children out of the layout (for example, dragged nodes). | +| `insertions` | Virtual entries folded into each container's cached dimensions, so a nested container's growth propagates to its ancestors. | + +| Plan method | Description | +|-------------|-------------| +| `containerPlan(container)` | The cached axes, content size, metrics, and eligible children. | +| `layoutPositions(container, startX, startY, localInsertions?)` | Simulated child positions and virtual entry rectangles. | +| `virtualDimensions(container)` | The container's simulated border-box size. | + +## Helpers + +| API | Description | +|-----|-------------| +| `flowAxesForDirection(direction)` | Main/cross axis and dimension names. | +| `inferFlowLayoutMetrics(container, axes)` | Gaps, start offsets, and line sizes from measured children. | +| `inferVisualLines(container, axes)` | Measured visual lines, in content-box coordinates. | +| `childRelativeOffset(containerBox, child)` | A child's offset from the container's content-box origin. | +| `layoutChildren(container, exclude?)` | Children minus excluded nodes. | +| `virtualEntrySizeFor(container, entry)` | An entry's size in a destination container, honoring `stretchItems`. | +| `LAYOUT_WRAP_TOLERANCE` | Wrap comparison tolerance absorbing browser measurement noise. | +| `LAYOUT_LINE_BREAK_TOLERANCE` | Backward main-axis movement that starts a new visual line. | diff --git a/docs/snapengine/reference/objects.mdx b/docs/snapengine/reference/objects.mdx index 4ae5bcf4..c0814ee2 100644 --- a/docs/snapengine/reference/objects.mdx +++ b/docs/snapengine/reference/objects.mdx @@ -96,11 +96,30 @@ object.schedule(() => { ```ts object.schedule(() => { - object.readDom(); - object.saveDomProperety("READ_1"); + const box = object.readDom(); + console.log(box.x, box.y, box.width, box.height, box.padding.left); + object.saveWorldPosition("READ_1"); }, { stage: "READ_1" }); ``` +### Element Boxes + +`readDom()` measures the element and returns an `ElementBox` +(see [Geometry](/docs/snapengine/reference/geometry)): + +| Field | Description | +|-------|-------------| +| `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 | @@ -117,9 +136,10 @@ object.schedule(() => { | `object.schedule(callback, config)` | Queues frame work. | | `object.destroy()` | Removes engine registrations and related resources. | | `elementObject.element` | DOM element assigned to an element object. | -| `elementObject.readDom(config?, stage?)` | Reads and caches DOM geometry. | -| `elementObject.getDomProperty(stage?)` | Returns cached DOM geometry. | -| `elementObject.copyDomProperty(fromStage, toStage)` | Copies cached DOM geometry between read stages. | -| `elementObject.saveDomProperety(stage?)` | Saves cached DOM position into the object transform. | +| `elementObject.readDom(config?, stage?)` | Measures the element and returns a new frozen `ElementBox`. | +| `elementObject.box` | The most recent measured `ElementBox`. | +| `elementObject.getStageBox(stage?)` | The box captured by the last read in a read stage. | +| `elementObject.copyStageBox(fromStage, toStage)` | Makes one read stage report another stage's box. | +| `elementObject.saveWorldPosition(stage?)` | Copies a stage box's position into the object's world transform. | | `elementObject.writeDom()` | Applies style, class, and data attribute state. | | `elementObject.writeTransform()` | Applies transform state to the DOM element. | diff --git a/docs/snapengine/reference/render_queue.mdx b/docs/snapengine/reference/render_queue.mdx index 717a86ea..37a0ef5b 100644 --- a/docs/snapengine/reference/render_queue.mdx +++ b/docs/snapengine/reference/render_queue.mdx @@ -82,33 +82,32 @@ object.transformOrigin = parentObject; ```ts object.schedule(() => { - object.readDom(); - const props = object.getDomProperty("READ_1"); + const box = object.readDom(); - console.log(props.screenX, props.screenY, props.width, props.height); + console.log(box.screen.x, box.screen.y, box.width, box.height); }, { stage: "READ_1" }); ``` ```ts object.schedule(() => { object.readDom(); - object.copyDomProperty("READ_2", "READ_3"); + object.copyStageBox("READ_2", "READ_3"); }, { stage: "READ_2" }); ``` ```ts object.schedule(() => { object.readDom(); - object.saveDomProperety("READ_1"); + object.saveWorldPosition("READ_1"); }, { stage: "READ_1" }); ``` ```ts object.schedule(() => { object.readDom({ unapplyTransform: true }); - const props = object.getDomProperty("READ_1"); + const box = object.getStageBox("READ_1"); - console.log(props.x, props.y); + console.log(box.x, box.y); }, { stage: "READ_1" }); ``` @@ -134,9 +133,9 @@ object.requestFLIP( | `FrameTask.cancel()` | Cancels a queued task callback. | | `readDom(config?, stage?)` | Reads DOM geometry in a read stage. | | `readDomRecursive(config?)` | Reads this object and child element objects recursively. | -| `getDomProperty(stage?)` | Returns a cached DOM property object. | -| `copyDomProperty(fromStage, toStage)` | Copies cached geometry between read stages. | -| `saveDomProperety(stage?)` | Saves read geometry into world transform position. | +| `getStageBox(stage?)` | Returns the box captured by the last read in a read stage. | +| `copyStageBox(fromStage, toStage)` | Makes one read stage report another stage's box. | +| `saveWorldPosition(stage?)` | Copies a stage box's position into the world transform. | | `writeDom()` | Applies pending style, classes, and data attributes. | | `writeTransform()` | Applies transform state as CSS transform. | | `requestFLIP(writeCallback, transformCallback)` | Queues a two-read/two-write FLIP sequence. | diff --git a/docs/snapline/guides/04_placement_camera.mdx b/docs/snapline/guides/04_placement_camera.mdx index 22e97434..cc0c095d 100644 --- a/docs/snapline/guides/04_placement_camera.mdx +++ b/docs/snapline/guides/04_placement_camera.mdx @@ -17,11 +17,9 @@ and reports commit or cancellation. It deliberately does not create nodes. ```ts const placement = new PlacementController({ - screenToWorld(screen) { - const camera = engine.camera!.getCameraFromScreen(screen.x, screen.y); - const world = engine.camera!.getWorldFromCamera(camera[0], camera[1]); - return { x: world[0], y: world[1] }; - }, + // pointerPositionFromScreen comes from @snap-engine/core. + screenToWorld: (screen) => + pointerPositionFromScreen(engine.camera, screen.x, screen.y), callbacks: { canPlace: ({ position }) => isInsideWorkspace(position), onCommit: ({ payload, position }) => addNode(payload, position), diff --git a/docs/snapline/reference/vanilla/node.mdx b/docs/snapline/reference/vanilla/node.mdx index 8eaa3951..03da042a 100644 --- a/docs/snapline/reference/vanilla/node.mdx +++ b/docs/snapline/reference/vanilla/node.mdx @@ -22,6 +22,10 @@ and `edgePan`. for persistence. `resolveNewLine` seeds serializable payload onto a newly dragged line; a connector-level callback may override it. +Geometry payloads use the shared types from `@snap-engine/core/geometry`: +`resolveDragPosition` returns a `Point`, `NodeGeometry` and `NodeResizeEvent` +extend `Rect`, and `node.geometrySnapshot()` returns a `Rect`. + ## Resize regions Create a `ResizeRegionMirror(engine, node, handle)` for each application DOM diff --git a/docs/snapline/reference/vanilla/placement.mdx b/docs/snapline/reference/vanilla/placement.mdx index df67ab05..d47c4cf7 100644 --- a/docs/snapline/reference/vanilla/placement.mdx +++ b/docs/snapline/reference/vanilla/placement.mdx @@ -8,7 +8,9 @@ frameworkKey: placement --- Create `PlacementController` with `screenToWorld`, optional callbacks, and an -optional normalized anchor. +optional normalized anchor. Points and sizes are the shared `Point` and `Size` +types from `@snap-engine/core/geometry`; under a camera, `screenToWorld` can +return `pointerPositionFromScreen(engine.camera, screen.x, screen.y)`. | Method | Result | | --- | --- | diff --git a/docs/snapline/reference/vanilla/select.mdx b/docs/snapline/reference/vanilla/select.mdx index 0fb39842..368c3318 100644 --- a/docs/snapline/reference/vanilla/select.mdx +++ b/docs/snapline/reference/vanilla/select.mdx @@ -14,7 +14,7 @@ it with `new RectSelectController(engine, parent, { callbacks })`. `SelectChangeEvent` carries the selected nodes for the in-progress marquee. Bind a marquee element with `bindGeometryWriter(callback)`: the callback -receives a `SelectRect` (`x`, `y`, `width`, `height`, `visible`) and writes +receives a `SelectRect` (a core geometry `Rect` plus `visible`) and writes element geometry directly, returning a cleanup function. Destroy the controller with `destroy(false)` when tearing down. 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/01_container.mdx b/docs/snapsort/04_reference/02_svelte/01_container.mdx index b28d6883..d95835f2 100644 --- a/docs/snapsort/04_reference/02_svelte/01_container.mdx +++ b/docs/snapsort/04_reference/02_svelte/01_container.mdx @@ -497,12 +497,15 @@ getItemHitbox?: (event: ItemHitboxEvent) => ItemHitbox; ``` Local, synchronous geometry policy for direct-child hover and swap targeting. -Return a world-space rectangle or circle. +Return a world-space `Rect` or `Circle` (from `@snap-engine/core/geometry`): +`{ shape: "rect", rect }` or `{ shape: "circle", circle }`. ```ts +import { rectCenter } from "@snap-engine/core/geometry"; + const getItemHitbox = (event: ItemHitboxEvent): ItemHitbox => ({ - shape: "rect", - rect: event.defaultRect, + shape: "circle", + circle: { ...rectCenter(event.defaultRect), radius: 24 }, }); ``` diff --git a/docs/snapsort/04_reference/02_svelte/03_ghost.mdx b/docs/snapsort/04_reference/02_svelte/03_ghost.mdx index 8f927974..3e7976a0 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 @@ -193,7 +193,7 @@ if (ghost.location.type === "slot") { ### `rect` -**Type:** `GhostRect` · **Read-only** · **Spacer and pointer-preview only** +**Type:** `Rect` (from `@snap-engine/core/geometry`) · **Read-only** · **Spacer and pointer-preview only** A world-space rectangle with `x`, `y`, `width`, and `height`. The component uses width and height for flow spacers and converts pointer-preview coordinates @@ -287,7 +287,7 @@ const stockInsertionMarkerRectOptions = { function insertionMarkerRect( marker: InsertionMarkerState, options: InsertionMarkerRectOptions, -): ContainerLocalRect; +): Rect; ``` Expands a marker's world-space `gap` into a rectangle positioned in the @@ -305,10 +305,7 @@ const rect = insertionMarkerRect(marker, { ### `toContainerLocalRect()` ```ts -function toContainerLocalRect( - worldRect: Readonly, - container: Container, -): ContainerLocalRect; +function toContainerLocalRect(worldRect: Rect, container: Container): Rect; ``` Converts a world-space rectangle to coordinates measured from a mounted @@ -319,12 +316,8 @@ included. It throws if the Container has no mounted element. const localRect = toContainerLocalRect(ghost.rect, ghost.location.container); ``` -### `ContainerLocalRect` - -**Type:** `{ readonly x: number; readonly y: number; readonly width: number; readonly height: number }` - -The return value of both presentation helpers, suitable for absolute -positioning inside the owning Container. +Both presentation helpers return a frozen `Rect` in the owning Container's +local space, suitable for absolute positioning inside it. ## DOM Contract diff --git a/docs/snapsort/04_reference/03_react/02_container.mdx b/docs/snapsort/04_reference/03_react/02_container.mdx index 7f3e6a56..c9900bd6 100644 --- a/docs/snapsort/04_reference/03_react/02_container.mdx +++ b/docs/snapsort/04_reference/03_react/02_container.mdx @@ -501,12 +501,15 @@ getItemHitbox?: (event: ItemHitboxEvent) => ItemHitbox; ``` Local, synchronous geometry policy for direct-child hover and swap targeting. -Return a world-space rectangle or circle. +Return a world-space `Rect` or `Circle` (from `@snap-engine/core/geometry`): +`{ shape: "rect", rect }` or `{ shape: "circle", circle }`. ```ts +import { rectCenter } from "@snap-engine/core/geometry"; + const getItemHitbox = (event: ItemHitboxEvent): ItemHitbox => ({ - shape: "rect", - rect: event.defaultRect, + shape: "circle", + circle: { ...rectCenter(event.defaultRect), radius: 24 }, }); ``` @@ -1314,8 +1317,7 @@ the stock adapter and choose marker presentation with `getItemHitbox` remains a direct-container geometry callback because its return value intentionally changes hover/swap targeting. It receives the dragged item, candidate `overItem`, direct owner, pointer, and frozen `defaultRect`. -Return either `{ shape: "rect", rect }` or -`{ shape: "circle", center, radius }`. +Return either `{ shape: "rect", rect }` or `{ shape: "circle", circle }`. - Configure persistent and ghost structural callbacks once on the root. Their event locations route updates to the source and destination records. diff --git a/docs/snapsort/04_reference/03_react/04_ghost.mdx b/docs/snapsort/04_reference/03_react/04_ghost.mdx index 9e13ae18..af0a2fd9 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 @@ -195,7 +195,7 @@ if (ghost.location.type === "slot") { ### `rect` -**Type:** `GhostRect` · **Read-only** · **Spacer and pointer-preview only** +**Type:** `Rect` (from `@snap-engine/core/geometry`) · **Read-only** · **Spacer and pointer-preview only** A world-space rectangle with `x`, `y`, `width`, and `height`. The component uses width and height for flow spacers and converts pointer-preview coordinates @@ -290,7 +290,7 @@ const stockInsertionMarkerRectOptions = { function insertionMarkerRect( marker: InsertionMarkerState, options: InsertionMarkerRectOptions, -): ContainerLocalRect; +): Rect; ``` Expands a marker's world-space `gap` into a rectangle positioned in the @@ -308,10 +308,7 @@ const rect = insertionMarkerRect(marker, { ### `toContainerLocalRect()` ```ts -function toContainerLocalRect( - worldRect: Readonly, - container: Container, -): ContainerLocalRect; +function toContainerLocalRect(worldRect: Rect, container: Container): Rect; ``` Converts a world-space rectangle to coordinates measured from a mounted @@ -322,12 +319,8 @@ included. It throws if the Container has no mounted element. const localRect = toContainerLocalRect(ghost.rect, ghost.location.container); ``` -### `ContainerLocalRect` - -**Type:** `{ readonly x: number; readonly y: number; readonly width: number; readonly height: number }` - -The return value of both presentation helpers, suitable for absolute -positioning inside the owning Container. +Both presentation helpers return a frozen `Rect` in the owning Container's +local space, suitable for absolute positioning inside it. ## DOM Contract 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/04_reference/05_callbacks.mdx b/docs/snapsort/04_reference/05_callbacks.mdx index c477e053..d98da1e4 100644 --- a/docs/snapsort/04_reference/05_callbacks.mdx +++ b/docs/snapsort/04_reference/05_callbacks.mdx @@ -43,10 +43,10 @@ interface DropPriorityEvent { containerMetadata: Record; index: number; staticPriority: number; - pointer: { x: number; y: number }; - dragRect: DropPriorityRect; - containerRect: DropPriorityRect; - containerContentRect: DropPriorityRect; + pointer: Point; + dragRect: Rect; + containerRect: Rect; + containerContentRect: Rect; depth: number; } ``` @@ -205,7 +205,7 @@ const pointerY = event.pointer.y; ### `dragRect` -**Type:** `DropPriorityRect` +**Type:** `Rect` The primary dragged Item's virtual world-space rectangle. Its leading edge preserves the pointer-to-Item offset captured at drag start. @@ -216,7 +216,7 @@ const leadingX = event.dragRect.x; ### `containerRect` -**Type:** `DropPriorityRect` +**Type:** `Rect` The destination Container's frozen world-space border box. All five standard callbacks use this rectangle when they need destination geometry. @@ -227,7 +227,7 @@ const right = event.containerRect.x + event.containerRect.width; ### `containerContentRect` -**Type:** `DropPriorityRect` +**Type:** `Rect` The destination Container's frozen world-space content box. Standard helpers do not use it, but custom policies can use it when borders and padding should @@ -251,11 +251,12 @@ scores. const nestedPriority = event.depth + 1; ``` -### `DropPriorityRect` +### Geometry types -**Type:** `{ x: number; y: number; width: number; height: number }` - -A frozen world-space rectangle captured for the current target resolution. +`Point` and `Rect` come from `@snap-engine/core/geometry`. Every rectangle is +frozen, in world space, and captured for the current target resolution; the +same module's helpers (`pointIntersectsRect`, `contentRect`, `rectCenter`, ...) +work on them directly. ## Priority Return Values diff --git a/docs/snapsort/design/direct-drag-accessibility-plan.md b/docs/snapsort/design/direct-drag-accessibility-plan.md index ae12775f..68db3e2d 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,193 @@ 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 Rect[]; + } + | { + readonly kind: "insertion"; + readonly target: ResolvedDropTarget & { + readonly insertion: InsertionMarkerPresentation; + }; + readonly memberRects: readonly Rect[]; + } + | { + readonly kind: "swap"; + readonly target: ResolvedDropTarget; + readonly targetItemId: ItemId; + readonly memberRects: readonly Rect[]; + }; +``` + +- 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 `LayoutPositions.virtualRects` (from `@snap-engine/core/layout`) +is the authoritative projected +geometry. + +For each candidate: + +1. Start from the frozen root drag snapshot. +2. Exclude every dragged participant through + `exclude: (node) => session.itemSet.has(node.value)`. 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 +315,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 +347,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 +367,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 +443,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 +493,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 +510,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 +525,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 +547,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 +578,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 +604,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/package.json b/package.json index e604cd51..0beb215b 100755 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "assets/snapline", "assets/snapzap/*" ], + "sideEffects": false, "main": "./src/index.ts", "types": "./src/index.ts", "exports": { @@ -27,6 +28,14 @@ "./collision": { "types": "./src/collision.ts", "import": "./src/collision.ts" + }, + "./geometry": { + "types": "./src/geometry.ts", + "import": "./src/geometry.ts" + }, + "./layout": { + "types": "./src/layout.ts", + "import": "./src/layout.ts" } }, "files": [ @@ -46,6 +55,8 @@ "test:camera-control": "playwright test -c tests/e2e/camera-control.playwright.config.ts", "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", @@ -72,7 +83,7 @@ "check:website": "npm run check --prefix website", "check:adapters": "FRAMEWORK=test svelte-check --tsconfig assets/asset-base/tsconfig.json && FRAMEWORK=test svelte-check --tsconfig assets/snapsort/tsconfig.json && FRAMEWORK=test svelte-check --tsconfig assets/snapline/tsconfig.json", "typecheck": "tsc --noEmit", - "ci": "npm run validate:packages && npm run check:snapsort-api && npm run test:snapsort-ut && npm run typecheck && npm run lint && npm run check:adapters && npm run check:website && npm run build", + "ci": "npm run validate:packages && npm run check:snapsort-api && npm run test:core-ut && npm run test:snapsort-ut && npm run test:snapline-ut && npm run typecheck && npm run lint && npm run check:adapters && npm run check:website && npm run build", "prepublishOnly": "npm run lint", "wdio": "wdio run ./wdio.conf.ts" }, diff --git a/src/AGENTS.md b/src/AGENTS.md index fcc4928d..4ea068d5 100644 --- a/src/AGENTS.md +++ b/src/AGENTS.md @@ -20,6 +20,8 @@ src/ ├── camera.ts # Camera system ├── input.ts # Input handling ├── collision.ts # Collision detection (optional) +├── geometry.ts # Shared geometry types and pure helpers +├── layout.ts # Layout simulation over measured box trees (optional) ├── animation.ts # Animation system (optional) ├── debug.ts # Debug renderer (optional) └── util.ts # Utilities @@ -37,6 +39,11 @@ Defined in `vite.config.mjs`: - AnimationObject, SequenceObject - **Collision:** `collision.ts` → `dist/collision.mjs` - CollisionEngine, RectCollider, CircleCollider, etc. +- **Geometry:** `geometry.ts` → `dist/geometry.mjs` + - Point, Size, Rect, Edges, Bounds, BoxModel, ElementBox types + - Pure rect/box-model helpers (intersection, content box, projection) +- **Layout:** `layout.ts` → `dist/layout.mjs` + - createLayoutResolutionPlan, LayoutNode, flow and slot (grid) backends - **Debug:** `debug.ts` → `dist/debug.mjs` - DebugRenderer @@ -51,7 +58,7 @@ Public API entry point. All external-facing exports. - `Engine`, `BaseObject`, `ElementObject`, `Camera`, and the `FrameController` interface - Input types (dragProp, pointerDownProp, etc.) -- Utilities (getDomProperty, EventProxyFactory) +- Utilities (measureElementBox, EventProxyFactory) ### `engine.ts` @@ -121,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 @@ -152,9 +168,28 @@ Unified input handling. - dragStart, drag, dragEnd - pinchStart, pinch, pinchEnd +### `geometry.ts` + +The one geometry vocabulary for core and every asset package. Pure: no DOM +reads, no Camera, no imports. Every other core module (and every asset) +describes points, rects, edges, and box models with these types instead of +declaring its own shapes. The collision engine's allocation-free scalar +kernels live here too, so collision and geometry share one implementation. + +### `layout.ts` + +Simulates CSS layout over a frozen tree of measured boxes (`LayoutNode`) +without reading the DOM: infers gaps, line sizes, and wrap capacity from +measured children, then re-lays them out with nodes excluded and virtual +entries inserted. Two backends: `flow` (flexbox-style accumulation and +wrapping) and `slots` (measured grid tracks, the basis for CSS grid +simulation). Imports only `geometry.ts`. SnapSort's drop prediction is the +main consumer. + ### `collision.ts` -Collision detection system. +Collision detection system. Geometric predicates (`rectsIntersect`, +`pointIntersectsRect`, ...) are imported from `geometry.ts`. **CollisionEngine:** @@ -167,7 +202,6 @@ Collision detection system. - RectCollider - CircleCollider -- LineCollider - PointCollider ### `animation.ts` @@ -240,6 +274,8 @@ is therefore supported; calling a recursive read there is not. - debug (optional) - animation (optional) - collision (optional) +- geometry (optional) +- layout (optional) **TypeScript:** Declarations generated to `dist/` via vite-plugin-dts @@ -247,17 +283,12 @@ is therefore supported; calling a recursive read there is not. ## Package Structure -``` -dist/ -├── snapengine.mjs # Main bundle -├── snapengine.d.ts # Type declarations -├── animation.mjs # Animation module -├── animation.d.ts -├── collision.mjs # Collision module -├── collision.d.ts -├── debug.mjs # Debug module -└── debug.d.ts -``` +The published package ships raw TypeScript: `package.json` `exports` map each +entry (`.`, `./animation`, `./collision`, `./debug`, `./geometry`, +`./layout`) to its `src/*.ts` file, and `"sideEffects": false` lets bundlers +drop unused modules. `npm run build` still produces ES bundles and rolled-up +declarations in `dist/` (one `.mjs` + `.d.ts` per entry), which verifies the +entries build cleanly. ## Import Patterns @@ -267,6 +298,7 @@ dist/ import { Engine, ElementObject } from "@snap-engine/core"; import { AnimationObject } from "@snap-engine/core/animation"; import { RectCollider } from "@snap-engine/core/collision"; +import { contentRect, type Rect } from "@snap-engine/core/geometry"; import { DebugRenderer } from "@snap-engine/core/debug"; ``` @@ -284,10 +316,10 @@ import { Engine } from "../../../src/index"; ## Key Principles - **Framework-agnostic:** Works with vanilla JS, React, Svelte, etc. -- **Built package:** Compiled to dist/, not raw source +- **Raw-source package:** Exports `src/*.ts` directly; `dist/` is a build check - **Stage-based rendering:** Prevents layout thrashing - **Single render loop:** All engines share one RAF loop -- **Optional features:** Collision, animation, debug are separate imports +- **Optional features:** Collision, animation, debug, geometry, and layout are separate imports ## Notes diff --git a/src/camera.ts b/src/camera.ts index 39c57f66..a8e2ef23 100644 --- a/src/camera.ts +++ b/src/camera.ts @@ -1,5 +1,5 @@ import { Engine } from "./engine"; -import type { ContainerBounds } from "./engine"; +import type { Bounds, PointerPosition, Rect } from "./geometry"; export interface CameraConfig { enableZoom?: boolean; @@ -296,7 +296,7 @@ export class Camera { * * @param bounds - Optional pre-computed container bounds. If not provided, reads from DOM. */ - updateCameraProperty(bounds?: ContainerBounds) { + updateCameraProperty(bounds?: Bounds) { if (!this.#containerDom) { return; } @@ -774,3 +774,79 @@ export class StationaryCamera extends Camera { } + +/** The Camera conversions needed to resolve screen values into world space. */ +export type ScreenToWorldMapper = Pick< + Camera, + "getCameraFromScreen" | "getWorldFromCamera" | "getWorldDeltaFromCameraDelta" +>; + +/** The Camera conversions needed to resolve world values into screen space. */ +export type WorldToScreenMapper = Pick< + Camera, + "getCameraFromWorld" | "getScreenFromCamera" +>; + +/** + * Resolve a viewport (client) point in world, camera, and screen space. + * Without a camera, all three spaces coincide. + */ +export function pointerPositionFromScreen( + camera: ScreenToWorldMapper | null, + screenX: number, + screenY: number, +): PointerPosition { + const screen = { x: screenX, y: screenY }; + if (!camera) return { x: screenX, y: screenY, camera: screen, screen }; + const [cameraX, cameraY] = camera.getCameraFromScreen(screenX, screenY); + const [worldX, worldY] = camera.getWorldFromCamera(cameraX, cameraY); + return { + x: worldX, + y: worldY, + camera: { x: cameraX, y: cameraY }, + screen, + }; +} + +/** + * Resolve a world point in world, camera, and screen space. + * Without a camera, all three spaces coincide. + */ +export function pointerPositionFromWorld( + camera: WorldToScreenMapper | null, + worldX: number, + worldY: number, +): PointerPosition { + if (!camera) { + const point = { x: worldX, y: worldY }; + return { x: worldX, y: worldY, camera: point, screen: point }; + } + const [cameraX, cameraY] = camera.getCameraFromWorld(worldX, worldY); + const [screenX, screenY] = camera.getScreenFromCamera(cameraX, cameraY); + return { + x: worldX, + y: worldY, + camera: { x: cameraX, y: cameraY }, + screen: { x: screenX, y: screenY }, + }; +} + +/** + * Map a viewport (client) rectangle into world space: the origin through + * the camera transform and the size by the camera zoom. + */ +export function worldRectFromScreenRect( + camera: ScreenToWorldMapper | null, + rect: Rect, +): Rect { + if (!camera) { + return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }; + } + const [cameraX, cameraY] = camera.getCameraFromScreen(rect.x, rect.y); + const [x, y] = camera.getWorldFromCamera(cameraX, cameraY); + const [width, height] = camera.getWorldDeltaFromCameraDelta( + rect.width, + rect.height, + ); + return { x, y, width, height }; +} diff --git a/src/collision.ts b/src/collision.ts index 674cf7ce..23e5e803 100644 --- a/src/collision.ts +++ b/src/collision.ts @@ -4,186 +4,42 @@ import { BaseObject, CoreObject } from "./object"; import { EventProxyFactory } from "./util"; import type { Engine } from "./engine"; +import { + circlesIntersectValues, + pointIntersectsBounds, + pointIntersectsCircleValues, + rectBoundsIntersect, + rectBoundsIntersectCircle, + type Bounds, + type Point, +} from "./geometry"; type ColliderType = "rect" | "circle" | "point"; -/** A world-space point used by allocation-free collision helpers. */ -interface CollisionPoint { - x: number; - y: number; -} - -/** A normalized world-space rectangle with non-negative dimensions. */ -interface CollisionRect extends CollisionPoint { - width: number; - height: number; -} - -/** A normalized world-space circle with a non-negative radius. */ -interface CollisionCircle extends CollisionPoint { - radius: number; -} - -function pointIntersectsBounds( - x: number, - y: number, - left: number, - top: number, - right: number, - bottom: number, -): boolean { - return x >= left && x <= right && y >= top && y <= bottom; -} - -function rectBoundsIntersect( - aLeft: number, - aTop: number, - aRight: number, - aBottom: number, - bLeft: number, - bTop: number, - bRight: number, - bBottom: number, -): boolean { - return ( - aLeft < bRight && - aRight > bLeft && - aTop < bBottom && - aBottom > bTop - ); -} - -function pointIntersectsCircleValues( - pointX: number, - pointY: number, - circleX: number, - circleY: number, - radius: number, -): boolean { - if (radius < 0) return false; - const deltaX = pointX - circleX; - const deltaY = pointY - circleY; - return deltaX * deltaX + deltaY * deltaY <= radius * radius; -} - -function circlesIntersectValues( - aX: number, - aY: number, - aRadius: number, - bX: number, - bY: number, - bRadius: number, -): boolean { - return pointIntersectsCircleValues(aX, aY, bX, bY, aRadius + bRadius); -} - -function rectBoundsIntersectCircle( - left: number, - top: number, - right: number, - bottom: number, - circleX: number, - circleY: number, - radius: number, -): boolean { - const nearestX = Math.max(left, Math.min(circleX, right)); - const nearestY = Math.max(top, Math.min(circleY, bottom)); - return pointIntersectsCircleValues( - nearestX, - nearestY, - circleX, - circleY, - radius, - ); -} - -/** Point/rectangle collision with edge-inclusive containment. */ -function pointIntersectsRect( - point: CollisionPoint, - rect: CollisionRect, -): boolean { - return pointIntersectsBounds( - point.x, - point.y, - rect.x, - rect.y, - rect.x + rect.width, - rect.y + rect.height, - ); -} - -/** Point/circle collision with edge-inclusive containment. */ -function pointIntersectsCircle( - point: CollisionPoint, - circle: CollisionCircle, -): boolean { - return pointIntersectsCircleValues( - point.x, - point.y, - circle.x, - circle.y, - circle.radius, - ); -} - -/** Circle collision with edge-inclusive tangency. */ -function circlesIntersect(a: CollisionCircle, b: CollisionCircle): boolean { - return circlesIntersectValues(a.x, a.y, a.radius, b.x, b.y, b.radius); -} - -/** Rectangle/circle collision with edge-inclusive tangency. */ -function rectIntersectsCircle( - rect: CollisionRect, - circle: CollisionCircle, -): boolean { - return rectBoundsIntersectCircle( - rect.x, - rect.y, - rect.x + rect.width, - rect.y + rect.height, - circle.x, - circle.y, - circle.radius, - ); -} - -/** Rectangle collision requiring positive overlap; touching edges do not collide. */ -function rectsIntersect(a: CollisionRect, b: CollisionRect): boolean { - return rectBoundsIntersect( - a.x, - a.y, - a.x + a.width, - a.y + a.height, - b.x, - b.y, - b.x + b.width, - b.y + b.height, - ); -} - -/** Euclidean distance from a point to a rectangle; zero inside its bounds. */ -function distanceToRect(point: CollisionPoint, rect: CollisionRect): number { - if (pointIntersectsRect(point, rect)) return 0; - const x = Math.max(rect.x, Math.min(point.x, rect.x + rect.width)); - const y = Math.max(rect.y, Math.min(point.y, rect.y + rect.height)); - return Math.hypot(point.x - x, point.y - y); +/** + * A collider's cached world-space bounds. + * + * `x`/`y` are always the top-left corner and `width`/`height` span the + * bounds, for every shape. `center` is the rectangle center, or the circle + * or point position; `radius` is zero for non-circles. + */ +interface ColliderBounds extends Bounds { + readonly center: Point; + readonly radius: number; } -interface ColliderWorldBounds { - x: number; - y: number; - scaleX: number; - scaleY: number; - width: number; - height: number; - radius: number; - left: number; - right: number; - top: number; - bottom: number; - centerX: number; - centerY: number; -} +const EMPTY_COLLIDER_BOUNDS: ColliderBounds = Object.freeze({ + x: 0, + y: 0, + width: 0, + height: 0, + left: 0, + top: 0, + right: 0, + bottom: 0, + center: Object.freeze({ x: 0, y: 0 }), + radius: 0, +}); interface CollisionEvent { onCollide: null | ((thisObject: Collider, otherObject: Collider) => void); @@ -276,21 +132,7 @@ class Collider extends CoreObject { #shapeVersion: number = 0; #cachedBoundsShapeVersion: number = -1; #cachedBoundsTransformEpoch: number = -1; - #cachedBounds: ColliderWorldBounds = { - x: 0, - y: 0, - scaleX: 1, - scaleY: 1, - width: 0, - height: 0, - radius: 0, - left: 0, - right: 0, - top: 0, - bottom: 0, - centerX: 0, - centerY: 0, - }; + #cachedBounds: ColliderBounds = EMPTY_COLLIDER_BOUNDS; type: ColliderType; @@ -347,7 +189,7 @@ class Collider extends CoreObject { this.#markShapeChange(); } - getWorldBoundsSnapshot(): ColliderWorldBounds { + getWorldBoundsSnapshot(): ColliderBounds { if ( this.#cachedBoundsShapeVersion === this.#shapeVersion && this.#cachedBoundsTransformEpoch === this.getTransformEpoch() @@ -356,8 +198,6 @@ class Collider extends CoreObject { } const transform = this.getWorldTransform(); - const width = this.#width * Math.abs(transform.scaleX); - const height = this.#height * Math.abs(transform.scaleY); const radius = this.localRadius * Math.max(Math.abs(transform.scaleX), Math.abs(transform.scaleY)); @@ -380,20 +220,23 @@ class Collider extends CoreObject { ? transform.y + radius : Math.max(transform.y, bottomEdge); + const width = right - left; + const height = bottom - top; + this.#cachedBounds = { - x: transform.x, - y: transform.y, - scaleX: transform.scaleX, - scaleY: transform.scaleY, + x: left, + y: top, width, height, - radius, left, - right, top, + right, bottom, - centerX: this.type === "rect" ? left + width / 2 : transform.x, - centerY: this.type === "rect" ? top + height / 2 : transform.y, + center: + this.type === "rect" + ? { x: left + width / 2, y: top + height / 2 } + : { x: transform.x, y: transform.y }, + radius, }; this.#cachedBoundsShapeVersion = this.#shapeVersion; this.#cachedBoundsTransformEpoch = this.getTransformEpoch(); @@ -464,8 +307,8 @@ class Collider extends CoreObject { return pointIntersectsCircleValues( x, y, - bounds.x, - bounds.y, + bounds.center.x, + bounds.center.y, bounds.radius, ); } @@ -640,7 +483,7 @@ class CollisionEngine { * preserve collider registration order and are intentionally unfiltered; * callers own any label, admission, or input-target policy. */ - queryPoint(point: { x: number; y: number }): Collider[] { + queryPoint(point: Point): Collider[] { return this.#objectList.filter((collider) => collider.containsWorldPoint(point.x, point.y), ); @@ -660,11 +503,11 @@ class CollisionEngine { } #colliderCenterX(c: Collider): number { - return c.getWorldBoundsSnapshot().centerX; + return c.getWorldBoundsSnapshot().center.x; } #colliderCenterY(c: Collider): number { - return c.getWorldBoundsSnapshot().centerY; + return c.getWorldBoundsSnapshot().center.y; } detectCollisions() { @@ -790,8 +633,8 @@ class CollisionEngine { rectBounds.top, rectBounds.right, rectBounds.bottom, - circleBounds.x, - circleBounds.y, + circleBounds.center.x, + circleBounds.center.y, circleBounds.radius, ); } @@ -800,8 +643,8 @@ class CollisionEngine { const rectBounds = rect.getWorldBoundsSnapshot(); const pointBounds = point.getWorldBoundsSnapshot(); return pointIntersectsBounds( - pointBounds.x, - pointBounds.y, + pointBounds.center.x, + pointBounds.center.y, rectBounds.left, rectBounds.top, rectBounds.right, @@ -812,7 +655,13 @@ class CollisionEngine { #isCirclePointIntersecting(circle: CircleCollider, point: PointCollider) { const circleBounds = circle.getWorldBoundsSnapshot(); const pointBounds = point.getWorldBoundsSnapshot(); - return pointIntersectsCircle(pointBounds, circleBounds); + return pointIntersectsCircleValues( + pointBounds.center.x, + pointBounds.center.y, + circleBounds.center.x, + circleBounds.center.y, + circleBounds.radius, + ); } #isCircleIntersecting(circleA: CircleCollider, circleB: CircleCollider) { @@ -821,7 +670,14 @@ class CollisionEngine { } const boundsA = circleA.getWorldBoundsSnapshot(); const boundsB = circleB.getWorldBoundsSnapshot(); - return circlesIntersect(boundsA, boundsB); + return circlesIntersectValues( + boundsA.center.x, + boundsA.center.y, + boundsA.radius, + boundsB.center.x, + boundsB.center.y, + boundsB.radius, + ); } #isPointPointIntersecting(pointA: PointCollider, pointB: PointCollider) { @@ -830,20 +686,15 @@ class CollisionEngine { } const boundsA = pointA.getWorldBoundsSnapshot(); const boundsB = pointB.getWorldBoundsSnapshot(); - return boundsA.x === boundsB.x && boundsA.y === boundsB.y; + return ( + boundsA.center.x === boundsB.center.x && + boundsA.center.y === boundsB.center.y + ); } } export { - type CollisionPoint, - type CollisionRect, - type CollisionCircle, - pointIntersectsRect, - pointIntersectsCircle, - circlesIntersect, - rectIntersectsCircle, - rectsIntersect, - distanceToRect, + type ColliderBounds, CollisionEngine, Collider, RectCollider, diff --git a/src/debug.ts b/src/debug.ts index 3986d2a5..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; @@ -79,7 +97,7 @@ export class DebugRenderer implements DebugRendererInterface { renderFrame( _stats: FrameStats, - engine: any, + engine: Engine, objectTable: Record, ): void { if (this.debugWindow == null) { @@ -103,27 +121,7 @@ export class DebugRenderer implements DebugRendererInterface { if (this.debugCtx == null) { return; } - for (const marker of Object.values(engine.debugMarkerList) as Array<{ - objectId: string; - id: string; - type: "point" | "rect" | "circle" | "text" | "line"; - persistent: boolean; - color: string; - tag?: string; - x: number; - y: number; - x2?: number; - y2?: number; - width?: number; - height?: number; - radius?: number; - text?: string; - filled?: boolean; - lineWidth?: number; - arrowEnd?: boolean; - arrowStart?: boolean; - arrowSize?: number; - }>) { + for (const marker of Object.values(engine.debugMarkerList)) { if (!this.isTagEnabled(marker.tag)) { continue; } @@ -131,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; @@ -141,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; @@ -233,25 +231,17 @@ export class DebugRenderer implements DebugRendererInterface { const elementObject = object; const colors = ["#FF0000A0", "#00FF00A0", "#0000FFA0"]; - const stages = ["READ_1", "READ_2", "READ_3"]; + const stages = ["READ_1", "READ_2", "READ_3"] as const; const tagNames = ["dom-read-1", "dom-read-2", "dom-read-3"]; for (let i = 0; i < 3; i++) { if (!this.isTagEnabled(tagNames[i])) continue; - const property = elementObject.getDomProperty(stages[i] as any); + const property = elementObject.getStageBox(stages[i]); this.debugCtx.stroke(); 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(); } @@ -264,12 +254,12 @@ export class DebugRenderer implements DebugRendererInterface { this.debugCtx.beginPath(); this.debugCtx.strokeStyle = "black"; this.debugCtx.lineWidth = 1; - this.debugCtx.rect( - cameraX, - cameraY, - elementObject.currentDomProperty.width, - elementObject.currentDomProperty.height, + const [width, height] = cameraDelta( + engine.camera, + elementObject.box.width, + elementObject.box.height, ); + this.debugCtx.rect(cameraX, cameraY, width, height); this.debugCtx.stroke(); } } @@ -293,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/engine.ts b/src/engine.ts index c145268d..9fe9c95a 100755 --- a/src/engine.ts +++ b/src/engine.ts @@ -2,7 +2,7 @@ import { StationaryCamera } from "./camera"; import type { Camera } from "./camera"; import { GlobalManager } from "./global"; import { InputControl } from "./input"; -import type { eventPosition } from "./input"; +import { boundsOf, type Bounds, type PointerPosition } from "./geometry"; import { BaseObject, FrameTask, detachAnimationFromOwner } from "./object"; import { reportConsumerError } from "./errors"; import type { CollisionEngine } from "./collision"; @@ -18,10 +18,10 @@ export interface EngineConfig {} export interface EdgePanController { startEdgePan( pointerId: number, - position: eventPosition, - onFrame: (position: eventPosition) => void, + position: PointerPosition, + onFrame: (position: PointerPosition) => void, ): void; - updateEdgePan(pointerId: number, position: eventPosition): void; + updateEdgePan(pointerId: number, position: PointerPosition): void; stopEdgePan(pointerId: number): void; } @@ -35,28 +35,17 @@ export type EngineEventType = | "containerResized" | "containerMoved"; -/** - * Container bounds data passed to engine event callbacks. - */ -export interface ContainerBounds { - left: number; - top: number; - right: number; - bottom: number; - width: number; - height: number; -} - /** * Props passed to engine event callbacks. */ export interface EngineEventProps { element: HTMLElement; - bounds: ContainerBounds; + bounds: Bounds; } type AnimationProcessor = (timestamp: number) => void; -type DebugMarker = { +/** A debug-renderer marker registered through `BaseObject.addDebug*`. */ +export type DebugMarker = { type: "point" | "rect" | "circle" | "text" | "line"; objectId: string; id: string; @@ -98,7 +87,7 @@ class Engine { #frameController: EngineFrameController; #containerElement: HTMLElement | null = null; // The DOM element for the engine's container. - #containerBounds: ContainerBounds | null = null; // Cached bounding rect of the container + #containerBounds: Bounds | null = null; // Cached bounding rect of the container #camera: Camera | null = null; // Optional camera instance #edgePanController: EdgePanController | null = null; #collisionEngine: CollisionEngine | null = null; // Optional collision engine instance @@ -175,11 +164,11 @@ class Engine { this.#containerElement = element; } - get containerBounds(): ContainerBounds | null { + get containerBounds(): Bounds | null { return this.#containerBounds; } - set containerBounds(bounds: ContainerBounds | null) { + set containerBounds(bounds: Bounds | null) { this.#containerBounds = bounds; } @@ -268,15 +257,7 @@ class Engine { * @internal */ #updateContainerBounds(element: HTMLElement) { - const rect = element.getBoundingClientRect(); - this.#containerBounds = { - left: rect.left, - top: rect.top, - right: rect.right, - bottom: rect.bottom, - width: rect.width, - height: rect.height, - }; + this.#containerBounds = boundsOf(element.getBoundingClientRect()); } /** diff --git a/src/geometry.ts b/src/geometry.ts new file mode 100644 index 00000000..7d4b51e8 --- /dev/null +++ b/src/geometry.ts @@ -0,0 +1,424 @@ +/** + * Shared geometry vocabulary and pure helpers. + * + * Every module in core and every asset package describes points, sizes, + * rectangles, and CSS box models with these types. Nothing in this module + * reads the DOM or depends on a Camera, so it is safe to use in any frame + * stage and in Node-side tests. + * + * Coordinate spaces are a property of where a value came from, not of its + * type: an `ElementBox` is world-space except for its explicit `screen` rect, + * and helpers here never convert between spaces. + */ + +/** A 2D point. */ +export interface Point { + readonly x: number; + readonly y: number; +} + +/** A 2D extent. */ +export interface Size { + readonly width: number; + readonly height: number; +} + +/** An axis-aligned rectangle anchored at its top-left corner. */ +export interface Rect extends Point, Size {} + +/** A circle anchored at its center. */ +export interface Circle extends Point { + readonly radius: number; +} + +/** Per-side thicknesses, matching CSS `margin`/`padding`/`border-width`. */ +export interface Edges { + readonly top: number; + readonly right: number; + readonly bottom: number; + readonly left: number; +} + +/** A rectangle with its edge coordinates precomputed (DOMRect-compatible). */ +export interface Bounds extends Rect { + readonly left: number; + readonly top: number; + readonly right: number; + readonly bottom: number; +} + +/** + * A CSS box model. The rectangle is the border box; `margin`, `padding`, and + * `border` are the CSS edge thicknesses around and inside it. + */ +export interface BoxModel extends Rect { + readonly margin: Edges; + readonly padding: Edges; + readonly border: Edges; +} + +/** + * A measured element box. + * + * The border-box rectangle and edges are world-space (inside a Camera layer, + * one world unit is one CSS pixel). `screen` is the element's transformed + * viewport rectangle in CSS pixels, exactly as `getBoundingClientRect()` + * reports it. + */ +export interface ElementBox extends BoxModel { + readonly screen: Rect; +} + +/** A pointer location resolved in world, camera, and screen space. */ +export interface PointerPosition extends Point { + readonly camera: Point; + readonly screen: Point; +} + +/** A rectangle axis name. */ +export type Axis = "x" | "y"; + +/** A rectangle dimension name. */ +export type Dimension = "width" | "height"; + +/** Zero thickness on every side. */ +export const ZERO_EDGES: Edges = Object.freeze({ + top: 0, + right: 0, + bottom: 0, + left: 0, +}); + +// --------------------------------------------------------------------------- +// Allocation-free scalar kernels shared with the collision engine. +// --------------------------------------------------------------------------- + +/** @internal Edge-inclusive point containment against scalar bounds. */ +export function pointIntersectsBounds( + x: number, + y: number, + left: number, + top: number, + right: number, + bottom: number, +): boolean { + return x >= left && x <= right && y >= top && y <= bottom; +} + +/** @internal Positive-overlap intersection of two scalar bounds. */ +export function rectBoundsIntersect( + aLeft: number, + aTop: number, + aRight: number, + aBottom: number, + bLeft: number, + bTop: number, + bRight: number, + bBottom: number, +): boolean { + return aLeft < bRight && aRight > bLeft && aTop < bBottom && aBottom > bTop; +} + +/** @internal Edge-inclusive point/circle containment on scalars. */ +export function pointIntersectsCircleValues( + pointX: number, + pointY: number, + circleX: number, + circleY: number, + radius: number, +): boolean { + if (radius < 0) return false; + const deltaX = pointX - circleX; + const deltaY = pointY - circleY; + return deltaX * deltaX + deltaY * deltaY <= radius * radius; +} + +/** @internal Edge-inclusive circle tangency on scalars. */ +export function circlesIntersectValues( + aX: number, + aY: number, + aRadius: number, + bX: number, + bY: number, + bRadius: number, +): boolean { + return pointIntersectsCircleValues(aX, aY, bX, bY, aRadius + bRadius); +} + +/** @internal Edge-inclusive rectangle/circle tangency on scalars. */ +export function rectBoundsIntersectCircle( + left: number, + top: number, + right: number, + bottom: number, + circleX: number, + circleY: number, + radius: number, +): boolean { + const nearestX = Math.max(left, Math.min(circleX, right)); + const nearestY = Math.max(top, Math.min(circleY, bottom)); + return pointIntersectsCircleValues( + nearestX, + nearestY, + circleX, + circleY, + radius, + ); +} + +// --------------------------------------------------------------------------- +// Predicates and measures. +// --------------------------------------------------------------------------- + +/** Point/rectangle collision with edge-inclusive containment. */ +export function pointIntersectsRect(point: Point, rect: Rect): boolean { + return pointIntersectsBounds( + point.x, + point.y, + rect.x, + rect.y, + rect.x + rect.width, + rect.y + rect.height, + ); +} + +/** Point/circle collision with edge-inclusive containment. */ +export function pointIntersectsCircle(point: Point, circle: Circle): boolean { + return pointIntersectsCircleValues( + point.x, + point.y, + circle.x, + circle.y, + circle.radius, + ); +} + +/** Circle collision with edge-inclusive tangency. */ +export function circlesIntersect(a: Circle, b: Circle): boolean { + return circlesIntersectValues(a.x, a.y, a.radius, b.x, b.y, b.radius); +} + +/** Rectangle/circle collision with edge-inclusive tangency. */ +export function rectIntersectsCircle(rect: Rect, circle: Circle): boolean { + return rectBoundsIntersectCircle( + rect.x, + rect.y, + rect.x + rect.width, + rect.y + rect.height, + circle.x, + circle.y, + circle.radius, + ); +} + +/** Rectangle collision requiring positive overlap; touching edges do not collide. */ +export function rectsIntersect(a: Rect, b: Rect): boolean { + return rectBoundsIntersect( + a.x, + a.y, + a.x + a.width, + a.y + a.height, + b.x, + b.y, + b.x + b.width, + b.y + b.height, + ); +} + +/** Whether `inner` lies entirely inside `outer`, edges inclusive. */ +export function rectContainsRect(outer: Rect, inner: Rect): boolean { + return ( + inner.x >= outer.x && + inner.y >= outer.y && + inner.x + inner.width <= outer.x + outer.width && + inner.y + inner.height <= outer.y + outer.height + ); +} + +/** Euclidean distance between two points. */ +export function distance(a: Point, b: Point): number { + return Math.hypot(a.x - b.x, a.y - b.y); +} + +/** Euclidean distance from a point to a rectangle; zero inside its bounds. */ +export function distanceToRect(point: Point, rect: Rect): number { + if (pointIntersectsRect(point, rect)) return 0; + const x = Math.max(rect.x, Math.min(point.x, rect.x + rect.width)); + const y = Math.max(rect.y, Math.min(point.y, rect.y + rect.height)); + return Math.hypot(point.x - x, point.y - y); +} + +/** The center point of a rectangle. */ +export function rectCenter(rect: Rect): Point { + return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; +} + +/** The area of a rectangle. */ +export function rectArea(rect: Size): number { + return rect.width * rect.height; +} + +/** + * Whether two rectangles match within `tolerance` on every component. + * The default tolerance of zero requires exact equality. + */ +export function rectsEqual(a: Rect, b: Rect, tolerance = 0): boolean { + return ( + Math.abs(a.x - b.x) <= tolerance && + Math.abs(a.y - b.y) <= tolerance && + Math.abs(a.width - b.width) <= tolerance && + Math.abs(a.height - b.height) <= tolerance + ); +} + +// --------------------------------------------------------------------------- +// Construction and mapping. +// --------------------------------------------------------------------------- + +/** A frozen copy holding only the rectangle fields of `rect`. */ +export function freezeRect(rect: Rect): Rect { + return Object.freeze({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }); +} + +/** A frozen `Bounds` for `rect`, with edge coordinates precomputed. */ +export function boundsOf(rect: Rect): Bounds { + return Object.freeze({ + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + left: rect.x, + top: rect.y, + right: rect.x + rect.width, + bottom: rect.y + rect.height, + }); +} + +/** The smallest rectangle containing every rectangle, or `null` when empty. */ +export function boundingRect(rects: Iterable): Rect | null { + let left = Infinity; + let top = Infinity; + let right = -Infinity; + let bottom = -Infinity; + for (const rect of rects) { + 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); + } + if (left === Infinity) return null; + return { x: left, y: top, width: right - left, height: bottom - top }; +} + +/** `rect` moved by `(dx, dy)`. */ +export function translateRect(rect: Rect, dx: number, dy: number): Rect { + return { + x: rect.x + dx, + y: rect.y + dy, + width: rect.width, + height: rect.height, + }; +} + +/** Linear interpolation between two rectangles; `t = 0` is `from`. */ +export function lerpRect(from: Rect, to: Rect, t: number): Rect { + return { + x: from.x + (to.x - from.x) * t, + y: from.y + (to.y - from.y) * t, + width: from.width + (to.width - from.width) * t, + height: from.height + (to.height - from.height) * t, + }; +} + +/** + * Map `rect` from the `from` frame into the `to` frame. + * + * The frames' size ratio scales position and size; a degenerate (zero-size) + * `from` axis maps with scale 1 so the result stays finite. + */ +export function projectRect(rect: Rect, from: Rect, to: Rect): Rect { + const scaleX = from.width > 0 ? to.width / from.width : 1; + const scaleY = from.height > 0 ? to.height / from.height : 1; + return { + x: to.x + (rect.x - from.x) * scaleX, + y: to.y + (rect.y - from.y) * scaleY, + width: rect.width * scaleX, + height: rect.height * scaleY, + }; +} + +/** Map every rectangle from the `from` frame into the `to` frame. */ +export function projectRects( + rects: readonly Rect[], + from: Rect, + to: Rect, +): Rect[] { + return rects.map((rect) => projectRect(rect, from, to)); +} + +// --------------------------------------------------------------------------- +// Box model. +// --------------------------------------------------------------------------- + +/** The per-side sum of two edge sets. */ +export function addEdges(a: Edges, b: Edges): Edges { + return { + top: a.top + b.top, + right: a.right + b.right, + bottom: a.bottom + b.bottom, + left: a.left + b.left, + }; +} + +/** `rect` shrunk by `edges`; the resulting size is clamped at zero. */ +export function insetRect(rect: Rect, edges: Edges): Rect { + return { + x: rect.x + edges.left, + y: rect.y + edges.top, + width: Math.max(0, rect.width - edges.left - edges.right), + height: Math.max(0, rect.height - edges.top - edges.bottom), + }; +} + +/** `rect` grown by `edges`. */ +export function outsetRect(rect: Rect, edges: Edges): Rect { + return { + x: rect.x - edges.left, + y: rect.y - edges.top, + width: rect.width + edges.left + edges.right, + height: rect.height + edges.top + edges.bottom, + }; +} + +/** Offset of the content box's top-left corner from the border box's. */ +export function contentOffset(box: BoxModel): Point { + return { + x: box.border.left + box.padding.left, + y: box.border.top + box.padding.top, + }; +} + +/** The padding box: the border box inset by the border. */ +export function paddingRect(box: BoxModel): Rect { + return insetRect(box, box.border); +} + +/** The content box: the border box inset by border and padding. */ +export function contentRect(box: BoxModel): Rect { + return insetRect(box, addEdges(box.border, box.padding)); +} + +/** The margin box: the border box grown by the margin. */ +export function marginRect(box: BoxModel): Rect { + return outsetRect(box, box.margin); +} + +/** CSS shorthand (`"1px 2px 3px 4px"`) for an edge set. */ +export function edgesToCss(edges: Edges): string { + return `${edges.top}px ${edges.right}px ${edges.bottom}px ${edges.left}px`; +} diff --git a/src/index.ts b/src/index.ts index aa2ea541..ff5b01eb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,18 @@ import { BaseObject, ObjectTransform, } from "./object"; -import type { DomElement, DomProperty } from "./object"; +import type { DomElement, TransformProperty } from "./object"; +import type { + Point, + Size, + Rect, + Circle, + Edges, + Bounds, + BoxModel, + ElementBox, + PointerPosition, +} from "./geometry"; import { GlobalManager } from "./global"; import type { FrameCallback, @@ -30,16 +41,19 @@ import type { PinchSnapshot, GestureHandoffControl, InputControlConfig, - eventPosition, } from "./input"; +import { measureElementBox, EventProxyFactory, mergeDefined } from "./util"; import { - getDomProperty, - cloneDomProperty, - EventProxyFactory, - mergeDefined, -} from "./util"; -import { Camera } from "./camera"; -import type { CameraConfig } from "./camera"; + Camera, + pointerPositionFromScreen, + pointerPositionFromWorld, + worldRectFromScreenRect, +} from "./camera"; +import type { + CameraConfig, + ScreenToWorldMapper, + WorldToScreenMapper, +} from "./camera"; export { Engine, @@ -50,8 +64,10 @@ export { GlobalManager, Camera, InputControl, - getDomProperty, - cloneDomProperty, + measureElementBox, + pointerPositionFromScreen, + pointerPositionFromWorld, + worldRectFromScreenRect, EventProxyFactory, mergeDefined, type pointerDownProp, @@ -72,10 +88,20 @@ export { type FrameController, type FrameInfo, type FrameSubscribeOptions, - type eventPosition, type EdgePanController, type DomElement, - type DomProperty, + type TransformProperty, + type Point, + type Size, + type Rect, + type Circle, + type Edges, + type Bounds, + type BoxModel, + type ElementBox, + type PointerPosition, type CameraConfig, + type ScreenToWorldMapper, + type WorldToScreenMapper, mouseButtonBitmap, }; diff --git a/src/input.ts b/src/input.ts index 3b23753e..7336bb12 100644 --- a/src/input.ts +++ b/src/input.ts @@ -1,6 +1,8 @@ import type { GlobalManager } from "./global"; import { BaseObject, ElementObject } from "./object"; import type { DomElement } from "./object"; +import { pointIntersectsBounds, type PointerPosition } from "./geometry"; +import { pointerPositionFromScreen } from "./camera"; import { reportConsumerError } from "./errors"; export enum mouseButton { @@ -19,19 +21,10 @@ export enum mouseButtonBitmap { FORWARD = 16, } -export interface eventPosition { - x: number; - y: number; - cameraX: number; - cameraY: number; - screenX: number; - screenY: number; -} - export interface pointerDownProp { event: PointerEvent; objectId: string | null; - position: eventPosition; + position: PointerPosition; button: number; isWithinEngine: boolean; } @@ -39,14 +32,14 @@ export interface pointerDownProp { export interface pointerMoveProp { event: PointerEvent | null; objectId: string | null; - position: eventPosition; + position: PointerPosition; button: number; } export interface pointerUpProp { event: PointerEvent; objectId: string | null; - position: eventPosition; + position: PointerPosition; button: number; cancelled: boolean; } @@ -58,7 +51,7 @@ export interface GestureHandoffControl { export interface mouseWheelProp { event: WheelEvent; objectId: string | null; - position: eventPosition; + position: PointerPosition; delta: number; } @@ -71,7 +64,7 @@ export interface keyDownProp { export interface dragStartProp extends GestureHandoffControl { objectId: string | null; pointerId: number; - start: eventPosition; + start: PointerPosition; button: number; isWithinEngine: boolean; } @@ -79,9 +72,9 @@ export interface dragStartProp extends GestureHandoffControl { export interface dragProp extends GestureHandoffControl { objectId: string | null; pointerId: number; - start: eventPosition; - position: eventPosition; - delta: eventPosition; + start: PointerPosition; + position: PointerPosition; + delta: PointerPosition; button: number; } @@ -89,14 +82,14 @@ export interface dragEndProp { event: PointerEvent; objectId: string | null; pointerId: number; - start: eventPosition; - end: eventPosition; + start: PointerPosition; + end: PointerPosition; button: number; cancelled: boolean; } export interface PinchSnapshot { - pointerList: eventPosition[]; + pointerList: PointerPosition[]; distance: number; } @@ -979,33 +972,12 @@ class InputControl { this.#dispatchGlobalEvent("keyDown", prop); }; - #getCoordinates(screenX: number, screenY: number): eventPosition { - if (this.#engine == null || this.#engine.camera == null) { - return { - x: screenX, - y: screenY, - cameraX: screenX, - cameraY: screenY, - screenX, - screenY, - }; - } - const [cameraX, cameraY] = this.#engine.camera.getCameraFromScreen( + #getCoordinates(screenX: number, screenY: number): PointerPosition { + return pointerPositionFromScreen( + this.#engine?.camera ?? null, screenX, screenY, ); - const [worldX, worldY] = this.#engine.camera.getWorldFromCamera( - cameraX, - cameraY, - ); - return { - x: worldX, - y: worldY, - cameraX, - cameraY, - screenX, - screenY, - }; } #handleDrag(pointer: TrackedPointer) { @@ -1071,10 +1043,14 @@ class InputControl { delta: { x: position.x - start.x, y: position.y - start.y, - cameraX: position.cameraX - start.cameraX, - cameraY: position.cameraY - start.cameraY, - screenX: position.screenX - start.screenX, - screenY: position.screenY - start.screenY, + camera: { + x: position.camera.x - start.camera.x, + y: position.camera.y - start.camera.y, + }, + screen: { + x: position.screen.x - start.screen.x, + y: position.screen.y - start.screen.y, + }, }, button: pointer.button, handoffTo: (objectOrId) => this.#handoffDrag(pointer.id, objectOrId), @@ -1358,11 +1334,13 @@ class InputControl { if (rect == null) { return true; } - return ( - screenX >= rect.left && - screenX <= rect.right && - screenY >= rect.top && - screenY <= rect.bottom + return pointIntersectsBounds( + screenX, + screenY, + rect.left, + rect.top, + rect.right, + rect.bottom, ); } diff --git a/assets/snapsort/src/layout.ts b/src/layout.ts similarity index 59% rename from assets/snapsort/src/layout.ts rename to src/layout.ts index 3fa4ecd2..721e2f57 100644 --- a/assets/snapsort/src/layout.ts +++ b/src/layout.ts @@ -1,9 +1,59 @@ -import type { DomProperty } from "@snap-engine/core"; -import type { ItemSnapshot, LayoutDirection, LayoutWrap } from "./snapshot"; +/** + * Layout simulation over measured box trees. + * + * Given a frozen tree of measured boxes (typically captured from the DOM at + * the start of a gesture), this module infers the metrics the browser used — + * content-box start offsets, main/cross gaps, line sizes, wrap capacity — and + * re-runs that layout with nodes removed and virtual entries inserted. It + * never reads the DOM, so a plan built from one snapshot answers any number + * of "what if" questions without layout thrash. + * + * Two backends share one plan: + * - `flow` re-accumulates entries along the main axis and wraps them against + * the measured capacity (flexbox-style flow). + * - `slots` places entries into measured track positions by index, the basis + * for simulating CSS grid. + */ +import { + addEdges, + contentOffset, + contentRect, + outsetRect, + type Axis, + type BoxModel, + type Dimension, + type Edges, + type Point, + type Rect, + type Size, +} from "./geometry"; + +/** Main-axis direction of a layout container. */ +export type LayoutDirection = "column" | "row"; + +/** Main-axis alignment of a layout container's lines. */ +export type LayoutMainAxisAlign = "start" | "center"; + +/** Layout backend: accumulated flow, or measured grid slots. */ +export type LayoutModel = "flow" | "slots"; + +/** Whether a flow container may wrap onto additional lines. */ +export type LayoutWrap = "auto" | "nowrap"; + +/** + * One node in a measured layout tree. Leaves only need `box`; containers + * also describe how they lay out their `children`. + */ +export interface LayoutNode> { + readonly box: BoxModel; + readonly children: readonly Child[]; + readonly direction: LayoutDirection; + readonly mainAxisAlign: LayoutMainAxisAlign; + readonly layoutModel: LayoutModel; + readonly wrap: LayoutWrap; + readonly stretchItems: boolean; +} -export type { LayoutDirection, LayoutMainAxisAlign } from "./snapshot"; -type AxisName = "x" | "y"; -type SizeName = "width" | "height"; /** * Tolerance for main-axis wrap comparisons. Measured geometry is noisy well * beyond double-precision: browsers lay out on a snapped grid (Blink 1/64px, @@ -19,23 +69,37 @@ type SizeName = "width" | "height"; * genuinely overflow would under-wrap; 0.05px sits ~5x above the worst * observed noise and ~100x below typical feature scale. */ -const LAYOUT_EPSILON = 0.05; -const LINE_RESET_EPSILON = 1; +export const LAYOUT_WRAP_TOLERANCE = 0.05; -/** @internal Whether measured main-axis coordinates begin a wrapped line. */ +/** + * How far a measured main-axis start must move backwards before it counts + * as the start of a new visual line, absorbing sub-pixel jitter between + * items on the same line. + */ +export const LAYOUT_LINE_BREAK_TOLERANCE = 1; + +/** + * Maximum spread between inter-row residuals for a slot grid to count as + * content-sized rows (rows that grow with their tallest entry) rather than + * fixed template tracks. + */ +const SLOT_ROW_RESIDUAL_TOLERANCE = 0.75; + +/** Whether measured main-axis coordinates begin a wrapped line. */ export function startsNewVisualLine( wrap: LayoutWrap, previousMainStart: number, nextMainStart: number, ): boolean { return ( - wrap !== "nowrap" && nextMainStart < previousMainStart - LINE_RESET_EPSILON + wrap !== "nowrap" && + nextMainStart < previousMainStart - LAYOUT_LINE_BREAK_TOLERANCE ); } -/** @internal Whether a measured flow layout can create another visual line. */ -export function flowLayoutCanWrap( - container: ItemSnapshot, +/** Whether a measured flow layout can create another visual line. */ +export function flowLayoutCanWrap>( + container: N, axes: FlowAxes, measuredLineCount: number, ): boolean { @@ -45,14 +109,16 @@ export function flowLayoutCanWrap( ); } +/** Axis and dimension names for a flow direction. */ export interface FlowAxes { readonly direction: LayoutDirection; - readonly main: AxisName; - readonly cross: AxisName; - readonly mainSize: SizeName; - readonly crossSize: SizeName; + readonly main: Axis; + readonly cross: Axis; + readonly mainSize: Dimension; + readonly crossSize: Dimension; } +/** Layout metrics inferred from a container's measured children. */ export interface FlowMetrics { readonly mainStart: number; readonly crossStart: number; @@ -72,83 +138,92 @@ export interface FlowMetrics { readonly measuredMainExtent: number; } -/** @internal One measured visual line in content-box-relative coordinates. */ -export interface SnapshotVisualLine { - readonly snapshots: readonly ItemSnapshot[]; +/** One measured visual line in content-box-relative coordinates. */ +export interface VisualLine { + readonly nodes: readonly N[]; readonly crossStart: number; readonly crossSize: number; } -export interface LayoutFilter { - excludeSnapshots?: Set>; - excludeValues?: Set; +/** The size and margins of an entry that is not (yet) in the tree. */ +export interface VirtualEntry extends Size { + readonly margin: Edges; } -export interface VirtualLayoutEntry { - width: number; - height: number; - margin: DomProperty["margin"]; +/** A virtual entry inserted into `container` before child `index`. */ +export interface VirtualInsertion { + readonly container: N; + readonly index: number; + readonly entry: VirtualEntry; } -export interface VirtualInsertion { - container: ItemSnapshot; - index: number; - entry: VirtualLayoutEntry; +/** Simulated positions for one container's children and virtual entries. */ +export interface LayoutPositions { + readonly itemPositions: Map; + readonly virtualRects: Map, Rect>; } -export interface VirtualDimensions { - width: number; - height: number; +/** Deterministic work-count hooks for tests. */ +export interface LayoutPlanDiagnostics { + onNodeVisit?: (node: N) => void; } -export interface FlowPositionResult { - itemPositions: Map, { x: number; y: number }>; - virtualRects: Map< - VirtualInsertion, - { x: number; y: number; width: number; height: number } - >; +/** Options for {@link createLayoutResolutionPlan}. */ +export interface LayoutPlanOptions { + /** Children to leave out of the layout (for example, dragged nodes). */ + 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; } -type FlowEntry = - | { kind: "item"; item: ItemSnapshot; width: number; height: number } +/** The cached layout inputs for one container in a resolution plan. */ +export interface LayoutContainerPlan { + readonly container: N; + readonly axes: FlowAxes; + readonly contentSize: Size; + readonly metrics: FlowMetrics; + readonly eligibleChildren: readonly N[]; +} + +/** An immutable layout plan for one frozen tree. */ +export interface LayoutResolutionPlan { + containerPlan(container: N): LayoutContainerPlan; + layoutPositions( + container: N, + startX: number, + startY: number, + localInsertions?: readonly VirtualInsertion[], + ): LayoutPositions; + virtualDimensions(container: N): Size; +} + +type FlowEntry = + | { kind: "item"; item: N; width: number; height: number } | { kind: "virtual"; - insertion: VirtualInsertion; + insertion: VirtualInsertion; width: number; height: number; }; -interface FlowLine { - entries: FlowEntry[]; +interface FlowLine { + entries: FlowEntry[]; mainSize: number; crossSize: number; } -export interface LayoutPlanDiagnostics { - // Internal deterministic work-count hook; not exported by the package root. - onSnapshotVisit?: (snapshot: ItemSnapshot) => void; -} - -export interface LayoutContainerPlan { - readonly snapshot: ItemSnapshot; - readonly axes: FlowAxes; - readonly contentSize: Readonly<{ width: number; height: number }>; - readonly metrics: FlowMetrics; - readonly eligibleChildren: readonly ItemSnapshot[]; -} - -export interface LayoutResolutionPlan { - containerPlan(container: ItemSnapshot): LayoutContainerPlan; - layoutPositions( - container: ItemSnapshot, - startX: number, - startY: number, - localInsertions?: readonly VirtualInsertion[], - ): FlowPositionResult; - virtualDimensions(container: ItemSnapshot): VirtualDimensions; -} - -function trailingMainMargin(entry: FlowEntry, axes: FlowAxes): number { +function trailingMainMargin>( + entry: FlowEntry, + axes: FlowAxes, +): number { const margin = entry.kind === "item" ? entry.item.box.margin @@ -156,6 +231,7 @@ function trailingMainMargin(entry: FlowEntry, axes: FlowAxes): number { return axes.main === "x" ? margin.right : margin.bottom; } +/** Axis and dimension names for `direction`. */ export function flowAxesForDirection(direction: LayoutDirection): FlowAxes { if (direction === "row") { return { @@ -176,97 +252,64 @@ export function flowAxesForDirection(direction: LayoutDirection): FlowAxes { }; } +/** A point from main- and cross-axis coordinates. */ export function pointFromAxes( axes: FlowAxes, main: number, cross: number, -): { x: number; y: number } { +): Point { return axes.main === "x" ? { x: main, y: cross } : { x: cross, y: main }; } -export function contentBoxOrigin(prop: DomProperty): { x: number; y: number } { - return { - x: prop.x + prop.border.left + prop.padding.left, - y: prop.y + prop.border.top + prop.padding.top, - }; -} - -export function contentBoxSize(prop: DomProperty): { - width: number; - height: number; -} { +/** `child`'s offset from `container`'s content-box origin. */ +export function childRelativeOffset(container: BoxModel, child: Point): Point { + const offset = contentOffset(container); return { - width: Math.max( - 0, - prop.width - - prop.border.left - - prop.border.right - - prop.padding.left - - prop.padding.right, - ), - height: Math.max( - 0, - prop.height - - prop.border.top - - prop.border.bottom - - prop.padding.top - - prop.padding.bottom, - ), + x: child.x - container.x - offset.x, + y: child.y - container.y - offset.y, }; } -export function childRelativeOffset( - containerProp: DomProperty, - childProp: DomProperty, -): { x: number; y: number } { - const origin = contentBoxOrigin(containerProp); - return { - x: childProp.x - origin.x, - y: childProp.y - origin.y, - }; -} - -export function layoutItems( - container: ItemSnapshot, - filter: LayoutFilter = {}, -): ItemSnapshot[] { - return container.children.filter( - (item) => - !filter.excludeSnapshots?.has(item) && - !filter.excludeValues?.has(item.value), - ); +/** `container`'s children, minus any `exclude` rejects. */ +export function layoutChildren>( + container: N, + exclude?: (node: N) => boolean, +): N[] { + return exclude + ? container.children.filter((child) => !exclude(child)) + : container.children.slice(); } /** - * Infer measured visual lines once from the frozen snapshot. Layout metrics - * and insertion geometry share this boundary detection so their understanding - * of wrapping cannot drift apart. + * Infer measured visual lines once from the frozen tree. Layout metrics and + * insertion geometry share this boundary detection so their understanding of + * wrapping cannot drift apart. */ -export function inferSnapshotVisualLines( - container: ItemSnapshot, +export function inferVisualLines>( + container: N, axes: FlowAxes, -): readonly SnapshotVisualLine[] { +): readonly VisualLine[] { const lines: Array<{ - snapshots: ItemSnapshot[]; + nodes: N[]; crossStart: number; crossEnd: number; }> = []; let previousMainStart: number | null = null; - for (const snapshot of container.children) { - const offset = childRelativeOffset(container.box, snapshot.box); + for (const node of container.children) { + const offset = childRelativeOffset(container.box, node.box); const mainStart = offset[axes.main]; const startsNewLine = previousMainStart !== null && startsNewVisualLine(container.wrap, previousMainStart, mainStart); const crossStart = offset[axes.cross]; - const crossEnd = crossStart + snapshot.box[axes.crossSize]; + const crossEnd = crossStart + node.box[axes.crossSize]; if (lines.length === 0 || startsNewLine) { - lines.push({ snapshots: [snapshot], crossStart, crossEnd }); + lines.push({ nodes: [node], crossStart, crossEnd }); } else { const line = lines[lines.length - 1]; - line.snapshots.push(snapshot); + line.nodes.push(node); line.crossStart = Math.min(line.crossStart, crossStart); line.crossEnd = Math.max(line.crossEnd, crossEnd); } @@ -276,7 +319,7 @@ export function inferSnapshotVisualLines( return Object.freeze( lines.map((line) => Object.freeze({ - snapshots: Object.freeze([...line.snapshots]), + nodes: Object.freeze([...line.nodes]), crossStart: line.crossStart, crossSize: Math.max(0, line.crossEnd - line.crossStart), }), @@ -294,27 +337,24 @@ function median(values: number[]): number { } /** - * Size a virtual insertion entry for its *destination* container. The single - * source of entry sizing for candidate simulation and the real flow spacer. + * Size a virtual entry for its *destination* container. * * For a `stretchItems` container the entry fills the container's cross axis * (width in column lists, height in row lists): content-box cross size minus * the entry's own cross margins, clamped to >= 0. The main-axis size always - * stays the dragged item's own — a todo item's height is content-driven. - * Without `stretchItems` the base size passes through unchanged (today's - * behavior). Keeping ghost rects destination-sized is what makes candidate - * center points correct when dragging between containers of different - * widths (e.g. from a parent list into a narrower nested list). + * stays the entry's own. Without `stretchItems` the base size passes through + * unchanged. Keeping virtual rects destination-sized keeps their centers + * correct when an entry moves between containers of different widths. */ -export function virtualEntrySizeFor( - container: ItemSnapshot, - base: { width: number; height: number; margin: DomProperty["margin"] }, -): { width: number; height: number } { +export function virtualEntrySizeFor>( + container: N, + base: VirtualEntry, +): Size { if (!container.stretchItems) { return { width: base.width, height: base.height }; } const axes = flowAxesForDirection(container.direction); - const content = contentBoxSize(container.box); + const content = contentRect(container.box); const crossMargins = axes.cross === "x" ? base.margin.left + base.margin.right @@ -325,8 +365,9 @@ export function virtualEntrySizeFor( : { width: base.width, height: cross }; } -export function inferFlowLayoutMetrics( - container: ItemSnapshot, +/** Infer start offsets, gaps, and line sizes from measured children. */ +export function inferFlowLayoutMetrics>( + container: N, axes: FlowAxes, ): FlowMetrics { const ordered = container.children; @@ -344,11 +385,11 @@ export function inferFlowLayoutMetrics( const firstOffset = childRelativeOffset(container.box, ordered[0].box); const mainGaps: number[] = []; - const visualLines = inferSnapshotVisualLines(container, axes); - const lineBySnapshot = new Map, SnapshotVisualLine>(); + const visualLines = inferVisualLines(container, axes); + const lineByNode = new Map>(); for (const line of visualLines) { - for (const snapshot of line.snapshots) { - lineBySnapshot.set(snapshot, line); + for (const node of line.nodes) { + lineByNode.set(node, line); } } let measuredMainExtent = 0; @@ -367,8 +408,7 @@ export function inferFlowLayoutMetrics( const next = ordered[i + 1]; if (next) { const nextOffset = childRelativeOffset(container.box, next.box); - const nextStartsNewLine = - lineBySnapshot.get(item) !== lineBySnapshot.get(next); + const nextStartsNewLine = lineByNode.get(item) !== lineByNode.get(next); if (!nextStartsNewLine) { const gap = nextOffset[axes.main] - (offset[axes.main] + item.box[axes.mainSize]); @@ -396,14 +436,7 @@ export function inferFlowLayoutMetrics( }; } -interface SlotRect { - readonly x: number; - readonly y: number; - readonly width: number; - readonly height: number; -} - -interface SlotEntryRect extends SlotRect { +interface SlotEntryRect extends Rect { readonly line: number; readonly crossOffset: number; } @@ -412,14 +445,15 @@ interface FlowBackendPlan { readonly kind: "flow"; readonly canWrap: boolean; readonly mainCapacity: number; + readonly wrapTolerance: number; } interface SlotBackendPlan { readonly kind: "slots"; - readonly slots: readonly SlotRect[]; - readonly fillAxis: AxisName; - readonly crossAxis: AxisName; - readonly crossSizeName: SizeName; + readonly slots: readonly Rect[]; + readonly fillAxis: Axis; + readonly crossAxis: Axis; + readonly crossSizeName: Dimension; readonly lineOfSlot: readonly number[]; readonly lineCrossStarts: readonly number[]; readonly lineMaxItemCross: readonly number[]; @@ -430,29 +464,22 @@ interface SlotBackendPlan { type LayoutBackendPlan = FlowBackendPlan | SlotBackendPlan; -interface ContainerPlanGeometry extends LayoutContainerPlan { - readonly entries: readonly FlowEntry[]; +interface ContainerPlanGeometry extends LayoutContainerPlan { + readonly entries: readonly FlowEntry[]; readonly backend: LayoutBackendPlan; } -interface InternalContainerPlan extends ContainerPlanGeometry { - readonly baseDimensions: VirtualDimensions; +interface InternalContainerPlan extends ContainerPlanGeometry { + readonly baseDimensions: Size; } -function localInsertionsFor( - container: ItemSnapshot, - insertions: readonly VirtualInsertion[], -): VirtualInsertion[] { - return insertions.filter((insertion) => insertion.container === container); -} - -function materializeEntries( - plan: ContainerPlanGeometry, - insertions: readonly VirtualInsertion[], -): FlowEntry[] { +function materializeEntries>( + plan: ContainerPlanGeometry, + insertions: readonly VirtualInsertion[], +): FlowEntry[] { const entries = plan.entries.slice(); for (const insertion of insertions) { - if (insertion.container !== plan.snapshot) continue; + if (insertion.container !== plan.container) continue; entries.splice(Math.max(0, Math.min(insertion.index, entries.length)), 0, { kind: "virtual", insertion, @@ -463,8 +490,10 @@ function materializeEntries( return entries; } -function createSlotBackendPlan(container: ItemSnapshot): SlotBackendPlan { - // Slots remain unfiltered: the dragged item's measured box is still valid +function createSlotBackendPlan>( + container: N, +): SlotBackendPlan { + // Slots remain unfiltered: an excluded child's measured box is still valid // geometry for whichever entry shifts into that slot. const slots = container.children.map((child) => { const rel = childRelativeOffset(container.box, child.box); @@ -475,13 +504,13 @@ function createSlotBackendPlan(container: ItemSnapshot): SlotBackendPlan { height: child.box.height, }); }); - const fillAxis: AxisName = + const fillAxis: Axis = slots.length >= 2 && Math.abs(slots[1].y - slots[0].y) > Math.abs(slots[1].x - slots[0].x) ? "y" : "x"; - const crossAxis: AxisName = fillAxis === "x" ? "y" : "x"; - const crossSizeName: SizeName = fillAxis === "x" ? "height" : "width"; + const crossAxis: Axis = fillAxis === "x" ? "y" : "x"; + const crossSizeName: Dimension = fillAxis === "x" ? "height" : "width"; // Accumulate line membership, starts, and maxima together. Candidate // materialization can then reuse this measured geometry without rescanning @@ -492,7 +521,9 @@ function createSlotBackendPlan(container: ItemSnapshot): SlotBackendPlan { const lineLengths: number[] = []; for (let index = 0; index < slots.length; index++) { const startsNewLine = - index === 0 || slots[index][fillAxis] < slots[index - 1][fillAxis] - 1; + index === 0 || + slots[index][fillAxis] < + slots[index - 1][fillAxis] - LAYOUT_LINE_BREAK_TOLERANCE; if (startsNewLine) { lineCrossStarts.push(slots[index][crossAxis]); lineMaxItemCross.push(slots[index][crossSizeName]); @@ -521,7 +552,10 @@ function createSlotBackendPlan(container: ItemSnapshot): SlotBackendPlan { } const contentSizedRows = residuals.length === 0 || - residuals.every((residual) => Math.abs(residual - residuals[0]) <= 0.75); + residuals.every( + (residual) => + Math.abs(residual - residuals[0]) <= SLOT_ROW_RESIDUAL_TOLERANCE, + ); return Object.freeze({ kind: "slots", @@ -562,12 +596,12 @@ function slotForEntry(backend: SlotBackendPlan, index: number): SlotEntryRect { * separate: slot position is a function of index and measured track geometry, * while flow position is accumulated from entry dimensions. */ -function materializeSlotLayout( +function materializeSlotLayout>( backend: SlotBackendPlan, startX: number, startY: number, - entries: FlowEntry[], -): FlowPositionResult { + entries: FlowEntry[], +): LayoutPositions { const entrySlots = entries.map((_, index) => slotForEntry(backend, index)); const lineCount = entrySlots.length ? Math.max(...entrySlots.map((slot) => slot.line)) + 1 @@ -603,11 +637,8 @@ function materializeSlotLayout( } } - const itemPositions = new Map, { x: number; y: number }>(); - const virtualRects = new Map< - VirtualInsertion, - { x: number; y: number; width: number; height: number } - >(); + const itemPositions = new Map(); + const virtualRects = new Map, Rect>(); for (let index = 0; index < entries.length; index++) { const entry = entries[index]; const slot = entrySlots[index]; @@ -641,16 +672,16 @@ function materializeSlotLayout( return { itemPositions, virtualRects }; } -function materializeFlowLayout( - plan: ContainerPlanGeometry, +function materializeFlowLayout>( + plan: ContainerPlanGeometry, backend: FlowBackendPlan, startX: number, startY: number, - entries: FlowEntry[], -): FlowPositionResult { - const { axes, contentSize, metrics, snapshot: container } = plan; - const lines: FlowLine[] = []; - let currentLine: FlowLine = { entries: [], mainSize: 0, crossSize: 0 }; + entries: FlowEntry[], +): LayoutPositions { + const { axes, contentSize, metrics, container } = plan; + const lines: FlowLine[] = []; + let currentLine: FlowLine = { entries: [], mainSize: 0, crossSize: 0 }; const pushCurrentLine = () => { if (currentLine.entries.length === 0) return; lines.push(currentLine); @@ -669,7 +700,7 @@ function materializeFlowLayout( metrics.mainGap + entryMainSize + entryTrailingMainMargin > - backend.mainCapacity + LAYOUT_EPSILON + backend.mainCapacity + backend.wrapTolerance ) { pushCurrentLine(); } @@ -682,11 +713,8 @@ function materializeFlowLayout( } pushCurrentLine(); - const itemPositions = new Map, { x: number; y: number }>(); - const virtualRects = new Map< - VirtualInsertion, - { x: number; y: number; width: number; height: number } - >(); + const itemPositions = new Map(); + const virtualRects = new Map, Rect>(); const origin = { x: startX, y: startY }; let cursorCross = origin[axes.cross] + metrics.crossStart; for (const line of lines) { @@ -714,28 +742,28 @@ function materializeFlowLayout( return { itemPositions, virtualRects }; } -function materializeLayout( - plan: ContainerPlanGeometry, +function materializeLayout>( + plan: ContainerPlanGeometry, startX: number, startY: number, - localInsertions: readonly VirtualInsertion[], -): FlowPositionResult { + localInsertions: readonly VirtualInsertion[], +): LayoutPositions { const entries = materializeEntries(plan, localInsertions); return plan.backend.kind === "slots" ? materializeSlotLayout(plan.backend, startX, startY, entries) : materializeFlowLayout(plan, plan.backend, startX, startY, entries); } -function dimensionsFromLayout( - plan: ContainerPlanGeometry, - localInsertions: readonly VirtualInsertion[], -): VirtualDimensions { +function dimensionsFromLayout>( + plan: ContainerPlanGeometry, + localInsertions: readonly VirtualInsertion[], +): Size { const positions = materializeLayout(plan, 0, 0, localInsertions); let maxX = 0; let maxY = 0; for (const entry of plan.entries) { if (entry.kind !== "item") continue; - const rel = childRelativeOffset(plan.snapshot.box, entry.item.box); + const rel = childRelativeOffset(plan.container.box, entry.item.box); const position = positions.itemPositions.get(entry.item) ?? rel; maxX = Math.max(maxX, position.x + entry.width); maxY = Math.max(maxY, position.y + entry.height); @@ -745,69 +773,54 @@ function dimensionsFromLayout( maxY = Math.max(maxY, rect.y + rect.height); } - const container = plan.snapshot; - const snapshotSize = { - width: container.box.width, - height: container.box.height, - }; + const box = plan.container.box; if (plan.entries.length === 0 && localInsertions.length === 0) { - return snapshotSize; + return { width: box.width, height: box.height }; } - const virtualSize = { - width: - container.box.border.left + - container.box.padding.left + - maxX + - container.box.padding.right + - container.box.border.right, - height: - container.box.border.top + - container.box.padding.top + - maxY + - container.box.padding.bottom + - container.box.border.bottom, - }; + const virtualSize = outsetRect( + { x: 0, y: 0, width: maxX, height: maxY }, + addEdges(box.border, box.padding), + ); return plan.axes.direction === "row" - ? { - width: snapshotSize.width, - height: Math.max(snapshotSize.height, virtualSize.height), - } - : { width: snapshotSize.width, height: virtualSize.height }; + ? { width: box.width, height: Math.max(box.height, virtualSize.height) } + : { width: box.width, height: virtualSize.height }; } /** - * Build one immutable layout plan for a frozen drop-target resolution. - * Descendant active insertions are folded into cached child dimensions, while - * `layoutPositions` accepts the local insertion that replaces the container's - * current pending ghost for an individual candidate. + * Build one immutable layout plan for a frozen tree. + * + * Every container's inputs are computed once and cached. `insertions` are + * folded into each container's cached dimensions, while `layoutPositions` + * accepts the local insertions for an individual candidate layout. */ -export function createLayoutResolutionPlan( - root: ItemSnapshot, - options: { - filter?: LayoutFilter; - insertions?: readonly VirtualInsertion[]; - diagnostics?: LayoutPlanDiagnostics; - } = {}, -): LayoutResolutionPlan { - const filter = options.filter ?? {}; +export function createLayoutResolutionPlan>( + root: N, + options: LayoutPlanOptions = {}, +): LayoutResolutionPlan { + const exclude = options.exclude; + const wrapTolerance = options.wrapTolerance ?? LAYOUT_WRAP_TOLERANCE; const insertions = Object.freeze([...(options.insertions ?? [])]); - const plans = new Map, InternalContainerPlan>(); + const plans = new Map>(); - const build = (container: ItemSnapshot): InternalContainerPlan => { + const build = (container: N): InternalContainerPlan => { const cached = plans.get(container); if (cached) return cached; - options.diagnostics?.onSnapshotVisit?.(container); - const eligibleChildren = Object.freeze(layoutItems(container, filter)); - const childPlans = new Map, InternalContainerPlan>(); + options.diagnostics?.onNodeVisit?.(container); + const eligibleChildren = Object.freeze(layoutChildren(container, exclude)); + const childPlans = new Map>(); for (const child of eligibleChildren) { childPlans.set(child, build(child)); } const axes = Object.freeze(flowAxesForDirection(container.direction)); - const contentSize = Object.freeze(contentBoxSize(container.box)); + const content = contentRect(container.box); + const contentSize = Object.freeze({ + width: content.width, + height: content.height, + }); const metrics = Object.freeze(inferFlowLayoutMetrics(container, axes)); const entries = Object.freeze( - eligibleChildren.map((child): FlowEntry => { + eligibleChildren.map((child): FlowEntry => { const dimensions = child.children.length > 0 ? childPlans.get(child)!.baseDimensions @@ -832,18 +845,21 @@ export function createLayoutResolutionPlan( contentSize[axes.mainSize], metrics.measuredMainExtent, ), + wrapTolerance, }); const geometry = { - snapshot: container, + container, axes, contentSize, metrics, eligibleChildren, entries, backend, - } satisfies ContainerPlanGeometry; - const localInsertions = localInsertionsFor(container, insertions); + } satisfies ContainerPlanGeometry; + const localInsertions = insertions.filter( + (insertion) => insertion.container === container, + ); const baseDimensions = Object.freeze( dimensionsFromLayout(geometry, localInsertions), ); @@ -852,61 +868,32 @@ export function createLayoutResolutionPlan( return plan; }; + const planFor = (container: N): InternalContainerPlan => { + const plan = plans.get(container); + if (!plan) throw new Error("Node is outside this layout resolution"); + return plan; + }; + build(root); return Object.freeze({ - containerPlan(container: ItemSnapshot): LayoutContainerPlan { - const plan = plans.get(container); - if (!plan) throw new Error("Snapshot is outside this layout resolution"); - return plan; + containerPlan(container: N): LayoutContainerPlan { + return planFor(container); }, layoutPositions( - container: ItemSnapshot, + container: N, startX: number, startY: number, - localInsertions: readonly VirtualInsertion[] = [], - ): FlowPositionResult { - const plan = plans.get(container); - if (!plan) throw new Error("Snapshot is outside this layout resolution"); - return materializeLayout(plan, startX, startY, localInsertions); + localInsertions: readonly VirtualInsertion[] = [], + ): LayoutPositions { + return materializeLayout( + planFor(container), + startX, + startY, + localInsertions, + ); }, - virtualDimensions(container: ItemSnapshot): VirtualDimensions { - const plan = plans.get(container); - if (!plan) throw new Error("Snapshot is outside this layout resolution"); - return plan.baseDimensions; + virtualDimensions(container: N): Size { + return planFor(container).baseDimensions; }, }); } - -export function flowLayoutPositions( - container: ItemSnapshot, - startX: number, - startY: number, - options: { - filter?: LayoutFilter; - insertions?: VirtualInsertion[]; - } = {}, -): FlowPositionResult { - const insertions = options.insertions ?? []; - const plan = createLayoutResolutionPlan(container, { - filter: options.filter, - insertions, - }); - return plan.layoutPositions( - container, - startX, - startY, - localInsertionsFor(container, insertions), - ); -} - -export function virtualDimensions( - container: ItemSnapshot, - options: { - filter?: LayoutFilter; - insertions?: VirtualInsertion[]; - } = {}, -): VirtualDimensions { - return createLayoutResolutionPlan(container, options).virtualDimensions( - container, - ); -} diff --git a/src/object.ts b/src/object.ts index 3c83dc1d..903cd356 100755 --- a/src/object.ts +++ b/src/object.ts @@ -2,11 +2,14 @@ import type { AnimationInterface } from "./animation"; import type { Collider } from "./collision"; import type { Engine } from "./engine"; import type { InputEventCallback } from "./input"; +import type { ElementBox } from "./geometry"; import { GlobalManager } from "./global"; import { + EMPTY_ELEMENT_BOX, EventProxyFactory, generateTransformString, - getDomProperty, + measureElementBox, + parseTransformOrigin, parseTransformString, setDomStyle, } from "./util"; @@ -37,23 +40,6 @@ export interface TransformProperty { type ReadonlyTransformProperty = Readonly; -export interface DomProperty extends TransformProperty { - height: number; - width: number; - screenX: number; - screenY: number; - margin: BoxSpacing; - padding: BoxSpacing; - border: BoxSpacing; -} - -interface BoxSpacing { - top: number; - right: number; - bottom: number; - left: number; -} - let transformEpoch = 0; const animationOwnerMap = new WeakMap(); @@ -89,13 +75,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 +113,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 { @@ -824,19 +837,7 @@ export class BaseObject extends CoreObject { clearAllDebugMarkers() { if (!this.engine) return; - for (const marker of Object.values(this.engine.debugMarkerList) as Array<{ - objectId: string; - id: string; - type: "point" | "rect" | "circle" | "text"; - persistent: boolean; - color: string; - x: number; - y: number; - width?: number; - height?: number; - radius?: number; - text?: string; - }>) { + for (const marker of Object.values(this.engine.debugMarkerList)) { if (marker.objectId == this.id) { delete this.engine.debugMarkerList[marker.id]; } @@ -916,44 +917,44 @@ export function detachAnimationFromOwner(animation: AnimationInterface) { owner.removeAnimationReference(animation); } -function createDomProperty(): DomProperty { - return { - x: 0, - y: 0, - height: 0, - width: 0, - scaleX: 1, - scaleY: 1, - screenX: 0, - screenY: 0, - margin: { - top: 0, - right: 0, - bottom: 0, - left: 0, - }, - padding: { - top: 0, - right: 0, - bottom: 0, - left: 0, - }, - border: { - top: 0, - right: 0, - bottom: 0, - left: 0, - }, - }; +/** + * 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 copyDomPropertyValue(target: DomProperty, source: DomProperty) { - Object.assign(target, { - ...source, - margin: { ...source.margin }, - padding: { ...source.padding }, - border: { ...source.border }, - }); +function stageBoxIndex(stage: FrameReadStages | null): number { + if (stage == "READ_1") return 0; + if (stage == "READ_2") return 1; + if (stage == "READ_3" || stage == null) return 2; + throw new Error(`Invalid stage: ${stage}`); } export class ElementObject< @@ -963,8 +964,12 @@ export class ElementObject< #style: Record = {}; #classList: string[] = []; #dataAttribute: Record = {}; - #property: DomProperty; - #domProperty: Array; + #box: ElementBox = EMPTY_ELEMENT_BOX; + #stageBoxes: [ElementBox, ElementBox, ElementBox] = [ + EMPTY_ELEMENT_BOX, + EMPTY_ELEMENT_BOX, + EMPTY_ELEMENT_BOX, + ]; #resizeObserver: ResizeObserver | null = null; #mutationObserver: MutationObserver | null = null; #state: any = {}; @@ -978,11 +983,6 @@ export class ElementObject< constructor(engine: Engine, parent: BaseObject | null = null) { super(engine, parent); - this.#property = createDomProperty(); - this.#domProperty = []; - for (let i = 0; i < 3; i++) { - this.#domProperty.push(createDomProperty()); - } this.transformMode = "direct"; this.transformOrigin = null; this.state = new Proxy(this.#state, { @@ -993,8 +993,14 @@ export class ElementObject< }); } - get currentDomProperty(): DomProperty { - return this.#property; + /** + * The element's most recent measured box. + * + * Each `readDom` produces a new frozen snapshot, so a captured box never + * changes after the fact. + */ + get box(): ElementBox { + return this.#box; } get style(): Record { @@ -1033,6 +1039,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; @@ -1060,43 +1075,38 @@ export class ElementObject< super.destroy(); } - getDomProperty(stage: FrameReadStages | null = null): DomProperty { - let index = 0; - if (stage == "READ_1") { - index = 0; - } else if (stage == "READ_2") { - index = 1; - } else if (stage == "READ_3" || stage == null) { - index = 2; - } else { - throw new Error(`Invalid stage: ${stage}`); - } - return this.#domProperty[index]; + /** The box captured by the last `readDom` in `stage` (default READ_3). */ + getStageBox(stage: FrameReadStages | null = null): ElementBox { + return this.#stageBoxes[stageBoxIndex(stage)]; } - copyDomProperty(fromStage: FrameReadStages, toStage: FrameReadStages): void { - copyDomPropertyValue( - this.getDomProperty(toStage), - this.getDomProperty(fromStage), - ); + /** Make `toStage` report the box captured in `fromStage`. */ + copyStageBox(fromStage: FrameReadStages, toStage: FrameReadStages): void { + this.#stageBoxes[stageBoxIndex(toStage)] = this.getStageBox(fromStage); } /** - * Save the DOM property to the transform property. - * Currently only saves the x and y properties. - * This function assumes that the element position has already been read from the DOM. + * Copy a stage box's position into this object's world transform. + * At IDLE the READ_2 box is used. Assumes the element was already read. */ - saveDomProperety(stage: FrameReadStages | null = null): void { + saveWorldPosition(stage: FrameReadStages | null = null): void { let currentStage = stage ?? this.global.currentStage; currentStage = currentStage == "IDLE" ? "READ_2" : currentStage; - const property = this.getDomProperty(currentStage as FrameReadStages); - this.worldTransform = { x: property.x, y: property.y }; + const box = this.getStageBox(currentStage as FrameReadStages); + this.worldTransform = { x: box.x, y: box.y }; } + /** + * Measure the element and return the new box snapshot. + * + * With `unapplyTransform`, the translation and scale of the element's own + * inline transform are removed so the box reports its untransformed + * layout position. + */ readDom( config: { unapplyTransform?: boolean } = {}, stage: FrameReadStages | null = null, - ): DomProperty { + ): ElementBox { const currentStage = stage ?? this.global.currentStage; if (!["READ_1", "READ_2", "READ_3", "IDLE"].includes(currentStage)) { @@ -1113,43 +1123,23 @@ export class ElementObject< throw new Error("Element is not set"); } - const property = getDomProperty(this.engine, this.#element); + let box = measureElementBox(this.engine.camera, this.#element, this.#box); const transform = this.#element.style.transform; - let transformApplied = { - x: 0, - y: 0, - scaleX: 1, - scaleY: 1, - }; - if (transform && transform != "none" && config.unapplyTransform) { - transformApplied = parseTransformString(transform); + box = unapplyInlineTransform(box, this.#element, transform); } - - this.#property.height = property.height / transformApplied.scaleY; - this.#property.width = property.width / transformApplied.scaleX; - this.#property.x = property.x - transformApplied.x; - this.#property.y = property.y - transformApplied.y; - this.#property.screenX = property.screenX; - this.#property.screenY = property.screenY; - this.#property.margin = property.margin; - this.#property.padding = property.padding; - this.#property.border = property.border; + this.#box = box; if (["READ_1", "READ_2", "READ_3"].includes(currentStage)) { - copyDomPropertyValue( - this.getDomProperty(currentStage as FrameReadStages), - this.#property, - ); + this.#stageBoxes[stageBoxIndex(currentStage as FrameReadStages)] = box; } - return this.#property; + return box; } readDomRecursive( config: { unapplyTransform?: boolean; - saveDomProperety?: boolean; saveWorldPosition?: boolean; } = {}, ) { @@ -1159,8 +1149,8 @@ export class ElementObject< } this.readDom(config); - if (config.saveDomProperety || config.saveWorldPosition) { - this.saveDomProperety(stage); + if (config.saveWorldPosition) { + this.saveWorldPosition(stage); } for (const child of this.children) { @@ -1233,8 +1223,8 @@ export class ElementObject< }; } else if (this.transformMode == "relative") { const [newX, newY] = [ - this.worldTransform.x - this.#property.x, - this.worldTransform.y - this.#property.y, + this.worldTransform.x - this.#box.x, + this.worldTransform.y - this.#box.y, ]; transformStyle = { transform: generateTransformString({ @@ -1248,8 +1238,8 @@ export class ElementObject< const origin = this.transformOrigin ?? this.parent; if (!origin) { const [newX, newY] = [ - this.worldTransform.x - this.#property.x, - this.worldTransform.y - this.#property.y, + this.worldTransform.x - this.#box.x, + this.worldTransform.y - this.#box.y, ]; transformStyle = { transform: generateTransformString({ diff --git a/src/util.ts b/src/util.ts index 241bdbfb..a8be14e5 100644 --- a/src/util.ts +++ b/src/util.ts @@ -1,4 +1,6 @@ -import type { DomElement, DomProperty, TransformProperty } from "./object"; +import { worldRectFromScreenRect, type ScreenToWorldMapper } from "./camera"; +import { ZERO_EDGES, type Edges, type ElementBox, type Rect } from "./geometry"; +import type { DomElement, TransformProperty } from "./object"; /** * Merges defined override values onto a complete defaults object. @@ -15,102 +17,130 @@ function mergeDefined(defaults: T, overrides: Partial): T { return merged; } +/** The CSS edge thicknesses read from an element's computed style. */ +interface MeasuredEdges { + readonly margin: Edges; + readonly padding: Edges; + readonly border: Edges; +} + +/** A frozen, all-zero element box used before the first DOM read. */ +const EMPTY_ELEMENT_BOX: ElementBox = Object.freeze({ + x: 0, + y: 0, + width: 0, + height: 0, + screen: Object.freeze({ x: 0, y: 0, width: 0, height: 0 }), + margin: ZERO_EDGES, + padding: ZERO_EDGES, + border: ZERO_EDGES, +}); + +function sameEdges(a: Edges, b: Edges): boolean { + return ( + a.top === b.top && + a.right === b.right && + a.bottom === b.bottom && + a.left === b.left + ); +} + +/** A frozen edge set, reusing `previous` or `ZERO_EDGES` when values match. */ +function internEdges( + top: number, + right: number, + bottom: number, + left: number, + previous: Edges | undefined, +): Edges { + const edges = { top, right, bottom, left }; + if (previous && sameEdges(previous, edges)) return previous; + if (sameEdges(ZERO_EDGES, edges)) return ZERO_EDGES; + return Object.freeze(edges); +} + +function readEdges( + css: CSSStyleDeclaration, + previous: ElementBox | undefined, +): MeasuredEdges { + const px = (value: string) => parseFloat(value) || 0; + return { + margin: internEdges( + px(css.marginTop), + px(css.marginRight), + px(css.marginBottom), + px(css.marginLeft), + previous?.margin, + ), + padding: internEdges( + px(css.paddingTop), + px(css.paddingRight), + px(css.paddingBottom), + px(css.paddingLeft), + previous?.padding, + ), + border: internEdges( + px(css.borderTopWidth), + px(css.borderRightWidth), + px(css.borderBottomWidth), + px(css.borderLeftWidth), + previous?.border, + ), + }; +} + /** - * Retrieves the position and dimensions of a DOM element in multiple coordinate spaces. + * Build an element box from a measured client rect and computed CSS edges. * - * Returns coordinates in world space (accounting for camera transform), camera space, - * and screen space, along with transformed dimensions. + * Pure: performs no DOM reads, so it can be exercised with a stub camera. + * 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 { + const world = worldRectFromScreenRect(camera, clientRect); + return Object.freeze({ + x: world.x, + y: world.y, + width: world.width, + height: world.height, + screen: Object.freeze({ + x: clientRect.x, + y: clientRect.y, + width: clientRect.width, + height: clientRect.height, + }), + margin: edges.margin, + padding: edges.padding, + border: edges.border, + }); +} + +/** + * Measure an element's box: its transformed client rect and computed CSS + * margin, padding, and border widths. * - * @param engine - The engine instance containing camera information. - * @param dom - The HTML element to measure. - * @returns An object containing position and size in various coordinate systems. + * Forces layout, so call it only in a READ stage. Pass the element's + * previous box to reuse unchanged edge objects. */ -function getDomProperty(engine: any, dom: DomElement) { - const rect = dom.getBoundingClientRect(); - const css = window.getComputedStyle(dom); - const margin_top = parseFloat(css.marginTop) || 0; - const margin_right = parseFloat(css.marginRight) || 0; - const margin_bottom = parseFloat(css.marginBottom) || 0; - const margin_left = parseFloat(css.marginLeft) || 0; - const padding_top = parseFloat(css.paddingTop) || 0; - const padding_right = parseFloat(css.paddingRight) || 0; - const padding_bottom = parseFloat(css.paddingBottom) || 0; - const padding_left = parseFloat(css.paddingLeft) || 0; - const border_top = parseFloat(css.borderTopWidth) || 0; - const border_right = parseFloat(css.borderRightWidth) || 0; - const border_bottom = parseFloat(css.borderBottomWidth) || 0; - const border_left = parseFloat(css.borderLeftWidth) || 0; - - if (engine == null || engine.camera == null) { - return { - height: rect.height, - width: rect.width, - x: rect.left, - y: rect.top, - cameraX: rect.left, - cameraY: rect.top, - screenX: rect.left, - screenY: rect.top, - margin: { - top: margin_top, - right: margin_right, - bottom: margin_bottom, - left: margin_left, - }, - padding: { - top: padding_top, - right: padding_right, - bottom: padding_bottom, - left: padding_left, - }, - border: { - top: border_top, - right: border_right, - bottom: border_bottom, - left: border_left, - }, - }; - } - const [cameraX, cameraY] = engine.camera.getCameraFromScreen( - rect.left, - rect.top, +function measureElementBox( + camera: ScreenToWorldMapper | null, + element: DomElement, + previous?: ElementBox, +): ElementBox { + const rect = element.getBoundingClientRect(); + const css = window.getComputedStyle(element); + return elementBoxFromMeasurement( + camera, + { x: rect.left, y: rect.top, width: rect.width, height: rect.height }, + readEdges(css, previous), ); - const [worldX, worldY] = engine.camera.getWorldFromCamera(cameraX, cameraY); - const [cameraWidth, cameraHeight] = - engine.camera.getCameraDeltaFromWorldDelta(rect.width, rect.height); - const [worldWidth, worldHeight] = engine.camera.getWorldDeltaFromCameraDelta( - cameraWidth, - cameraHeight, - ); - - return { - height: worldHeight, - width: worldWidth, - x: worldX, - y: worldY, - cameraX: cameraX, - cameraY: cameraY, - screenX: rect.left, - screenY: rect.top, - margin: { - top: margin_top, - right: margin_right, - bottom: margin_bottom, - left: margin_left, - }, - padding: { - top: padding_top, - right: padding_right, - bottom: padding_bottom, - left: padding_left, - }, - border: { - top: border_top, - right: border_right, - bottom: border_bottom, - left: border_left, - }, - }; } /** @@ -126,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]; } /** @@ -198,28 +284,15 @@ function EventProxyFactory( }); } -function cloneDomProperty(prop: DomProperty): DomProperty { - return { - x: prop.x, - y: prop.y, - height: prop.height, - width: prop.width, - scaleX: prop.scaleX, - scaleY: prop.scaleY, - screenX: prop.screenX, - screenY: prop.screenY, - margin: { ...prop.margin }, - padding: { ...prop.padding }, - border: { ...prop.border }, - }; -} - +export type { MeasuredEdges }; export { setDomStyle, EventProxyFactory, - getDomProperty, - cloneDomProperty, + EMPTY_ELEMENT_BOX, + measureElementBox, + 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/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