diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b50758e..0875a7e2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,10 +17,13 @@ jobs: - run: npm ci - run: npm run validate:packages - run: npm run check:snapsort-api + - run: npm run test:core-ut - run: npm run test:snapsort-ut + - run: npm run test:snapline-ut - run: npm run typecheck - run: npm run lint - run: npm run check:adapters - run: npm ci --prefix website + - run: npm run check:tests - run: npm run check:website - run: npm run build diff --git a/AGENTS.md b/AGENTS.md index 446e8c8a..52601865 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -179,9 +179,20 @@ npm run dev:react # React demo **Run tests:** ```bash -npm test +npm test # every unit suite (tests/ut) +npm run test:e2e # every e2e project on Chromium +npm run test:snapsort # one project: core, asset-base, snapline, + # snapsort, or layout ``` +End-to-end suites live in `tests/e2e///`, one Playwright +config per project (`tests/e2e//playwright.config.ts`). Servers and +ports come from `tests/e2e/shared/servers.ts`. Tests that never open a page +belong in `tests/ut/`. + +Tests cover the engine and asset packages, driven through the `demo/` apps. +The website is not tested: do not add specs for its pages or gallery. + ## Release Workflow Publishing is triggered by pushing version tags, not by pushing `main`. diff --git a/SNAPSORT_SIMPLIFICATION.md b/SNAPSORT_SIMPLIFICATION.md index a6e62533..cac2404e 100644 --- a/SNAPSORT_SIMPLIFICATION.md +++ b/SNAPSORT_SIMPLIFICATION.md @@ -443,7 +443,6 @@ npm run validate:packages npm run check:adapters npm run check:website npm run test:snapsort -npx playwright test -c tests/e2e/docs-framework-code.playwright.config.ts --grep "SnapSort callback docs" ``` **Commit:** `refactor(snapsort): trim the 0.5 compatibility API` @@ -701,10 +700,8 @@ or colliding application ID fails. npm run test:snapsort npm run test:snapsort-react npm run test:snapsort-svelte -npm run test:snapsort-examples npm run check:adapters npm run check:website -npx playwright test -c tests/e2e/docs-framework-code.playwright.config.ts ``` **Commit:** `refactor(snapsort): unify ghost transactions` @@ -786,8 +783,6 @@ After all approved phases: npm run ci npm run test:snapsort npm run test:layout -npm run test:snapsort-examples -npx playwright test -c tests/e2e/docs-framework-code.playwright.config.ts ``` `npm run ci` does not run the Playwright suites, so it is necessary but not diff --git a/assets/snapline/src/node.ts b/assets/snapline/src/node.ts index a1f96a59..5f45103d 100644 --- a/assets/snapline/src/node.ts +++ b/assets/snapline/src/node.ts @@ -326,7 +326,10 @@ class NodeMirror extends ElementObject { /* Reconciles state with what the browser actually rendered */ #syncMeasuredGeometry(stage: "READ_1" | "READ_2"): void { if (!this.element) return; - const property = this.readDom({ unapplyTransform: false }, stage); + // The collision box is a child of this node and inherits its scale, so + // it takes the untransformed size: without this, a scaled node's scale + // would apply twice. + const property = this.readDom({ unapplyTransform: true }, stage); // During resize, setSizeState sets the correct dimensions. if (!this.#isResizing) { this.#hitBox.width = property.width; diff --git a/assets/snapsort/AGENTS.md b/assets/snapsort/AGENTS.md index 8c14cf73..748be5bf 100644 --- a/assets/snapsort/AGENTS.md +++ b/assets/snapsort/AGENTS.md @@ -247,7 +247,10 @@ no pre-mutation FLIP rectangle and must be ignored safely by animation code. virtual rectangle retains the initial pointer-to-item offset. There is no implicit deepest-container preference; an application may opt into `prioritizeTreeDepth` through `getDropPriority` when it wants explicit - virtual-X/pointer-Y depth policy. + virtual-X/pointer-Y depth policy. Because the cross axis never enters the + score, side-by-side destinations (columns of a board) opt into + `prioritizePointerContainer` so the column under the pointer wins over a + neighbor whose gap merely lines up on the main axis. - Wrapped rows and columns use the selected visual line's measured cross-axis band. A boundary that wraps uses the next line's leading edge and band; append uses the previous line's trailing edge and band. diff --git a/assets/snapsort/src/drag/pointer-controller.ts b/assets/snapsort/src/drag/pointer-controller.ts index bd15b951..078feecb 100644 --- a/assets/snapsort/src/drag/pointer-controller.ts +++ b/assets/snapsort/src/drag/pointer-controller.ts @@ -1,3 +1,4 @@ +import { freezePoint } from "@snap-engine/core/geometry"; import type { dragEndProp, dragProp, @@ -6,16 +7,6 @@ import type { 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; diff --git a/assets/snapsort/src/drag/session.ts b/assets/snapsort/src/drag/session.ts index 3cf8af82..24d35156 100644 --- a/assets/snapsort/src/drag/session.ts +++ b/assets/snapsort/src/drag/session.ts @@ -1,6 +1,7 @@ import type { AnimationObject } from "@snap-engine/core/animation"; import type { ElementBox, dragStartProp } from "@snap-engine/core"; import { + freezePoint, freezeRect, type BoxModel, type Rect, @@ -102,16 +103,6 @@ interface DropTargetUpdate { readonly shouldClear: boolean; } -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 { return Object.freeze({ ...location }); } diff --git a/assets/snapsort/src/keyboard-controller.ts b/assets/snapsort/src/keyboard-controller.ts index 814a56ca..c5d63920 100644 --- a/assets/snapsort/src/keyboard-controller.ts +++ b/assets/snapsort/src/keyboard-controller.ts @@ -189,6 +189,16 @@ export class KeyboardDragController { prop.event.preventDefault(); }; + #isMovementKey(key: string): boolean { + const { previous, next } = this.#bindings; + return ( + previous.column.has(key) || + previous.row.has(key) || + next.column.has(key) || + next.row.has(key) + ); + } + #handleActiveDirectSession( event: KeyboardEvent, input: DirectDragController, @@ -204,7 +214,13 @@ export class KeyboardDragController { } const direction = input.currentTarget?.container.direction; - if (!direction) return; + if (!direction) { + // The lift is still activating, so there is no target to move from + // yet. Consume movement keys anyway: otherwise an arrow pressed right + // after lifting falls through to the browser and scrolls the page. + if (this.#isMovementKey(event.key)) event.preventDefault(); + return; + } if (this.#bindings.previous[direction].has(event.key)) { input.movePrevious(); diff --git a/demo/react/src/snapsort/SnapSortFixtures.jsx b/demo/react/src/snapsort/SnapSortFixtures.jsx index c116e2b8..01c0a77e 100644 --- a/demo/react/src/snapsort/SnapSortFixtures.jsx +++ b/demo/react/src/snapsort/SnapSortFixtures.jsx @@ -10,6 +10,7 @@ import { import { defaultAnimations, Item as CoreItem } from "@snap-engine/snapsort"; import { prioritizeIntersectingContainer, + prioritizePointerContainer, rejectDrop, } from "@snap-engine/snapsort/callbacks"; import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; @@ -1399,12 +1400,30 @@ export function SnapSortComponentsDemo() { [columns], ); + // Programmatic removal through SnapSort (animated by the owning Container) + // versus a direct state deletion (not animated), for the e2e suite. + const removeItemThroughSnapSort = useCallback( + (itemId) => { + const column = columns.find((candidate) => + candidate.items.some((item) => item.id === itemId), + ); + return column + ? (containerRefs.current.get(column.id)?.removeItem(itemId) ?? false) + : false; + }, + [columns], + ); + useEffect(() => { window.__snapsortMoveComponentItem = moveItemAcrossColumns; + window.__snapsortRemoveComponentItem = removeItemThroughSnapSort; + window.__snapsortDeleteComponentItem = deleteItem; return () => { delete window.__snapsortMoveComponentItem; + delete window.__snapsortRemoveComponentItem; + delete window.__snapsortDeleteComponentItem; }; - }, [moveItemAcrossColumns]); + }, [moveItemAcrossColumns, removeItemThroughSnapSort, deleteItem]); return (
@@ -2224,6 +2243,10 @@ export function SnapSortInsertionDemo() { direction: "column", mode: "insertion", name: `insertion-${column.id}`, + // Insertion ranks gaps by main-axis distance alone, so a + // side-by-side column needs pointer-container priority to + // keep the marker in the column under the pointer. + callbacks: { getDropPriority: prioritizePointerContainer }, }} itemId={column.id} key={column.id} diff --git a/demo/svelte/src/demo/drop_snap_nested/DropSnapNestedDemo.svelte b/demo/svelte/src/demo/drop_snap_nested/DropSnapNestedDemo.svelte index 74500e34..83432f3f 100644 --- a/demo/svelte/src/demo/drop_snap_nested/DropSnapNestedDemo.svelte +++ b/demo/svelte/src/demo/drop_snap_nested/DropSnapNestedDemo.svelte @@ -766,19 +766,19 @@ color: #000; } - :global(.snapsort-container) { + .snapsort-demo :global(.snapsort-container) { gap: var(--size-8); min-height: 40px; } - :global(.snapsort-container .snapsort-container) { + .snapsort-demo :global(.snapsort-container .snapsort-container) { border: 2px solid #000; padding: var(--size-8); } - :global(.demo-item), - :global(.layer-item), - :global(.snapsort-item) { + .snapsort-demo :global(.demo-item), + .snapsort-demo :global(.layer-item), + .snapsort-demo :global(.snapsort-item) { margin: var(--size-4); border: 2px solid #000; background: #fff; @@ -786,13 +786,13 @@ box-sizing: border-box; } - :global(.demo-item:active), - :global(.layer-item:active), - :global(.snapsort-item:active) { + .snapsort-demo :global(.demo-item:active), + .snapsort-demo :global(.layer-item:active), + .snapsort-demo :global(.snapsort-item:active) { cursor: grabbing; } - :global(.demo-item p) { + .snapsort-demo :global(.demo-item p) { margin: 0; padding: var(--size-8) var(--size-12); font-size: 1rem; @@ -804,7 +804,7 @@ min-height: 240px; } - :global(.demo-item.size-item p) { + .snapsort-demo :global(.demo-item.size-item p) { display: flex; align-items: center; justify-content: center; @@ -812,12 +812,12 @@ text-align: center; } - :global(.demo-item.row-item) { + .snapsort-demo :global(.demo-item.row-item) { min-width: 50px; text-align: center; } - :global(.demo-item.selected) { + .snapsort-demo :global(.demo-item.selected) { border-color: #6366f1; box-shadow: inset 0 0 0 2px #6366f1; background: #eef2ff; @@ -829,7 +829,7 @@ color: #888; } - :global(.demo-item.sub-item) { + .snapsort-demo :global(.demo-item.sub-item) { opacity: 0.6; } @@ -880,14 +880,14 @@ user-select: none; } - :global(.ghost) { + .snapsort-demo :global(.ghost) { background: #e5e5e5; border: 2px solid #9a9a9a; box-sizing: border-box; opacity: 1; } - :global(.double-row-ghost-label) { + .snapsort-demo :global(.double-row-ghost-label) { display: flex; align-items: center; justify-content: center; diff --git a/demo/svelte/src/demo/nested_items/NestedItemsDemo.svelte b/demo/svelte/src/demo/nested_items/NestedItemsDemo.svelte deleted file mode 100644 index 84a82fa3..00000000 --- a/demo/svelte/src/demo/nested_items/NestedItemsDemo.svelte +++ /dev/null @@ -1,615 +0,0 @@ - - -
-
- -
- - -
-
-

Flat List

-

Regular items in a snapsort container.

-
-
- - {#each flatTree.entries as entry (entry.itemId)} - {#if entry.isGhost} - {:else if entry.childTree} - {:else}

{entry.value}

- {/if} - {/each} -
-
-
- - -
-
-

Nested Container

-

A container with nested sub-containers and items.

-
-
- - {#each nestedGroupTree.entries as entry (entry.itemId)} - {#if entry.isGhost} - - {:else if entry.childTree} - - {#each entry.childTree.entries as child (child.itemId)} - {#if child.isGhost} - {:else if child.childTree} - {:else}

{child.value.label}

- {/if} - {/each} -
- {:else} -

{entry.value.label}

- {/if} - {/each} -
-
-
- - -
-
-

Draggable Sub-Containers

-

Nested containers that can be dragged and reordered.

-
-
- - {#each dragNestedTree.entries as entry (entry.itemId)} - {#if entry.isGhost} - - {:else if entry.childTree} - - {#each entry.childTree.entries as child (child.itemId)} - {#if child.isGhost} - {:else if child.childTree} - {:else}

{child.value.label}

- {/if} - {/each} -
- {:else} -

{entry.value.label}

- {/if} - {/each} -
-
-
- - -
-
-

Row Layout

-

Items arranged horizontally in a row container.

-
-
- - {#each rowTree.entries as entry (entry.itemId)} - {#if entry.isGhost} - {:else if entry.childTree} - {:else}

{entry.value}

- {/if} - {/each} -
-
-
- - -
-
-

Nested Row Groups

-

Row items with a nested row sub-group that can be reordered.

-
-
- - {#each nestedRowTree.entries as entry (entry.itemId)} - {#if entry.isGhost} - - {:else if entry.childTree} - - {#each entry.childTree.entries as child (child.itemId)} - {#if child.isGhost} - {:else if child.childTree} - {:else}

{child.value.label}

- {/if} - {/each} -
- {:else} -

{entry.value.label}

- {/if} - {/each} -
-
-
- - -
-
-

Wrapping Row

-

Many row items that wrap into multiple lines.

-
-
- - {#each wrapTree.entries as entry (entry.itemId)} - {#if entry.isGhost} - {:else if entry.childTree} - {:else}

{entry.value}

- {/if} - {/each} -
-
-
- - -
-
-

Layers Panel

-

Figma-style layers. Groups are nested containers that can be reordered alongside regular layers.

-
-
- - {#each layerTree.entries as entry (entry.itemId)} - {#if entry.isGhost} - - {:else if entry.childTree && entry.value.kind === "group"} - -
{entry.value.label}
- {#each entry.childTree.entries as child (child.itemId)} - {#if child.isGhost} - - {:else if child.childTree} - - {:else if child.value.kind === "leaf"} - -
- {child.value.icon} - {child.value.name} -
-
- {/if} - {/each} -
- {:else if entry.value.kind === "leaf"} - -
- {entry.value.icon} - {entry.value.name} -
-
- {/if} - {/each} -
-
-
- -
-
-
- -{#if debugMode} -
-
-

Debug Tags

-
- - -
-
- {#each DEBUG_TAGS as tag} - - {/each} -
-{/if} -
- - diff --git a/demo/svelte/src/demo/snapsort_insertion/SnapSortInsertionDemo.svelte b/demo/svelte/src/demo/snapsort_insertion/SnapSortInsertionDemo.svelte index f1260bea..18c5fc6d 100644 --- a/demo/svelte/src/demo/snapsort_insertion/SnapSortInsertionDemo.svelte +++ b/demo/svelte/src/demo/snapsort_insertion/SnapSortInsertionDemo.svelte @@ -12,7 +12,10 @@ type RenderTree, type RenderTreeEvent, } from "@snap-engine/snapsort"; - import { rejectDrop } from "@snap-engine/snapsort/callbacks"; + import { + prioritizePointerContainer, + rejectDrop, + } from "@snap-engine/snapsort/callbacks"; import type { DragStartEvent } from "@snap-engine/snapsort"; import { renderTreeCallbacks } from "../snapsort-render-tree"; @@ -281,6 +284,10 @@ mode: "insertion", direction: "column", name: `insertion-${entry.itemId}`, + // Insertion ranks gaps by main-axis distance alone, so a + // side-by-side column needs pointer-container priority to keep + // the marker in the column under the pointer. + callbacks: { getDropPriority: prioritizePointerContainer }, }} locked={true} metadata={{ columnId: entry.itemId }} diff --git a/docs/snapengine/reference/geometry.mdx b/docs/snapengine/reference/geometry.mdx index bd024253..027be53b 100644 --- a/docs/snapengine/reference/geometry.mdx +++ b/docs/snapengine/reference/geometry.mdx @@ -68,6 +68,7 @@ produced: an `ElementBox` is world-space except for its `screen` rectangle. | Function | Description | |----------|-------------| +| `freezePoint(point)` | A frozen copy holding only the point fields. | | `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. | diff --git a/docs/snapline/design/current-architecture.md b/docs/snapline/design/current-architecture.md index 8951ae84..06a1673f 100644 --- a/docs/snapline/design/current-architecture.md +++ b/docs/snapline/design/current-architecture.md @@ -446,4 +446,4 @@ types). Adapter contracts: | React adapters (incl. ControlledGraph) | `assets/snapline/src/react/*.tsx` | | Controlled-graph demos | `demo/svelte/src/demo/node_ui_edges/`, `demo/react/` | | Unit tests | `tests/ut/snapline-graph-mirror.spec.ts`, `tests/ut/snapline-line-reconciler.spec.ts`, `tests/ut/snapline-connector-config.spec.ts` | -| Browser tests | `tests/e2e/snapline-edges.spec.ts`, `tests/e2e/snapline-edges-react.spec.ts` | +| Browser tests | `tests/e2e/snapline/edges/edges.spec.ts`, `tests/e2e/snapline/edges/edges.react.spec.ts` | diff --git a/docs/snapline/design/nodegraph-composition.md b/docs/snapline/design/nodegraph-composition.md index 57dcebe1..e5e93739 100644 --- a/docs/snapline/design/nodegraph-composition.md +++ b/docs/snapline/design/nodegraph-composition.md @@ -844,14 +844,14 @@ The representation artifact is versioned and separate from canonical line records: ```ts +// The serializable part of ConnectorGeometrySnapshot: a core geometry Rect +// (world space) plus the connector anchor. interface SerializedConnectorGeometry { x: number; y: number; width: number; height: number; center: ConnectorAnchor; - scaleX: number; - scaleY: number; } interface GraphRenderSnapshot { diff --git a/docs/snapline/design/planned-rearchitecture.md b/docs/snapline/design/planned-rearchitecture.md index fd8954e3..8bfd7502 100644 --- a/docs/snapline/design/planned-rearchitecture.md +++ b/docs/snapline/design/planned-rearchitecture.md @@ -46,10 +46,8 @@ The final simplification review has landed: the gesture and record admission checks share one structural check plus one predicate check, the settle path's redundant eviction block and the reconciler's unused local-topology notify forwarding are gone, remaining single-class `_`-prefixed fields moved to `#` -privates, connector membership is encapsulated behind `NodeMirror`'s internal -attachment boundary, and an informational perf benchmark -(`tests/ut/snapline-perf.spec.ts`) guards the reconcile / candidate-discovery -/ bulk-load hot paths. The complete verification matrix — unit suites, all +privates, and connector membership is encapsulated behind `NodeMirror`'s +internal attachment boundary. The complete verification matrix — unit suites, all six SnapLine e2e suites, package validation, and the docs e2e — passes. This document is retained as the record of the re-architecture's decisions diff --git a/package-lock.json b/package-lock.json index 307bc0db..728659b8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "@playwright/test": "^1.61.1", "@sveltejs/vite-plugin-svelte": "^5.0.3", "@types/eslint__js": "^8.42.3", + "@types/jsdom": "^21.1.7", "@types/node": "^20.14.11", "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", @@ -2060,6 +2061,18 @@ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", "license": "MIT" }, + "node_modules/@types/jsdom": { + "version": "21.1.7", + "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-21.1.7.tgz", + "integrity": "sha512-yOriVnggzrnQ3a9OKOCxaVuSug3w3/SbOj5i7VwXWZEyUNl3bLF9V3MfxGbZKuwqJOQyRfqXyROBB1CoZLFWzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/tough-cookie": "*", + "parse5": "^7.0.0" + } + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -2096,6 +2109,13 @@ "@types/react": "^19.0.0" } }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/trusted-types": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", diff --git a/package.json b/package.json index 0beb215b..01ec7780 100755 --- a/package.json +++ b/package.json @@ -51,39 +51,43 @@ "server:react": "FRAMEWORK=react vite serve demo/react --config demo/react/vite.config.mjs --host", "server:svelte": "FRAMEWORK=svelte vite serve demo/svelte --config demo/svelte/vite.config.mjs --host", "dev:all": "concurrently --kill-others \"npm run dev:vanilla\" \"npm run dev:react\"", - "test": "start-server-and-test server:vanilla http://localhost:3001 'playwright test'", - "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": "playwright test", + "test:ui": "playwright test --ui", "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", - "test:snapline-edges": "playwright test -c tests/e2e/snapline-edges.playwright.config.ts", - "test:snapline-overlay": "playwright test -c tests/e2e/snapline-overlay.playwright.config.ts", - "test:snapline-camera": "playwright test -c tests/e2e/snapline-camera.playwright.config.ts", - "test:snapline-group": "playwright test -c tests/e2e/snapline-group.playwright.config.ts", - "test:snapline-resize": "playwright test -c tests/e2e/snapline-resize.playwright.config.ts", - "test:snapline-react": "playwright test -c tests/e2e/snapline-react.playwright.config.ts", - "test:layout": "playwright test -c tests/e2e/snapsort-layout.playwright.config.ts", - "test:snapsort": "playwright test -c tests/e2e/snapsort.playwright.config.ts", - "test:snapsort-svelte": "playwright test -c tests/e2e/snapsort.playwright.config.ts --project=svelte-chromium", - "test:snapsort-react": "playwright test -c tests/e2e/snapsort.playwright.config.ts --project=react-chromium", - "test:snapsort-examples": "playwright test -c tests/e2e/snapsort-examples.playwright.config.ts", + "test:e2e": "npm run test:core -- --project=chromium && npm run test:asset-base && npm run test:snapline && npm run test:snapsort && npm run test:layout -- --project=svelte-chromium", + "test:core": "playwright test -c tests/e2e/core/playwright.config.ts", + "test:core-zoom": "playwright test -c tests/e2e/core/playwright.config.ts measure/", + "test:asset-base": "playwright test -c tests/e2e/asset-base/playwright.config.ts", + "test:camera-control": "playwright test -c tests/e2e/asset-base/playwright.config.ts --project=svelte camera-control/", + "test:camera-control-react": "playwright test -c tests/e2e/asset-base/playwright.config.ts --project=react camera-control/", + "test:asset-base-react": "playwright test -c tests/e2e/asset-base/playwright.config.ts --project=react react-context/", + "test:snapline": "playwright test -c tests/e2e/snapline/playwright.config.ts", + "test:snapline-nodes": "playwright test -c tests/e2e/snapline/playwright.config.ts --project=svelte nodes/", + "test:snapline-camera": "playwright test -c tests/e2e/snapline/playwright.config.ts --project=svelte camera/", + "test:snapline-edges": "playwright test -c tests/e2e/snapline/playwright.config.ts --project=svelte edges/edges.spec.ts", + "test:snapline-overlay": "playwright test -c tests/e2e/snapline/playwright.config.ts --project=svelte edges/overlay.spec.ts", + "test:snapline-group": "playwright test -c tests/e2e/snapline/playwright.config.ts --project=svelte group/", + "test:snapline-resize": "playwright test -c tests/e2e/snapline/playwright.config.ts --project=svelte resize/", + "test:snapline-react": "playwright test -c tests/e2e/snapline/playwright.config.ts --project=react", + "test:snapsort": "playwright test -c tests/e2e/snapsort/playwright.config.ts", + "test:snapsort-svelte": "playwright test -c tests/e2e/snapsort/playwright.config.ts --project=svelte-chromium", + "test:snapsort-react": "playwright test -c tests/e2e/snapsort/playwright.config.ts --project=react-chromium", + "test:layout": "playwright test -c tests/e2e/snapsort/layout.playwright.config.ts", "promo:snapsort": "playwright test -c tests/promo/snapsort-promo.playwright.config.ts && node scripts/convert-snapsort-promo.mjs", - "test:ui": "start-server-and-test server:vanilla http://localhost:3001 'playwright test --ui'", "render:collision-dots": "node scripts/render_collision_text_dots.mjs", "format": "prettier --write src", "lint": "eslint src assets/snapline --ext .ts", "build": "vite build --mode production", "build:dev": "FRAMEWORK=test npx vite build --mode development", "check:snapsort-api": "tsc -p tests/types/tsconfig.snapsort-api.json", + "check:tests": "tsc -p tsconfig.tests.json", "validate:packages": "node scripts/validate-packages.mjs", "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: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", + "ci": "npm run validate:packages && npm run check:snapsort-api && npm run check:tests && 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" }, @@ -114,6 +118,7 @@ "@playwright/test": "^1.61.1", "@sveltejs/vite-plugin-svelte": "^5.0.3", "@types/eslint__js": "^8.42.3", + "@types/jsdom": "^21.1.7", "@types/node": "^20.14.11", "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", diff --git a/playwright.config.ts b/playwright.config.ts index 6605acdc..b1ce93d6 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,58 +1,16 @@ -import { defineConfig, devices } from "@playwright/test"; - -const framework = process.env.FRAMEWORK || "vanilla"; +import { defineConfig } from "@playwright/test"; /** - * See https://playwright.dev/docs/test-configuration. + * Unit tests: DOM-free (or JSDOM) specs under tests/ut, run in Node. + * + * `npm test` runs all of them; the `test:*-ut` scripts run one package's. + * End-to-end suites live in tests/e2e// with their own configs; + * see the `test:` scripts. */ export default defineConfig({ - testDir: "./tests", - + testDir: "./tests/ut", fullyParallel: true, retries: process.env.CI ? 2 : 0, workers: process.env.CI ? 1 : undefined, - - projects: [ - { - name: "chromium", - use: { ...devices["Desktop Chrome"] }, - }, - - { - name: "firefox", - use: { ...devices["Desktop Firefox"] }, - }, - - // { - // name: "webkit", - // use: { ...devices["Desktop Safari"] }, - // }, - - /* Test against mobile viewports. */ - // { - // name: 'Mobile Chrome', - // use: { ...devices['Pixel 5'] }, - // }, - // { - // name: 'Mobile Safari', - // use: { ...devices['iPhone 12'] }, - // }, - - /* Test against branded browsers. */ - // { - // name: 'Microsoft Edge', - // use: { ...devices['Desktop Edge'], channel: 'msedge' }, - // }, - // { - // name: 'Google Chrome', - // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, - // }, - ], - - /* Not working at the moment, need to figure out why. */ - // webServer: { - // command: `npm run server:${framework}`, - // url: `http://localhost:3001`, - // reuseExistingServer: !process.env.CI, - // }, + projects: [{ name: "chromium" }], }); diff --git a/src/geometry.ts b/src/geometry.ts index 7d4b51e8..65ca5bda 100644 --- a/src/geometry.ts +++ b/src/geometry.ts @@ -275,6 +275,11 @@ export function rectsEqual(a: Rect, b: Rect, tolerance = 0): boolean { // Construction and mapping. // --------------------------------------------------------------------------- +/** A frozen copy holding only the point fields of `point`. */ +export function freezePoint(point: Point): Point { + return Object.freeze({ x: point.x, y: point.y }); +} + /** A frozen copy holding only the rectangle fields of `rect`. */ export function freezeRect(rect: Rect): Rect { return Object.freeze({ diff --git a/tests/e2e/asset-base-react.playwright.config.ts b/tests/e2e/asset-base-react.playwright.config.ts deleted file mode 100644 index 822b7a1a..00000000 --- a/tests/e2e/asset-base-react.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.ASSET_BASE_REACT_TEST_PORT ?? 3033); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: "asset-base-react.spec.ts", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 820 }, - }, - webServer: { - cwd: repoRoot, - command: `npx vite serve demo/react --config demo/react/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/camera-control.spec.ts b/tests/e2e/asset-base/camera-control/camera-control.spec.ts similarity index 100% rename from tests/e2e/camera-control.spec.ts rename to tests/e2e/asset-base/camera-control/camera-control.spec.ts diff --git a/tests/e2e/asset-base/playwright.config.ts b/tests/e2e/asset-base/playwright.config.ts new file mode 100644 index 00000000..b9d57133 --- /dev/null +++ b/tests/e2e/asset-base/playwright.config.ts @@ -0,0 +1,35 @@ +// Asset Base suite: camera control on both framework adapters, plus React +// context and ref wiring. `*.react.spec.ts` files run only on React. +// +// Run with: npm run test:asset-base +import { defineConfig } from "@playwright/test"; +import { PORTS, baseURL, demoServer, sharedUse } from "../shared/servers"; + +const use = { + ...sharedUse, + channel: "chrome", + viewport: { width: 1280, height: 820 }, +}; + +export default defineConfig({ + testDir: ".", + fullyParallel: false, + workers: 1, + reporter: [["list"]], + projects: [ + { + name: "svelte", + testIgnore: ["**/*.react.spec.ts"], + use: { ...use, baseURL: baseURL(PORTS.assetBaseSvelte) }, + }, + { + name: "react", + testIgnore: ["**/*.svelte.spec.ts"], + use: { ...use, baseURL: baseURL(PORTS.assetBaseReact) }, + }, + ], + webServer: [ + demoServer("svelte", PORTS.assetBaseSvelte), + demoServer("react", PORTS.assetBaseReact), + ], +}); diff --git a/tests/e2e/asset-base-react.spec.ts b/tests/e2e/asset-base/react-context/context-refs.react.spec.ts similarity index 87% rename from tests/e2e/asset-base-react.spec.ts rename to tests/e2e/asset-base/react-context/context-refs.react.spec.ts index 1c57954e..5d9a38ed 100644 --- a/tests/e2e/asset-base-react.spec.ts +++ b/tests/e2e/asset-base/react-context/context-refs.react.spec.ts @@ -17,7 +17,7 @@ test("shares contexts, exposes refs, and survives Strict Mode remounts", async ( await expect(refStatus).toHaveAttribute("data-camera-ref", "true"); await expect(refStatus).toHaveAttribute("data-background-ref", "true"); - await expect(page.getByTestId("asset-base-engine")).toHaveAttribute( + await expect(page.getByTestId("camera-engine")).toHaveAttribute( "style", /width: 100%/, ); @@ -28,11 +28,11 @@ test("shares contexts, exposes refs, and survives Strict Mode remounts", async ( await page.getByTestId("toggle-debug").click(); await expect( - page.getByTestId("asset-base-engine").locator("canvas"), + page.getByTestId("camera-engine").locator("canvas"), ).toHaveCount(1); await page.getByTestId("toggle-engine").click(); - await expect(page.getByTestId("asset-base-engine")).toHaveCount(0); + await expect(page.getByTestId("camera-engine")).toHaveCount(0); await page.evaluate(() => window.dispatchEvent(new Event("scroll"))); await page.getByTestId("toggle-engine").click(); diff --git a/tests/e2e/camera-control-react.playwright.config.ts b/tests/e2e/camera-control-react.playwright.config.ts deleted file mode 100644 index 6cb26105..00000000 --- a/tests/e2e/camera-control-react.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.CAMERA_CONTROL_REACT_TEST_PORT ?? 3032); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: "camera-control.spec.ts", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 820 }, - }, - webServer: { - cwd: repoRoot, - command: `npx vite serve demo/react --config demo/react/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/camera-control.playwright.config.ts b/tests/e2e/camera-control.playwright.config.ts deleted file mode 100644 index b1d7a20b..00000000 --- a/tests/e2e/camera-control.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.CAMERA_CONTROL_TEST_PORT ?? 3028); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: "camera-control.spec.ts", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 820 }, - }, - webServer: { - cwd: repoRoot, - command: `FRAMEWORK=svelte npx vite build --mode development && npx vite serve demo/svelte --config demo/svelte/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/core-zoom.playwright.config.ts b/tests/e2e/core-zoom.playwright.config.ts deleted file mode 100644 index d62931ba..00000000 --- a/tests/e2e/core-zoom.playwright.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -// 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/animation/variable-channels.spec.ts b/tests/e2e/core/animation/variable-channels.spec.ts new file mode 100644 index 00000000..89cec48b --- /dev/null +++ b/tests/e2e/core/animation/variable-channels.spec.ts @@ -0,0 +1,66 @@ +import { expect, test } from "@playwright/test"; +import { repoRoot } from "../../shared/servers"; + +// AnimationObject drives `$` variables through pooled `--snap-var-*` custom +// properties on the target. A finished animation must clear its channel before +// releasing it: the next animation's Web Animation can stay pending until the +// following frame, and would sample the stale terminal value until then. + +test.beforeEach(async ({ page }) => { + await page.goto("/"); +}); + +test("resets pooled animation variables before a channel is reused", async ({ + page, +}) => { + const animationModuleUrl = `/@fs${repoRoot}/src/animation.ts`; + const result = await page.evaluate(async (moduleUrl) => { + const { AnimationObject } = await import(/* @vite-ignore */ moduleUrl); + const target = document.createElement("div"); + document.body.appendChild(target); + + const first = new AnimationObject( + target, + { $value: [0, 1] }, + { duration: 40 }, + ); + first.play(); + for (let frame = 0; frame < 20 && !first.requestDelete; frame++) { + await new Promise((resolve) => + requestAnimationFrame(() => resolve()), + ); + } + + const propertiesAfterFinish = Array.from(target.style).filter((name) => + name.startsWith("--snap-var-"), + ); + const samples: number[] = []; + const second = new AnimationObject( + target, + { $value: [0.25, 0.75] }, + { + duration: 800, + tick: (values: Record) => samples.push(values.$value), + }, + ); + const acquiredProperties = Array.from(target.style) + .filter((name) => name.startsWith("--snap-var-")) + .map((name) => target.style.getPropertyValue(name)); + second.play(); + second.progress = 0; + second.calculateFrame(performance.now()); + second.cancel(); + target.remove(); + + return { + acquiredProperties, + firstSample: samples[0] ?? null, + propertiesAfterFinish, + }; + }, animationModuleUrl); + + expect(result.propertiesAfterFinish).toEqual([]); + expect(result.acquiredProperties).toHaveLength(1); + expect(Number(result.acquiredProperties[0])).toBeCloseTo(0.25); + expect(result.firstSample).toBeCloseTo(0.25); +}); diff --git a/tests/e2e/core-zoom.spec.ts b/tests/e2e/core/measure/zoom-read-dom.spec.ts similarity index 98% rename from tests/e2e/core-zoom.spec.ts rename to tests/e2e/core/measure/zoom-read-dom.spec.ts index 9bd3e031..8d2b4237 100644 --- a/tests/e2e/core-zoom.spec.ts +++ b/tests/e2e/core/measure/zoom-read-dom.spec.ts @@ -1,4 +1,5 @@ import { expect, test, type Page } from "@playwright/test"; +import { coreImportPath } from "../../shared/servers"; // ElementObject.readDom under a real zoomed Camera: the measured border box is // world-space (CSS pixels inside the camera layer), computed edges pass @@ -28,7 +29,6 @@ async function measureAtZoom( 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); diff --git a/tests/e2e/core/playwright.config.ts b/tests/e2e/core/playwright.config.ts new file mode 100644 index 00000000..dac9e2e3 --- /dev/null +++ b/tests/e2e/core/playwright.config.ts @@ -0,0 +1,29 @@ +// Core engine suite across all three engines: measurement under a real +// Camera (each quantizes layout differently) and Web Animations timing. +// +// Run with: npm run test:core +import { defineConfig } from "@playwright/test"; +import { + BROWSERS, + PORTS, + baseURL, + demoServer, + sharedUse, +} from "../shared/servers"; + +export default defineConfig({ + testDir: ".", + fullyParallel: false, + workers: 1, + reporter: [["list"]], + use: { + ...sharedUse, + baseURL: baseURL(PORTS.core), + viewport: { width: 1280, height: 900 }, + }, + projects: (["chromium", "firefox", "webkit"] as const).map((browser) => ({ + name: browser, + use: { ...BROWSERS[browser], viewport: { width: 1280, height: 900 } }, + })), + webServer: demoServer("svelte", PORTS.core), +}); diff --git a/tests/e2e/docs-framework-code.playwright.config.ts b/tests/e2e/docs-framework-code.playwright.config.ts deleted file mode 100644 index c7a823a1..00000000 --- a/tests/e2e/docs-framework-code.playwright.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { defineConfig, devices } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = 5191; -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: [ - "material-surface-ssr.spec.ts", - "snapdesign-gallery-virtual-pointer.spec.ts", - "snapdesign-control-matrix.spec.ts", - "snapdesign-kanban-board.spec.ts", - "snapdesign-precision-slider.spec.ts", - "snapdesign-sideways-cards.spec.ts", - "snapdesign-swap-controls.spec.ts", - "snapdesign-toucan-lesson.spec.ts", - "snapsort-landing-regression.spec.ts", - "website-navigation.spec.ts", - "website-engine-lifecycle.spec.ts", - ], - workers: 1, - reporter: [["list"]], - use: { - ...devices["Desktop Chrome"], - baseURL: `http://127.0.0.1:${port}`, - }, - webServer: { - cwd: resolve(repoRoot, "website"), - command: `npm run dev -- --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/material-surface-ssr.spec.ts b/tests/e2e/material-surface-ssr.spec.ts deleted file mode 100644 index 268436ff..00000000 --- a/tests/e2e/material-surface-ssr.spec.ts +++ /dev/null @@ -1,692 +0,0 @@ -import { expect, test } from "@playwright/test"; -import { - createMaterialStyle, - defaultMaterialSettings, -} from "../../website/src/lib/components/materialSurface"; - -test("serializes material lighting without a browser", () => { - const raisedStyle = createMaterialStyle("raised", defaultMaterialSettings); - const recessedStyle = createMaterialStyle("recessed", defaultMaterialSettings); - - expect(raisedStyle).toContain("--material-light-angle: 325deg"); - expect(raisedStyle).toContain("--material-shadow-far-x:"); - expect(raisedStyle).toContain( - "--material-normal-315: color-mix(in hsl, color-mix(", - ); - expect(raisedStyle).toContain("--material-specular-peak:"); - expect(recessedStyle).toContain("--material-light-angle: 505deg"); - expect(recessedStyle).not.toBe(raisedStyle); -}); - -test("clamps invalid material values during serialization", () => { - const style = createMaterialStyle("raised", { - ...defaultMaterialSettings, - shadowDistance: -2, - shadowBlur: -4, - shadowStrength: 2, - rimWidth: -1, - creviceBrightness: 2, - }); - - expect(style).toContain("--material-rim-width: 0px"); - expect(style).toContain("--material-shadow-far-blur: 0px"); - expect(style).toContain("--material-shadow-strength: 1.000"); - expect(style).toContain("--material-shadow-far-x: 0.000px"); - expect(style).toContain( - "--material-crevice-color: color-mix(in srgb, #000 0.000%, #fff 100.000%)", - ); -}); - -test("includes complete button material styles in server-rendered HTML", async ({ request }) => { - const response = await request.get("/snapdesign"); - - expect(response.ok()).toBe(true); - const html = await response.text(); - const buttonSurface = html.match( - /]*class="[^"]*snap-button-surface[^"]*"[^>]*>/, - )?.[0]; - - expect(buttonSurface).toBeDefined(); - expect(buttonSurface).toContain("--material-light-angle:"); - expect(buttonSurface).toContain("--material-shadow-far-x:"); - expect(buttonSurface).toContain("--material-normal-315:"); - expect(buttonSurface).toContain("--material-specular-peak:"); - expect(buttonSurface).toContain("--material-crevice-visibility: hidden"); - expect(buttonSurface).toContain( - "--material-color: var(--snap-button-color)", - ); -}); - -test("server-renders material radios from Slot and Circle surfaces", async ({ request }) => { - const response = await request.get("/snapdesign"); - - expect(response.ok()).toBe(true); - const html = await response.text(); - expect(html).toContain("snap-radio checked"); - expect(html).toContain("snap-slot"); - expect(html).toContain("radio-slot"); - expect(html).toContain("circle"); - expect(html).toContain("radio-circle"); - expect(html).toContain("--radio-size: 22px"); - expect(html).toContain("--circle-color: var(--radio-accent-color)"); -}); - -test("server-renders material checkbox from square material surfaces", async ({ request }) => { - const response = await request.get("/snapdesign"); - - expect(response.ok()).toBe(true); - const html = await response.text(); - expect(html).toContain("snap-checkbox checked"); - expect(html).toContain("checkbox-slot"); - expect(html).toContain("checkbox-square"); - expect(html).toContain("--checkbox-size: 22px"); - expect(html).toContain("--material-color: var(--checkbox-accent-color)"); -}); - -test("hydrates server-rendered buttons and keeps material interactions reactive", async ({ page }) => { - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - page.on("console", (message) => { - if (message.type() === "error") pageErrors.push(message.text()); - }); - page.on("requestfailed", (request) => { - pageErrors.push(`${request.url()}: ${request.failure()?.errorText}`); - }); - await page.goto("/snapdesign"); - - const svelteTab = page.getByRole("tab", { name: "Svelte" }); - await expect(async () => { - await svelteTab.click(); - expect(await svelteTab.getAttribute("aria-selected")).toBe("true"); - }).toPass(); - expect(pageErrors).toEqual([]); - - const button = page.getByRole("button", { name: "Default", exact: true }).first(); - const surface = button.locator(".snap-button-surface"); - const content = surface.locator(".material-content"); - await expect(button).toHaveCSS("font-family", /Bitcount Grid Single/); - await expect(content).toHaveCSS("padding-top", "8px"); - await expect(content).toHaveCSS("padding-bottom", "6px"); - const minimalButton = page - .getByRole("group", { name: "Minimal buttons" }) - .getByRole("button", { - name: "Default", - }); - await expect(minimalButton).toHaveCSS("font-family", /Bitcount Grid Single/); - await expect(minimalButton).toHaveCSS("padding-top", "10px"); - await expect(minimalButton).toHaveCSS("padding-bottom", "8px"); - const activeButton = page - .getByRole("group", { name: "Skeuomorphic buttons" }) - .getByRole("button", { name: "Active" }); - await expect(activeButton.locator(".snap-button-content")).toHaveCSS( - "color", - "rgb(255, 93, 15)", - ); - await expect(activeButton.locator(".snap-button-content")).toHaveCSS( - "text-shadow", - /rgba?\(255, 93, 15/, - ); - await expect( - page.getByRole("group", { name: /buttons/ }).getByRole("button", { - name: "Disabled", - }), - ).toHaveCount(0); - const shadowBlur = () => surface.evaluate((element) => - Number.parseFloat( - getComputedStyle(element).getPropertyValue("--material-shadow-far-blur"), - ), - ); - - expect(await shadowBlur()).toBeCloseTo(6.25); - await button.hover(); - await expect.poll(shadowBlur).toBeCloseTo(1.25); -}); - -test("material radios preserve native grouping and agreed sizing", async ({ page }) => { - await page.goto("/snapdesign"); - - const group = page.getByRole("group", { - name: "Skeuomorphic selection controls", - }); - const first = group.getByRole("radio", { name: "First" }); - const second = group.getByRole("radio", { name: "Second" }); - const firstControl = first.locator(".."); - const secondControl = second.locator(".."); - const slot = firstControl.locator(".radio-slot"); - const circle = firstControl.locator(".radio-circle"); - - await expect(first).toBeChecked(); - await expect(second).not.toBeChecked(); - await expect(firstControl).toHaveCSS("width", "22px"); - await expect(circle).toHaveCSS("width", "13px"); - await expect(firstControl.locator(".radio-slot .radio-circle")).toHaveCount(0); - - const [controlBox, circleBox] = await Promise.all([ - firstControl.boundingBox(), - circle.boundingBox(), - ]); - expect(controlBox).not.toBeNull(); - expect(circleBox).not.toBeNull(); - expect( - Math.abs( - controlBox!.x + controlBox!.width / 2 - - (circleBox!.x + circleBox!.width / 2), - ), - ).toBeLessThan(0.5); - expect( - Math.abs( - controlBox!.y + controlBox!.height / 2 - - (circleBox!.y + circleBox!.height / 2), - ), - ).toBeLessThan(0.5); - - const materialVariable = (locator: typeof slot, name: string) => - locator.evaluate( - (element, propertyName) => - getComputedStyle(element).getPropertyValue(propertyName).trim(), - name, - ); - expect(await materialVariable(slot, "--material-rim-width")).toBe("0.4px"); - expect(await materialVariable(slot, "--material-shadow-far-blur")).toBe("3px"); - expect(await materialVariable(circle, "--material-rim-width")).toBe("0.55px"); - expect(await materialVariable(circle, "--material-shadow-far-blur")).toBe("3.5px"); - - const shadowDistance = async (locator: typeof slot) => { - const [x, y] = await Promise.all([ - materialVariable(locator, "--material-shadow-far-x"), - materialVariable(locator, "--material-shadow-far-y"), - ]); - return Math.hypot(Number.parseFloat(x), Number.parseFloat(y)); - }; - expect(await shadowDistance(slot)).toBeCloseTo(3.5, 2); - expect(await shadowDistance(circle)).toBeCloseTo(3, 2); - - await expect(async () => { - await second.check(); - await expect(secondControl).toHaveClass(/checked/); - }).toPass(); - await expect(first).not.toBeChecked(); - await expect(second).toBeChecked(); - - await second.press("ArrowUp"); - await expect(first).toBeChecked(); - await expect(firstControl).toHaveClass(/checked/); - await expect(secondControl).not.toHaveClass(/checked/); -}); - -test("material checkbox keeps native behavior and centers its raised square", async ({ page }) => { - await page.goto("/snapdesign"); - - const group = page.getByRole("group", { - name: "Skeuomorphic selection controls", - }); - const checkbox = group.getByRole("checkbox", { name: "Checkbox" }); - const control = checkbox.locator(".."); - const slot = control.locator(".checkbox-slot"); - const square = control.locator(".checkbox-square"); - - await expect(checkbox).toBeChecked(); - await expect(control).toHaveClass(/checked/); - await expect(control).toHaveCSS("width", "22px"); - await expect(slot).toHaveCSS("border-radius", "3px"); - await expect(square).toHaveCSS("width", "16px"); - await expect(square).toHaveCSS("border-radius", "2px"); - await expect(control.locator(".checkbox-check")).toHaveCount(2); - await expect(control.locator(".checkbox-slot .checkbox-square")).toHaveCount(0); - - const [controlBox, squareBox] = await Promise.all([ - control.boundingBox(), - square.boundingBox(), - ]); - expect(controlBox).not.toBeNull(); - expect(squareBox).not.toBeNull(); - expect( - Math.abs( - controlBox!.x + controlBox!.width / 2 - - (squareBox!.x + squareBox!.width / 2), - ), - ).toBeLessThan(0.5); - expect( - Math.abs( - controlBox!.y + controlBox!.height / 2 - - (squareBox!.y + squareBox!.height / 2), - ), - ).toBeLessThan(0.5); - - await expect(async () => { - await checkbox.uncheck(); - await expect(control).not.toHaveClass(/checked/); - }).toPass(); - await expect(checkbox).not.toBeChecked(); - - await checkbox.focus(); - await checkbox.press("Space"); - await expect(checkbox).toBeChecked(); - await expect(control).toHaveClass(/checked/); -}); - -test("minimal selection controls use aligned labels and inset orange indicators", async ({ page }) => { - await page.goto("/snapdesign"); - - const group = page.getByRole("group", { name: "Minimal selection controls" }); - const textStarts = await group.locator("label > span:last-child").evaluateAll( - (labels) => labels.map((label) => label.getBoundingClientRect().x), - ); - expect(Math.max(...textStarts) - Math.min(...textStarts)).toBeLessThan(0.5); - - const toggleTrack = group.locator(".minimal-toggle > span").first(); - const checkboxBox = group.locator(".minimal-checkbox-box"); - const radioRings = group.locator(".minimal-radio-ring"); - await expect(toggleTrack).toHaveCSS("border-radius", "999px"); - await expect(checkboxBox).toHaveCSS("border-radius", "3px"); - await expect(radioRings.first()).toHaveCSS("border-radius", "50%"); - await expect(radioRings).toHaveCount(2); - - const indicatorStyle = await radioRings.first().evaluate((element) => { - const style = getComputedStyle(element, "::before"); - return { - width: style.width, - height: style.height, - borderRadius: style.borderRadius, - background: style.backgroundColor, - }; - }); - expect(indicatorStyle).toEqual({ - width: "14px", - height: "14px", - borderRadius: "50%", - background: "rgb(255, 93, 15)", - }); -}); - -test("dial occupies the top-right UI element slot", async ({ page }) => { - await page.goto("/snapdesign"); - - const [title, buttons, dial] = await Promise.all([ - page.locator(".oversized-section-title").boundingBox(), - page.locator(".buttons-card").boundingBox(), - page.locator(".dial-card").boundingBox(), - ]); - expect(title).not.toBeNull(); - expect(buttons).not.toBeNull(); - expect(dial).not.toBeNull(); - expect(Math.abs(title!.y - dial!.y)).toBeLessThan(0.5); - expect(Math.abs(buttons!.y - dial!.y)).toBeLessThan(0.5); - expect(dial!.x).toBeGreaterThan(buttons!.x); -}); - -test("Layout section follows the title, specimens, and table composition", async ({ page }) => { - await page.goto("/snapdesign"); - - const [heading, containers, table] = await Promise.all([ - page.locator(".layout-section .section-heading").boundingBox(), - page.locator(".layout-section .container-card").boundingBox(), - page.locator(".layout-section .table-card").boundingBox(), - ]); - expect(heading).not.toBeNull(); - expect(containers).not.toBeNull(); - expect(table).not.toBeNull(); - expect(containers!.y).toBeGreaterThanOrEqual(heading!.y + heading!.height - 0.5); - expect(Math.abs(containers!.y - table!.y)).toBeLessThan(0.5); - expect(Math.abs(containers!.height - table!.height)).toBeLessThan(0.5); - expect(table!.width).toBeGreaterThan(containers!.width); - await expect(page.locator(".layout-section .cards-slots-stage > *")).toHaveCount(4); -}); - -test("top navigation matches the SnapDesign page width and surface", async ({ page }) => { - await page.setViewportSize({ width: 1600, height: 900 }); - await page.goto("/snapdesign"); - - const header = page.locator(".site-header"); - const nav = page.locator(".nav-bar"); - const wordmark = page.locator(".wordmark"); - const projectTrigger = page.getByRole("button", { - name: /Switch project\. Current project: SnapDesign/, - }); - const projectMenu = page.locator("#project-nav-menu"); - const showcase = page.locator(".showcase-section").first(); - const github = page.locator(".github-link"); - await expect(header).toHaveCSS("background-color", "rgb(246, 246, 246)"); - await expect(header).toHaveCSS("border-bottom", "1px solid rgb(215, 215, 215)"); - await expect(wordmark).toHaveText("SnapDesign"); - await expect(wordmark).toHaveAttribute("href", "/snapdesign"); - await expect(wordmark).toHaveCSS("font-family", "Geist, sans-serif"); - - await projectTrigger.click(); - await expect(projectMenu).toBeVisible(); - await expect(projectMenu).toHaveCSS("background-color", "rgb(255, 255, 255)"); - await expect(projectMenu).toHaveCSS("border", "1px solid rgba(0, 0, 0, 0.24)"); - await expect(projectMenu).toHaveCSS("border-radius", "8px"); - await expect(projectMenu).toHaveCSS( - "box-shadow", - "rgba(36, 38, 39, 0.05) 0px 3px 10px 0px", - ); - await expect(projectMenu).toHaveCSS("padding-top", "8px"); - await expect(projectMenu).toHaveCSS("padding-bottom", "8px"); - - const projectOptions = await projectMenu.getByRole("link").all(); - expect(projectOptions).toHaveLength(4); - for (const option of projectOptions) { - await expect(option).toHaveCSS("color", "rgb(8, 8, 8)"); - await expect(option).toHaveCSS("font-family", "Geist, sans-serif"); - await expect(option).toHaveCSS("font-size", "20px"); - await expect(option).toHaveCSS("font-weight", "500"); - await expect(option).toHaveCSS("letter-spacing", "-0.8px"); - await expect(option).toHaveCSS("line-height", "20px"); - } - await expect(wordmark).toHaveCSS("color", "rgb(8, 8, 8)"); - await expect(wordmark).toHaveCSS("font-size", "20px"); - await expect(wordmark).toHaveCSS("font-weight", "500"); - await expect(wordmark).toHaveCSS("letter-spacing", "-0.8px"); - await expect(wordmark).toHaveCSS("line-height", "20px"); - - const snapSortOption = projectMenu.getByRole("link", { name: "SnapSort" }); - await snapSortOption.hover(); - await expect(snapSortOption).toHaveCSS("background-color", "rgb(236, 236, 235)"); - await expect( - projectMenu - .getByRole("link", { name: "SnapDesign" }) - .locator(".project-nav-check"), - ).toHaveAttribute("aria-hidden", "true"); - - const [navBox, showcaseBox, githubBox, wordmarkBox, projectMenuBox] = await Promise.all([ - nav.boundingBox(), - showcase.boundingBox(), - github.boundingBox(), - wordmark.boundingBox(), - projectMenu.boundingBox(), - ]); - expect(navBox).not.toBeNull(); - expect(showcaseBox).not.toBeNull(); - expect(githubBox).not.toBeNull(); - expect(wordmarkBox).not.toBeNull(); - expect(projectMenuBox).not.toBeNull(); - expect(navBox!.width).toBeCloseTo(1400); - expect(navBox!.x).toBeCloseTo(showcaseBox!.x); - expect(navBox!.x + navBox!.width).toBeCloseTo( - showcaseBox!.x + showcaseBox!.width, - ); - expect(githubBox!.x + githubBox!.width).toBeCloseTo( - navBox!.x + navBox!.width, - ); - expect(projectMenuBox!.x).toBeCloseTo(wordmarkBox!.x); -}); - -test("SnapDesign dropdown picker uses the compact-card surface", async ({ page }) => { - await page.goto("/snapdesign"); - - const select = page.locator("#select-default"); - const styles = await select.evaluate((element) => { - const closed = getComputedStyle(element); - const picker = getComputedStyle(element, "::picker(select)"); - const option = getComputedStyle(element.querySelector("option")!); - const groupedSelect = document.querySelector("#select-grouped")!; - const groupedPicker = getComputedStyle(groupedSelect, "::picker(select)"); - const iconSelect = document.querySelector("#select-icons")!; - const iconPicker = getComputedStyle(iconSelect, "::picker(select)"); - const optgroup = getComputedStyle(groupedSelect.querySelector("optgroup")!); - const secondOptgroup = getComputedStyle(groupedSelect.querySelectorAll("optgroup")[1]); - const groupedOption = getComputedStyle(groupedSelect.querySelector("option")!); - return { - closedBorder: closed.border, - closedShadow: closed.boxShadow, - closedPaddingLeft: closed.paddingLeft, - pickerBackground: picker.backgroundColor, - pickerBorder: picker.border, - pickerRadius: picker.borderRadius, - pickerShadow: picker.boxShadow, - pickerPaddingBlock: `${picker.paddingTop} ${picker.paddingBottom}`, - groupedPickerPaddingBlock: `${groupedPicker.paddingTop} ${groupedPicker.paddingBottom}`, - iconPickerPaddingBlock: `${iconPicker.paddingTop} ${iconPicker.paddingBottom}`, - optionBackground: option.backgroundColor, - optgroupFont: optgroup.fontFamily, - optgroupColor: optgroup.color, - optgroupFontSize: optgroup.fontSize, - optgroupFontWeight: optgroup.fontWeight, - optgroupTextIndent: optgroup.textIndent, - secondOptgroupMarginTop: secondOptgroup.marginTop, - groupedOptionFont: groupedOption.fontFamily, - groupedOptionColor: groupedOption.color, - groupedOptionFontSize: groupedOption.fontSize, - }; - }); - expect(styles).toEqual({ - closedBorder: "1px solid rgb(213, 216, 220)", - closedShadow: "none", - closedPaddingLeft: "16px", - pickerBackground: "rgb(255, 255, 255)", - pickerBorder: "1px solid rgba(0, 0, 0, 0.24)", - pickerRadius: "8px", - pickerShadow: "rgba(36, 38, 39, 0.05) 0px 3px 10px 0px", - pickerPaddingBlock: "8px 8px", - groupedPickerPaddingBlock: "16px 16px", - iconPickerPaddingBlock: "8px 8px", - optionBackground: "rgba(0, 0, 0, 0)", - optgroupFont: '"Bitcount Grid Single", monospace', - optgroupColor: "rgba(0, 0, 0, 0.58)", - optgroupFontSize: "14.4px", - optgroupFontWeight: "400", - optgroupTextIndent: "8px", - secondOptgroupMarginTop: "24px", - groupedOptionFont: "Geist, sans-serif", - groupedOptionColor: "rgb(51, 54, 55)", - groupedOptionFontSize: "16px", - }); - - await select.click(); - const optionTwo = page.getByRole("option", { name: "Option Two" }); - await expect(optionTwo).toBeVisible(); - await optionTwo.hover(); - await expect(optionTwo).toHaveCSS("background-color", "rgb(236, 236, 235)"); - await optionTwo.click(); - await expect(select).toHaveValue("option2"); - - const grouped = page.locator("#select-grouped"); - await select.focus(); - await select.press("Tab"); - await expect(grouped).toBeFocused(); - - await grouped.selectOption({ label: "Item B2" }); - await expect(grouped).toHaveValue("Item B2"); - - const iconSelect = page.locator("#select-icons"); - await expect(iconSelect.locator("option .material-symbols-rounded")).toHaveCount(3); - await iconSelect.selectOption("animation"); - await expect(iconSelect).toHaveValue("animation"); - await expect(iconSelect.locator("selectedcontent")).toContainText("Motion"); -}); - -test("progress card contains full-width minimal progress and loading displays", async ({ page }) => { - await page.goto("/snapdesign"); - - const card = page.locator(".progress-card"); - await expect(card.getByRole("group", { name: "Minimal progress" })).toBeVisible(); - await expect(card.locator("progress")).toHaveCount(4); - await expect( - card.getByRole("progressbar", { name: "Loading", exact: true }), - ).toBeAttached(); - await expect(card.getByRole("progressbar", { name: "Braille progress" })).toBeAttached(); - await expect(card.getByRole("progressbar", { name: "Braille loading" })).toBeAttached(); - await expect(card.locator(".ascii-progress").first()).toContainText("65%"); - await expect(card.locator(".ascii-progress-value")).toHaveCount(2); - await expect(card.locator(".ascii-progress-cells > span")).toHaveCount(60); - await expect(card.locator(".ascii-loading-cell")).toHaveCount(20); - await expect(card.locator(".braille-progress-cells")).toContainText("⣿"); - await expect(card.locator(".braille-progress-cells")).toContainText("⣀"); - await expect(card.locator(".braille-loading-cell")).toHaveCount(40); - await expect(card.getByRole("slider")).toHaveCount(0); - await expect(card.locator(".material-progress")).toHaveCount(0); - - const [stackBox, progressBox, loadingBox, valueBox, brailleProgressBox, brailleLoadingBox] = await Promise.all([ - card.locator(".progress-stack").boundingBox(), - card.locator(".ascii-progress-visual").first().boundingBox(), - card.locator(".ascii-loading-visual").first().boundingBox(), - card.locator(".ascii-progress-value").first().boundingBox(), - card.locator(".braille-progress-visual").boundingBox(), - card.locator(".braille-loading-visual").boundingBox(), - ]); - expect(stackBox).not.toBeNull(); - expect(progressBox).not.toBeNull(); - expect(loadingBox).not.toBeNull(); - expect(valueBox).not.toBeNull(); - expect(brailleProgressBox).not.toBeNull(); - expect(brailleLoadingBox).not.toBeNull(); - expect(Math.abs(progressBox!.width - stackBox!.width)).toBeLessThan(0.5); - expect(Math.abs(loadingBox!.width - stackBox!.width)).toBeLessThan(0.5); - expect(Math.abs(brailleProgressBox!.width - stackBox!.width)).toBeLessThan(0.5); - expect(Math.abs(brailleLoadingBox!.width - stackBox!.width)).toBeLessThan(0.5); - expect( - Math.abs( - valueBox!.x + valueBox!.width / 2 - - (progressBox!.x + progressBox!.width / 2), - ), - ).toBeLessThan(0.5); - await expect(card.locator(".ascii-progress-value").first()).toHaveCSS( - "font-family", - /Geist Mono/, - ); - const brailleLoadingStyle = await card.locator(".braille-loading-cell").first().evaluate( - (element) => { - const style = getComputedStyle(element); - const glyph = getComputedStyle(element, "::before"); - return { - transform: style.transform, - animationName: glyph.animationName, - }; - }, - ); - expect(brailleLoadingStyle.transform).toBe("none"); - expect(brailleLoadingStyle.animationName).toContain("braille-loading-wave"); -}); - -test("dial specimens omit disabled controls and use a borderless direction dot", async ({ page }) => { - await page.goto("/snapdesign"); - - await expect(page.getByRole("slider", { name: /Disabled .* dial/ })).toHaveCount(0); - const dial = page.getByRole("slider", { name: "Skeuomorphic dial" }); - const directionDot = dial.locator(".dial-direction"); - await expect(directionDot).toHaveClass(/circle/); - await expect(directionDot).toHaveCSS("width", "8px"); - await expect(directionDot).toHaveCSS("height", "8px"); - expect( - await directionDot.evaluate((element) => - getComputedStyle(element).getPropertyValue("--material-rim-visibility").trim(), - ), - ).toBe("hidden"); - - const [dialBounds, directionBounds] = await Promise.all([ - dial.boundingBox(), - directionDot.boundingBox(), - ]); - expect(dialBounds).not.toBeNull(); - expect(directionBounds).not.toBeNull(); - expect(directionBounds!.x).toBeGreaterThanOrEqual(dialBounds!.x); - expect(directionBounds!.y).toBeGreaterThanOrEqual(dialBounds!.y); - expect(directionBounds!.x + directionBounds!.width).toBeLessThanOrEqual( - dialBounds!.x + dialBounds!.width, - ); - expect(directionBounds!.y + directionBounds!.height).toBeLessThanOrEqual( - dialBounds!.y + dialBounds!.height, - ); - const initialTransform = await directionDot.evaluate((element) => { - const matrix = new DOMMatrix(getComputedStyle(element).transform); - return { a: matrix.a, b: matrix.b, c: matrix.c, d: matrix.d }; - }); - expect(initialTransform).toEqual({ a: 1, b: 0, c: 0, d: 1 }); - const initialDirectionOffsetX = - directionBounds!.x + directionBounds!.width / 2 - - (dialBounds!.x + dialBounds!.width / 2); - - const value = dial.locator(".dial-value"); - await expect(value).toHaveText("320"); - await expect(dial).toHaveAttribute("aria-valuetext", "320"); - await expect(value).toHaveCSS("font-family", /Bitcount Grid Single/); - await expect( - page.getByRole("group", { name: "Skeuomorphic dial" }).locator("output"), - ).toHaveCount(0); - - const markers = dial.locator(".dial-marker"); - await expect(markers).toHaveCount(36); - await expect( - page.getByRole("slider", { name: "Minimal dial" }).locator(".dial-marker"), - ).toHaveCount(36); - await expect(dial.locator('.dial-marker.selected[data-marker-angle="320"]')).toHaveCount(1); - await expect(markers.first()).toHaveCSS("width", "3px"); - await expect(markers.first()).toHaveCSS("height", "3px"); - await expect(markers.first()).toHaveCSS("border-radius", "50%"); - const [dialBox, topMarkerBox] = await Promise.all([ - dial.boundingBox(), - markers.first().boundingBox(), - ]); - expect(dialBox).not.toBeNull(); - expect(topMarkerBox).not.toBeNull(); - expect(dialBox!.y - (topMarkerBox!.y + topMarkerBox!.height)).toBeGreaterThanOrEqual(5); - - await expect(async () => { - await dial.press("Home"); - expect(await dial.getAttribute("aria-valuenow")).toBe("0"); - }).toPass(); - await expect(value).toHaveText("0"); - const zeroMarker = dial.locator('.dial-marker.selected[data-marker-angle="0"]'); - await expect(zeroMarker).toHaveCount(1); - await expect.poll(() => - zeroMarker.evaluate((element) => { - const matrix = new DOMMatrix(getComputedStyle(element).transform); - return Math.hypot(matrix.a, matrix.b); - }), - ).toBeCloseTo(2); - await dial.press("ArrowRight"); - await expect(dial).toHaveAttribute("aria-valuenow", "10"); - await expect(value).toHaveText("10"); - await expect(dial.locator('.dial-marker.selected[data-marker-angle="10"]')).toHaveCount(1); - await dial.press("ArrowLeft"); - await expect(dial).toHaveAttribute("aria-valuenow", "0"); - const [rotatedDialBounds, rotatedDirectionBounds] = await Promise.all([ - dial.boundingBox(), - directionDot.boundingBox(), - ]); - expect(rotatedDialBounds).not.toBeNull(); - expect(rotatedDirectionBounds).not.toBeNull(); - const rotatedDirectionOffsetX = - rotatedDirectionBounds!.x + rotatedDirectionBounds!.width / 2; - const rotatedDialCenterX = - rotatedDialBounds!.x + rotatedDialBounds!.width / 2; - expect(rotatedDirectionOffsetX - rotatedDialCenterX).toBeCloseTo(0); - expect(initialDirectionOffsetX).not.toBeCloseTo(0); - expect(rotatedDirectionBounds!.y).toBeLessThan( - rotatedDialBounds!.y + rotatedDialBounds!.height / 2, - ); - const rotatedTransform = await directionDot.evaluate((element) => { - const matrix = new DOMMatrix(getComputedStyle(element).transform); - return { a: matrix.a, b: matrix.b, c: matrix.c, d: matrix.d }; - }); - expect(rotatedTransform).toEqual({ a: 1, b: 0, c: 0, d: 1 }); - - const pointerDialBox = await dial.boundingBox(); - expect(pointerDialBox).not.toBeNull(); - await dial.hover({ - position: { - x: pointerDialBox!.width - 2, - y: pointerDialBox!.height / 2, - }, - }); - await page.mouse.down(); - await expect(dial).toHaveClass(/dragging/); - await expect(dial.locator(".dial-marker.selected")).toHaveCSS( - "background-color", - "rgb(255, 93, 15)", - ); - await expect(dial.locator(".dial-marker.selected")).toHaveCSS( - "transition-duration", - "0.15s, 0s, 0.15s", - ); - await page.mouse.up(); - await expect(dial).not.toHaveClass(/dragging/); - await expect(dial.locator(".dial-marker.selected")).toHaveCSS( - "transition-duration", - "0.15s, 0.15s, 0.15s", - ); - - await page.emulateMedia({ reducedMotion: "reduce" }); - await expect(markers.first()).toHaveCSS("transition-duration", "0s"); -}); diff --git a/tests/e2e/playwright-matrix.ts b/tests/e2e/playwright-matrix.ts deleted file mode 100644 index c3ca5804..00000000 --- a/tests/e2e/playwright-matrix.ts +++ /dev/null @@ -1,67 +0,0 @@ -// Single source of truth for the snapsort Playwright test matrix: browser -// devices, framework demo servers, and the shared per-project settings. -// Every config builds its projects from here so all browsers and frameworks -// run tests under identical conditions (viewport, trace, screenshots) — add -// a browser or tweak an option in one place and every suite follows. -import { devices } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -export const repoRoot = resolve( - dirname(fileURLToPath(import.meta.url)), - "../..", -); - -export const BROWSERS = { - chromium: devices["Desktop Chrome"], - firefox: devices["Desktop Firefox"], - webkit: devices["Desktop Safari"], -} as const; -export type BrowserName = keyof typeof BROWSERS; - -export const FRAMEWORK_PORTS = { - svelte: Number(process.env.SNAPSORT_SVELTE_TEST_PORT ?? 3027), - react: Number(process.env.SNAPSORT_REACT_TEST_PORT ?? 3031), -} as const; -export type FrameworkName = keyof typeof FRAMEWORK_PORTS; - -const sharedUse = { - screenshot: "only-on-failure" as const, - trace: "retain-on-failure" as const, - viewport: { width: 1400, height: 950 }, -}; - -/** - * Cross product of frameworks x browsers as Playwright projects named - * `-`, all running the same `testMatch` set. - */ -export function frameworkBrowserProjects(options: { - frameworks: readonly FrameworkName[]; - browsers: readonly BrowserName[]; - testMatch: string[]; -}) { - return options.frameworks.flatMap((framework) => - options.browsers.map((browser) => ({ - name: `${framework}-${browser}`, - testMatch: options.testMatch, - use: { - ...BROWSERS[browser], - baseURL: `http://127.0.0.1:${FRAMEWORK_PORTS[framework]}`, - ...sharedUse, - }, - })), - ); -} - -/** One vite demo server per framework, on that framework's fixed test port. */ -export function frameworkWebServers(frameworks: readonly FrameworkName[]) { - return frameworks.map((framework) => ({ - cwd: repoRoot, - command: - `npx vite serve demo/${framework} --config demo/${framework}/vite.config.mjs ` + - `--host 127.0.0.1 --port ${FRAMEWORK_PORTS[framework]} --strictPort --force`, - url: `http://127.0.0.1:${FRAMEWORK_PORTS[framework]}`, - reuseExistingServer: false, - timeout: 30_000, - })); -} diff --git a/tests/e2e/shared/servers.ts b/tests/e2e/shared/servers.ts new file mode 100644 index 00000000..c2175e9f --- /dev/null +++ b/tests/e2e/shared/servers.ts @@ -0,0 +1,67 @@ +// Single source of truth for the e2e suites: repo paths, browser devices, +// dev servers, and one port table. Each project config +// (tests/e2e//playwright.config.ts) builds its servers and projects +// from here, so every suite runs under the same conditions and no two +// configs ever compete for a port when run side by side. +import { devices } from "@playwright/test"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +export const repoRoot = resolve( + dirname(fileURLToPath(import.meta.url)), + "../../..", +); + +/** + * Vite `/@fs` URL of core's entry, for in-page `import()` so a test can reach + * the same module instances (GlobalManager, containers) as the demo it drives. + */ +export const coreImportPath = `/@fs${repoRoot}/src/index.ts`; + +export const BROWSERS = { + chromium: devices["Desktop Chrome"], + firefox: devices["Desktop Firefox"], + webkit: devices["Desktop Safari"], +} as const; +export type BrowserName = keyof typeof BROWSERS; + +export type FrameworkName = "svelte" | "react"; + +function port(envName: string, fallback: number): number { + return Number(process.env[envName] ?? fallback); +} + +/** Every dev server port used by the e2e suites; each is unique. */ +export const PORTS = { + core: port("CORE_E2E_PORT", 3040), + assetBaseSvelte: port("ASSET_BASE_SVELTE_E2E_PORT", 3041), + assetBaseReact: port("ASSET_BASE_REACT_E2E_PORT", 3042), + snaplineSvelte: port("SNAPLINE_SVELTE_E2E_PORT", 3043), + snaplineReact: port("SNAPLINE_REACT_E2E_PORT", 3044), + snapsortSvelte: port("SNAPSORT_SVELTE_E2E_PORT", 3027), + snapsortReact: port("SNAPSORT_REACT_E2E_PORT", 3031), + snapsortLayout: port("SNAPSORT_LAYOUT_E2E_PORT", 3045), +} as const; + +/** Failure artifacts every suite keeps. */ +export const sharedUse = { + screenshot: "only-on-failure" as const, + trace: "retain-on-failure" as const, +}; + +export function baseURL(serverPort: number): string { + return `http://127.0.0.1:${serverPort}`; +} + +/** A vite dev server for one framework's demo app. */ +export function demoServer(framework: FrameworkName, serverPort: number) { + return { + cwd: repoRoot, + command: + `npx vite serve demo/${framework} --config demo/${framework}/vite.config.mjs ` + + `--host 127.0.0.1 --port ${serverPort} --strictPort --force`, + url: baseURL(serverPort), + reuseExistingServer: false, + timeout: 30_000, + }; +} diff --git a/tests/e2e/snapdesign-control-matrix.spec.ts b/tests/e2e/snapdesign-control-matrix.spec.ts deleted file mode 100644 index 98b84032..00000000 --- a/tests/e2e/snapdesign-control-matrix.spec.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { expect, test, type Locator } from "@playwright/test"; - -type CellGeometry = { - name: string; - left: number; - top: number; - right: number; - bottom: number; - width: number; - height: number; - scrollWidth: number; - scrollHeight: number; -}; - -type MatrixGeometry = { - left: number; - top: number; - right: number; - bottom: number; - clientWidth: number; - clientHeight: number; - scrollWidth: number; - scrollHeight: number; - cells: CellGeometry[]; -}; - -async function readMatrixGeometry(matrix: Locator): Promise { - return matrix.evaluate((element) => { - const matrixRect = element.getBoundingClientRect(); - return { - left: matrixRect.left, - top: matrixRect.top, - right: matrixRect.right, - bottom: matrixRect.bottom, - clientWidth: element.clientWidth, - clientHeight: element.clientHeight, - scrollWidth: element.scrollWidth, - scrollHeight: element.scrollHeight, - cells: Array.from( - element.querySelectorAll("[data-control-cell]"), - (cell) => { - const rect = cell.getBoundingClientRect(); - return { - name: cell.dataset.controlCell ?? "", - left: rect.left, - top: rect.top, - right: rect.right, - bottom: rect.bottom, - width: rect.width, - height: rect.height, - scrollWidth: cell.scrollWidth, - scrollHeight: cell.scrollHeight, - }; - }, - ), - }; - }); -} - -function roundedUnique(values: number[]) { - return new Set(values.map((value) => Math.round(value))).size; -} - -function expectTwoByThree(geometry: MatrixGeometry) { - expect(geometry.cells).toHaveLength(6); - expect( - Math.abs(geometry.clientWidth - geometry.clientHeight), - ).toBeLessThanOrEqual(1); - expect(roundedUnique(geometry.cells.map((cell) => cell.left))).toBe(2); - expect(roundedUnique(geometry.cells.map((cell) => cell.top))).toBe(3); - - const widths = geometry.cells.map((cell) => cell.width); - const heights = geometry.cells.map((cell) => cell.height); - expect(Math.max(...widths) - Math.min(...widths)).toBeLessThan(1); - expect(Math.max(...heights) - Math.min(...heights)).toBeLessThan(1); -} - -test("renders an interactive, responsive 2 by 3 control matrix", async ({ - page, -}) => { - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.setViewportSize({ width: 1440, height: 1000 }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="control-matrix"]'); - const stage = exhibit.locator(".control-matrix-stage"); - const matrix = exhibit.locator("[data-control-matrix]"); - await exhibit.scrollIntoViewIfNeeded(); - - await expect( - exhibit.getByRole("heading", { name: "Control matrix" }), - ).toBeVisible(); - await expect(stage).toHaveAttribute( - "aria-label", - "Interactive UI control matrix", - ); - expectTwoByThree(await readMatrixGeometry(matrix)); - - const button = exhibit.getByRole("button", { name: "Run action" }); - await expect(button).toHaveAttribute("aria-pressed", "false"); - await button.click(); - await expect(button).toHaveAttribute("aria-pressed", "true"); - - const dial = exhibit.getByRole("slider", { name: "Dial specimen" }); - await expect(dial).toHaveAttribute("aria-valuenow", "130"); - await dial.focus(); - await page.keyboard.press("ArrowRight"); - await expect(dial).toHaveAttribute("aria-valuenow", "140"); - - const slider = exhibit.getByRole("slider", { name: "Slider specimen" }); - await expect(slider).toHaveValue("65"); - await slider.focus(); - await page.keyboard.press("ArrowRight"); - await expect(slider).toHaveValue("70"); - - const toggle = exhibit.getByRole("switch", { name: "Toggle specimen" }); - await expect(toggle).toHaveAttribute("aria-checked", "true"); - await toggle.click(); - await expect(toggle).toHaveAttribute("aria-checked", "false"); - - const checkbox = exhibit.getByRole("checkbox", { - name: "Checkbox specimen", - }); - await expect(checkbox).toBeChecked(); - await checkbox.click(); - await expect(checkbox).not.toBeChecked(); - - await exhibit.getByRole("radio", { name: "Option B" }).click(); - await expect(exhibit.getByRole("radio", { name: "Option B" })).toBeChecked(); - await expect( - exhibit.getByRole("radio", { name: "Option A" }), - ).not.toBeChecked(); - const radioPositions = await exhibit - .getByRole("radiogroup", { name: "Radio specimen" }) - .getByRole("radio") - .evaluateAll((labels) => - labels.map((label) => { - const rect = label.getBoundingClientRect(); - return { left: rect.left, top: rect.top }; - }), - ); - expect( - Math.abs(radioPositions[0].left - radioPositions[1].left), - ).toBeLessThan(1); - expect(radioPositions[1].top).toBeGreaterThan(radioPositions[0].top); - - await page.setViewportSize({ width: 390, height: 844 }); - await exhibit.scrollIntoViewIfNeeded(); - const narrowGeometry = await readMatrixGeometry(matrix); - expectTwoByThree(narrowGeometry); - expect(narrowGeometry.scrollWidth).toBe(narrowGeometry.clientWidth); - expect(narrowGeometry.scrollHeight).toBe(narrowGeometry.clientHeight); - for (const cell of narrowGeometry.cells) { - expect(cell.left).toBeGreaterThanOrEqual(narrowGeometry.left - 1); - expect(cell.top).toBeGreaterThanOrEqual(narrowGeometry.top - 1); - expect(cell.right).toBeLessThanOrEqual(narrowGeometry.right + 1); - expect(cell.bottom).toBeLessThanOrEqual(narrowGeometry.bottom + 1); - } - - expect(pageErrors).toEqual([]); -}); - -test("autoplays every control in the matrix", async ({ page }) => { - await page.setViewportSize({ width: 1440, height: 1000 }); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="control-matrix"]'); - const matrix = exhibit.locator("[data-control-matrix]"); - await exhibit.scrollIntoViewIfNeeded(); - await expect(matrix).toHaveAttribute( - "data-control-autoplay-phase", - "complete", - { - timeout: 8_000, - }, - ); - - await expect( - exhibit.getByRole("button", { name: "Run action" }), - ).toHaveAttribute("aria-pressed", "true"); - await expect( - exhibit.getByRole("slider", { name: "Dial specimen" }), - ).toHaveAttribute("aria-valuenow", "200"); - await expect( - exhibit.getByRole("slider", { name: "Slider specimen" }), - ).toHaveValue("35"); - await expect( - exhibit.getByRole("switch", { name: "Toggle specimen" }), - ).toHaveAttribute("aria-checked", "false"); - await expect( - exhibit.getByRole("checkbox", { name: "Checkbox specimen" }), - ).not.toBeChecked(); - await expect(exhibit.getByRole("radio", { name: "Option B" })).toBeChecked(); - - await expect(matrix).toHaveAttribute( - "data-control-autoplay-phase", - "resting", - { timeout: 8_000 }, - ); - await expect( - exhibit.getByRole("slider", { name: "Slider specimen" }), - ).toHaveValue("65"); - await expect( - exhibit.getByRole("slider", { name: "Dial specimen" }), - ).toHaveAttribute("aria-valuenow", "130"); -}); diff --git a/tests/e2e/snapdesign-gallery-virtual-pointer.spec.ts b/tests/e2e/snapdesign-gallery-virtual-pointer.spec.ts deleted file mode 100644 index 39ac2941..00000000 --- a/tests/e2e/snapdesign-gallery-virtual-pointer.spec.ts +++ /dev/null @@ -1,1063 +0,0 @@ -import { expect, test, type Page } from "@playwright/test"; - -const INITIAL_ORDER = "todo-promo,todo-accessibility,todo-ssr,todo-publish"; -const FINAL_ORDER = "todo-accessibility,todo-ssr,todo-publish,todo-promo"; -const VIRTUAL_POINTER_ID = 2_000_000_001; -const NESTED_VIRTUAL_POINTER_ID = 2_000_000_002; -const NESTED_INITIAL_ROOT_ORDER = "inbox,planning,archive"; -const NESTED_INITIAL_CHILD_ORDER = "research,wireframes,review"; -const NESTED_FINAL_ROOT_ORDER = "review,archive,planning"; -const NESTED_FINAL_CHILD_ORDER = "inbox,research,wireframes"; - -type PointerTraceEvent = { - type: string; - pointerId: number | null; - pointerType: string | null; - isPrimary: boolean | null; - isTrusted: boolean; - button: number; - buttons: number; - clientX: number; - clientY: number; - cursorX: number | null; - cursorY: number | null; - cursorLeft: number | null; - cursorTop: number | null; - cursorState: string | null; - targetKind: "toggle" | "grip" | "list" | "other"; - itemId: string | null; - timestamp: number; -}; - -type GalleryFrame = { - timestamp: number; - phase: string | null; - active: string | null; - order: string | null; - completed: string | null; - targetIndex: string | null; - dropIndex: string | null; - cursorState: string | null; - ghostCount: number; - sessionStatus: string | null; - sessionPointerId: number | null; -}; - -type ViewportRect = { - left: number; - top: number; - right: number; - bottom: number; - width: number; - height: number; -}; - -type ScrollGeometry = { - scrollX: number; - scrollY: number; - demo: ViewportRect; - cursor: ViewportRect; -}; - -type InViewScrollSample = { - before: ScrollGeometry; - after: ScrollGeometry; - eventCount: number; -}; - -type GalleryTrace = { - events: PointerTraceEvent[]; - frames: GalleryFrame[]; - ghostObserved: boolean; - ghostEntryTypes: string[]; - dragSessionObserved: boolean; - inViewScroll: InViewScrollSample | null; - moveItemCalls: number; -}; - -function recordPageErrors(page: Page): string[] { - const errors: string[] = []; - page.on("pageerror", (error) => errors.push(error.message)); - return errors; -} - -async function openPausedGallery(page: Page) { - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const demo = page.locator(".todo-demo"); - await demo.scrollIntoViewIfNeeded(); - await expect(demo).toHaveAttribute("data-todo-phase", "reduced"); - await expect(demo).toHaveAttribute("data-todo-autoplay-active", "false"); - return demo; -} - -async function installGalleryTrace( - page: Page, - options: { - interruptOnActiveDrag?: boolean; - scrollDuringActiveDrag?: boolean; - } = {}, -): Promise { - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; - await page.evaluate( - async ({ - coreImportPath, - interruptOnActiveDrag, - scrollDuringActiveDrag, - virtualPointerId, - }) => { - const { GlobalManager } = await import(coreImportPath); - const demo = document.querySelector(".todo-demo"); - const list = demo?.querySelector('[data-demo="todo-list"]'); - const cursor = demo?.querySelector("[data-virtual-pointer]"); - const promo = demo?.querySelector( - '[data-todo-id="todo-promo"]', - ); - if (!demo || !list || !cursor || !promo) { - throw new Error("Todo Gallery trace targets are missing."); - } - - const containers = - GlobalManager.getInstance().data.dragAndDropContainers ?? []; - const container = containers.find( - (candidate: any) => candidate.element === list, - ); - if (!container) { - throw new Error("Todo Gallery SnapSort container is missing."); - } - - const trace = { - events: [], - frames: [], - ghostObserved: false, - ghostEntryTypes: [], - dragSessionObserved: false, - inViewScroll: null, - moveItemCalls: 0, - lastFrameSignature: "", - interruptionRequested: false, - inViewScrollRequested: false, - } as GalleryTrace & { - interruptionRequested: boolean; - inViewScrollRequested: boolean; - lastFrameSignature: string; - }; - - const addUnique = (values: string[], value: string | undefined) => { - if (value && !values.includes(value)) values.push(value); - }; - - const observeGhosts = (root: ParentNode = demo) => { - const entries = [ - ...(root instanceof Element && - root.matches("[data-snapsort-ghost-entry]") - ? [root] - : []), - ...root.querySelectorAll("[data-snapsort-ghost-entry]"), - ] as HTMLElement[]; - if (entries.length > 0) trace.ghostObserved = true; - for (const entry of entries) { - addUnique(trace.ghostEntryTypes, entry.dataset.snapsortGhostEntry); - } - }; - - const readViewportRect = (element: Element): ViewportRect => { - const rect = element.getBoundingClientRect(); - return { - left: rect.left, - top: rect.top, - right: rect.right, - bottom: rect.bottom, - width: rect.width, - height: rect.height, - }; - }; - - const readScrollGeometry = (): ScrollGeometry => ({ - scrollX: window.scrollX, - scrollY: window.scrollY, - demo: readViewportRect(demo), - cursor: readViewportRect(cursor), - }); - - const captureInViewScroll = () => { - trace.inViewScrollRequested = true; - const before = readScrollGeometry(); - const maxScrollY = Math.max( - 0, - document.documentElement.scrollHeight - window.innerHeight, - ); - const forwardTarget = Math.min(before.scrollY + 48, maxScrollY); - const targetScrollY = - forwardTarget !== before.scrollY - ? forwardTarget - : Math.max(0, before.scrollY - 48); - const previousScrollBehavior = - document.documentElement.style.scrollBehavior; - document.documentElement.style.scrollBehavior = "auto"; - window.scrollTo(before.scrollX, targetScrollY); - const after = readScrollGeometry(); - document.documentElement.style.scrollBehavior = previousScrollBehavior; - trace.inViewScroll = { - before, - after, - eventCount: trace.events.length, - }; - }; - - const recordFrame = (timestamp: number) => { - observeGhosts(); - const session = container.dragSession; - if (session?.status === "active") trace.dragSessionObserved = true; - if ( - scrollDuringActiveDrag && - session?.status === "active" && - !trace.inViewScrollRequested - ) { - captureInViewScroll(); - } - if ( - interruptOnActiveDrag && - session?.status === "active" && - !trace.interruptionRequested - ) { - trace.interruptionRequested = true; - window.scrollTo(0, document.documentElement.scrollHeight); - } - const frame: GalleryFrame = { - timestamp, - phase: demo.dataset.todoPhase ?? null, - active: demo.dataset.todoAutoplayActive ?? null, - order: list.dataset.todoOrder ?? null, - completed: promo.dataset.completed ?? null, - targetIndex: demo.dataset.todoTargetIndex ?? null, - dropIndex: demo.dataset.todoDropIndex ?? null, - cursorState: cursor.dataset.virtualPointerState ?? null, - ghostCount: demo.querySelectorAll("[data-snapsort-ghost-entry]") - .length, - sessionStatus: session?.status ?? null, - sessionPointerId: session?.pointerId ?? null, - }; - const signature = JSON.stringify({ ...frame, timestamp: 0 }); - if (signature !== trace.lastFrameSignature) { - trace.lastFrameSignature = signature; - trace.frames.push(frame); - } - }; - - const recordEvent = (event: Event) => { - if (!(event instanceof MouseEvent) || event.isTrusted) return; - const isPointerEvent = event instanceof PointerEvent; - if (isPointerEvent && event.pointerId !== virtualPointerId) return; - if ( - !isPointerEvent && - event.type !== "mousedown" && - event.type !== "mouseup" && - event.type !== "click" - ) { - return; - } - - const target = event.target instanceof Element ? event.target : null; - if (!isPointerEvent && !target?.closest(".todo-demo")) return; - const rect = cursor.getBoundingClientRect(); - const cursorX = Number(cursor.dataset.virtualPointerX); - const cursorY = Number(cursor.dataset.virtualPointerY); - const targetKind = target?.closest(".todo-toggle") - ? "toggle" - : target?.closest(".grip") - ? "grip" - : target?.closest('[data-demo="todo-list"]') - ? "list" - : "other"; - - trace.events.push({ - type: event.type, - pointerId: isPointerEvent ? event.pointerId : null, - pointerType: isPointerEvent ? event.pointerType : null, - isPrimary: isPointerEvent ? event.isPrimary : null, - isTrusted: event.isTrusted, - button: event.button, - buttons: event.buttons, - clientX: event.clientX, - clientY: event.clientY, - cursorX: Number.isFinite(cursorX) ? cursorX : null, - cursorY: Number.isFinite(cursorY) ? cursorY : null, - cursorLeft: Number.isFinite(rect.left) ? rect.left : null, - cursorTop: Number.isFinite(rect.top) ? rect.top : null, - cursorState: cursor.dataset.virtualPointerState ?? null, - targetKind, - itemId: - target?.closest("[data-todo-id]")?.dataset.todoId ?? - null, - timestamp: event.timeStamp, - }); - }; - - for (const type of [ - "pointerdown", - "mousedown", - "pointermove", - "pointerup", - "mouseup", - "pointercancel", - "click", - ]) { - document.addEventListener(type, recordEvent, { capture: true }); - } - - const observer = new MutationObserver((records) => { - for (const record of records) { - for (const node of record.addedNodes) { - if (node instanceof Element) observeGhosts(node); - } - } - recordFrame(performance.now()); - }); - observer.observe(demo, { - attributes: true, - childList: true, - subtree: true, - attributeFilter: [ - "data-completed", - "data-snapsort-ghost", - "data-snapsort-ghost-entry", - "data-todo-autoplay-active", - "data-todo-drop-index", - "data-todo-order", - "data-todo-phase", - "data-todo-target-index", - "data-virtual-pointer-state", - ], - }); - - container.engine.frameController.subscribe(({ timestamp }: any) => { - recordFrame(timestamp); - }); - recordFrame(performance.now()); - - if (typeof container.moveItem !== "function") { - throw new Error("Todo Gallery container has no moveItem API."); - } - container.moveItem = (..._args: unknown[]) => { - trace.moveItemCalls += 1; - throw new Error("Todo Gallery automation called moveItem()."); - }; - - ( - globalThis as typeof globalThis & { - __snapdesignVirtualPointerTrace?: GalleryTrace; - } - ).__snapdesignVirtualPointerTrace = trace; - }, - { - coreImportPath, - interruptOnActiveDrag: options.interruptOnActiveDrag ?? false, - scrollDuringActiveDrag: options.scrollDuringActiveDrag ?? false, - virtualPointerId: VIRTUAL_POINTER_ID, - }, - ); -} - -async function readGalleryTrace(page: Page): Promise { - return page.evaluate(() => { - const trace = ( - globalThis as typeof globalThis & { - __snapdesignVirtualPointerTrace?: GalleryTrace; - } - ).__snapdesignVirtualPointerTrace; - if (!trace) throw new Error("Todo Gallery trace was not installed."); - return { - events: trace.events, - frames: trace.frames, - ghostObserved: trace.ghostObserved, - ghostEntryTypes: trace.ghostEntryTypes, - dragSessionObserved: trace.dragSessionObserved, - inViewScroll: trace.inViewScroll, - moveItemCalls: trace.moveItemCalls, - }; - }); -} - -function frameAfter( - frames: GalleryFrame[], - start: number, - predicate: (frame: GalleryFrame) => boolean, -): number { - return frames.findIndex((frame, index) => index > start && predicate(frame)); -} - -test("drives the Todo reel through synthetic pointer events and a real SnapSort drop", async ({ - page, -}) => { - const pageErrors = recordPageErrors(page); - const demo = await openPausedGallery(page); - await installGalleryTrace(page); - - await page.emulateMedia({ reducedMotion: "no-preference" }); - - await expect - .poll( - async () => { - const trace = await readGalleryTrace(page); - const movedIndex = trace.frames.findIndex( - (frame) => frame.phase === "moved" && frame.order === FINAL_ORDER, - ); - const resetIndex = frameAfter( - trace.frames, - movedIndex, - (frame) => - frame.order === INITIAL_ORDER && - frame.completed === "false" && - frame.cursorState === "hidden" && - frame.ghostCount === 0 && - frame.sessionStatus === null, - ); - const secondMovedIndex = frameAfter( - trace.frames, - resetIndex, - (frame) => - frame.phase === "moved" && - frame.order === FINAL_ORDER && - frame.dropIndex === "3", - ); - return ( - movedIndex >= 0 && - resetIndex > movedIndex && - secondMovedIndex > resetIndex - ); - }, - { timeout: 15_000 }, - ) - .toBe(true); - - const trace = await readGalleryTrace(page); - expect(trace.moveItemCalls).toBe(0); - expect(trace.ghostObserved).toBe(true); - expect(trace.ghostEntryTypes.length).toBeGreaterThan(0); - expect(trace.dragSessionObserved).toBe(true); - expect( - trace.frames.some( - (frame) => - frame.sessionStatus === "active" && - frame.sessionPointerId === VIRTUAL_POINTER_ID, - ), - ).toBe(true); - expect(trace.frames.some((frame) => frame.targetIndex === "3")).toBe(true); - expect(trace.frames.some((frame) => frame.dropIndex === "3")).toBe(true); - - const toggleDownIndex = trace.events.findIndex( - (event) => event.type === "pointerdown" && event.targetKind === "toggle", - ); - const toggleMouseDownIndex = trace.events.findIndex( - (event, index) => - index > toggleDownIndex && - event.type === "mousedown" && - event.targetKind === "toggle", - ); - const toggleUpIndex = trace.events.findIndex( - (event, index) => - index > toggleMouseDownIndex && - event.type === "pointerup" && - event.targetKind === "toggle", - ); - const toggleMouseUpIndex = trace.events.findIndex( - (event, index) => - index > toggleUpIndex && - event.type === "mouseup" && - event.targetKind === "toggle", - ); - const clickIndex = trace.events.findIndex( - (event, index) => - index > toggleMouseUpIndex && - event.type === "click" && - event.targetKind === "toggle", - ); - const gripDownIndex = trace.events.findIndex( - (event, index) => - index > clickIndex && - event.type === "pointerdown" && - event.targetKind === "grip" && - event.itemId === "todo-promo", - ); - const gripUpIndex = trace.events.findIndex( - (event, index) => - index > gripDownIndex && - event.type === "pointerup" && - event.targetKind === "grip", - ); - - expect(toggleDownIndex).toBeGreaterThanOrEqual(0); - expect(toggleMouseDownIndex).toBeGreaterThan(toggleDownIndex); - expect(toggleUpIndex).toBeGreaterThan(toggleMouseDownIndex); - expect(toggleMouseUpIndex).toBeGreaterThan(toggleUpIndex); - expect(clickIndex).toBeGreaterThan(toggleMouseUpIndex); - expect(gripDownIndex).toBeGreaterThan(clickIndex); - expect(gripUpIndex).toBeGreaterThan(gripDownIndex); - expect(trace.events[toggleDownIndex]).toMatchObject({ - button: 0, - buttons: 1, - cursorState: "pressed", - }); - expect(trace.events[toggleUpIndex]).toMatchObject({ - button: 0, - buttons: 0, - }); - expect(trace.events[toggleMouseDownIndex]).toMatchObject({ - button: 0, - buttons: 1, - cursorState: "pressed", - }); - expect(trace.events[toggleMouseUpIndex]).toMatchObject({ - button: 0, - buttons: 0, - }); - expect(trace.events[gripDownIndex]).toMatchObject({ - button: 0, - buttons: 1, - cursorState: "pressed", - }); - expect(trace.events[gripUpIndex]).toMatchObject({ - button: 0, - buttons: 0, - }); - - const dragMoves = trace.events - .slice(gripDownIndex + 1, gripUpIndex) - .filter((event) => event.type === "pointermove" && event.buttons === 1); - expect(dragMoves.length).toBeGreaterThan(5); - expect(trace.events.some((event) => event.type === "pointercancel")).toBe( - false, - ); - - for (const [index, event] of trace.events.entries()) { - expect(event.isTrusted).toBe(false); - if (event.type.startsWith("pointer")) { - expect(event.pointerId).toBe(VIRTUAL_POINTER_ID); - expect(event.pointerType).toBe("mouse"); - expect(event.isPrimary).toBe(true); - } else { - expect(event.pointerId).toBeNull(); - expect(event.pointerType).toBeNull(); - expect(event.isPrimary).toBeNull(); - } - expect(event.cursorX).not.toBeNull(); - expect(event.cursorY).not.toBeNull(); - expect(event.cursorLeft).not.toBeNull(); - expect(event.cursorTop).not.toBeNull(); - // Chromium exposes constructed MouseEvent coordinates as integer CSS - // pixels even though the cursor transform retains sub-pixel precision. - expect(Math.abs(event.clientX - event.cursorX!)).toBeLessThanOrEqual(1.1); - expect(Math.abs(event.clientY - event.cursorY!)).toBeLessThanOrEqual(1.1); - expect(Math.abs(event.clientX - event.cursorLeft!)).toBeLessThanOrEqual( - 1.1, - ); - expect(Math.abs(event.clientY - event.cursorTop!)).toBeLessThanOrEqual(1.1); - if (index > 0) { - expect(event.timestamp).toBeGreaterThanOrEqual( - trace.events[index - 1].timestamp, - ); - } - } - - await expect(demo).toHaveAttribute("data-todo-autoplay-active", "true"); - expect(pageErrors).toEqual([]); -}); - -test("keeps the active virtual drag anchored to the demo during an in-view scroll", async ({ - page, -}) => { - const pageErrors = recordPageErrors(page); - const demo = await openPausedGallery(page); - await installGalleryTrace(page, { scrollDuringActiveDrag: true }); - await page.emulateMedia({ reducedMotion: "no-preference" }); - - await expect - .poll( - async () => { - const trace = await readGalleryTrace(page); - return ( - trace.inViewScroll !== null && - trace.frames.some( - (frame) => - frame.phase === "moved" && - frame.order === FINAL_ORDER && - frame.dropIndex === "3", - ) - ); - }, - { timeout: 8_000 }, - ) - .toBe(true); - - const trace = await readGalleryTrace(page); - const sample = trace.inViewScroll; - expect(sample).not.toBeNull(); - if (!sample) throw new Error("The in-view scroll sample was not recorded."); - - const scrollDeltaX = sample.after.scrollX - sample.before.scrollX; - const scrollDeltaY = sample.after.scrollY - sample.before.scrollY; - const demoDeltaX = sample.after.demo.left - sample.before.demo.left; - const demoDeltaY = sample.after.demo.top - sample.before.demo.top; - const cursorDeltaX = sample.after.cursor.left - sample.before.cursor.left; - const cursorDeltaY = sample.after.cursor.top - sample.before.cursor.top; - const beforeLocalX = sample.before.cursor.left - sample.before.demo.left; - const beforeLocalY = sample.before.cursor.top - sample.before.demo.top; - const afterLocalX = sample.after.cursor.left - sample.after.demo.left; - const afterLocalY = sample.after.cursor.top - sample.after.demo.top; - - expect(Math.abs(scrollDeltaY)).toBeGreaterThanOrEqual(40); - expect(Math.abs(demoDeltaX + scrollDeltaX)).toBeLessThanOrEqual(0.5); - expect(Math.abs(demoDeltaY + scrollDeltaY)).toBeLessThanOrEqual(0.5); - expect(Math.abs(cursorDeltaX - demoDeltaX)).toBeLessThanOrEqual(0.5); - expect(Math.abs(cursorDeltaY - demoDeltaY)).toBeLessThanOrEqual(0.5); - expect(Math.abs(afterLocalX - beforeLocalX)).toBeLessThanOrEqual(0.5); - expect(Math.abs(afterLocalY - beforeLocalY)).toBeLessThanOrEqual(0.5); - - expect(trace.moveItemCalls).toBe(0); - expect(trace.ghostObserved).toBe(true); - expect(trace.dragSessionObserved).toBe(true); - expect(trace.frames.some((frame) => frame.targetIndex === "3")).toBe(true); - expect(trace.frames.some((frame) => frame.dropIndex === "3")).toBe(true); - expect(trace.events.some((event) => event.type === "pointercancel")).toBe( - false, - ); - const firstPostScrollMove = trace.events - .slice(sample.eventCount) - .find((event) => event.type === "pointermove"); - expect(firstPostScrollMove).toBeDefined(); - expect( - Math.abs(firstPostScrollMove!.clientX - firstPostScrollMove!.cursorX!), - ).toBeLessThanOrEqual(1.1); - expect( - Math.abs(firstPostScrollMove!.clientY - firstPostScrollMove!.cursorY!), - ).toBeLessThanOrEqual(1.1); - expect( - Math.abs(firstPostScrollMove!.clientX - firstPostScrollMove!.cursorLeft!), - ).toBeLessThanOrEqual(1.1); - expect( - Math.abs(firstPostScrollMove!.clientY - firstPostScrollMove!.cursorTop!), - ).toBeLessThanOrEqual(1.1); - await expect(demo).toHaveAttribute("data-todo-autoplay-active", "true"); - expect(pageErrors).toEqual([]); -}); - -test("keeps autoplay active when a virtual drag leaves the viewport", async ({ - page, -}) => { - const pageErrors = recordPageErrors(page); - const demo = await openPausedGallery(page); - await installGalleryTrace(page, { interruptOnActiveDrag: true }); - await page.emulateMedia({ reducedMotion: "no-preference" }); - - await expect - .poll(async () => (await readGalleryTrace(page)).dragSessionObserved, { - timeout: 7_000, - }) - .toBe(true); - - await expect(demo).toHaveAttribute("data-todo-autoplay-active", "true"); - await expect(demo.locator('[data-demo="todo-list"]')).toHaveAttribute( - "data-todo-order", - FINAL_ORDER, - { timeout: 15_000 }, - ); - await expect(demo.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); - - const trace = await readGalleryTrace(page); - const cancel = trace.events.find((event) => event.type === "pointercancel"); - expect(cancel).toBeUndefined(); - expect(trace.moveItemCalls).toBe(0); - expect(trace.ghostObserved).toBe(true); - expect(trace.dragSessionObserved).toBe(true); - expect(pageErrors).toEqual([]); -}); - -test("keeps the virtual pointer reel static when reduced motion is requested", async ({ - page, -}) => { - const pageErrors = recordPageErrors(page); - const demo = await openPausedGallery(page); - await installGalleryTrace(page); - - await page.waitForTimeout(750); - - await expect(demo).toHaveAttribute("data-todo-phase", "reduced"); - await expect(demo).toHaveAttribute("data-todo-autoplay-active", "false"); - await expect(page.locator('[data-demo="todo-list"]')).toHaveAttribute( - "data-todo-order", - INITIAL_ORDER, - ); - await expect(page.locator('[data-todo-id="todo-promo"]')).toHaveAttribute( - "data-completed", - "true", - ); - const cursor = demo.locator("[data-virtual-pointer]"); - await expect(cursor).toHaveAttribute("data-virtual-pointer-state", "hidden"); - await expect(cursor).toHaveCSS("display", "none"); - await expect(page.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); - - const trace = await readGalleryTrace(page); - expect(trace.events).toEqual([]); - expect(trace.ghostObserved).toBe(false); - expect(trace.dragSessionObserved).toBe(false); - expect(trace.moveItemCalls).toBe(0); - expect(pageErrors).toEqual([]); -}); - -test("drives all three nested-container moves through real handle events", async ({ - page, -}) => { - const pageErrors = recordPageErrors(page); - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const demo = page.locator(".nested-demo"); - await demo.scrollIntoViewIfNeeded(); - await expect(demo).toHaveAttribute("data-nested-phase", "reduced"); - await expect(demo).toHaveAttribute("data-nested-autoplay-active", "false"); - await expect(demo.locator('[data-demo="nested-containers"]')).toHaveAttribute( - "data-nested-root-order", - NESTED_INITIAL_ROOT_ORDER, - ); - await expect(demo.locator("[data-nested-child-order]")).toHaveAttribute( - "data-nested-child-order", - NESTED_INITIAL_CHILD_ORDER, - ); - await expect(demo.locator(".snapsort-handle")).toHaveCount(6); - await expect(demo.locator("[data-nested-container-handle]")).toHaveCount(1); - await expect( - demo.locator("[data-virtual-pointer] .virtual-pointer-image"), - ).toHaveAttribute("src", /^data:image\/svg\+xml/); - - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; - await page.evaluate( - async ({ coreImportPath, pointerId }) => { - const { GlobalManager } = await import(coreImportPath); - const demo = document.querySelector(".nested-demo"); - const rootElement = demo?.querySelector( - '[data-demo="nested-containers"]', - ); - const childElement = demo?.querySelector( - '[data-nested-container-id="planning"]', - ); - const cursor = demo?.querySelector("[data-virtual-pointer]"); - if (!demo || !rootElement || !childElement || !cursor) { - throw new Error("Nested Gallery trace targets are missing."); - } - - const containers = - GlobalManager.getInstance().data.dragAndDropContainers ?? []; - const root = containers.find( - (candidate: any) => candidate.element === rootElement, - ); - const child = containers.find( - (candidate: any) => candidate.element === childElement, - ); - if (!root || !child) { - throw new Error("Nested Gallery SnapSort containers are missing."); - } - - type NestedEvent = { - type: string; - pointerId: number; - itemId: string | null; - handleKind: "item" | "container" | "other"; - buttons: number; - isTrusted: boolean; - clientX: number; - clientY: number; - cursorLeft: number; - cursorTop: number; - }; - type NestedFrame = { - phase: string | null; - rootOrder: string | null; - childOrder: string | null; - dropOwner: string | null; - dropIndex: string | null; - dropItem: string | null; - ghostCount: number; - sessionStatus: string | null; - sessionPointerId: number | null; - sessionItemId: string | null; - }; - type NestedTrace = { - events: NestedEvent[]; - frames: NestedFrame[]; - moveItemCalls: number; - ghostObserved: boolean; - childLocked: boolean; - lastFrameSignature: string; - }; - - const trace: NestedTrace = { - events: [], - frames: [], - moveItemCalls: 0, - ghostObserved: false, - childLocked: child.locked, - lastFrameSignature: "", - }; - - const recordFrame = () => { - const session = root.dragSession; - const ghostCount = demo.querySelectorAll( - "[data-snapsort-ghost-entry]", - ).length; - if (ghostCount > 0) trace.ghostObserved = true; - const frame: NestedFrame = { - phase: demo.dataset.nestedPhase ?? null, - rootOrder: rootElement.dataset.nestedRootOrder ?? null, - childOrder: - demo.querySelector("[data-nested-child-order]") - ?.dataset.nestedChildOrder ?? null, - dropOwner: demo.dataset.nestedDropOwner ?? null, - dropIndex: demo.dataset.nestedDropIndex ?? null, - dropItem: demo.dataset.nestedDropItem ?? null, - ghostCount, - sessionStatus: session?.status ?? null, - sessionPointerId: session?.pointerId ?? null, - sessionItemId: session?.primaryItem.itemId ?? null, - }; - const signature = JSON.stringify(frame); - if (signature !== trace.lastFrameSignature) { - trace.lastFrameSignature = signature; - trace.frames.push(frame); - } - }; - - const recordPointerEvent = (event: Event) => { - if (!(event instanceof PointerEvent) || event.pointerId !== pointerId) { - return; - } - const target = event.target instanceof Element ? event.target : null; - const cursorRect = cursor.getBoundingClientRect(); - trace.events.push({ - type: event.type, - pointerId: event.pointerId, - itemId: - target?.closest("[data-nested-item-id]")?.dataset - .nestedItemId ?? - target?.closest("[data-nested-container-id]")?.dataset - .nestedContainerId ?? - null, - handleKind: target?.closest("[data-nested-container-handle]") - ? "container" - : target?.closest("[data-nested-item-handle]") - ? "item" - : "other", - buttons: event.buttons, - isTrusted: event.isTrusted, - clientX: event.clientX, - clientY: event.clientY, - cursorLeft: cursorRect.left, - cursorTop: cursorRect.top, - }); - }; - - for (const type of [ - "pointerdown", - "pointermove", - "pointerup", - "pointercancel", - ]) { - document.addEventListener(type, recordPointerEvent, { capture: true }); - } - - const observer = new MutationObserver(recordFrame); - observer.observe(demo, { - attributes: true, - childList: true, - subtree: true, - attributeFilter: [ - "data-nested-child-order", - "data-nested-drop-index", - "data-nested-drop-item", - "data-nested-drop-owner", - "data-nested-phase", - "data-nested-root-order", - "data-snapsort-ghost-entry", - ], - }); - root.engine.frameController.subscribe(recordFrame); - recordFrame(); - - for (const container of [root, child]) { - if (typeof container.moveItem !== "function") { - throw new Error("Nested Gallery container has no moveItem API."); - } - container.moveItem = (..._args: unknown[]) => { - trace.moveItemCalls += 1; - throw new Error("Nested Gallery automation called moveItem()."); - }; - } - - ( - globalThis as typeof globalThis & { - __snapdesignNestedPointerTrace?: NestedTrace; - } - ).__snapdesignNestedPointerTrace = trace; - }, - { coreImportPath, pointerId: NESTED_VIRTUAL_POINTER_ID }, - ); - - await page.emulateMedia({ reducedMotion: "no-preference" }); - await expect - .poll( - () => - page.evaluate( - ({ finalRootOrder, finalChildOrder }) => { - const trace = ( - globalThis as typeof globalThis & { - __snapdesignNestedPointerTrace?: { - frames: Array<{ - phase: string | null; - rootOrder: string | null; - childOrder: string | null; - dropOwner: string | null; - dropIndex: string | null; - dropItem: string | null; - }>; - }; - } - ).__snapdesignNestedPointerTrace; - return Boolean( - trace?.frames.some( - (frame) => - frame.phase === "complete" && - frame.rootOrder === finalRootOrder && - frame.childOrder === finalChildOrder && - frame.dropOwner === "root" && - frame.dropIndex === "2" && - frame.dropItem === "planning", - ), - ); - }, - { - finalRootOrder: NESTED_FINAL_ROOT_ORDER, - finalChildOrder: NESTED_FINAL_CHILD_ORDER, - }, - ), - { timeout: 10_000 }, - ) - .toBe(true); - - const trace = await page.evaluate(() => { - const trace = ( - globalThis as typeof globalThis & { - __snapdesignNestedPointerTrace?: { - events: Array<{ - type: string; - pointerId: number; - itemId: string | null; - handleKind: "item" | "container" | "other"; - buttons: number; - isTrusted: boolean; - clientX: number; - clientY: number; - cursorLeft: number; - cursorTop: number; - }>; - frames: Array<{ - phase: string | null; - rootOrder: string | null; - childOrder: string | null; - dropOwner: string | null; - dropIndex: string | null; - dropItem: string | null; - ghostCount: number; - sessionStatus: string | null; - sessionPointerId: number | null; - sessionItemId: string | null; - }>; - moveItemCalls: number; - ghostObserved: boolean; - childLocked: boolean; - }; - } - ).__snapdesignNestedPointerTrace; - if (!trace) throw new Error("Nested Gallery trace was not installed."); - return trace; - }); - - expect(trace.moveItemCalls).toBe(0); - expect(trace.ghostObserved).toBe(true); - expect(trace.childLocked).toBe(false); - expect( - trace.frames.some( - (frame) => - frame.phase === "inside" && - frame.rootOrder === "planning,archive" && - frame.childOrder === "inbox,research,wireframes,review" && - frame.dropOwner === "planning" && - frame.dropIndex === "0" && - frame.dropItem === "inbox", - ), - ).toBe(true); - expect( - trace.frames.some( - (frame) => - frame.phase === "outside" && - frame.rootOrder === "planning,review,archive" && - frame.childOrder === NESTED_FINAL_CHILD_ORDER && - frame.dropOwner === "root" && - frame.dropIndex === "1" && - frame.dropItem === "review", - ), - ).toBe(true); - - for (const itemId of ["inbox", "review", "planning"]) { - expect( - trace.frames.some( - (frame) => - frame.sessionStatus === "active" && - frame.sessionPointerId === NESTED_VIRTUAL_POINTER_ID && - frame.sessionItemId === itemId, - ), - ).toBe(true); - } - - const pointerDowns = trace.events.filter( - (event) => event.type === "pointerdown", - ); - expect(pointerDowns.slice(0, 3)).toMatchObject([ - { - pointerId: NESTED_VIRTUAL_POINTER_ID, - itemId: "inbox", - handleKind: "item", - buttons: 1, - isTrusted: false, - }, - { - pointerId: NESTED_VIRTUAL_POINTER_ID, - itemId: "review", - handleKind: "item", - buttons: 1, - isTrusted: false, - }, - { - pointerId: NESTED_VIRTUAL_POINTER_ID, - itemId: "planning", - handleKind: "container", - buttons: 1, - isTrusted: false, - }, - ]); - expect(trace.events.some((event) => event.type === "pointercancel")).toBe( - false, - ); - expect(trace.events.length).toBeGreaterThan(20); - for (const event of trace.events) { - expect(event.pointerId).toBe(NESTED_VIRTUAL_POINTER_ID); - expect(event.isTrusted).toBe(false); - expect(Math.abs(event.clientX - event.cursorLeft)).toBeLessThanOrEqual(1.1); - expect(Math.abs(event.clientY - event.cursorTop)).toBeLessThanOrEqual(1.1); - } - - const cursorBox = await demo.locator("[data-virtual-pointer]").boundingBox(); - expect(cursorBox?.width).toBe(32); - expect(cursorBox?.height).toBe(32); - expect(pageErrors).toEqual([]); -}); diff --git a/tests/e2e/snapdesign-kanban-board.spec.ts b/tests/e2e/snapdesign-kanban-board.spec.ts deleted file mode 100644 index 1f0a2076..00000000 --- a/tests/e2e/snapdesign-kanban-board.spec.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { expect, test } from "@playwright/test"; - -async function dragBetween( - page: import("@playwright/test").Page, - source: import("@playwright/test").Locator, - target: import("@playwright/test").Locator, -) { - const sourceBox = await source.boundingBox(); - const targetBox = await target.boundingBox(); - if (!sourceBox || !targetBox) throw new Error("Kanban geometry is missing"); - - await page.mouse.move( - sourceBox.x + sourceBox.width / 2, - sourceBox.y + sourceBox.height / 2, - ); - await page.mouse.down(); - await page.mouse.move( - targetBox.x + targetBox.width / 2, - targetBox.y + targetBox.height / 2, - { steps: 16 }, - ); - await page.mouse.up(); -} - -test("Kanban board anchors two initially centered columns and supports progressive moves", async ({ - page, -}) => { - await page.setViewportSize({ width: 1440, height: 1100 }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="kanban-board"]'); - await exhibit.scrollIntoViewIfNeeded(); - const stage = exhibit.locator(".kanban-stage"); - const columns = exhibit.locator(".kanban-column"); - - await expect(columns).toHaveCount(2); - await expect(columns.nth(0).locator(".kanban-card")).toHaveCount(3); - await expect(columns.nth(1).locator(".kanban-card")).toHaveCount(3); - await expect(exhibit.locator(".kanban-card-category")).toHaveCount(6); - await expect(exhibit.locator(".kanban-card-due")).toHaveCount(6); - await expect(exhibit.locator(".kanban-card-avatar")).toHaveCount(6); - await expect( - exhibit.locator('[data-kanban-card="kanban-research"]'), - ).toHaveAttribute( - "aria-label", - "Research references, Research, due Today, assigned to Maya Chen", - ); - await expect(exhibit.getByRole("heading", { name: "To Do" })).toBeVisible(); - await expect(exhibit.getByRole("heading", { name: "Done" })).toBeVisible(); - - const layout = await stage.evaluate((element) => { - const stageRect = element.getBoundingClientRect(); - const board = element.querySelector(".kanban-board"); - const viewport = element.querySelector(".kanban-viewport"); - if (!board) throw new Error("Kanban board is missing"); - if (!viewport) throw new Error("Kanban viewport is missing"); - const boardRect = board.getBoundingClientRect(); - const viewportRect = viewport.getBoundingClientRect(); - return { - overflow: getComputedStyle(element).overflow, - centeredHorizontally: - Math.abs( - boardRect.left + boardRect.width / 2 - - (stageRect.left + stageRect.width / 2), - ) < 2, - centeredInitially: - Math.abs( - boardRect.top + boardRect.height / 2 - - (viewportRect.top + viewportRect.height / 2), - ) < 2, - boardTop: boardRect.top, - shorterThanStage: boardRect.height < stageRect.height * 0.75, - pageOverflow: document.documentElement.scrollWidth > window.innerWidth, - }; - }); - expect(layout).toMatchObject({ - overflow: "hidden", - centeredHorizontally: true, - centeredInitially: true, - shorterThanStage: true, - pageOverflow: false, - }); - - await dragBetween( - page, - exhibit.locator('[data-kanban-card="kanban-research"]'), - exhibit.locator('[data-kanban-card="kanban-copy"]'), - ); - await expect - .poll(() => - columns - .nth(0) - .locator(".kanban-card") - .evaluateAll((cards) => - cards.map((card) => card.getAttribute("data-kanban-card")), - ), - ) - .toEqual(["kanban-wireframe", "kanban-copy", "kanban-research"]); - - await dragBetween( - page, - exhibit.locator('[data-kanban-card="kanban-research"]'), - exhibit.locator('[data-kanban-card="kanban-components"]'), - ); - await expect(columns.nth(0).locator(".kanban-card")).toHaveCount(2); - await expect(columns.nth(1).locator(".kanban-card")).toHaveCount(4); - await expect( - columns.nth(1).locator('[data-kanban-card="kanban-research"]'), - ).toHaveCount(1); - await expect - .poll(() => - stage.locator(".kanban-board").evaluate((board) => - board.getBoundingClientRect().top, - ), - ) - .toBeCloseTo(layout.boardTop, 0); - expect(pageErrors).toEqual([]); -}); diff --git a/tests/e2e/snapdesign-precision-slider.spec.ts b/tests/e2e/snapdesign-precision-slider.spec.ts deleted file mode 100644 index a4abdac5..00000000 --- a/tests/e2e/snapdesign-precision-slider.spec.ts +++ /dev/null @@ -1,818 +0,0 @@ -import { expect, test } from "@playwright/test"; - -const geometryTolerance = 0.5; -const precisionCenterGap = 20; -const precisionIdleTickHeight = 8; -const precisionTickOpacity = 1; -const precisionTickWidth = 2; -const visibleLabelOpacity = 0.29; -const minimumLabelDarkness = 70; -const maximumLabelDarkness = 94; - -type OrangeAlignment = { - orangeCount: number; - markerIndex: number; - centerDelta: number; -}; - -type SelectionPresentation = { - accentColor: string; - tickColor: string; - labelColor: string; - accentTickCount: number; - accentLabelCount: number; - activeZIndex: number; - maximumZIndex: number; - maximumZIndexCount: number; - tickTransitionProperty: string; - labelTransitionProperty: string; -}; - -test("sliders keep native controls in SSR and own unique Engine visual layers", async ({ - page, - request, -}) => { - const response = await request.get("/snapdesign"); - - expect(response.ok()).toBe(true); - const html = await response.text(); - expect(html).toContain('id="precision-range"'); - expect(html).toContain('id="precision-range-engine"'); - expect(html).toContain('type="range"'); - - await page.goto("/snapdesign"); - - const sliderCount = await page.locator(".slider").count(); - expect(sliderCount).toBeGreaterThan(0); - await expect(page.locator(".slider > input[type=range]")).toHaveCount( - sliderCount, - ); - await expect( - page.locator(".slider > .snap-engine-canvas.slider-visual"), - ).toHaveCount(sliderCount); - - const engineIds = await page - .locator(".slider > .snap-engine-canvas.slider-visual") - .evaluateAll((engines) => engines.map((engine) => engine.id)); - expect(engineIds.every(Boolean)).toBe(true); - expect(new Set(engineIds).size).toBe(engineIds.length); -}); - -test("precision slider uses stable compositor-only markers with a tapered lens", async ({ - page, -}) => { - await page.setViewportSize({ width: 1000, height: 900 }); - await page.goto("/snapdesign"); - - const input = page.getByRole("slider", { name: "Precision slider" }); - const slider = input.locator(".."); - const ruler = slider.locator(".precision-ruler"); - const marks = ruler.locator(".precision-mark"); - const ticks = ruler.locator(".precision-tick"); - const labels = ruler.locator(".precision-label"); - - await input.scrollIntoViewIfNeeded(); - await expect(ruler).toHaveCSS("opacity", "1"); - await expect(marks).toHaveCount(101); - await expect(ticks).toHaveCount(101); - await expect(labels).toHaveCount(101); - await expect(ruler.locator(".precision-coarse-mark")).toHaveCount(0); - await expect(ruler.locator(".precision-zoom-mark")).toHaveCount(0); - - expect( - await marks.evaluateAll((elements) => - elements.every( - (element) => - element.querySelectorAll(".precision-tick").length === 1 && - element.querySelectorAll(".precision-label").length === 1, - ), - ), - ).toBe(true); - expect( - await ticks.evaluateAll((elements) => - elements.every((element) => getComputedStyle(element).height === "24px"), - ), - ).toBe(true); - expect( - await labels.evaluateAll((elements) => - elements.every( - (element) => Number.parseFloat(getComputedStyle(element).opacity) === 0, - ), - ), - ).toBe(true); - - const idleTickMetrics = await ticks.evaluateAll((elements) => { - const metrics = elements.map((element) => { - const box = element.getBoundingClientRect(); - return { - height: box.height, - opacity: Number.parseFloat(getComputedStyle(element).opacity), - width: box.width, - }; - }); - return { - minimumHeight: Math.min(...metrics.map(({ height }) => height)), - maximumHeight: Math.max(...metrics.map(({ height }) => height)), - minimumOpacity: Math.min(...metrics.map(({ opacity }) => opacity)), - maximumOpacity: Math.max(...metrics.map(({ opacity }) => opacity)), - minimumWidth: Math.min(...metrics.map(({ width }) => width)), - maximumWidth: Math.max(...metrics.map(({ width }) => width)), - }; - }); - expect(idleTickMetrics.minimumHeight).toBeCloseTo(precisionIdleTickHeight, 2); - expect(idleTickMetrics.maximumHeight).toBeCloseTo(precisionIdleTickHeight, 2); - expect(idleTickMetrics.minimumOpacity).toBeCloseTo(precisionTickOpacity, 3); - expect(idleTickMetrics.maximumOpacity).toBeCloseTo(precisionTickOpacity, 3); - expect(idleTickMetrics.minimumWidth).toBeCloseTo(precisionTickWidth, 2); - expect(idleTickMetrics.maximumWidth).toBeCloseTo(precisionTickWidth, 2); - - const initialMarkCount = await marks.count(); - const initialLabelCount = await labels.count(); - const initialPrecisionNodes = await ruler.evaluateHandle((element) => [ - ...element.querySelectorAll( - ".precision-mark, .precision-tick, .precision-label", - ), - ]); - const markerBounds = await ticks.evaluateAll((elements) => { - const firstBox = elements[0].getBoundingClientRect(); - const lastBox = elements[elements.length - 1].getBoundingClientRect(); - return { - start: firstBox.left + firstBox.width / 2, - end: lastBox.left + lastBox.width / 2, - }; - }); - const inputBox = await input.boundingBox(); - expect(inputBox).not.toBeNull(); - - const readVisibleLabelTexts = () => - labels.evaluateAll( - (elements, opacityThreshold) => - elements - .filter( - (element) => - Number.parseFloat(getComputedStyle(element).opacity) >= - opacityThreshold, - ) - .map((element) => element.textContent?.trim()), - visibleLabelOpacity, - ); - - const readOrangeAlignment = () => - slider.evaluate((root) => { - const thumb = root.querySelector(".slider-thumb"); - const orangeMarks = [ - ...root.querySelectorAll(".precision-mark"), - ].filter( - (mark) => - mark.querySelector(".precision-tick")?.style - .backgroundColor === "var(--slider-accent-color)", - ); - const orangeTick = - orangeMarks[0]?.querySelector(".precision-tick"); - - if (!thumb || !orangeTick || orangeMarks.length !== 1) { - return { - orangeCount: orangeMarks.length, - markerIndex: -1, - centerDelta: Number.POSITIVE_INFINITY, - }; - } - - const thumbBox = thumb.getBoundingClientRect(); - const tickBox = orangeTick.getBoundingClientRect(); - return { - orangeCount: orangeMarks.length, - markerIndex: Number(orangeMarks[0].dataset.markerIndex), - centerDelta: - tickBox.left + - tickBox.width / 2 - - (thumbBox.left + thumbBox.width / 2), - }; - }); - - const assertOrangeAlignment = ( - alignment: OrangeAlignment, - currentValue: string, - ) => { - expect(alignment.orangeCount).toBe(1); - expect(alignment.markerIndex).toBe(Math.round(Number(currentValue))); - expect(Math.abs(alignment.centerDelta)).toBeLessThan(geometryTolerance); - }; - - const assertOrangeAligned = async () => { - const [alignment, currentValue] = await Promise.all([ - readOrangeAlignment(), - input.inputValue(), - ]); - assertOrangeAlignment(alignment, currentValue); - }; - - const waitForLensFrame = () => - page.evaluate( - () => - new Promise((resolve) => { - requestAnimationFrame(() => resolve()); - }), - ); - - const setDraggedValue = async (nextValue: number) => { - return slider.evaluate((root, value) => { - const inputElement = root.querySelector( - 'input[type="range"]', - ); - if (!inputElement) throw new Error("Precision slider input is missing"); - - inputElement.value = String(value); - inputElement.dispatchEvent(new Event("input", { bubbles: true })); - - return new Promise<{ - alignment: OrangeAlignment; - currentValue: string; - presentation: SelectionPresentation; - }>((resolve) => { - requestAnimationFrame(() => { - const thumb = root.querySelector(".slider-thumb"); - const markerNodes = [ - ...root.querySelectorAll(".precision-mark"), - ]; - const orangeMarks = markerNodes.filter( - (mark) => - mark.querySelector(".precision-tick")?.style - .backgroundColor === "var(--slider-accent-color)", - ); - const orangeTick = - orangeMarks[0]?.querySelector(".precision-tick"); - const activeIndex = Math.round(Number(inputElement.value)); - const activeMarker = markerNodes.find( - (marker) => Number(marker.dataset.markerIndex) === activeIndex, - ); - const activeTick = - activeMarker?.querySelector(".precision-tick"); - const activeLabel = - activeMarker?.querySelector(".precision-label"); - const accentProbe = document.createElement("span"); - accentProbe.style.backgroundColor = "var(--slider-accent-color)"; - root.append(accentProbe); - const accentColor = getComputedStyle(accentProbe).backgroundColor; - accentProbe.remove(); - const zIndices = markerNodes.map((marker) => { - const zIndex = Number.parseInt(getComputedStyle(marker).zIndex, 10); - return Number.isNaN(zIndex) ? 0 : zIndex; - }); - const maximumZIndex = Math.max(...zIndices); - const presentation = { - accentColor, - tickColor: activeTick - ? getComputedStyle(activeTick).backgroundColor - : "", - labelColor: activeLabel ? getComputedStyle(activeLabel).color : "", - accentTickCount: markerNodes.filter((marker) => { - const tick = marker.querySelector(".precision-tick"); - return tick - ? getComputedStyle(tick).backgroundColor === accentColor - : false; - }).length, - accentLabelCount: markerNodes.filter((marker) => { - const label = - marker.querySelector(".precision-label"); - return label - ? getComputedStyle(label).color === accentColor - : false; - }).length, - activeZIndex: activeMarker - ? Number.parseInt(getComputedStyle(activeMarker).zIndex, 10) - : Number.NEGATIVE_INFINITY, - maximumZIndex, - maximumZIndexCount: zIndices.filter( - (zIndex) => zIndex === maximumZIndex, - ).length, - tickTransitionProperty: activeTick - ? getComputedStyle(activeTick).transitionProperty - : "", - labelTransitionProperty: activeLabel - ? getComputedStyle(activeLabel).transitionProperty - : "", - }; - - if (!thumb || !orangeTick || orangeMarks.length !== 1) { - resolve({ - alignment: { - orangeCount: orangeMarks.length, - markerIndex: -1, - centerDelta: Number.POSITIVE_INFINITY, - }, - currentValue: inputElement.value, - presentation, - }); - return; - } - - const thumbBox = thumb.getBoundingClientRect(); - const tickBox = orangeTick.getBoundingClientRect(); - resolve({ - alignment: { - orangeCount: orangeMarks.length, - markerIndex: Number(orangeMarks[0].dataset.markerIndex), - centerDelta: - tickBox.left + - tickBox.width / 2 - - (thumbBox.left + thumbBox.width / 2), - }, - currentValue: inputElement.value, - presentation, - }); - }); - }); - }, nextValue); - }; - - const assertSelectionPresentation = (presentation: SelectionPresentation) => { - expect(presentation.tickColor).toBe(presentation.accentColor); - expect(presentation.labelColor).toBe(presentation.accentColor); - expect(presentation.accentTickCount).toBe(1); - expect(presentation.accentLabelCount).toBe(1); - expect(presentation.activeZIndex).toBe(presentation.maximumZIndex); - expect(presentation.maximumZIndexCount).toBe(1); - expect( - presentation.tickTransitionProperty - .split(",") - .map((property) => property.trim()), - ).toEqual(["transform"]); - expect( - presentation.labelTransitionProperty - .split(",") - .map((property) => property.trim()), - ).toEqual(["transform", "opacity"]); - }; - - await page.mouse.move( - inputBox!.x + inputBox!.width / 2, - inputBox!.y + inputBox!.height / 2, - ); - await expect.poll(readVisibleLabelTexts).toEqual(["50"]); - const hoverReadout = await marks - .filter({ has: page.locator('.precision-label:text-is("50")') }) - .evaluate((marker) => { - const tick = marker.querySelector(".precision-tick"); - const label = marker.querySelector(".precision-label"); - if (!tick || !label) throw new Error("Hover readout is incomplete"); - const markerNodes = [ - ...(marker.parentElement?.querySelectorAll( - ".precision-mark", - ) ?? []), - ]; - const ordinaryMarker = markerNodes.find( - (candidate) => candidate.dataset.markerIndex === "49", - ); - const ordinaryTick = - ordinaryMarker?.querySelector(".precision-tick"); - const ordinaryLabel = - ordinaryMarker?.querySelector(".precision-label"); - if (!ordinaryTick || !ordinaryLabel) { - throw new Error("Ordinary precision marker is missing"); - } - const zIndices = markerNodes.map((candidate) => { - const zIndex = Number.parseInt(getComputedStyle(candidate).zIndex, 10); - return Number.isNaN(zIndex) ? 0 : zIndex; - }); - const maximumZIndex = Math.max(...zIndices); - return { - labelHeight: label.getBoundingClientRect().height, - labelFontSize: Number.parseFloat(getComputedStyle(label).fontSize), - labelOpacity: Number.parseFloat(getComputedStyle(label).opacity), - labelColor: getComputedStyle(label).color, - ordinaryLabelColor: getComputedStyle(ordinaryLabel).color, - tickHeight: tick.getBoundingClientRect().height, - tickOpacity: Number.parseFloat(getComputedStyle(tick).opacity), - tickColor: getComputedStyle(tick).backgroundColor, - ordinaryTickColor: getComputedStyle(ordinaryTick).backgroundColor, - zIndex: Number.parseInt(getComputedStyle(marker).zIndex, 10), - maximumZIndex, - maximumZIndexCount: zIndices.filter( - (zIndex) => zIndex === maximumZIndex, - ).length, - }; - }); - expect(hoverReadout.labelHeight).toBeCloseTo( - hoverReadout.labelFontSize * 0.78, - 1, - ); - expect(hoverReadout.labelOpacity).toBe(1); - expect(hoverReadout.labelColor).toBe(hoverReadout.ordinaryLabelColor); - expect(hoverReadout.tickHeight).toBeCloseTo(precisionIdleTickHeight, 2); - expect(hoverReadout.tickOpacity).toBe(precisionTickOpacity); - expect(hoverReadout.tickColor).toBe(hoverReadout.ordinaryTickColor); - expect(hoverReadout.zIndex).toBe(hoverReadout.maximumZIndex); - expect(hoverReadout.maximumZIndexCount).toBe(1); - - await page.mouse.move(inputBox!.x - 10, inputBox!.y + inputBox!.height / 2); - await expect.poll(readVisibleLabelTexts).toEqual([]); - - await page.mouse.move( - inputBox!.x + inputBox!.width / 2, - inputBox!.y + inputBox!.height / 2, - ); - await page.mouse.down(); - await expect(slider).toHaveClass(/dragging/); - - const initialSnapshot = await setDraggedValue(50); - assertOrangeAlignment( - initialSnapshot.alignment, - initialSnapshot.currentValue, - ); - assertSelectionPresentation(initialSnapshot.presentation); - - await expect - .poll(readVisibleLabelTexts) - .toEqual(["48", "49", "50", "51", "52"]); - await assertOrangeAligned(); - - const draggedTickMetrics = await ticks.evaluateAll((elements) => { - const metrics = elements.map((element) => { - const box = element.getBoundingClientRect(); - return { - height: box.height, - opacity: Number.parseFloat(getComputedStyle(element).opacity), - width: box.width, - }; - }); - return { - minimumHeight: Math.min(...metrics.map(({ height }) => height)), - minimumOpacity: Math.min(...metrics.map(({ opacity }) => opacity)), - maximumOpacity: Math.max(...metrics.map(({ opacity }) => opacity)), - minimumWidth: Math.min(...metrics.map(({ width }) => width)), - maximumWidth: Math.max(...metrics.map(({ width }) => width)), - }; - }); - expect(draggedTickMetrics.minimumHeight).toBeGreaterThanOrEqual( - precisionIdleTickHeight - 0.01, - ); - expect(draggedTickMetrics.minimumOpacity).toBeGreaterThanOrEqual( - precisionTickOpacity - 0.001, - ); - expect(draggedTickMetrics.maximumOpacity).toBeLessThanOrEqual( - precisionTickOpacity, - ); - expect(draggedTickMetrics.minimumWidth).toBeCloseTo(precisionTickWidth, 2); - expect(draggedTickMetrics.maximumWidth).toBeCloseTo(precisionTickWidth, 2); - - const grayTickPresentation = await ticks.evaluateAll((elements) => { - const grayTicks = elements.filter( - (element) => - element.style.backgroundColor !== "var(--slider-accent-color)", - ); - return { - count: grayTicks.length, - colors: [ - ...new Set( - grayTicks.map((element) => getComputedStyle(element).backgroundColor), - ), - ], - opacities: [ - ...new Set( - grayTicks.map((element) => - Number.parseFloat(getComputedStyle(element).opacity), - ), - ), - ], - }; - }); - expect(grayTickPresentation.count).toBe(100); - expect(grayTickPresentation.colors).toHaveLength(1); - expect(grayTickPresentation.opacities).toEqual([precisionTickOpacity]); - - const selectedTick = marks - .filter({ has: page.locator('.precision-label:text-is("50")') }) - .locator(".precision-tick"); - await expect - .poll(() => - selectedTick.evaluate( - (element) => element.getBoundingClientRect().height, - ), - ) - .toBeGreaterThan(23.5); - - const visibleReadouts = await marks.evaluateAll( - (elements, opacityThreshold) => - elements - .flatMap((marker) => { - const label = marker.querySelector(".precision-label"); - const tick = marker.querySelector(".precision-tick"); - if ( - !label || - !tick || - Number.parseFloat(getComputedStyle(label).opacity) < - opacityThreshold - ) { - return []; - } - - const markerBox = marker.getBoundingClientRect(); - const tickBox = tick.getBoundingClientRect(); - const labelBox = label.getBoundingClientRect(); - return [ - { - index: Number(marker.getAttribute("data-marker-index")), - text: label.textContent?.trim(), - markerCenter: markerBox.left + markerBox.width / 2, - tickCenter: tickBox.left + tickBox.width / 2, - tickHeight: tickBox.height, - labelCenter: labelBox.left + labelBox.width / 2, - labelColor: label.style.color, - }, - ]; - }) - .sort((left, right) => left.index - right.index), - visibleLabelOpacity, - ); - - expect(visibleReadouts.map(({ text }) => text)).toEqual([ - "48", - "49", - "50", - "51", - "52", - ]); - for (let index = 0; index < visibleReadouts.length; index += 1) { - const readout = visibleReadouts[index]; - expect(Math.abs(readout.markerCenter - readout.tickCenter)).toBeLessThan( - geometryTolerance, - ); - expect(Math.abs(readout.labelCenter - readout.tickCenter)).toBeLessThan( - geometryTolerance, - ); - } - - const visibleGaps = visibleReadouts - .slice(1) - .map( - (readout, index) => - readout.tickCenter - visibleReadouts[index].tickCenter, - ); - expect(visibleGaps[1]).toBeCloseTo(precisionCenterGap, 0); - expect(visibleGaps[2]).toBeCloseTo(precisionCenterGap, 0); - expect(visibleGaps[0]).toBeGreaterThan(0); - expect(visibleGaps[0]).toBeLessThan(visibleGaps[1]); - expect(visibleGaps[3]).toBeGreaterThan(0); - expect(visibleGaps[3]).toBeLessThan(visibleGaps[2]); - - const lensCenters = await marks.evaluateAll((elements) => - elements.slice(46, 55).map((element) => { - const tick = element.querySelector(".precision-tick"); - const box = tick?.getBoundingClientRect(); - return box ? box.left + box.width / 2 : Number.NaN; - }), - ); - const leftLensGaps = [ - lensCenters[4] - lensCenters[3], - lensCenters[3] - lensCenters[2], - lensCenters[2] - lensCenters[1], - lensCenters[1] - lensCenters[0], - ]; - const rightLensGaps = [ - lensCenters[5] - lensCenters[4], - lensCenters[6] - lensCenters[5], - lensCenters[7] - lensCenters[6], - lensCenters[8] - lensCenters[7], - ]; - for (const gaps of [leftLensGaps, rightLensGaps]) { - expect(gaps[0]).toBeCloseTo(precisionCenterGap, 0); - for (let index = 1; index < gaps.length; index += 1) { - expect(gaps[index]).toBeGreaterThan(0); - expect(gaps[index]).toBeLessThan(gaps[index - 1]); - } - } - - for (const readout of visibleReadouts.filter(({ index }) => index !== 50)) { - const darkness = Number(readout.labelColor.match(/ (\d+)%/)?.[1]); - expect(darkness).toBeGreaterThanOrEqual(minimumLabelDarkness); - expect(darkness).toBeLessThanOrEqual(maximumLabelDarkness); - } - expect(visibleReadouts[2].tickHeight).toBeGreaterThan( - visibleReadouts[1].tickHeight, - ); - expect(visibleReadouts[1].tickHeight).toBeGreaterThan( - visibleReadouts[0].tickHeight, - ); - expect(visibleReadouts[2].tickHeight).toBeGreaterThan( - visibleReadouts[3].tickHeight, - ); - expect(visibleReadouts[3].tickHeight).toBeGreaterThan( - visibleReadouts[4].tickHeight, - ); - - expect( - await marks.evaluateAll((elements) => - elements.every((marker) => { - const label = marker.querySelector(".precision-label"); - const tick = marker.querySelector(".precision-tick"); - return ( - marker.getAttribute("style")?.includes("translate3d") === true && - marker.style.left === "" && - marker.style.height === "" && - tick?.style.height === "" && - tick?.style.opacity === "" && - label?.style.left === "" && - label?.style.bottom === "" && - label?.style.fontSize === "" - ); - }), - ), - ).toBe(true); - expect( - await labels.evaluateAll( - (elements) => - new Set(elements.map((element) => getComputedStyle(element).fontSize)) - .size, - ), - ).toBe(1); - await expect(selectedTick).toHaveCSS("box-shadow", "none"); - const selectedLabel = marks - .filter({ has: page.locator('.precision-label:text-is("50")') }) - .locator(".precision-label"); - await expect(selectedLabel).toHaveCSS("font-weight", "400"); - await expect(selectedLabel).toHaveCSS("text-shadow", "none"); - expect( - await selectedTick.evaluate((element) => element.style.backgroundColor), - ).toBe("var(--slider-accent-color)"); - expect(await selectedLabel.evaluate((element) => element.style.color)).toBe( - "var(--slider-accent-color)", - ); - - const assertOrderedAndContained = async () => { - const centers = await ticks.evaluateAll((elements) => - elements.map((element) => { - const box = element.getBoundingClientRect(); - return box.left + box.width / 2; - }), - ); - for (let index = 0; index < centers.length; index += 1) { - expect(centers[index]).toBeGreaterThanOrEqual( - markerBounds.start - geometryTolerance, - ); - expect(centers[index]).toBeLessThanOrEqual( - markerBounds.end + geometryTolerance, - ); - if (index > 0) { - expect(centers[index]).toBeGreaterThanOrEqual(centers[index - 1]); - } - } - }; - - const assertEdgeSelectionDominates = async ( - rimIndex: number, - activeIndex: number, - interiorIndex: number, - ) => { - await expect - .poll(() => - marks.evaluateAll( - (elements, { indices, idleHeight }) => { - const [rim, active, interior] = indices.map((index) => { - const marker = elements[index]; - const tick = marker.querySelector(".precision-tick"); - const label = - marker.querySelector(".precision-label"); - return { - tickHeight: tick?.getBoundingClientRect().height ?? 0, - labelHeight: label?.getBoundingClientRect().height ?? 0, - }; - }); - return { - rimUsesIdleHeight: Math.abs(rim.tickHeight - idleHeight) < 0.1, - selectedUsesFullHeight: active.tickHeight > 23.5, - selectedTickDominates: active.tickHeight > rim.tickHeight, - selectedLabelDominates: active.labelHeight > rim.labelHeight, - interiorTapers: - interior.tickHeight > rim.tickHeight && - interior.tickHeight < active.tickHeight, - rimFallsOffFaster: rim.labelHeight < interior.labelHeight, - }; - }, - { - indices: [rimIndex, activeIndex, interiorIndex], - idleHeight: precisionIdleTickHeight, - }, - ), - ) - .toEqual({ - rimUsesIdleHeight: true, - selectedUsesFullHeight: true, - selectedTickDominates: true, - selectedLabelDominates: true, - interiorTapers: true, - rimFallsOffFaster: true, - }); - }; - - await assertOrderedAndContained(); - - for (const nextValue of [8, 50.4, 92]) { - const snapshot = await setDraggedValue(nextValue); - assertOrangeAlignment(snapshot.alignment, snapshot.currentValue); - assertSelectionPresentation(snapshot.presentation); - await assertOrderedAndContained(); - } - const centeredSnapshot = await setDraggedValue(50); - assertOrangeAlignment( - centeredSnapshot.alignment, - centeredSnapshot.currentValue, - ); - assertSelectionPresentation(centeredSnapshot.presentation); - - const nearLeftSnapshot = await setDraggedValue(1); - assertOrangeAlignment( - nearLeftSnapshot.alignment, - nearLeftSnapshot.currentValue, - ); - assertSelectionPresentation(nearLeftSnapshot.presentation); - await assertEdgeSelectionDominates(0, 1, 2); - await assertOrderedAndContained(); - - const nearRightSnapshot = await setDraggedValue(99); - assertOrangeAlignment( - nearRightSnapshot.alignment, - nearRightSnapshot.currentValue, - ); - assertSelectionPresentation(nearRightSnapshot.presentation); - await assertEdgeSelectionDominates(100, 99, 98); - await assertOrderedAndContained(); - - await page.mouse.move(inputBox!.x + 1, inputBox!.y + inputBox!.height / 2); - await expect.poll(() => input.inputValue()).toBe("0"); - await waitForLensFrame(); - await assertOrangeAligned(); - await expect.poll(readVisibleLabelTexts).toEqual(["0", "1", "2"]); - await assertOrderedAndContained(); - - await page.mouse.move( - inputBox!.x + inputBox!.width - 1, - inputBox!.y + inputBox!.height / 2, - ); - await expect.poll(() => input.inputValue()).toBe("100"); - await waitForLensFrame(); - await assertOrangeAligned(); - await expect.poll(readVisibleLabelTexts).toEqual(["98", "99", "100"]); - await assertOrderedAndContained(); - - expect(await marks.count()).toBe(initialMarkCount); - expect(await labels.count()).toBe(initialLabelCount); - await page.mouse.up(); - await expect(slider).not.toHaveClass(/dragging/); - await expect.poll(readVisibleLabelTexts).toEqual(["100"]); - expect((await readOrangeAlignment()).orangeCount).toBe(0); - await page.mouse.move( - inputBox!.x + inputBox!.width + 10, - inputBox!.y + inputBox!.height / 2, - ); - await expect.poll(readVisibleLabelTexts).toEqual([]); - await expect - .poll(() => - ticks.evaluateAll((elements) => - Math.max( - ...elements.map((element) => element.getBoundingClientRect().height), - ), - ), - ) - .toBeLessThan(8.5); - const releasedTickMetrics = await ticks.evaluateAll((elements) => ({ - minimumHeight: Math.min( - ...elements.map((element) => element.getBoundingClientRect().height), - ), - minimumOpacity: Math.min( - ...elements.map((element) => - Number.parseFloat(getComputedStyle(element).opacity), - ), - ), - maximumOpacity: Math.max( - ...elements.map((element) => - Number.parseFloat(getComputedStyle(element).opacity), - ), - ), - })); - expect(releasedTickMetrics.minimumHeight).toBeGreaterThanOrEqual( - precisionIdleTickHeight - 0.01, - ); - expect(releasedTickMetrics.minimumOpacity).toBeGreaterThanOrEqual( - precisionTickOpacity - 0.001, - ); - expect(releasedTickMetrics.maximumOpacity).toBeLessThanOrEqual( - precisionTickOpacity, - ); - expect(await marks.count()).toBe(initialMarkCount); - expect(await labels.count()).toBe(initialLabelCount); - expect( - await ruler.evaluate((element, initialNodes) => { - const currentNodes = [ - ...element.querySelectorAll( - ".precision-mark, .precision-tick, .precision-label", - ), - ]; - return ( - currentNodes.length === initialNodes.length && - currentNodes.every((node, index) => node === initialNodes[index]) - ); - }, initialPrecisionNodes), - ).toBe(true); - await initialPrecisionNodes.dispose(); -}); diff --git a/tests/e2e/snapdesign-sideways-cards.spec.ts b/tests/e2e/snapdesign-sideways-cards.spec.ts deleted file mode 100644 index 26df9a10..00000000 --- a/tests/e2e/snapdesign-sideways-cards.spec.ts +++ /dev/null @@ -1,408 +0,0 @@ -import { expect, test, type Page } from "@playwright/test"; - -test("sideways playing cards flip accessibly and preserve drag reordering", async ({ - page, -}) => { - await page.setViewportSize({ width: 1440, height: 1100 }); - await page.emulateMedia({ reducedMotion: "reduce" }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="sideways-insert"]'); - await exhibit.scrollIntoViewIfNeeded(); - const demo = exhibit.locator(".sideways-demo"); - await expect(demo).toHaveAttribute("data-sideways-phase", "reduced"); - await expect(demo).toHaveAttribute("data-sideways-autoplay-active", "false"); - const cards = exhibit.locator(".sideways-list > .snapsort-item"); - - await expect(cards).toHaveCount(4); - const clubs = exhibit.getByRole("button", { name: /3 of clubs/ }); - const diamonds = exhibit.getByRole("button", { name: /5 of diamonds/ }); - await expect(clubs).toHaveCount(1); - await expect(diamonds).toHaveCount(1); - await expect( - exhibit.getByRole("button", { name: /7 of hearts/ }), - ).toHaveCount(1); - await expect( - exhibit.getByRole("button", { name: /9 of spades/ }), - ).toHaveCount(1); - - await clubs.click(); - await expect(clubs).toHaveAttribute("aria-pressed", "true"); - await expect(clubs).toHaveAttribute("data-card-side", "back"); - await expect( - clubs.locator(".card-back-label", { hasText: "SnapSort" }), - ).toHaveCount(2); - const cardBackFits = await clubs.evaluate((element) => { - const frame = element.querySelector(".card-back-frame"); - const labels = element.querySelectorAll(".card-back-label"); - if (!frame || labels.length !== 2) return false; - const frameRect = frame.getBoundingClientRect(); - return [...labels].every((label) => { - const labelRect = label.getBoundingClientRect(); - return ( - labelRect.left >= frameRect.left && labelRect.right <= frameRect.right - ); - }); - }); - expect(cardBackFits).toBe(true); - - await diamonds.focus(); - await page.keyboard.press("Enter"); - await expect(diamonds).toHaveAttribute("aria-pressed", "true"); - await page.keyboard.press("Space"); - await expect(diamonds).toHaveAttribute("aria-pressed", "false"); - - const cardGeometry = await exhibit - .locator(".playing-card") - .evaluateAll((elements) => - elements.map((element) => { - const rect = element.getBoundingClientRect(); - const pip = element.querySelector(".card-pip"); - return { - ratio: rect.width / rect.height, - maskImage: pip ? getComputedStyle(pip).maskImage : "none", - }; - }), - ); - for (const card of cardGeometry) { - expect(card.ratio).toBeCloseTo(5 / 7, 2); - expect(card.maskImage).not.toBe("none"); - } - - const firstBox = await cards.nth(0).boundingBox(); - const lastBox = await cards.nth(3).boundingBox(); - if (!firstBox || !lastBox) - throw new Error("Playing-card geometry is missing"); - await page.mouse.move( - firstBox.x + firstBox.width / 2, - firstBox.y + firstBox.height / 2, - ); - await page.mouse.down(); - await page.mouse.move( - lastBox.x + lastBox.width + 12, - lastBox.y + lastBox.height / 2, - { steps: 16 }, - ); - const targetSpacer = exhibit.locator( - '[data-snapsort-ghost-entry="target-spacer"]', - ); - await expect(targetSpacer).toHaveCount(1); - await expect(targetSpacer).toHaveCSS( - "background-color", - "rgb(211, 211, 210)", - ); - await expect(targetSpacer).toHaveCSS("outline-style", "none"); - await page.mouse.up(); - - await expect - .poll(() => - exhibit - .locator(".playing-card") - .evaluateAll((elements) => - elements.map((element) => element.getAttribute("data-card-suit")), - ), - ) - .toEqual(["diamonds", "hearts", "spades", "clubs"]); - await expect(clubs).toHaveAttribute("aria-pressed", "true"); - await expect(clubs).toHaveAttribute("data-card-side", "back"); - - await clubs.click(); - await expect(clubs).toHaveAttribute("aria-pressed", "false"); - await expect(clubs).toHaveAttribute("data-card-side", "front"); - expect(pageErrors).toEqual([]); -}); - -type SidewaysFrame = { - phase: string | null; - cycle: string | null; - order: string | null; - revealId: string | null; - dropItem: string | null; - dropIndex: string | null; - sides: Record; -}; - -type SidewaysTrace = { - frames: SidewaysFrame[]; - clickTargets: string[]; - activeDragItems: string[]; - ghostObserved: boolean; - moveItemCalls: number; -}; - -async function installSidewaysTrace(page: Page) { - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; - await page.evaluate( - async ({ coreImportPath }) => { - const { GlobalManager } = await import(coreImportPath); - const demo = document.querySelector(".sideways-demo"); - const list = demo?.querySelector( - '[data-demo="sideways-insert"]', - ); - if (!demo || !list) { - throw new Error("Sideways Gallery trace targets are missing."); - } - - const containers = - GlobalManager.getInstance().data.dragAndDropContainers ?? []; - const container = containers.find( - (candidate: any) => candidate.element === list, - ); - if (!container) { - throw new Error("Sideways Gallery SnapSort container is missing."); - } - - const trace = { - frames: [], - clickTargets: [], - activeDragItems: [], - ghostObserved: false, - moveItemCalls: 0, - lastFrameSignature: "", - lastActiveDragItem: null, - } as SidewaysTrace & { - lastFrameSignature: string; - lastActiveDragItem: string | null; - }; - - const captureFrame = () => { - const session = container.dragSession; - const activeItem = - session?.status === "active" - ? String(session.primaryItem.itemId) - : null; - if (activeItem !== trace.lastActiveDragItem) { - trace.lastActiveDragItem = activeItem; - if (activeItem) trace.activeDragItems.push(activeItem); - } - if (demo.querySelector("[data-snapsort-ghost-entry]")) { - trace.ghostObserved = true; - } - - const sides = Object.fromEntries( - [ - ...demo.querySelectorAll("[data-sideways-card-id]"), - ].map((item) => [ - item.dataset.sidewaysCardId ?? "", - item.querySelector(".playing-card")?.dataset - .cardSide ?? null, - ]), - ); - const frame: SidewaysFrame = { - phase: demo.dataset.sidewaysPhase ?? null, - cycle: demo.dataset.sidewaysCycle ?? null, - order: list.dataset.sidewaysOrder ?? null, - revealId: demo.dataset.sidewaysRevealId ?? null, - dropItem: demo.dataset.sidewaysDropItem ?? null, - dropIndex: demo.dataset.sidewaysDropIndex ?? null, - sides, - }; - const signature = JSON.stringify(frame); - if (signature !== trace.lastFrameSignature) { - trace.lastFrameSignature = signature; - trace.frames.push(frame); - } - }; - - document.addEventListener( - "click", - (event) => { - if ( - !(event instanceof MouseEvent) || - event.isTrusted || - !(event.target instanceof Element) - ) { - return; - } - const card = event.target.closest( - "[data-sideways-card-id]", - ); - if (card) trace.clickTargets.push(card.dataset.sidewaysCardId ?? ""); - }, - { capture: true }, - ); - - const observer = new MutationObserver(captureFrame); - observer.observe(demo, { - attributes: true, - childList: true, - subtree: true, - attributeFilter: [ - "data-card-side", - "data-sideways-cycle", - "data-sideways-drop-index", - "data-sideways-drop-item", - "data-sideways-order", - "data-sideways-phase", - "data-sideways-reveal-id", - "data-snapsort-ghost-entry", - ], - }); - container.engine.frameController.subscribe(captureFrame); - captureFrame(); - - if (typeof container.moveItem !== "function") { - throw new Error("Sideways Gallery container has no moveItem API."); - } - container.moveItem = (..._args: unknown[]) => { - trace.moveItemCalls += 1; - throw new Error("Sideways Gallery automation called moveItem()."); - }; - - ( - globalThis as typeof globalThis & { - __sidewaysTrace?: SidewaysTrace; - } - ).__sidewaysTrace = trace; - }, - { coreImportPath }, - ); -} - -async function readSidewaysTrace(page: Page): Promise { - return page.evaluate(() => { - const trace = ( - globalThis as typeof globalThis & { - __sidewaysTrace?: SidewaysTrace; - } - ).__sidewaysTrace; - if (!trace) throw new Error("Sideways Gallery trace was not installed."); - return { - frames: trace.frames, - clickTargets: trace.clickTargets, - activeDragItems: trace.activeDragItems, - ghostObserved: trace.ghostObserved, - moveItemCalls: trace.moveItemCalls, - }; - }); -} - -test("autoplays four flips, three real shuffles, and rotating reveals", async ({ - page, -}) => { - test.setTimeout(30_000); - await page.setViewportSize({ width: 1440, height: 1100 }); - await page.emulateMedia({ reducedMotion: "reduce" }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const demo = page.locator(".sideways-demo"); - await demo.scrollIntoViewIfNeeded(); - await expect(demo).toHaveAttribute("data-sideways-phase", "reduced"); - await installSidewaysTrace(page); - await page.emulateMedia({ reducedMotion: "no-preference" }); - - await expect - .poll( - async () => { - const trace = await readSidewaysTrace(page); - return trace.frames.some( - (frame) => - frame.phase === "complete" && - frame.cycle === "2" && - frame.revealId === "side-design", - ); - }, - { timeout: 24_000 }, - ) - .toBe(true); - - const trace = await readSidewaysTrace(page); - expect(trace.clickTargets.slice(0, 5)).toEqual([ - "side-discover", - "side-design", - "side-build", - "side-ship", - "side-discover", - ]); - expect(trace.activeDragItems.slice(0, 3)).toEqual([ - "side-discover", - "side-ship", - "side-design", - ]); - expect(trace.frames).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - phase: "shuffle-1", - order: "side-design,side-build,side-ship,side-discover", - dropItem: "side-discover", - dropIndex: "3", - }), - expect.objectContaining({ - phase: "shuffle-2", - order: "side-ship,side-design,side-build,side-discover", - dropItem: "side-ship", - dropIndex: "0", - }), - expect.objectContaining({ - phase: "shuffle-3", - order: "side-ship,side-build,side-discover,side-design", - dropItem: "side-design", - dropIndex: "3", - }), - expect.objectContaining({ - phase: "complete", - cycle: "1", - revealId: "side-discover", - sides: { - "side-build": "back", - "side-design": "back", - "side-discover": "front", - "side-ship": "back", - }, - }), - expect.objectContaining({ - phase: "complete", - cycle: "2", - revealId: "side-design", - sides: { - "side-build": "back", - "side-design": "front", - "side-discover": "back", - "side-ship": "back", - }, - }), - ]), - ); - expect(trace.ghostObserved).toBe(true); - expect(trace.moveItemCalls).toBe(0); - expect(pageErrors).toEqual([]); -}); - -test("trusted input takes control of the sideways autoplay", async ({ - page, -}) => { - await page.setViewportSize({ width: 1440, height: 1100 }); - await page.emulateMedia({ reducedMotion: "no-preference" }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="sideways-insert"]'); - const demo = exhibit.locator(".sideways-demo"); - await demo.scrollIntoViewIfNeeded(); - await expect(demo).toHaveAttribute("data-sideways-autoplay-active", "true"); - - const hearts = exhibit.getByRole("button", { name: /7 of hearts/ }); - await hearts.click(); - const manualStartedAt = Date.now(); - await expect(demo).toHaveAttribute("data-sideways-manual", "true"); - await expect(demo).toHaveAttribute("data-sideways-autoplay-active", "false"); - await expect(demo.locator("[data-virtual-pointer]")).toHaveAttribute( - "data-virtual-pointer-state", - "hidden", - ); - - await page.locator(".gallery-hero").scrollIntoViewIfNeeded(); - await expect(demo).toHaveAttribute("data-sideways-manual", "true"); - await expect(demo).toHaveAttribute("data-sideways-autoplay-active", "false"); - await expect(demo).toHaveAttribute("data-sideways-manual", "false", { - timeout: 10_000, - }); - expect(Date.now() - manualStartedAt).toBeGreaterThanOrEqual(7_500); - await expect(demo).toHaveAttribute("data-sideways-autoplay-active", "true"); - expect(pageErrors).toEqual([]); -}); diff --git a/tests/e2e/snapdesign-swap-controls.spec.ts b/tests/e2e/snapdesign-swap-controls.spec.ts deleted file mode 100644 index 3161dafd..00000000 --- a/tests/e2e/snapdesign-swap-controls.spec.ts +++ /dev/null @@ -1,285 +0,0 @@ -import { expect, test } from "@playwright/test"; - -test("runs independent gallery drags concurrently", async ({ page }) => { - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.setViewportSize({ width: 1440, height: 900 }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; - const pointerImportPath = - "/src/routes/snapdesign/gallery/virtual-pointer.ts"; - const report = await page.evaluate( - async ({ coreImportPath, pointerImportPath }) => { - const [{ GlobalManager }, { VirtualPointerController }] = - await Promise.all([ - import(coreImportPath), - import(pointerImportPath), - ]); - const requireElement = (selector: string) => { - const element = document.querySelector(selector); - if (!element) throw new Error(`Missing concurrency target: ${selector}`); - return element; - }; - - const swapRootElement = requireElement( - '[data-demo="swap-mode"]', - ); - const sidewaysRootElement = requireElement( - '[data-demo="sideways-insert"]', - ); - const containers = - GlobalManager.getInstance().data.dragAndDropContainers ?? []; - const swapRoot = containers.find( - (container: { element?: Element }) => - container.element === swapRootElement, - ); - const sidewaysRoot = containers.find( - (container: { element?: Element }) => - container.element === sidewaysRootElement, - ); - if ( - !swapRoot || - !sidewaysRoot || - swapRoot.engine !== sidewaysRoot.engine - ) { - throw new Error("Independent gallery roots do not share one engine."); - } - - const swapDemo = requireElement(".swap-stage"); - const sidewaysDemo = requireElement(".sideways-demo"); - const swapHandle = requireElement( - '[data-swap-label="A"] .swap-tile-label', - ); - const sidewaysHandle = requireElement( - '[data-sideways-card-id="side-discover"] .playing-card', - ); - const swapCursor = swapDemo.querySelector( - "[data-virtual-pointer]", - ); - const sidewaysCursor = sidewaysDemo.querySelector( - "[data-virtual-pointer]", - ); - if (!swapCursor || !sidewaysCursor) { - throw new Error("Concurrent virtual pointers are missing."); - } - - const controller = new AbortController(); - const swapPointer = new VirtualPointerController( - swapRoot.engine, - swapCursor, - { - coordinateRoot: swapDemo, - signal: controller.signal, - pointerId: 2_000_000_101, - }, - ); - const sidewaysPointer = new VirtualPointerController( - sidewaysRoot.engine, - sidewaysCursor, - { - coordinateRoot: sidewaysDemo, - signal: controller.signal, - pointerId: 2_000_000_102, - }, - ); - - try { - await Promise.all([ - swapPointer.moveTo(swapHandle, { duration: 0 }), - sidewaysPointer.moveTo(sidewaysHandle, { duration: 0 }), - ]); - await Promise.all([ - swapPointer.press(swapHandle), - sidewaysPointer.press(sidewaysHandle), - ]); - await swapPointer.activateDrag(); - await swapPointer.waitUntil( - () => swapRoot.dragSession?.status === "active", - ); - await sidewaysPointer.activateDrag(); - await sidewaysPointer.waitUntil( - () => sidewaysRoot.dragSession?.status === "active", - ); - - const activePointerIds = [ - swapRoot.dragSession?.pointerId, - sidewaysRoot.dragSession?.pointerId, - ]; - const simultaneous = activePointerIds.every( - (pointerId) => pointerId != null, - ); - - if (swapPointer.pressed) await swapPointer.release(); - if (sidewaysPointer.pressed) await sidewaysPointer.release(); - await Promise.all([ - swapPointer.waitUntil(() => swapRoot.dragSession == null), - sidewaysPointer.waitUntil(() => sidewaysRoot.dragSession == null), - ]); - - return { - activePointerIds, - simultaneous, - sessionsEnded: - swapRoot.dragSession == null && sidewaysRoot.dragSession == null, - }; - } finally { - controller.abort(); - swapPointer.destroy(); - sidewaysPointer.destroy(); - } - }, - { coreImportPath, pointerImportPath }, - ); - - expect(report).toEqual({ - activePointerIds: [2_000_000_101, 2_000_000_102], - simultaneous: true, - sessionsEnded: true, - }); - expect(pageErrors).toEqual([]); -}); - -test("starts every gallery autoplay reel without viewport entry", async ({ - page, -}) => { - await page.setViewportSize({ width: 1440, height: 900 }); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - await expect(page.locator(".todo-demo")).toHaveAttribute( - "data-todo-autoplay-active", - "true", - ); - await expect(page.locator(".nested-demo")).toHaveAttribute( - "data-nested-autoplay-active", - "true", - ); - await expect(page.locator(".sideways-demo")).toHaveAttribute( - "data-sideways-autoplay-active", - "true", - ); - await expect(page.locator("[data-lesson-active]")).toHaveAttribute( - "data-lesson-active", - "true", - ); - await expect(page.locator("[data-control-matrix]")).toHaveAttribute( - "data-control-autoplay-active", - "true", - ); - await expect(page.locator(".swap-stage")).toHaveAttribute( - "data-swap-autoplay-active", - "true", - ); -}); - -test("swap controls use centered ten-degree dials without starting a tile drag", async ({ - page, -}) => { - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.setViewportSize({ width: 1440, height: 1100 }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="swap-mode"]'); - await exhibit.scrollIntoViewIfNeeded(); - const swapItems = exhibit.locator(".swap-grid > .snapsort-item"); - const labels = () => - swapItems.evaluateAll((items) => - items.map((item) => item.getAttribute("data-swap-label")), - ); - - const dial = exhibit.getByRole("slider", { name: "Dial A" }); - const markers = dial.locator(".dial-marker"); - await expect(markers).toHaveCount(36); - await expect(dial).toHaveAttribute("aria-valuenow", "40"); - const dialBody = dial.locator(".dial-body"); - await expect(dialBody).toHaveCSS("--material-shadow-far-blur", "11.25px"); - await expect(dialBody).toHaveCSS("--material-rim-width", "1.75px"); - - const markerGeometry = await dial.evaluate((element) => { - const dialRect = element.getBoundingClientRect(); - const markerRects = [ - ...element.querySelectorAll(".dial-marker"), - ].map((marker) => marker.getBoundingClientRect()); - const centers = markerRects.map((rect) => ({ - x: rect.left + rect.width / 2, - y: rect.top + rect.height / 2, - })); - return { - dialCenterX: dialRect.left + dialRect.width / 2, - dialCenterY: dialRect.top + dialRect.height / 2, - markerCenterX: - centers.reduce((sum, center) => sum + center.x, 0) / centers.length, - markerCenterY: - centers.reduce((sum, center) => sum + center.y, 0) / centers.length, - }; - }); - expect(markerGeometry.markerCenterX).toBeCloseTo( - markerGeometry.dialCenterX, - 2, - ); - expect(markerGeometry.markerCenterY).toBeCloseTo( - markerGeometry.dialCenterY, - 2, - ); - - const dialBox = await dial.boundingBox(); - if (!dialBox) throw new Error("Swap dial geometry is missing"); - await dial.click({ - position: { x: dialBox.width - 2, y: dialBox.height / 2 }, - }); - await expect(dial).toHaveAttribute("aria-valuenow", "90"); - await expect.poll(labels).toEqual(["A", "B", "C", "D", "E", "F"]); - await expect(exhibit.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); - - const lcdGeometry = await exhibit - .locator(".lcd-tile") - .first() - .evaluate((tile) => { - const display = tile.querySelector(".code-lcd-display"); - if (!display) throw new Error("Swap LCD display is missing"); - const tileRect = tile.getBoundingClientRect(); - const displayRect = display.getBoundingClientRect(); - return { - top: displayRect.top - tileRect.top, - right: tileRect.right - displayRect.right, - bottom: tileRect.bottom - displayRect.bottom, - left: displayRect.left - tileRect.left, - radius: getComputedStyle(display).borderRadius, - }; - }); - expect(lcdGeometry.top).toBeCloseTo(4, 1); - expect(lcdGeometry.right).toBeCloseTo(4, 1); - expect(lcdGeometry.bottom).toBeCloseTo(4, 1); - expect(lcdGeometry.left).toBeCloseTo(4, 1); - expect(lcdGeometry.radius).toBe("12px"); - expect(pageErrors).toEqual([]); -}); - -test("autoplays A with F and then C with D through swap mode", async ({ - page, -}) => { - await page.setViewportSize({ width: 1440, height: 1100 }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="swap-mode"]'); - const demo = exhibit.locator(".swap-stage"); - await expect(demo).toHaveAttribute("data-swap-autoplay-active", "true"); - - await expect(demo).toHaveAttribute("data-swap-order", "F,B,C,D,E,A", { - timeout: 8_000, - }); - await expect(demo).toHaveAttribute("data-swap-order", "F,B,D,C,E,A", { - timeout: 5_000, - }); - await expect(demo).toHaveAttribute("data-swap-phase", "complete"); - await expect(demo.locator("[data-virtual-pointer]")).toHaveAttribute( - "data-virtual-pointer-state", - "visible", - ); - expect(pageErrors).toEqual([]); -}); diff --git a/tests/e2e/snapdesign-toucan-lesson.spec.ts b/tests/e2e/snapdesign-toucan-lesson.spec.ts deleted file mode 100644 index c0f09023..00000000 --- a/tests/e2e/snapdesign-toucan-lesson.spec.ts +++ /dev/null @@ -1,743 +0,0 @@ -import { expect, test } from "@playwright/test"; - -const initialBankIds = [ - "lesson-exists", - "lesson-very", - "lesson-usage", - "lesson-this", - "lesson-new", - "lesson-subject", - "lesson-library", - "lesson-many", - "lesson-useful", - "lesson-context", - "lesson-link", -]; - -const distractorIds = ["lesson-very", "lesson-new", "lesson-useful"]; - -const correctAnswerIds = [ - "lesson-this", - "lesson-library", - "lesson-context", - "lesson-many", - "lesson-link", - "lesson-usage", - "lesson-subject", - "lesson-exists", -]; - -const initialBankOrder = initialBankIds.join(","); -const distractorOrder = distractorIds.join(","); -const correctAnswerOrder = correctAnswerIds.join(","); -const imperfectDraftOrder = [ - "lesson-this", - "lesson-new", - "lesson-library", - "lesson-link", - "lesson-many", - "lesson-context", -].join(","); -const draftWithoutDistractorOrder = [ - "lesson-this", - "lesson-library", - "lesson-link", - "lesson-many", - "lesson-context", -].join(","); -const firstCorrectionOrder = [ - "lesson-this", - "lesson-library", - "lesson-context", - "lesson-link", - "lesson-many", -].join(","); -const secondCorrectionOrder = [ - "lesson-this", - "lesson-library", - "lesson-many", - "lesson-context", - "lesson-link", -].join(","); -const correctedDraftOrder = [ - "lesson-this", - "lesson-library", - "lesson-context", - "lesson-many", - "lesson-link", -].join(","); -const toucanVirtualPointerId = 2_000_000_003; - -type ToucanAutoplaySample = { - phase: string; - order: string; - checkState: string; -}; - -type ToucanAutoplayTrace = { - samples: ToucanAutoplaySample[]; - pointerIds: number[]; - returningPressedMoves: number; - returningPlacements: string[]; - answerCollapsePlacements: Record; - answerCollapseBatches: Record; - reorderPaths: number[][]; - ghostObserved: boolean; -}; - -test("autoplays an imperfect draft, corrects it, and checks once", async ({ - page, -}) => { - test.setTimeout(45_000); - await page.setViewportSize({ width: 1440, height: 900 }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="toucan-lesson"]'); - const lesson = exhibit.locator(".toucan-lesson"); - await lesson.evaluate((element, virtualPointerId) => { - const trace: ToucanAutoplayTrace = { - samples: [], - pointerIds: [], - returningPressedMoves: 0, - returningPlacements: [], - answerCollapsePlacements: {}, - answerCollapseBatches: {}, - reorderPaths: [], - ghostObserved: false, - }; - const collapseIds = [ - "lesson-library", - "lesson-context", - "lesson-link", - "lesson-many", - ]; - let mutationBatch = 0; - let returnPointerPressed = false; - const captureReturningPlacement = () => { - if ( - element.dataset.lessonPhase !== "returning" || - !returnPointerPressed - ) { - return; - } - - const ghost = element.querySelector( - '[data-snapsort-ghost-entry="target-spacer"]', - ); - const slot = ghost?.closest("[data-lesson-slot-for]"); - const placement = slot - ? `slot:${slot.dataset.lessonSlotFor}` - : ghost?.closest(".toucan-answer-zone") - ? "answer" - : ghost?.closest(".toucan-bank-zone") - ? "bank" - : "none"; - if (trace.returningPlacements.at(-1) !== placement) { - trace.returningPlacements.push(placement); - } - - for (const itemId of collapseIds) { - if (trace.answerCollapsePlacements[itemId] !== undefined) continue; - const item = element.querySelector( - `[data-snapsort-item-id="${itemId}"]`, - ); - if (item?.style.transform.startsWith("translate3d(")) { - trace.answerCollapsePlacements[itemId] = placement; - trace.answerCollapseBatches[itemId] = mutationBatch; - } - } - }; - const capture = () => { - const sample = { - phase: element.dataset.lessonPhase ?? "", - order: element.dataset.lessonAnswerOrder ?? "", - checkState: element.dataset.lessonCheckState ?? "", - }; - const previous = trace.samples.at(-1); - if ( - previous?.phase !== sample.phase || - previous.order !== sample.order || - previous.checkState !== sample.checkState - ) { - trace.samples.push(sample); - } - if (element.querySelector("[data-snapsort-ghost-entry]")) { - trace.ghostObserved = true; - } - captureReturningPlacement(); - }; - const observer = new MutationObserver(() => { - mutationBatch += 1; - capture(); - }); - observer.observe(element, { - attributes: true, - attributeFilter: [ - "data-lesson-phase", - "data-lesson-answer-order", - "data-lesson-check-state", - "style", - ], - childList: true, - subtree: true, - }); - document.addEventListener( - "pointerdown", - (event) => { - if (!trace.pointerIds.includes(event.pointerId)) { - trace.pointerIds.push(event.pointerId); - } - if (event.pointerId === virtualPointerId) { - returnPointerPressed = true; - if (element.dataset.lessonPhase === "reordering") { - trace.reorderPaths.push([]); - } - } - }, - { capture: true }, - ); - const releaseVirtualPointer = (event: PointerEvent) => { - if (event.pointerId === virtualPointerId) { - returnPointerPressed = false; - } - }; - document.addEventListener("pointerup", releaseVirtualPointer, { - capture: true, - }); - document.addEventListener("pointercancel", releaseVirtualPointer, { - capture: true, - }); - document.addEventListener( - "pointermove", - (event) => { - if (event.pointerId === virtualPointerId && event.buttons === 1) { - if (element.dataset.lessonPhase === "returning") { - trace.returningPressedMoves += 1; - } - if (element.dataset.lessonPhase === "reordering") { - trace.reorderPaths.at(-1)?.push(event.clientX); - } - } - }, - { capture: true }, - ); - capture(); - Reflect.set(window, "__toucanAutoplayTrace", trace); - }, toucanVirtualPointerId); - - await lesson.scrollIntoViewIfNeeded(); - await expect(lesson).toHaveAttribute("data-lesson-active", "true"); - await expect - .poll( - () => - page.evaluate(() => { - const trace = Reflect.get( - window, - "__toucanAutoplayTrace", - ) as ToucanAutoplayTrace | undefined; - return trace?.samples.some( - (sample) => - sample.phase === "complete" && sample.checkState === "correct", - ) ?? false; - }), - { timeout: 35_000 }, - ) - .toBe(true); - - const completedTrace = await page.evaluate( - () => Reflect.get(window, "__toucanAutoplayTrace") as ToucanAutoplayTrace, - ); - const phases = completedTrace.samples.map((sample) => sample.phase); - const orders = completedTrace.samples.map((sample) => sample.order); - const draftingOrders = completedTrace.samples - .filter((sample) => sample.phase === "drafting" && sample.order !== "") - .map((sample) => sample.order); - expect(draftingOrders.slice(0, 2)).toEqual([ - "lesson-this", - "lesson-this,lesson-new", - ]); - expect(phases).toEqual( - expect.arrayContaining([ - "drafting", - "hesitating", - "returning", - "reordering", - "finishing", - "checking", - "complete", - ]), - ); - expect(orders).toEqual( - expect.arrayContaining([ - imperfectDraftOrder, - draftWithoutDistractorOrder, - firstCorrectionOrder, - secondCorrectionOrder, - correctedDraftOrder, - correctAnswerOrder, - ]), - ); - expect(completedTrace.pointerIds).toContain(toucanVirtualPointerId); - expect(completedTrace.ghostObserved).toBe(true); - expect(completedTrace.returningPressedMoves).toBeGreaterThan(1); - const targetSlotPlacement = "slot:lesson-new"; - const pressedReturningPlacements = - completedTrace.returningPlacements.filter( - (placement) => placement !== "none", - ); - expect(pressedReturningPlacements.at(-1)).toBe(targetSlotPlacement); - expect( - pressedReturningPlacements.filter( - (placement) => placement === targetSlotPlacement, - ).length, - ).toBeLessThanOrEqual(2); - expect(Object.keys(completedTrace.answerCollapsePlacements).sort()).toEqual( - [ - "lesson-library", - "lesson-context", - "lesson-link", - "lesson-many", - ].sort(), - ); - expect(completedTrace.reorderPaths.length).toBeGreaterThanOrEqual(3); - for (const path of completedTrace.reorderPaths.slice(-3)) { - expect(path.length).toBeGreaterThan(1); - const firstLeftwardMove = path.findIndex( - (x, index, values) => index > 0 && x < values[index - 1] - 1, - ); - expect(firstLeftwardMove).toBeGreaterThan(0); - const rightwardReversals = path - .slice(firstLeftwardMove + 1) - .filter((x, index, values) => index > 0 && x > values[index - 1] + 1); - expect(rightwardReversals).toHaveLength(0); - } - expect( - completedTrace.samples.some((sample) => sample.checkState === "incorrect"), - ).toBe(false); - - const completedSampleIndex = completedTrace.samples.findIndex( - (sample) => sample.phase === "complete" && sample.checkState === "correct", - ); - await expect - .poll( - () => - page.evaluate((startIndex) => { - const trace = Reflect.get( - window, - "__toucanAutoplayTrace", - ) as ToucanAutoplayTrace | undefined; - return trace?.samples - .slice(startIndex + 1) - .some((sample) => sample.order === "") ?? false; - }, completedSampleIndex), - { timeout: 5_000 }, - ) - .toBe(true); - expect(pageErrors).toEqual([]); -}); - -test("keeps one persistent container per word-bank tile", async ({ page }) => { - await page.setViewportSize({ width: 1440, height: 1100 }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="toucan-lesson"]'); - const stage = exhibit.locator(".toucan-stage"); - const lesson = exhibit.locator(".toucan-lesson"); - const answer = exhibit.locator(".toucan-answer-zone"); - const bank = exhibit.locator(".toucan-bank-zone"); - const checkButton = exhibit.getByRole("button", { name: "Check" }); - - await expect(stage).not.toHaveAttribute("inert", ""); - await expect(stage).not.toHaveAttribute("aria-hidden", "true"); - await expect(stage).toHaveCSS("pointer-events", "auto"); - await expect(stage).toHaveAttribute("role", "group"); - await expect(lesson).toHaveAttribute( - "data-lesson-bank-order", - initialBankOrder, - ); - await expect(bank.locator("button.lesson-word")).toHaveCount(11); - await expect(checkButton).toBeDisabled(); - await expect(bank.locator("[data-lesson-stub-for]")).toHaveCount(0); - - await lesson.scrollIntoViewIfNeeded(); - await expect(lesson).toHaveAttribute("data-lesson-active", "true"); - await bank.locator('[data-lesson-tile-id="lesson-very"]').click(); - await expect(lesson).toHaveAttribute("data-lesson-manual", "true"); - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - "lesson-very", - ); - await page.waitForTimeout(700); - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - "lesson-very", - ); - await expect(bank.locator("[data-lesson-slot-for]")).toHaveCount(11); - await expect(checkButton).toBeEnabled(); - await checkButton.click(); - await expect( - exhibit.getByRole("button", { name: "Try again" }), - ).toBeVisible(); - await expect( - bank.locator('[data-lesson-stub-for="lesson-very"]'), - ).toHaveCount(1); - await answer.locator('[data-lesson-tile-id="lesson-very"]').click(); - await expect(lesson).toHaveAttribute("data-lesson-answer-order", ""); - await expect(exhibit.getByRole("button", { name: "Check" })).toBeDisabled(); - await expect( - bank.locator( - '[data-lesson-slot-for="lesson-very"] [data-lesson-tile-id="lesson-very"]', - ), - ).toHaveCount(1); - await expect(exhibit.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); - expect(pageErrors).toEqual([]); -}); - -test("drags from the bank, reorders the answer, and returns to its fixed slot", async ({ - page, -}) => { - await page.setViewportSize({ width: 1440, height: 1100 }); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="toucan-lesson"]'); - const lesson = exhibit.locator(".toucan-lesson"); - const answer = exhibit.locator(".toucan-answer-zone"); - const bank = exhibit.locator(".toucan-bank-zone"); - await lesson.scrollIntoViewIfNeeded(); - - const initialSlots = await bank.evaluate((element) => - Array.from( - element.querySelectorAll(":scope > [data-lesson-slot-for]"), - ).map((slot) => { - const tile = slot.querySelector("[data-lesson-tile-id]"); - const rect = slot.getBoundingClientRect(); - return { - id: tile?.dataset.lessonTileId ?? "", - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }; - }), - ); - expect(initialSlots.map((slot) => slot.id)).toEqual(initialBankIds); - - const draggableTile = bank.locator( - 'button[data-lesson-tile-id="lesson-this"]', - ); - const tileBox = await draggableTile.boundingBox(); - const answerBox = await exhibit.locator(".toucan-answer-zone").boundingBox(); - if (!tileBox || !answerBox) - throw new Error("Toucan drag geometry is missing"); - await page.mouse.move( - tileBox.x + tileBox.width / 2, - tileBox.y + tileBox.height / 2, - ); - await page.mouse.down(); - await page.mouse.move( - answerBox.x + answerBox.width / 2, - answerBox.y + answerBox.height / 2, - { steps: 5 }, - ); - await page.mouse.up(); - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - "lesson-this", - ); - await expect( - bank.locator('[data-lesson-stub-for="lesson-this"]'), - ).toHaveCount(1); - await page.waitForTimeout(500); - - await bank.locator('[data-lesson-tile-id="lesson-library"]').click(); - await page.waitForTimeout(500); - const firstAnswerTile = answer.locator('[data-lesson-tile-id="lesson-this"]'); - const secondAnswerTile = answer.locator( - '[data-lesson-tile-id="lesson-library"]', - ); - const firstAnswerBox = await firstAnswerTile.boundingBox(); - const secondAnswerBox = await secondAnswerTile.boundingBox(); - if (!firstAnswerBox || !secondAnswerBox) { - throw new Error("Toucan answer reorder geometry is missing"); - } - await page.mouse.move( - secondAnswerBox.x + secondAnswerBox.width / 2, - secondAnswerBox.y + secondAnswerBox.height / 2, - ); - await page.mouse.down(); - await page.mouse.move( - firstAnswerBox.x + firstAnswerBox.width / 2, - firstAnswerBox.y + firstAnswerBox.height / 2, - { steps: 8 }, - ); - await page.mouse.up(); - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - "lesson-library,lesson-this", - ); - await page.waitForTimeout(500); - - const returnTile = answer.locator('[data-lesson-tile-id="lesson-this"]'); - const returnTileBox = await returnTile.boundingBox(); - const bankBox = await bank.boundingBox(); - if (!returnTileBox || !bankBox) { - throw new Error("Toucan return geometry is missing"); - } - await page.mouse.move( - returnTileBox.x + returnTileBox.width / 2, - returnTileBox.y + returnTileBox.height / 2, - ); - await page.mouse.down(); - await page.mouse.move( - bankBox.x + bankBox.width - 8, - bankBox.y + bankBox.height - 8, - { - steps: 10, - }, - ); - await page.mouse.up(); - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - "lesson-library", - ); - await expect( - bank.locator( - '[data-lesson-slot-for="lesson-this"] [data-lesson-tile-id="lesson-this"]', - ), - ).toHaveCount(1); - await page.waitForTimeout(500); - - const movedSlots = await bank.evaluate((element) => - Array.from( - element.querySelectorAll(":scope > [data-lesson-slot-for]"), - ).map((slot) => { - const tile = slot.querySelector("[data-lesson-tile-id]"); - const stub = slot.matches("[data-lesson-stub-for]") - ? slot - : slot.querySelector("[data-lesson-stub-for]"); - const rect = slot.getBoundingClientRect(); - return { - id: tile?.dataset.lessonTileId ?? stub?.dataset.lessonStubFor ?? "", - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - stub: Boolean(stub), - }; - }), - ); - expect(movedSlots).toHaveLength(initialSlots.length); - for (const [index, slot] of movedSlots.entries()) { - const initial = initialSlots[index]; - expect(slot.id).toBe(initial.id); - expect(Math.abs(slot.x - initial.x)).toBeLessThanOrEqual(1); - expect(Math.abs(slot.y - initial.y)).toBeLessThanOrEqual(1); - expect(Math.abs(slot.width - initial.width)).toBeLessThanOrEqual(1); - expect(Math.abs(slot.height - initial.height)).toBeLessThanOrEqual(1); - } - expect(movedSlots.find((slot) => slot.id === "lesson-library")?.stub).toBe( - true, - ); - await expect(exhibit.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); -}); - -test("returns an answer tile through the open bank corridor", async ({ - page, -}) => { - await page.setViewportSize({ width: 1440, height: 1100 }); - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="toucan-lesson"]'); - const lesson = exhibit.locator(".toucan-lesson"); - const answer = exhibit.locator(".toucan-answer-zone"); - const bank = exhibit.locator(".toucan-bank-zone"); - await lesson.scrollIntoViewIfNeeded(); - - await bank.locator('[data-lesson-tile-id="lesson-this"]').click(); - await bank.locator('[data-lesson-tile-id="lesson-library"]').click(); - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - "lesson-this,lesson-library", - ); - await page.waitForTimeout(500); - - const sibling = answer.locator('[data-snapsort-item-id="lesson-library"]'); - await sibling.evaluate((element) => { - const trace = { translated: false }; - const capture = () => { - if ((element as HTMLElement).style.transform.startsWith("translate3d(")) { - trace.translated = true; - } - }; - const observer = new MutationObserver(capture); - observer.observe(element, { - attributes: true, - attributeFilter: ["style"], - }); - Reflect.set(window, "__toucanCorridorAnimation", { observer, trace }); - }); - - const source = answer.locator('[data-lesson-tile-id="lesson-this"]'); - const sourceBox = await source.boundingBox(); - const corridor = await exhibit.evaluate((element) => { - const answerElement = element.querySelector( - ".toucan-answer-zone", - ); - const bankElement = element.querySelector( - ".toucan-bank-zone", - ); - const slots = Array.from( - element.querySelectorAll( - ".toucan-bank-zone > [data-lesson-slot-for]", - ), - ); - if (!answerElement || !bankElement || slots.length === 0) return null; - const answerRect = answerElement.getBoundingClientRect(); - const bankRect = bankElement.getBoundingClientRect(); - const visibleRowsTop = Math.min( - ...slots.map((slot) => slot.getBoundingClientRect().top), - ); - const answerBottom = answerRect.bottom; - return { - answerBottom, - bankTop: bankRect.top, - visibleRowsTop, - x: bankRect.left + bankRect.width / 2, - y: answerBottom + (visibleRowsTop - answerBottom) / 2, - }; - }); - if (!sourceBox || !corridor) { - throw new Error("Toucan corridor drag geometry is missing"); - } - expect(Math.abs(corridor.bankTop - corridor.answerBottom)).toBeLessThanOrEqual( - 1, - ); - expect(corridor.visibleRowsTop).toBeGreaterThan(corridor.answerBottom + 8); - - await page.mouse.move( - sourceBox.x + sourceBox.width / 2, - sourceBox.y + sourceBox.height / 2, - ); - await page.mouse.down(); - await page.mouse.move(corridor.x, corridor.y, { steps: 12 }); - await expect( - bank.locator('[data-snapsort-ghost-entry="target-spacer"]'), - ).toHaveCount(1); - await expect( - answer.locator('[data-snapsort-ghost-entry="target-spacer"]'), - ).toHaveCount(0); - await expect - .poll(() => - page.evaluate(() => { - const state = Reflect.get(window, "__toucanCorridorAnimation") as { - trace: { translated: boolean }; - }; - return state.trace.translated; - }), - ) - .toBe(true); - await page.mouse.up(); - - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - "lesson-library", - ); - await expect( - bank.locator( - '[data-lesson-slot-for="lesson-this"] [data-lesson-tile-id="lesson-this"]', - ), - ).toHaveCount(1); - await expect(exhibit.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); - await page.evaluate(() => { - const state = Reflect.get(window, "__toucanCorridorAnimation") as { - observer: MutationObserver; - }; - state.observer.disconnect(); - }); - expect(pageErrors).toEqual([]); -}); - -test("completed tiles, distractors, and writing lines remain deterministic", async ({ - page, -}) => { - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.setViewportSize({ width: 1440, height: 1100 }); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const exhibit = page.locator('[data-gallery="toucan-lesson"]'); - const lesson = exhibit.locator(".toucan-lesson"); - const answer = exhibit.locator(".toucan-answer-zone"); - const bank = exhibit.locator(".toucan-bank-zone"); - await lesson.scrollIntoViewIfNeeded(); - - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - correctAnswerOrder, - ); - await expect(lesson).toHaveAttribute( - "data-lesson-bank-order", - distractorOrder, - ); - await expect(bank.locator("[data-lesson-stub-for]")).toHaveCount(8); - - const bankContainment = await bank.evaluate((element) => ({ - clientHeight: element.clientHeight, - scrollHeight: element.scrollHeight, - rowCount: new Set( - Array.from( - element.querySelectorAll( - ":scope > [data-lesson-slot-for]", - ), - (slot) => Math.round(slot.getBoundingClientRect().y), - ), - ).size, - })); - expect(bankContainment.scrollHeight).toBe(bankContainment.clientHeight); - expect(bankContainment.rowCount).toBe(2); - - const lineClearances = await answer.evaluate((element) => { - const lineTops = Array.from( - element.querySelectorAll("[data-answer-rule]"), - (line) => line.getBoundingClientRect().top, - ); - return Array.from( - element.querySelectorAll(".lesson-word"), - ).map((word) => { - const visualBottom = word.getBoundingClientRect().bottom + 6; - const line = lineTops.find((top) => top > visualBottom); - return line === undefined - ? Number.NEGATIVE_INFINITY - : line - visualBottom; - }); - }); - expect(Math.min(...lineClearances)).toBeGreaterThanOrEqual(5.5); - - await bank.locator('button[data-lesson-tile-id="lesson-very"]').focus(); - await page.keyboard.press("Enter"); - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - `${correctAnswerOrder},lesson-very`, - ); - await expect(lesson).not.toHaveClass(/complete/); - await expect( - bank.locator('[data-lesson-stub-for="lesson-very"]'), - ).toHaveCount(1); - - await page.waitForTimeout(500); - await answer.locator('button[data-lesson-tile-id="lesson-very"]').click(); - await expect(lesson).toHaveAttribute( - "data-lesson-answer-order", - correctAnswerOrder, - ); - await expect(lesson).toHaveClass(/complete/); - await expect( - bank.locator('[data-lesson-stub-for="lesson-very"]'), - ).toHaveCount(0); -}); diff --git a/tests/e2e/snapline-camera.playwright.config.ts b/tests/e2e/snapline-camera.playwright.config.ts deleted file mode 100644 index 14e193d6..00000000 --- a/tests/e2e/snapline-camera.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.SNAPLINE_CAMERA_TEST_PORT ?? 3030); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: "snapline-camera.spec.ts", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 900 }, - }, - webServer: { - cwd: repoRoot, - command: `npx vite serve demo/svelte --config demo/svelte/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/snapline-edges.playwright.config.ts b/tests/e2e/snapline-edges.playwright.config.ts deleted file mode 100644 index 6fda8d95..00000000 --- a/tests/e2e/snapline-edges.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.SNAPLINE_EDGES_TEST_PORT ?? 3034); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: "snapline-edges.spec.ts", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 900 }, - }, - webServer: { - cwd: repoRoot, - command: `npx vite serve demo/svelte --config demo/svelte/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/snapline-group.playwright.config.ts b/tests/e2e/snapline-group.playwright.config.ts deleted file mode 100644 index 9739c781..00000000 --- a/tests/e2e/snapline-group.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.SNAPLINE_GROUP_TEST_PORT ?? 3031); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: "snapline-group.spec.ts", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 900 }, - }, - webServer: { - cwd: repoRoot, - command: `npx vite serve demo/svelte --config demo/svelte/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/snapline-overlay.playwright.config.ts b/tests/e2e/snapline-overlay.playwright.config.ts deleted file mode 100644 index 8afad9b9..00000000 --- a/tests/e2e/snapline-overlay.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.SNAPLINE_OVERLAY_TEST_PORT ?? 3036); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: "snapline-overlay.spec.ts", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 900 }, - }, - webServer: { - cwd: repoRoot, - command: `npx vite serve demo/svelte --config demo/svelte/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/snapline-react.playwright.config.ts b/tests/e2e/snapline-react.playwright.config.ts deleted file mode 100644 index 9b67cca4..00000000 --- a/tests/e2e/snapline-react.playwright.config.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.SNAPLINE_REACT_TEST_PORT ?? 3030); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: [ - "node-react.spec.ts", - "snapline-react-features.spec.ts", - "snapline-edges-react.spec.ts", - ], - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 900 }, - }, - webServer: { - cwd: repoRoot, - command: `npx vite serve demo/react --config demo/react/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/snapline-resize.playwright.config.ts b/tests/e2e/snapline-resize.playwright.config.ts deleted file mode 100644 index ac40a4be..00000000 --- a/tests/e2e/snapline-resize.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.SNAPLINE_RESIZE_TEST_PORT ?? 3032); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: "snapline-resize.spec.ts", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 900 }, - }, - webServer: { - cwd: repoRoot, - command: `npx vite serve demo/svelte --config demo/svelte/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/snapline.playwright.config.ts b/tests/e2e/snapline.playwright.config.ts deleted file mode 100644 index 1808ec69..00000000 --- a/tests/e2e/snapline.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const port = Number(process.env.SNAPLINE_TEST_PORT ?? 3029); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: "node.spec.ts", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - baseURL: `http://127.0.0.1:${port}`, - channel: "chrome", - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1280, height: 900 }, - }, - webServer: { - cwd: repoRoot, - command: `npx vite serve demo/svelte --config demo/svelte/vite.config.mjs --host 127.0.0.1 --port ${port} --strictPort --force`, - url: `http://127.0.0.1:${port}`, - reuseExistingServer: false, - timeout: 30_000, - }, -}); diff --git a/tests/e2e/snapline-camera.spec.ts b/tests/e2e/snapline/camera/camera.spec.ts similarity index 96% rename from tests/e2e/snapline-camera.spec.ts rename to tests/e2e/snapline/camera/camera.spec.ts index 50878fa5..300f0065 100644 --- a/tests/e2e/snapline-camera.spec.ts +++ b/tests/e2e/snapline/camera/camera.spec.ts @@ -52,16 +52,6 @@ test("background drag pans the camera", async ({ page }) => { expect(after!.y - before!.y).toBeLessThan(-100); }); -test("ctrl+wheel zooms the camera", async ({ page }) => { - const before = await cameraTransform(page); - await page.mouse.move(640, 450); - // The camera starts at its max zoom (1), so scroll down / pinch-in zooms out. - await page.keyboard.down("Control"); - await page.mouse.wheel(0, 240); - await page.keyboard.up("Control"); - await expect.poll(() => cameraTransform(page)).not.toBe(before); -}); - test("dragging a node does not pan the camera", async ({ page }) => { const nodeB = page.locator("[data-snapline-type='node']", { hasText: "Node B", diff --git a/tests/e2e/snapline-edges-react.spec.ts b/tests/e2e/snapline/edges/edges.react.spec.ts similarity index 86% rename from tests/e2e/snapline-edges-react.spec.ts rename to tests/e2e/snapline/edges/edges.react.spec.ts index 4d7ace64..0076f753 100644 --- a/tests/e2e/snapline-edges-react.spec.ts +++ b/tests/e2e/snapline/edges/edges.react.spec.ts @@ -33,19 +33,6 @@ test.beforeEach(async ({ page }) => { await expect(connectorOf(page, "Node A", "output")).toBeVisible(); }); -test("react: gesture connect emits one intent and the line survives sync", async ({ - page, -}) => { - await dragFromTo( - page, - await centerOf(connectorOf(page, "Node A", "output")), - await centerOf(connectorOf(page, "Node B", "input")), - ); - await expect(page.getByTestId("connect-intents")).toHaveText("1"); - await expect(page.getByTestId("edge-count")).toHaveText("1"); - await expect(page.locator(LINE)).toHaveCount(1); -}); - test("react: programmatic edge add renders a line with zero intents", async ({ page, }) => { @@ -60,7 +47,10 @@ test("react: full input replaces via ONE atomic request", async ({ page }) => { await centerOf(connectorOf(page, "Node A", "output")), await centerOf(connectorOf(page, "Node B", "input")), ); + // A gesture connect emits exactly one intent and its line survives sync. + await expect(page.getByTestId("connect-intents")).toHaveText("1"); await expect(page.getByTestId("edge-count")).toHaveText("1"); + await expect(page.locator(LINE)).toHaveCount(1); await dragFromTo( page, await centerOf(connectorOf(page, "Node C", "output")), diff --git a/tests/e2e/snapline-edges.spec.ts b/tests/e2e/snapline/edges/edges.spec.ts similarity index 100% rename from tests/e2e/snapline-edges.spec.ts rename to tests/e2e/snapline/edges/edges.spec.ts diff --git a/tests/e2e/snapline-overlay.spec.ts b/tests/e2e/snapline/edges/overlay.spec.ts similarity index 100% rename from tests/e2e/snapline-overlay.spec.ts rename to tests/e2e/snapline/edges/overlay.spec.ts diff --git a/tests/e2e/snapline/group/group.react.spec.ts b/tests/e2e/snapline/group/group.react.spec.ts new file mode 100644 index 00000000..2e64713f --- /dev/null +++ b/tests/e2e/snapline/group/group.react.spec.ts @@ -0,0 +1,54 @@ +import { expect, test, type Locator, type Page } from "@playwright/test"; + +// React-adapter parity coverage for the group node — mirrors +// group/group.spec.ts. + +async function centerOf(locator: Locator) { + const box = await locator.boundingBox(); + expect(box).not.toBeNull(); + return { x: box!.x + box!.width / 2, y: box!.y + box!.height / 2 }; +} + +async function dragFromTo( + page: Page, + from: { x: number; y: number }, + to: { x: number; y: number }, +) { + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(to.x, to.y, { steps: 14 }); + await page.mouse.up(); +} + +const NODE = "[data-snapline-type='node']"; + +test("react: group carries its in-box members and resize updates membership", async ({ + page, +}) => { + await page.goto("/snapline-group"); + await expect(page.locator(NODE)).toHaveCount(3); + await expect(page.locator("[data-snapline-type='group']")).toHaveCount(1); + // Seed: Node A and Node C inside, Node B outside. + await expect(page.locator("[data-member='true']")).toHaveCount(2); + + const nodeA = page.locator(NODE, { hasText: "Node A" }); + const nodeB = page.locator(NODE, { hasText: "Node B" }); + const beforeA = await nodeA.boundingBox(); + const beforeB = await nodeB.boundingBox(); + + // Move the group by its header: members ride, outsider stays. + const header = await centerOf( + page.locator("[data-snapline-part='group-header']"), + ); + await dragFromTo(page, header, { x: header.x + 120, y: header.y + 60 }); + const afterA = await nodeA.boundingBox(); + const afterB = await nodeB.boundingBox(); + expect(afterA!.x - beforeA!.x).toBeGreaterThan(90); + expect(Math.abs(afterB!.x - beforeB!.x)).toBeLessThan(8); + + // Resize the group over Node B: it becomes a member. + const box = await page.locator("[data-snapline-type='group']").boundingBox(); + const corner = { x: box!.x + box!.width - 3, y: box!.y + box!.height - 3 }; + await dragFromTo(page, corner, { x: corner.x + 200, y: corner.y }); + await expect(nodeB).toHaveAttribute("data-member", "true"); +}); diff --git a/tests/e2e/snapline-group.spec.ts b/tests/e2e/snapline/group/group.spec.ts similarity index 96% rename from tests/e2e/snapline-group.spec.ts rename to tests/e2e/snapline/group/group.spec.ts index 09baef46..af7848a4 100644 --- a/tests/e2e/snapline-group.spec.ts +++ b/tests/e2e/snapline/group/group.spec.ts @@ -62,14 +62,7 @@ test("dragging the group header carries its in-box members, not outsiders", asyn // Non-member B stays put. expect(Math.abs(afterB!.x - beforeB!.x)).toBeLessThan(8); expect(Math.abs(afterB!.y - beforeB!.y)).toBeLessThan(8); -}); - -test("carried members do not fire enter/leave (cue count stays stable)", async ({ - page, -}) => { - const header = await centerOf(page.locator(HEADER)); - await dragFromTo(page, header, { x: header.x + 60, y: header.y + 40 }); - // A and C merely moved with the group — still members, no flicker. + // Carried members stay members: moving with the group is not a leave. await expect(page.locator(MEMBER)).toHaveCount(2); }); diff --git a/tests/e2e/node-react.spec.ts b/tests/e2e/snapline/nodes/nodes.react.spec.ts similarity index 86% rename from tests/e2e/node-react.spec.ts rename to tests/e2e/snapline/nodes/nodes.react.spec.ts index bba6a8f4..b6a5443e 100644 --- a/tests/e2e/node-react.spec.ts +++ b/tests/e2e/snapline/nodes/nodes.react.spec.ts @@ -80,23 +80,6 @@ test("renders the React SnapLine demo nodes and connectors", async ({ await expect(page.locator("[data-snapline-type='selection']")).toHaveCount(1); }); -test("connects two React SnapLine nodes", async ({ page }) => { - const nodeA = page.locator("[data-snapline-type='node']", { - hasText: "Node A", - }); - const nodeB = page.locator("[data-snapline-type='node']", { - hasText: "Node B", - }); - const output = nodeA.locator("[data-snapline-name='output']"); - const input = nodeB.locator("[data-snapline-name='input']"); - - await dragFromTo(page, await centerOf(output), await centerOf(input)); - - await expect( - page.locator("[data-snapline-type='connector-line']"), - ).toHaveCount(1); -}); - test("keeps a React line endpoint aligned while the target node is moving", async ({ page, }) => { diff --git a/tests/e2e/node.spec.ts b/tests/e2e/snapline/nodes/nodes.spec.ts similarity index 100% rename from tests/e2e/node.spec.ts rename to tests/e2e/snapline/nodes/nodes.spec.ts diff --git a/tests/e2e/snapline/playwright.config.ts b/tests/e2e/snapline/playwright.config.ts new file mode 100644 index 00000000..49556ca2 --- /dev/null +++ b/tests/e2e/snapline/playwright.config.ts @@ -0,0 +1,36 @@ +// SnapLine suite, one folder per feature (nodes, camera, edges, group, +// resize). Svelte runs every spec except `*.react.spec.ts`; React runs only +// the `*.react.spec.ts` adapter-parity specs. +// +// Run with: npm run test:snapline +import { defineConfig } from "@playwright/test"; +import { PORTS, baseURL, demoServer, sharedUse } from "../shared/servers"; + +const use = { + ...sharedUse, + channel: "chrome", + viewport: { width: 1280, height: 900 }, +}; + +export default defineConfig({ + testDir: ".", + fullyParallel: false, + workers: 1, + reporter: [["list"]], + projects: [ + { + name: "svelte", + testIgnore: ["**/*.react.spec.ts"], + use: { ...use, baseURL: baseURL(PORTS.snaplineSvelte) }, + }, + { + name: "react", + testMatch: ["**/*.react.spec.ts"], + use: { ...use, baseURL: baseURL(PORTS.snaplineReact) }, + }, + ], + webServer: [ + demoServer("svelte", PORTS.snaplineSvelte), + demoServer("react", PORTS.snaplineReact), + ], +}); diff --git a/tests/e2e/snapline-react-features.spec.ts b/tests/e2e/snapline/resize/resize.react.spec.ts similarity index 61% rename from tests/e2e/snapline-react-features.spec.ts rename to tests/e2e/snapline/resize/resize.react.spec.ts index 93d2faf2..7241743c 100644 --- a/tests/e2e/snapline-react-features.spec.ts +++ b/tests/e2e/snapline/resize/resize.react.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Locator, type Page } from "@playwright/test"; -// React-adapter parity coverage for the JS node resize and the group node — -// mirrors the svelte suites (snapline-resize.spec.ts / snapline-group.spec.ts). +// React-adapter parity coverage for the JS node resize — mirrors +// resize/resize.spec.ts. async function centerOf(locator: Locator) { const box = await locator.boundingBox(); @@ -73,34 +73,3 @@ test("react: a plain node moves (not resizes) when grabbed at its BR corner", as expect(after!.x - before!.x).toBeGreaterThan(70); expect(Math.abs(after!.width - before!.width)).toBeLessThan(4); }); - -test("react: group carries its in-box members and resize updates membership", async ({ - page, -}) => { - await page.goto("/snapline-group"); - await expect(page.locator(NODE)).toHaveCount(3); - await expect(page.locator("[data-snapline-type='group']")).toHaveCount(1); - // Seed: Node A and Node C inside, Node B outside. - await expect(page.locator("[data-member='true']")).toHaveCount(2); - - const nodeA = page.locator(NODE, { hasText: "Node A" }); - const nodeB = page.locator(NODE, { hasText: "Node B" }); - const beforeA = await nodeA.boundingBox(); - const beforeB = await nodeB.boundingBox(); - - // Move the group by its header: members ride, outsider stays. - const header = await centerOf( - page.locator("[data-snapline-part='group-header']"), - ); - await dragFromTo(page, header, { x: header.x + 120, y: header.y + 60 }); - const afterA = await nodeA.boundingBox(); - const afterB = await nodeB.boundingBox(); - expect(afterA!.x - beforeA!.x).toBeGreaterThan(90); - expect(Math.abs(afterB!.x - beforeB!.x)).toBeLessThan(8); - - // Resize the group over Node B: it becomes a member. - const box = await page.locator("[data-snapline-type='group']").boundingBox(); - const corner = { x: box!.x + box!.width - 3, y: box!.y + box!.height - 3 }; - await dragFromTo(page, corner, { x: corner.x + 200, y: corner.y }); - await expect(nodeB).toHaveAttribute("data-member", "true"); -}); diff --git a/tests/e2e/snapline-resize.spec.ts b/tests/e2e/snapline/resize/resize.spec.ts similarity index 91% rename from tests/e2e/snapline-resize.spec.ts rename to tests/e2e/snapline/resize/resize.spec.ts index 1d00b18b..9786f029 100644 --- a/tests/e2e/snapline-resize.spec.ts +++ b/tests/e2e/snapline/resize/resize.spec.ts @@ -269,18 +269,6 @@ test("a north drag holds the bottom edge with one pointermove per animation fram expect(Math.max(...bottoms) - Math.min(...bottoms)).toBeLessThanOrEqual(2); }); -test("resize regions own their native CSS cursor", async ({ page }) => { - const nodeA = page.locator("[data-snapline-type='node']", { - hasText: "Resizable A", - }); - const east = nodeA.locator( - "[data-snapline-part='resize-region'][data-handle='e']", - ); - await east.hover(); - await expect(east).toHaveCSS("cursor", "ew-resize"); - await expect(nodeA).not.toHaveAttribute("data-snapline-resize-handle"); -}); - test("a plain (non-resizable) node moves when grabbed at its BR corner", async ({ page, }) => { @@ -298,32 +286,6 @@ test("a plain (non-resizable) node moves when grabbed at its BR corner", async ( expect(Math.abs(after!.width - before!.width)).toBeLessThan(4); // not resized }); -test("tl anchor: dragging the top-left handle grows the box while the BR corner stays fixed", async ({ - page, -}) => { - const nodeC = page.locator("[data-snapline-type='node']", { - hasText: "TL Anchor C", - }); - const before = await nodeC.boundingBox(); - const brBefore = { - x: before!.x + before!.width, - y: before!.y + before!.height, - }; - - // Press the TL corner (the anchor) and drag outward (up-left): grows the box. - const tl = { x: before!.x + 2, y: before!.y + 2 }; - await dragFromTo(page, tl, { x: tl.x - 90, y: tl.y - 60 }); - await waitForAnimationFrame(page); - - const after = await nodeC.boundingBox(); - expect(after!.width - before!.width).toBeGreaterThan(60); - expect(after!.height - before!.height).toBeGreaterThan(30); - // The OPPOSITE (bottom-right) corner must not move. - const brAfter = { x: after!.x + after!.width, y: after!.y + after!.height }; - expect(Math.abs(brAfter.x - brBefore.x)).toBeLessThanOrEqual(4); - expect(Math.abs(brAfter.y - brBefore.y)).toBeLessThanOrEqual(4); -}); - // The anchored edge must hold on EVERY painted frame, not just once the drag // settles (which is all the assertions above check). Measuring the rendered // rect rather than the authored `style.height` is the point: those two diverge @@ -436,7 +398,8 @@ for (const [direction, wheelDeltaY] of [ hasText: "Resizable A", }); const eastHandle = nodeA.locator(".resize-region[data-handle='e']"); - const cssWidth = () => nodeA.evaluate((node) => node.offsetWidth); + const cssWidth = () => + nodeA.evaluate((node) => (node as HTMLElement).offsetWidth); const zoom = async () => (await nodeA.boundingBox())!.width / (await cssWidth()); diff --git a/tests/e2e/snapsort-drag-snapshot.spec.ts b/tests/e2e/snapsort-drag-snapshot.spec.ts deleted file mode 100644 index 1934f503..00000000 --- a/tests/e2e/snapsort-drag-snapshot.spec.ts +++ /dev/null @@ -1,6737 +0,0 @@ -import { expect, test, type Locator, type Page } from "@playwright/test"; -import { mkdir, writeFile } from "node:fs/promises"; -import { dirname } from "node:path"; -import { contentRect } from "../../src/geometry"; -import { virtualEntrySizeFor } from "../../src/layout"; -import type { ItemSnapshot } from "../../assets/snapsort/src/snapshot"; -import { - determineDropTarget, - determineInsertionDropTarget, - determineProgressiveDropTarget, - determineSwapDropTarget, -} from "../../assets/snapsort/src/algorithm"; -import { BaseObject } from "../../src/object"; -import type { ElementBox, Rect } from "../../src/geometry"; -import { - prioritizeIntersectingContainer, - prioritizeNearestContainerEdge, - prioritizePointerContainer, - prioritizeTreeDepth, - rejectDrop, -} from "../../assets/snapsort/src/callbacks"; -import { - Container as SnapSortContainer, - defaultAnimations, -} from "../../assets/snapsort/src/container"; -import type { DragVisual } from "../../assets/snapsort/src/index"; -import { Item as SnapSortItem } from "../../assets/snapsort/src/item"; -import { DragSessionController as DragSession } from "../../assets/snapsort/src/drag/session"; -import { - clearDragSession, - installDragSession, -} from "../../assets/snapsort/src/drag/session-store"; -import { - builtinStrategies, - type SortMode, -} from "../../assets/snapsort/src/drag/drop-strategy"; -import { - DROP_REJECT_PRIORITY, - type DropPriorityEvent, -} from "../../assets/snapsort/src/events"; -import { - assertCanFireItemMove, - assertCanFireItemSwap, -} from "../../assets/snapsort/src/mutation"; -import { - flowLayoutPositions, - makeContainerSnapshot, - makeItemSnapshot, - rowCounts, - simulatedRowCounts, -} from "../helpers/layout-grid"; - - -test("built-in modes choose composable drag visual defaults that can be overridden before activation", () => { - let nextId = 0; - const engine = { - global: { - data: {}, - queue: {}, - createId: () => `drag-visual-default-${++nextId}`, - registerObject: () => {}, - unregisterObject: () => {}, - }, - input: { - subscribeGlobalCursorEvent: () => {}, - unsubscribeGlobalCursorEvent: () => {}, - }, - }; - const expected = { - euclidean: "item", - progressive: "item", - insertion: "none", - swap: "preview", - } as const satisfies Record; - - for (const mode of Object.keys(expected) as SortMode[]) { - const root = new SnapSortContainer(engine, null, { - itemId: `drag-visual-${mode}-root`, - mode, - }); - const item = new SnapSortItem(engine, root, { - itemId: `drag-visual-${mode}-item`, - }); - const source = { - container: root, - containerMetadata: root.metadata, - index: 0, - }; - const session = new DragSession( - root, - [item], - [source], - builtinStrategies[mode], - { - inputType: "pointer", - prop: { - handoffTo: () => {}, - pointerId: 1, - start: { x: 10, y: 20 }, - } as never, - }, - ); - installDragSession(root, session); - const handle = root.dragSession!; - const nested = new SnapSortContainer(engine, root, { - itemId: `drag-visual-${mode}-nested`, - mode, - }); - - expect(handle).toBe(session); - expect(nested.dragSession).toBeNull(); - expect(Object.isFrozen(handle)).toBe(false); - expect(Object.isFrozen(handle.input)).toBe(true); - expect(Object.isFrozen(handle.items)).toBe(true); - expect(Object.isFrozen(handle.sources)).toBe(true); - expect(Object.isFrozen(handle.sources[0])).toBe(true); - if (handle.input.inputType !== "pointer") { - throw new Error("Expected pointer input"); - } - expect(Object.isFrozen(handle.input.start)).toBe(true); - expect(Object.isFrozen(handle.input.pointer)).toBe(true); - expect("strategy" in handle).toBe(true); - expect("ghosts" in handle).toBe(false); - expect("cancel" in handle).toBe(true); - expect(() => (handle.items as any[]).push(item)).toThrow(); - expect(() => ((handle.sources[0] as any).index = 2)).toThrow(); - expect(() => ((handle.input.pointer as any).x = 30)).toThrow(); - - expect(handle.dragVisual).toBe(expected[mode]); - expect(() => { - (handle as any).dragVisual = "clone"; - }).toThrow(/DragSession\.dragVisual/); - const override = expected[mode] === "preview" ? "none" : "preview"; - handle.dragVisual = override; - expect(handle.dragVisual).toBe(override); - handle.dropEffect = "none"; - expect(handle.dropEffect).toBe("none"); - session.phase = "active"; - expect(() => { - handle.dragVisual = expected[mode]; - }).toThrow(/DragSession\.dragVisual/); - handle.dropEffect = "move"; - expect(() => { - (handle as any).dropEffect = "copy"; - }).toThrow(/DragSession\.dropEffect/); - session.phase = "dropping"; - expect(() => { - handle.dropEffect = "none"; - }).toThrow(/DragSession\.dropEffect/); - session.phase = "ended"; - expect(() => { - handle.dropEffect = "none"; - }).toThrow(/DragSession\.dropEffect/); - expect(handle.dragVisual).toBe(override); - - clearDragSession(root, session); - expect(root.dragSession).toBeNull(); - nested.destroy(false); - item.destroy(false); - root.destroy(false); - } -}); - -test("container animations are opt-in and expose the standard preset", () => { - let nextId = 0; - const engine = { - global: { - data: {}, - queue: {}, - createId: () => `animation-config-test-${++nextId}`, - registerObject: () => {}, - }, - input: { - subscribeGlobalCursorEvent: () => {}, - unsubscribeGlobalCursorEvent: () => {}, - }, - }; - - const immediate = new SnapSortContainer(engine, null, { - itemId: "animation-immediate-root", - }); - const animated = new SnapSortContainer(engine, null, { - itemId: "animation-enabled-root", - animation: defaultAnimations, - }); - const partiallyDisabled = new SnapSortContainer(engine, null, { - itemId: "animation-partially-disabled-root", - animation: { reorder: null, drop: defaultAnimations.drop }, - }); - const disabled = new SnapSortContainer(engine, null, { - itemId: "animation-disabled-root", - animation: null, - }); - - expect(immediate.config.animation).toBeUndefined(); - expect(immediate.reorderAnimationConfig(immediate)).toBeNull(); - expect(immediate.dropAnimationConfig(immediate)).toBeNull(); - expect(defaultAnimations).toEqual({ - reorder: { duration: 100, timing_function: "ease-out" }, - drop: { duration: 100, timing_function: "ease-out" }, - move: { duration: 100, timing_function: "ease-out" }, - }); - expect(animated.reorderAnimationConfig(animated)).toBe( - defaultAnimations.reorder, - ); - expect(animated.dropAnimationConfig(animated)).toBe(defaultAnimations.drop); - expect( - partiallyDisabled.reorderAnimationConfig(partiallyDisabled), - ).toBeNull(); - expect(partiallyDisabled.dropAnimationConfig(partiallyDisabled)).toBe( - defaultAnimations.drop, - ); - expect(disabled.reorderAnimationConfig(disabled)).toBeNull(); - expect(disabled.dropAnimationConfig(disabled)).toBeNull(); -}); - -test("item drag snapshots freeze a shallow copy of current metadata", () => { - let nextId = 0; - const engine = { - global: { - data: {}, - queue: {}, - createId: () => `metadata-snapshot-${++nextId}`, - registerObject: () => {}, - unregisterObject: () => {}, - }, - input: { - subscribeGlobalCursorEvent: () => {}, - unsubscribeGlobalCursorEvent: () => {}, - }, - }; - const item = new SnapSortItem(engine as never, null, { - itemId: "metadata-item", - }); - const original = { version: 1 }; - item.metadata = original; - - const snapshot = item.captureDragSnapshotTree(); - item.metadata = { version: 2 }; - - expect(snapshot.metadata).not.toBe(original); - expect(snapshot.metadata.version).toBe(1); - expect(Object.isFrozen(snapshot.metadata)).toBe(true); - expect(item.metadata.version).toBe(2); -}); - -test("custom adapters never inherit Vanilla DOM callbacks", () => { - let nextId = 0; - const engine = { - global: { - data: {}, - queue: {}, - createId: () => `ownership-test-${++nextId}`, - registerObject: () => {}, - }, - input: { - subscribeGlobalCursorEvent: () => {}, - unsubscribeGlobalCursorEvent: () => {}, - }, - }; - const onItemMove = () => {}; - - const vanilla = new SnapSortContainer(engine, null, { - itemId: "ownership-vanilla-root", - }); - const framework = new SnapSortContainer(engine, null, { - itemId: "ownership-framework-root", - adapter: { callbacks: {}, commit: (mutation) => mutation() }, - callbacks: { onItemMove }, - }); - const frameworkWithoutMutation = new SnapSortContainer(engine, null, { - itemId: "ownership-framework-without-mutation-root", - adapter: { callbacks: {}, commit: (mutation) => mutation() }, - }); - - expect(vanilla.adapter.callbacks.onItemInsert).toBeDefined(); - expect(vanilla.adapter.callbacks.onGhostInsert).toBeDefined(); - expect(framework.callbacks.onItemMove).toBe(onItemMove); - expect(framework.callbacks.onItemInsert).toBeUndefined(); - expect(framework.callbacks.onItemRemove).toBeUndefined(); - expect(framework.callbacks.onGhostInsert).toBeUndefined(); - expect(framework.callbacks.onGhostMove).toBeUndefined(); - expect(framework.callbacks.onGhostRemove).toBeUndefined(); - expect(() => assertCanFireItemMove(frameworkWithoutMutation)).toThrow( - /requires callbacks\.onItemMove or callbacks\.onItemInsert/, - ); - expect(() => assertCanFireItemSwap(framework)).toThrow( - /requires callbacks\.onItemSwap/, - ); - expect(() => assertCanFireItemSwap(vanilla)).not.toThrow(); -}); - -test("visual geometry invalidations coalesce at the root container", async () => { - let nextId = 0; - const queue = { - READ_1: new Map(), - WRITE_1: new Map(), - READ_2: new Map(), - WRITE_2: new Map(), - READ_3: new Map(), - WRITE_3: new Map(), - }; - const events: Array<{ - items: readonly unknown[]; - reasons: readonly string[]; - }> = []; - const engine = { - global: { - data: {}, - queue, - createId: () => `geometry-test-${++nextId}`, - registerObject: () => {}, - }, - input: { - subscribeGlobalCursorEvent: () => {}, - unsubscribeGlobalCursorEvent: () => {}, - }, - }; - const root = new SnapSortContainer(engine, null, { - itemId: "visual-geometry-root", - adapter: { callbacks: {}, commit: (mutation) => mutation() }, - callbacks: { - onVisualGeometryInvalidated: (event) => { - events.push(event); - if (events.length === 1) { - root.invalidateVisualGeometry([second], "settle"); - } - }, - }, - }); - const child = new SnapSortContainer(engine, root, { - itemId: "visual-geometry-child", - }); - const first = { isGhost: false } as never; - const second = { isGhost: false } as never; - const ghost = { isGhost: true } as never; - - child.invalidateVisualGeometry([first, ghost], "drag"); - root.invalidateVisualGeometry([first, second], "animation"); - - const rootQueue = queue.READ_1.get(root.id); - expect(rootQueue?.size).toBe(1); - const task = [...rootQueue!.values()][0]!; - for (const callback of task.callback ?? []) await callback(); - - expect(events).toHaveLength(1); - expect(events[0]!.items).toEqual([first, second]); - expect(events[0]!.reasons).toEqual(["drag", "animation"]); - expect(queue.READ_1.get(root.id)?.size).toBe(1); - - const nextTask = [...queue.READ_1.get(root.id)!.values()][0]!; - for (const callback of nextTask.callback ?? []) await callback(); - - expect(events).toHaveLength(2); - expect(events[1]!.items).toEqual([second]); - expect(events[1]!.reasons).toEqual(["settle"]); -}); -type Box = ElementBox; - -type LayoutCase = { - name: string; - width: number; - padding: { top: number; right: number; bottom: number; left: number }; - border: { top: number; right: number; bottom: number; left: number }; - columnGap: number; - rowGap: number; - itemWidths: number[]; - itemHeights: number[]; - itemBorders: number[]; -}; - -type BrowserLayoutCase = { - name: string; - container: Box; - items: Array<{ id: string; box: Box }>; - draggedId: string; - ghost: { width: number; height: number }; - actualGhosts: Array<{ index: number; x: number; y: number }>; -}; - -type DragSample = { - step: number; - mouse: { x: number; y: number }; - spacerCount: number; - spacer: Rect | null; - spacerParentId: string | null; - spacerParentKind: string | null; - spacerParentText: string | null; - spacerIndex: number | null; - spacerPrevious: (Rect & { text: string }) | null; - spacerNext: (Rect & { text: string }) | null; - spacerDomPrevious: (Rect & { text: string }) | null; - spacerDomNext: (Rect & { text: string }) | null; - dragged: (Rect & { centerX: number; centerY: number }) | null; - draggedCenterDelta: number | null; - draggedSourceColumnZIndex?: string | null; - draggedAttribute?: string | null; - frameRects?: Array<{ - role: string; - text: string; - id: string | null; - transform: string; - rect: Rect; - }>; -}; - -type DomTraceEntry = { - type: string; - target: string; - parent?: string; - before?: string | null; - time: number; -}; - -type SnapSortLifecycleState = { - spacerCount: number; - draggingTexts: string[]; - draggingStyles: Array<{ - text: string; - position: string; - zIndex: string; - transform: string; - }>; - nestedOuterChildren: Array<{ - id: string; - classes: string[]; - text: string; - }>; -}; - -type SelfInsertProbeState = { - found: boolean; - childIndex: number | null; - duplicateCount: number | null; - insertEvents: Array<{ - index: number; - selfBefore: boolean; - beforeText: string | null; - }>; - beforeOrder: string[]; - afterOrder: string[]; - domChildren: string[]; -}; - -type MockSnapSortItem = { - id: string; - itemId: string; - metadata: Record; - direction: "row" | "column"; - mainAxisAlign: "start"; - locked: boolean; - isGhost: boolean; - parent?: MockSnapSortItem | null; - callbacks?: { - getDropPriority?: (event: DropPriorityEvent) => number | undefined; - }; - dropPriority?: number; - dragSnapshot: ItemSnapshot; - box: Box; - itemOrderedList: MockSnapSortItem[]; - children: MockSnapSortItem[]; - worldTransform: { x: number; y: number; scaleX: number; scaleY: number }; - dragPositionX: number; - dragPositionY: number; - dragPointerPosition: { x: number; y: number } | null; - depth: number; - name?: string; - config?: Record; - numberOfItems?: number; - addDebugRect: () => void; - addDebugCircle: () => void; - addDebugLine: () => void; - addDebugText: () => void; - clearDebugMarker: () => void; -}; - -async function installSnapsortTrace(page: Page) { - await page.addInitScript(() => { - const win = window as unknown as { - __snapsortTrace: { - dom: DomTraceEntry[]; - mutations: Array<{ - type: string; - target: string; - attr: string | null; - time: number; - }>; - }; - __snapsortActiveText?: string; - __snapsortActiveIndex?: number; - __snapsortActiveId?: string; - }; - - const trace = { - dom: [] as DomTraceEntry[], - mutations: [] as Array<{ - type: string; - target: string; - attr: string | null; - time: number; - }>, - }; - win.__snapsortTrace = trace; - - const describe = (node: unknown) => { - if (!(node instanceof Element)) return String(node); - const text = node.textContent?.trim().replace(/\s+/g, " ").slice(0, 40); - const id = node.id ? `#${node.id}` : ""; - const classes = [...node.classList].slice(0, 4).join("."); - return `${node.tagName.toLowerCase()}${id}${classes ? `.${classes}` : ""}${text ? ` "${text}"` : ""}`; - }; - - const shouldTrace = (node: unknown) => - node instanceof Element && - (node.id === "spacer" || - node.classList.contains("snapsort-item") || - node.classList.contains("snapsort-item-wrapper") || - node.classList.contains("snapsort-container") || - node.closest?.(".snapsort-container") != null); - - const originalAppendChild = Node.prototype.appendChild; - Node.prototype.appendChild = function (child: T): T { - if (shouldTrace(child) || shouldTrace(this)) { - trace.dom.push({ - type: "appendChild", - target: describe(child), - parent: describe(this), - time: performance.now(), - }); - } - return originalAppendChild.call(this, child) as T; - }; - - const originalInsertBefore = Node.prototype.insertBefore; - Node.prototype.insertBefore = function ( - child: T, - before: Node | null, - ): T { - if (shouldTrace(child) || shouldTrace(this)) { - trace.dom.push({ - type: "insertBefore", - target: describe(child), - parent: describe(this), - before: before ? describe(before) : null, - time: performance.now(), - }); - } - return originalInsertBefore.call(this, child, before) as T; - }; - - const originalRemove = Element.prototype.remove; - Element.prototype.remove = function () { - if (shouldTrace(this)) { - trace.dom.push({ - type: "remove", - target: describe(this), - parent: describe(this.parentElement), - time: performance.now(), - }); - } - return originalRemove.call(this); - }; - - const mutationObserver = new MutationObserver((mutations) => { - for (const mutation of mutations) { - if (shouldTrace(mutation.target)) { - trace.mutations.push({ - type: mutation.type, - target: describe(mutation.target), - attr: mutation.attributeName, - time: performance.now(), - }); - } - } - }); - - const observeDocument = () => { - const documentElement = document.documentElement; - if (!documentElement) return; - mutationObserver.observe(documentElement, { - attributes: true, - attributeFilter: ["class", "style", "data-engine-id"], - childList: true, - subtree: true, - }); - }; - if (document.documentElement) observeDocument(); - else { - document.addEventListener("DOMContentLoaded", observeDocument, { - once: true, - }); - } - }); -} - -function center(rect: Rect) { - return { - x: rect.x + rect.width / 2, - y: rect.y + rect.height / 2, - }; -} - -function layoutBox( - rect: Rect, - margin: Partial = {}, - padding: Partial = {}, - border: Partial = {}, -): Box { - return { - ...rect, - screen: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - margin: { - top: margin.top ?? 0, - right: margin.right ?? 0, - bottom: margin.bottom ?? 0, - left: margin.left ?? 0, - }, - padding: { - top: padding.top ?? 0, - right: padding.right ?? 0, - bottom: padding.bottom ?? 0, - left: padding.left ?? 0, - }, - border: { - top: border.top ?? 0, - right: border.right ?? 0, - bottom: border.bottom ?? 0, - left: border.left ?? 0, - }, - }; -} - -function itemSnapshot( - value: T, - box: Box, - children: ItemSnapshot[] = [], - direction: "row" | "column" = "column", -): ItemSnapshot { - return { - value, - itemId: String(value), - metadata: {}, - direction, - mainAxisAlign: "start", - layoutModel: "flow", - wrap: "auto", - stretchItems: false, - locked: false, - box, - children, - }; -} - -type SnapshotFixture = Omit< - ItemSnapshot, - | "itemId" - | "metadata" - | "mainAxisAlign" - | "layoutModel" - | "wrap" - | "stretchItems" - | "children" -> & { - itemId?: string; - metadata?: ItemSnapshot["metadata"]; - mainAxisAlign?: ItemSnapshot["mainAxisAlign"]; - layoutModel?: ItemSnapshot["layoutModel"]; - wrap?: ItemSnapshot["wrap"]; - stretchItems?: ItemSnapshot["stretchItems"]; - children: SnapshotFixture[]; -}; - -function snapshotFixture(fixture: SnapshotFixture): ItemSnapshot { - return { - ...fixture, - itemId: fixture.itemId ?? String(fixture.value), - metadata: fixture.metadata ?? {}, - mainAxisAlign: fixture.mainAxisAlign ?? "start", - layoutModel: fixture.layoutModel ?? "flow", - wrap: fixture.wrap ?? "auto", - stretchItems: fixture.stretchItems ?? false, - children: fixture.children.map(snapshotFixture), - }; -} - -function mockSnapSortItem( - id: string, - rect: Rect, - children: MockSnapSortItem[] = [], - direction: "row" | "column" = "column", -): MockSnapSortItem { - const box = layoutBox(rect); - const item: MockSnapSortItem = { - id, - itemId: id, - metadata: {}, - direction, - mainAxisAlign: "start", - locked: false, - isGhost: false, - parent: null, - callbacks: undefined, - dropPriority: 0, - dragSnapshot: null as unknown as ItemSnapshot, - box, - itemOrderedList: children, - children, - worldTransform: { x: rect.x, y: rect.y, scaleX: 1, scaleY: 1 }, - dragPositionX: rect.x, - dragPositionY: rect.y, - dragPointerPosition: null, - depth: 0, - addDebugRect: () => {}, - addDebugCircle: () => {}, - addDebugLine: () => {}, - addDebugText: () => {}, - clearDebugMarker: () => {}, - }; - item.getIndexAndContainer = () => { - const container = item.parent; - return { - container, - index: container ? container.itemOrderedList.indexOf(item) : -1, - }; - }; - Object.defineProperties(item, { - dragPositionX: { - get: () => item.worldTransform.x, - configurable: true, - }, - dragPositionY: { - get: () => item.worldTransform.y, - configurable: true, - }, - dragPointerPosition: { - get: () => null, - configurable: true, - }, - }); - item.dragSnapshot = itemSnapshot( - item, - box, - children.map((child) => child.dragSnapshot), - direction, - ); - for (const child of children) { - child.depth = item.depth + 1; - child.parent = item; - } - return item; -} - -function mockSnapSortContainer( - id: string, - rect: Rect, - children: MockSnapSortItem[], - direction: "row" | "column", -): MockSnapSortItem { - const item = mockSnapSortItem(id, rect, children, direction); - item.config = {}; - item.name = id; - item.numberOfItems = children.length; - return item; -} - -function dropPriorityFixture() { - const dragged = mockSnapSortItem("dragged", { - x: 10, - y: 10, - width: 20, - height: 20, - }); - const source = mockSnapSortContainer( - "source", - { x: -100, y: 0, width: 50, height: 50 }, - [dragged], - "column", - ); - const near = mockSnapSortContainer( - "near", - { x: 0, y: 0, width: 100, height: 50 }, - [], - "column", - ); - const far = mockSnapSortContainer( - "far", - { x: 0, y: 65, width: 100, height: 50 }, - [], - "column", - ); - const root = mockSnapSortContainer( - "root", - { x: 0, y: 0, width: 100, height: 115 }, - [near, far], - "column", - ); - root.callbacks = { getDropPriority: rejectDrop }; - return { dragged, source, near, far, root }; -} - -test.describe("standard SnapSort drop callbacks", () => { - const event = { - pointer: { x: 15, y: 25 }, - dragRect: { x: 5, y: 5, width: 10, height: 10 }, - containerRect: { x: 10, y: 20, width: 30, height: 40 }, - } as DropPriorityEvent; - - test("pointer and drag intersection priorities share core collision semantics", () => { - expect(prioritizePointerContainer(event)).toBe(1); - expect( - prioritizePointerContainer({ - ...event, - pointer: { x: 9, y: 25 }, - }), - ).toBeUndefined(); - expect(prioritizeIntersectingContainer(event)).toBeUndefined(); - expect( - prioritizeIntersectingContainer({ - ...event, - dragRect: { x: 5, y: 25, width: 10, height: 10 }, - }), - ).toBe(1); - expect( - prioritizeIntersectingContainer({ - ...event, - dragRect: { x: 0, y: 20, width: 10, height: 10 }, - }), - ).toBeUndefined(); - }); - - test("nearest-container scoring and unconditional rejection are reusable", () => { - expect(prioritizeNearestContainerEdge(event)).toBe(1); - expect( - prioritizeNearestContainerEdge({ - ...event, - pointer: { x: 7, y: 16 }, - }), - ).toBeCloseTo(1 / 6); - expect( - prioritizeNearestContainerEdge({ - ...event, - pointer: { x: 4, y: 12 }, - }), - ).toBeLessThan(1 / 6); - expect(DROP_REJECT_PRIORITY).toBe(-1); - expect(rejectDrop({} as DropPriorityEvent)).toBe(DROP_REJECT_PRIORITY); - }); - - test("tree depth uses the virtual leading x edge and pointer y", () => { - const treeEvent = { - ...event, - staticPriority: 0, - depth: 3, - containerRect: { x: 10, y: 20, width: 30, height: 40 }, - dragRect: { x: 10, y: 0, width: 80, height: 10 }, - pointer: { x: 100, y: 20 }, - } as DropPriorityEvent; - - expect(prioritizeTreeDepth(treeEvent)).toBe(4); - expect( - prioritizeTreeDepth({ - ...treeEvent, - dragRect: { ...treeEvent.dragRect, x: 40 }, - pointer: { x: 0, y: 60 }, - }), - ).toBe(4); - expect( - prioritizeTreeDepth({ - ...treeEvent, - dragRect: { ...treeEvent.dragRect, x: 9 }, - pointer: { x: 15, y: 25 }, - }), - ).toBe(0); - expect( - prioritizeTreeDepth({ - ...treeEvent, - pointer: { x: 15, y: 61 }, - }), - ).toBe(0); - }); -}); - -test("drop priority filters containers before each placement mode ranks slots", () => { - const { dragged, near, far, root } = dropPriorityFixture(); - - expect(determineDropTarget(dragged as any, root as any)?.container).toBe( - near, - ); - far.dropPriority = 1; - - expect(determineDropTarget(dragged as any, root as any)?.container).toBe(far); - expect( - determineProgressiveDropTarget(dragged as any, root as any)?.container, - ).toBe(far); - expect( - determineInsertionDropTarget(dragged as any, root as any)?.container, - ).toBe(far); - - far.callbacks = { getDropPriority: rejectDrop }; - expect(determineDropTarget(dragged as any, root as any)?.container).toBe( - near, - ); - expect( - determineProgressiveDropTarget(dragged as any, root as any)?.container, - ).toBe(near); - expect( - determineInsertionDropTarget(dragged as any, root as any)?.container, - ).toBe(near); -}); - -test("Euclidean priority resolves mismatched zones before ranking their slots", () => { - const dragged = mockSnapSortItem("dragged", { - x: 300, - y: 170, - width: 20, - height: 20, - }); - const largeZone = mockSnapSortContainer( - "large-zone", - { x: 0, y: 0, width: 400, height: 200 }, - [], - "row", - ); - const smallZone = mockSnapSortContainer( - "small-zone", - { x: 0, y: 200, width: 400, height: 40 }, - [], - "column", - ); - const root = mockSnapSortContainer( - "root", - { x: 0, y: 0, width: 400, height: 240 }, - [largeZone, smallZone], - "column", - ); - root.callbacks = { getDropPriority: rejectDrop }; - - expect(determineDropTarget(dragged as any, root as any)?.container).toBe( - smallZone, - ); - - smallZone.callbacks = { - getDropPriority: prioritizeIntersectingContainer, - }; - largeZone.callbacks = { - getDropPriority: prioritizeIntersectingContainer, - }; - expect(determineDropTarget(dragged as any, root as any)?.container).toBe( - largeZone, - ); -}); - -test("priority -1 rejects a container", () => { - const { dragged, near, far, root } = dropPriorityFixture(); - let priorityCalls = 0; - far.dropPriority = 100; - far.callbacks = { - getDropPriority: (event) => { - priorityCalls++; - return rejectDrop(event); - }, - }; - - expect(determineDropTarget(dragged as any, root as any)?.container).toBe( - near, - ); - expect(priorityCalls).toBe(1); -}); - -test("priority -1 can reject every destination and be overridden dynamically", () => { - const { dragged, near, far, root } = dropPriorityFixture(); - near.dropPriority = DROP_REJECT_PRIORITY; - far.dropPriority = DROP_REJECT_PRIORITY; - - expect(determineDropTarget(dragged as any, root as any)).toBeNull(); - - near.callbacks = { getDropPriority: () => 0 }; - expect(determineDropTarget(dragged as any, root as any)?.container).toBe( - near, - ); -}); - -test("drop priority runs once for a container with multiple candidate slots", () => { - const dragged = mockSnapSortItem("dragged", { - x: 10, - y: 10, - width: 20, - height: 20, - }); - const first = mockSnapSortItem("first", { - x: 0, - y: 0, - width: 100, - height: 20, - }); - const second = mockSnapSortItem("second", { - x: 0, - y: 20, - width: 100, - height: 20, - }); - const target = mockSnapSortContainer( - "target", - { x: 0, y: 0, width: 100, height: 60 }, - [first, second], - "column", - ); - const root = mockSnapSortContainer( - "root", - { x: 0, y: 0, width: 100, height: 60 }, - [target], - "column", - ); - root.callbacks = { getDropPriority: rejectDrop }; - - let priorityCalls = 0; - target.callbacks = { - getDropPriority: () => { - priorityCalls++; - return undefined; - }, - }; - - expect(determineDropTarget(dragged as any, root as any)?.container).toBe( - target, - ); - expect(priorityCalls).toBe(1); -}); - -test("priority supports rejection, fallback, and nonnegative overrides", () => { - const { dragged, near, far, root } = dropPriorityFixture(); - near.dropPriority = DROP_REJECT_PRIORITY; - far.dropPriority = 0.5; - near.callbacks = { getDropPriority: () => undefined }; - - expect(determineDropTarget(dragged as any, root as any)?.container).toBe(far); - - near.callbacks = { getDropPriority: () => 0.75 }; - expect(determineDropTarget(dragged as any, root as any)?.container).toBe( - near, - ); -}); - -test("drop policy events expose source, destination, metadata, and geometry", () => { - const { dragged, source, near, far, root } = dropPriorityFixture(); - dragged.metadata = { kind: "card" }; - source.metadata = { dropGroup: "cards" }; - near.metadata = { dropGroup: "cards" }; - let priorityEvent: DropPriorityEvent | null = null; - near.callbacks = { - getDropPriority: (event) => { - priorityEvent = event; - return undefined; - }, - }; - far.callbacks = { getDropPriority: rejectDrop }; - - determineDropTarget(dragged as any, root as any); - - expect(priorityEvent).toMatchObject({ - itemId: "dragged", - itemMetadata: { kind: "card" }, - source: { - container: source, - containerMetadata: { dropGroup: "cards" }, - index: 0, - }, - sources: [ - { - container: source, - containerMetadata: { dropGroup: "cards" }, - index: 0, - }, - ], - container: near, - containerMetadata: { dropGroup: "cards" }, - index: 0, - }); - expect(priorityEvent).toMatchObject({ - staticPriority: 0, - pointer: { x: 20, y: 20 }, - dragRect: { x: 10, y: 10, width: 20, height: 20 }, - containerRect: { x: 0, y: 0, width: 100, height: 50 }, - containerContentRect: { x: 0, y: 0, width: 100, height: 50 }, - depth: 1, - }); -}); - -test("applications can replace grouping with source and destination metadata", () => { - const { dragged, source, near, far, root } = dropPriorityFixture(); - source.metadata = { dropGroup: "cards" }; - near.metadata = { dropGroup: "cards" }; - far.metadata = { dropGroup: "files" }; - far.dropPriority = 10; - const prioritizeMatchingGroup = (event: DropPriorityEvent) => - event.source?.containerMetadata.dropGroup === - event.containerMetadata.dropGroup - ? undefined - : rejectDrop(event); - near.callbacks = { getDropPriority: prioritizeMatchingGroup }; - far.callbacks = { getDropPriority: prioritizeMatchingGroup }; - - expect(determineDropTarget(dragged as any, root as any)?.container).toBe( - near, - ); -}); - -test("drop policy events preserve every source in a multi-item drag", () => { - const { dragged, source, near, far, root } = dropPriorityFixture(); - const companion = mockSnapSortItem("companion", { - x: -80, - y: 20, - width: 20, - height: 20, - }); - const companionSource = mockSnapSortContainer( - "companion-source", - { x: -100, y: 0, width: 50, height: 50 }, - [companion], - "column", - ); - dragged.metadata = { order: 1 }; - companion.metadata = { order: 2 }; - source.metadata = { dropGroup: "cards" }; - companionSource.metadata = { dropGroup: "cards" }; - let event: DropPriorityEvent | null = null; - near.callbacks = { - getDropPriority: (nextEvent) => { - event = nextEvent; - return undefined; - }, - }; - far.callbacks = { getDropPriority: rejectDrop }; - const session = { - items: [dragged, companion], - sources: [ - { - container: source, - containerMetadata: source.metadata, - index: 0, - }, - { - container: companionSource, - containerMetadata: companionSource.metadata, - index: 0, - }, - ], - activeSources: [ - { - container: source, - containerMetadata: source.metadata, - index: 0, - }, - { - container: companionSource, - containerMetadata: companionSource.metadata, - index: 0, - }, - ], - itemSet: new Set([dragged, companion]), - snapshotItemSet: new Set([dragged, companion]), - pointer: { x: 20, y: 20 }, - }; - - determineInsertionDropTarget(dragged as any, root as any, session as any); - - expect(event?.items.map((item) => item.itemId)).toEqual([ - "dragged", - "companion", - ]); - expect(event?.itemsMetadata).toEqual([{ order: 1 }, { order: 2 }]); - expect(event?.source?.container).toBe(source); - expect(event?.sources.map((location) => location?.container)).toEqual([ - source, - companionSource, - ]); -}); - -test("drop priority rejects malformed configured and callback values", () => { - const configured = dropPriorityFixture(); - configured.far.dropPriority = Number.POSITIVE_INFINITY; - expect(() => - determineDropTarget(configured.dragged as any, configured.root as any), - ).toThrow(/dropPriority must be -1 or a finite nonnegative number/); - - for (const value of [-2, -0.5, Number.NEGATIVE_INFINITY, "1", null, {}]) { - const malformed = dropPriorityFixture(); - malformed.far.dropPriority = value as never; - expect(() => - determineDropTarget(malformed.dragged as any, malformed.root as any), - ).toThrow(/dropPriority must be -1 or a finite nonnegative number/); - } - - for (const value of [ - -2, - -0.5, - Number.NEGATIVE_INFINITY, - Number.POSITIVE_INFINITY, - Number.NaN, - "1", - null, - {}, - ]) { - const callback = dropPriorityFixture(); - callback.far.callbacks = { getDropPriority: () => value as never }; - expect(() => - determineDropTarget(callback.dragged as any, callback.root as any), - ).toThrow(/getDropPriority must be -1 or a finite nonnegative number/); - } -}); - -test("a container priority does not propagate to nested containers", () => { - const dragged = mockSnapSortItem("dragged", { - x: 10, - y: 10, - width: 20, - height: 20, - }); - const child = mockSnapSortContainer( - "child", - { x: 0, y: 0, width: 50, height: 50 }, - [], - "column", - ); - const parent = mockSnapSortContainer( - "parent", - { x: 0, y: 0, width: 100, height: 100 }, - [child], - "column", - ); - const root = mockSnapSortContainer( - "root", - { x: 0, y: 0, width: 100, height: 100 }, - [parent], - "column", - ); - root.callbacks = { getDropPriority: rejectDrop }; - parent.dropPriority = 1; - let childStaticPriority: number | null = null; - child.callbacks = { - getDropPriority: (event) => { - childStaticPriority = event.staticPriority; - return undefined; - }, - }; - - const target = determineDropTarget(dragged as any, root as any); - expect(childStaticPriority).toBe(0); - expect(target?.container).toBe(parent); -}); - -test("swap collects every hovered container before applying priority", () => { - let nextId = 0; - const engine = { - global: { - data: {}, - queue: {}, - createId: () => `swap-priority-${++nextId}`, - registerObject: () => {}, - unregisterObject: () => {}, - }, - input: { - subscribeGlobalCursorEvent: () => {}, - unsubscribeGlobalCursorEvent: () => {}, - }, - collisionEngine: null, - animationList: [], - }; - const makeItem = ( - itemId: string, - rect: Rect, - children: BaseObject[] = [], - container = false, - ) => { - const item = new BaseObject(engine as never) as BaseObject & - Record; - const box = layoutBox(rect); - item.itemId = itemId; - item.metadata = {}; - item.direction = "column"; - item.mainAxisAlign = "start"; - item.locked = false; - item.isGhost = false; - item.itemOrderedList = children; - item.children = children; - item.box = box; - item.depth = 0; - item.callbacks = undefined; - item.dropPriority = 0; - item.worldTransform = { x: rect.x, y: rect.y }; - Object.defineProperties(item, { - dragPositionX: { get: () => item.worldTransform.x }, - dragPositionY: { get: () => item.worldTransform.y }, - dragPointerPosition: { get: () => null }, - }); - if (container) { - item.config = {}; - item.name = itemId; - item.numberOfItems = children.length; - } - item.dragSnapshot = itemSnapshot( - item, - box, - children.map((child) => (child as any).dragSnapshot), - "column", - ); - return item; - }; - - const smallTarget = makeItem("small-target", { - x: 0, - y: 0, - width: 20, - height: 20, - }); - const largeTarget = makeItem("large-target", { - x: 0, - y: 0, - width: 60, - height: 60, - }); - const smallContainer = makeItem( - "small-container", - { x: 0, y: 0, width: 50, height: 50 }, - [smallTarget], - true, - ); - const preferredContainer = makeItem( - "preferred-container", - { x: 0, y: 0, width: 100, height: 100 }, - [largeTarget], - true, - ); - smallContainer.depth = 1; - preferredContainer.depth = 1; - preferredContainer.dropPriority = 1; - let smallHitboxOwner: unknown = null; - let preferredHitboxOwner: unknown = null; - smallContainer.callbacks = { - getItemHitbox: (event: any) => { - smallHitboxOwner = event.container; - return { - shape: "rect", - rect: { x: 80, y: 80, width: 10, height: 10 }, - }; - }, - }; - preferredContainer.callbacks = { - getItemHitbox: (event: any) => { - preferredHitboxOwner = event.container; - return { - shape: "circle", - circle: { x: 10, y: 10, radius: 8 }, - }; - }, - }; - const root = makeItem( - "root", - { x: 0, y: 0, width: 120, height: 120 }, - [smallContainer, preferredContainer], - true, - ); - root.callbacks = { getDropPriority: rejectDrop }; - const dragged = makeItem("dragged", { - x: 150, - y: 150, - width: 20, - height: 20, - }); - const session = { - items: [dragged], - sources: [null], - itemSet: new Set([dragged]), - pointer: { x: 10, y: 10 }, - }; - - const target = determineSwapDropTarget( - dragged as never, - root as never, - session as never, - ); - expect(target?.container).toBe(preferredContainer); - expect(target?.index).toBe(0); - expect(smallHitboxOwner).toBe(smallContainer); - expect(preferredHitboxOwner).toBe(preferredContainer); - - preferredContainer.callbacks = { - ...preferredContainer.callbacks, - getDropPriority: rejectDrop, - }; - expect( - determineSwapDropTarget(dragged as never, root as never, session as never), - ).toBeNull(); - - preferredContainer.callbacks = { - getItemHitbox: () => ({ - shape: "rect", - rect: { x: 0, y: 0, width: Number.NaN, height: 10 }, - }), - }; - expect(() => - determineSwapDropTarget(dragged as never, root as never, session as never), - ).toThrow(/getItemHitbox/); -}); - -function virtualInsertionPosition( - container: ItemSnapshot, - dragged: ItemSnapshot, - startX: number, - startY: number, - index: number, - width: number, - height: number, -) { - const insertion = { - container, - index, - entry: { - width, - height, - margin: dragged.box.margin, - }, - }; - const rect = flowLayoutPositions(container, startX, startY, { - exclude: (node) => node === dragged, - insertions: [insertion], - }).virtualRects.get(insertion); - return rect ? { x: rect.x, y: rect.y } : null; -} - -test("progressive placement selects the ghost slot under the dragged center", () => { - const dragged = mockSnapSortItem("dragged", { - x: 0, - y: 0, - width: 50, - height: 40, - }); - const columnItems = [ - mockSnapSortItem("a", { x: 0, y: 0, width: 80, height: 40 }), - mockSnapSortItem("b", { x: 0, y: 48, width: 80, height: 40 }), - mockSnapSortItem("c", { x: 0, y: 96, width: 80, height: 40 }), - ]; - const column = mockSnapSortContainer( - "column", - { x: 0, y: 0, width: 140, height: 180 }, - columnItems, - "column", - ); - dragged.worldTransform = { x: 15, y: 48, scaleX: 1, scaleY: 1 }; - - expect( - determineProgressiveDropTarget(dragged as any, column as any), - ).toMatchObject({ container: column, index: 1 }); - - const rowItems = [ - mockSnapSortItem("a", { x: 0, y: 0, width: 60, height: 40 }), - mockSnapSortItem("b", { x: 68, y: 0, width: 60, height: 40 }), - mockSnapSortItem("c", { x: 136, y: 0, width: 60, height: 40 }), - ]; - const row = mockSnapSortContainer( - "row", - { x: 0, y: 0, width: 240, height: 80 }, - rowItems, - "row", - ); - dragged.worldTransform = { x: 73, y: 0, scaleX: 1, scaleY: 1 }; - - expect( - determineProgressiveDropTarget(dragged as any, row as any), - ).toMatchObject({ container: row, index: 1 }); -}); - -test("euclidean placement keeps parent slots reachable next to nested containers", () => { - const before = mockSnapSortItem("before", { - x: 0, - y: 0, - width: 80, - height: 40, - }); - const dragged = mockSnapSortItem("dragged", { - x: 4, - y: 52, - width: 50, - height: 40, - }); - const nestedItem = mockSnapSortItem("nested-item", { - x: 4, - y: 100, - width: 50, - height: 40, - }); - const nested = mockSnapSortContainer( - "nested", - { x: 0, y: 48, width: 120, height: 96 }, - [dragged, nestedItem], - "column", - ); - const after = mockSnapSortItem("after", { - x: 0, - y: 152, - width: 80, - height: 40, - }); - const root = mockSnapSortContainer( - "root", - { x: 0, y: 0, width: 160, height: 220 }, - [before, nested, after], - "column", - ); - dragged.worldTransform = { x: 1, y: 49, scaleX: 1, scaleY: 1 }; - - const target = determineDropTarget(dragged as any, root as any); - - expect(target?.container).toBe(root); - expect(target?.index).toBe(1); -}); - -test("insertion placement maps a downward same-container gap to the live index", () => { - const itemA = mockSnapSortItem("a", { - x: 0, - y: 0, - width: 120, - height: 40, - }); - const dragged = mockSnapSortItem("dragged", { - x: 0, - y: 48, - width: 120, - height: 40, - }); - const itemB = mockSnapSortItem("b", { - x: 0, - y: 96, - width: 120, - height: 40, - }); - const itemC = mockSnapSortItem("c", { - x: 0, - y: 144, - width: 120, - height: 40, - }); - const container = mockSnapSortContainer( - "container", - { x: 0, y: 0, width: 120, height: 184 }, - [itemA, dragged, itemB, itemC], - "column", - ); - dragged.worldTransform = { x: 0, y: 120, scaleX: 1, scaleY: 1 }; - - const target = determineInsertionDropTarget(dragged as any, container as any); - - expect(target?.container).toBe(container); - expect(target?.index).toBe(3); - expect(target?.insertion).toMatchObject({ - gap: { orientation: "horizontal", x: 0, y: 140, length: 120 }, - previous: { item: itemB }, - next: { item: itemC }, - isCurrentPlacement: false, - }); -}); - -test.describe("SnapSort insertion marker strategy", () => { - test("keeps insertion marker absolute and does not displace siblings during hover", async ({ - page, - }) => { - await page.goto("/snapsort-insertion", { waitUntil: "networkidle" }); - - const firstList = page.locator(".insertion-list").first(); - const firstCard = firstList.locator(".insertion-card").first(); - const secondCard = firstList.locator(".insertion-card").nth(1); - - const firstRect = await itemRect(firstCard); - const secondBefore = await itemRect(secondCard); - const start = center(firstRect); - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x, start.y + firstRect.height + 18); - await page.waitForTimeout(120); - - const marker = page.locator('[data-snapsort-ghost="insertion"]').first(); - await expect(marker).toHaveCount(1); - - const markerState = await marker.evaluate((element) => { - const style = window.getComputedStyle(element); - const rect = element.getBoundingClientRect(); - return { - position: style.position, - inlineHeight: element.style.height, - computedHeight: style.height, - borderTopWidth: style.borderTopWidth, - rectHeight: rect.height, - }; - }); - expect(markerState.position).toBe("absolute"); - expect(markerState.inlineHeight).toBe("3px"); - expect(markerState.computedHeight).toBe("3px"); - expect(markerState.borderTopWidth).toBe("0px"); - expect(markerState.rectHeight).toBeCloseTo(3, 1); - - const secondDuring = await itemRect(secondCard); - expect(Math.abs(secondDuring.x - secondBefore.x)).toBeLessThan(1); - expect(Math.abs(secondDuring.y - secondBefore.y)).toBeLessThan(1); - - await page.mouse.up(); - }); - - test("moves one stable marker between both outer edges of the current item", async ({ - page, - }) => { - await page.goto("/snapsort-insertion", { waitUntil: "networkidle" }); - - const firstList = page.locator(".insertion-list").first(); - const cards = firstList.locator(".insertion-card"); - const dragged = cards.nth(1); - const beforeOrder = await cards.locator("strong").allTextContents(); - const firstBefore = await itemRect(cards.first()); - const draggedBefore = await itemRect(dragged); - const thirdBefore = await itemRect(cards.nth(2)); - const start = center(draggedBefore); - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x, draggedBefore.y + 4); - await page.waitForTimeout(120); - - const marker = page.locator('[data-snapsort-ghost="insertion"]'); - await expect(marker).toHaveCount(1); - const leadingRect = await itemRect(marker); - await marker.evaluate((element) => { - element.setAttribute("data-test-marker-identity", "stable"); - }); - - await page.mouse.move(start.x, draggedBefore.y + draggedBefore.height - 4); - await page.waitForTimeout(120); - - await expect(marker).toHaveCount(1); - await expect( - page.locator('[data-test-marker-identity="stable"]'), - ).toHaveCount(1); - const trailingRect = await itemRect(marker); - expect(trailingRect.y - leadingRect.y).toBeGreaterThan( - draggedBefore.height / 2, - ); - - for (const [current, before] of [ - [await itemRect(cards.first()), firstBefore], - [await itemRect(cards.nth(2)), thirdBefore], - ]) { - expect(Math.abs(current.x - before.x)).toBeLessThan(1); - expect(Math.abs(current.y - before.y)).toBeLessThan(1); - } - - await page.mouse.up(); - await expect(marker).toHaveCount(0); - await expect(cards.locator("strong")).toHaveText(beforeOrder); - }); -}); - -test("insertion placement maps an upward same-container gap to the live index", () => { - const itemA = mockSnapSortItem("a", { - x: 0, - y: 0, - width: 120, - height: 40, - }); - const itemB = mockSnapSortItem("b", { - x: 0, - y: 48, - width: 120, - height: 40, - }); - const dragged = mockSnapSortItem("dragged", { - x: 0, - y: 96, - width: 120, - height: 40, - }); - const itemC = mockSnapSortItem("c", { - x: 0, - y: 144, - width: 120, - height: 40, - }); - const container = mockSnapSortContainer( - "container", - { x: 0, y: 0, width: 120, height: 184 }, - [itemA, itemB, dragged, itemC], - "column", - ); - dragged.worldTransform = { x: 0, y: 32, scaleX: 1, scaleY: 1 }; - - const target = determineInsertionDropTarget(dragged as any, container as any); - - expect(target?.container).toBe(container); - expect(target?.index).toBe(1); - expect(target?.insertion).toMatchObject({ - gap: { orientation: "horizontal", x: 0, y: 44, length: 120 }, - previous: { item: itemA }, - next: { item: itemB }, - isCurrentPlacement: false, - }); -}); - -test("insertion placement keeps the top boundary reachable when dragging the first item", () => { - const dragged = mockSnapSortItem("dragged", { - x: 0, - y: 0, - width: 120, - height: 40, - }); - const itemA = mockSnapSortItem("a", { - x: 0, - y: 48, - width: 120, - height: 40, - }); - const itemB = mockSnapSortItem("b", { - x: 0, - y: 96, - width: 120, - height: 40, - }); - const container = mockSnapSortContainer( - "container", - { x: 0, y: 0, width: 120, height: 136 }, - [dragged, itemA, itemB], - "column", - ); - dragged.worldTransform = { x: 0, y: -22, scaleX: 1, scaleY: 1 }; - - const target = determineInsertionDropTarget(dragged as any, container as any); - - expect(target?.container).toBe(container); - expect(target?.index).toBe(1); - expect(target?.insertion).toMatchObject({ - gap: { orientation: "horizontal", x: 0, y: 0, length: 120 }, - previous: null, - next: { item: dragged }, - isCurrentPlacement: true, - }); -}); - -test("insertion placement keeps the bottom boundary reachable when dragging the last item", () => { - const itemA = mockSnapSortItem("a", { - x: 0, - y: 0, - width: 120, - height: 40, - }); - const itemB = mockSnapSortItem("b", { - x: 0, - y: 48, - width: 120, - height: 40, - }); - const dragged = mockSnapSortItem("dragged", { - x: 0, - y: 96, - width: 120, - height: 40, - }); - const container = mockSnapSortContainer( - "container", - { x: 0, y: 0, width: 120, height: 136 }, - [itemA, itemB, dragged], - "column", - ); - dragged.worldTransform = { x: 0, y: 132, scaleX: 1, scaleY: 1 }; - - const target = determineInsertionDropTarget(dragged as any, container as any); - - expect(target?.container).toBe(container); - expect(target?.index).toBe(3); - expect(target?.insertion).toMatchObject({ - gap: { orientation: "horizontal", x: 0, y: 136, length: 120 }, - previous: { item: dragged }, - next: null, - isCurrentPlacement: true, - }); -}); - -test("insertion placement spans the container content box on the marker cross axis", () => { - const itemA = mockSnapSortItem("a", { - x: 34, - y: 40, - width: 120, - height: 40, - }); - const dragged = mockSnapSortItem("dragged", { - x: 34, - y: 88, - width: 120, - height: 40, - }); - const itemB = mockSnapSortItem("b", { - x: 34, - y: 136, - width: 120, - height: 40, - }); - const container = mockSnapSortContainer( - "container", - { x: 10, y: 20, width: 220, height: 180 }, - [itemA, dragged, itemB], - "column", - ); - const containerBox = layoutBox( - { x: 10, y: 20, width: 220, height: 180 }, - {}, - { top: 8, right: 12, bottom: 8, left: 20 }, - { top: 2, right: 2, bottom: 2, left: 2 }, - ); - container.dragSnapshot = { - ...container.dragSnapshot, - box: containerBox, - }; - container.box = containerBox; - dragged.worldTransform = { x: 34, y: 112, scaleX: 1, scaleY: 1 }; - - const target = determineInsertionDropTarget(dragged as any, container as any); - - expect(target?.container).toBe(container); - expect(target?.insertion?.gap).toEqual({ - orientation: "horizontal", - x: 32, - y: 132, - length: 184, - }); -}); - -test("insertion placement shows a centered marker for an empty row container", () => { - const dragged = mockSnapSortItem("dragged", { - x: 0, - y: 0, - width: 60, - height: 32, - }); - const container = mockSnapSortContainer( - "container", - { x: 10, y: 20, width: 200, height: 80 }, - [], - "row", - ); - dragged.worldTransform = { x: 80, y: 44, scaleX: 1, scaleY: 1 }; - - const target = determineInsertionDropTarget(dragged as any, container as any); - - expect(target?.container).toBe(container); - expect(target?.index).toBe(0); - expect(target?.insertion).toEqual({ - gap: { orientation: "vertical", x: 110, y: 20, length: 80 }, - previous: null, - next: null, - isCurrentPlacement: false, - }); -}); - -test("progressive placement uses the cross-axis line in wrapped rows", () => { - const dragged = mockSnapSortItem("dragged", { - x: 0, - y: 0, - width: 70, - height: 40, - }); - const rowItems = [ - dragged, - mockSnapSortItem("a", { x: 80, y: 0, width: 70, height: 40 }), - mockSnapSortItem("b", { x: 0, y: 48, width: 70, height: 40 }), - mockSnapSortItem("c", { x: 80, y: 48, width: 70, height: 40 }), - ]; - const row = mockSnapSortContainer( - "wrapped-row", - { x: 0, y: 0, width: 160, height: 96 }, - rowItems, - "row", - ); - dragged.worldTransform = { x: 4, y: 48, scaleX: 1, scaleY: 1 }; - - expect( - determineProgressiveDropTarget(dragged as any, row as any), - ).toMatchObject({ container: row, index: 2 }); -}); - -test("wraps a horizontal ghost when its trailing margin exceeds the content width", () => { - const container = snapshotFixture({ - value: "container", - direction: "row", - locked: false, - box: layoutBox({ x: 0, y: 0, width: 313, height: 120 }), - children: [ - { - value: "item-1", - direction: "column", - locked: false, - box: layoutBox( - { x: 4, y: 0, width: 100, height: 40 }, - { left: 4, right: 4 }, - ), - children: [], - }, - { - value: "item-2", - direction: "column", - locked: false, - box: layoutBox( - { x: 112, y: 0, width: 100, height: 40 }, - { left: 4, right: 4 }, - ), - children: [], - }, - ], - }); - const dragged = snapshotFixture({ - value: "dragged", - direction: "column", - locked: false, - box: layoutBox( - { x: 0, y: 0, width: 90, height: 40 }, - { left: 4, right: 4 }, - ), - children: [], - }); - - const simulated = virtualInsertionPosition( - container, - dragged, - 0, - 0, - 2, - dragged.box.width, - dragged.box.height, - ); - - expect(simulated).toEqual({ x: 4, y: 40 }); -}); - -test("wraps fractional horizontal overflow at browser flex precision", () => { - const container = snapshotFixture({ - value: "container", - direction: "row", - mainAxisAlign: "start", - locked: false, - box: layoutBox({ x: 0, y: 0, width: 317.2, height: 120 }), - children: [ - { - value: "item-1", - direction: "column", - mainAxisAlign: "start", - locked: false, - box: layoutBox( - { x: 4, y: 0, width: 100, height: 40 }, - { left: 4, right: 4 }, - ), - children: [], - }, - { - value: "item-2", - direction: "column", - mainAxisAlign: "start", - locked: false, - box: layoutBox( - { x: 112, y: 0, width: 100, height: 40 }, - { left: 4, right: 4 }, - ), - children: [], - }, - ], - }); - const dragged = snapshotFixture({ - value: "dragged", - direction: "column", - mainAxisAlign: "start", - locked: false, - box: layoutBox( - { x: 0, y: 0, width: 93.5, height: 40 }, - { left: 4, right: 4 }, - ), - children: [], - }); - - const simulated = virtualInsertionPosition( - container, - dragged, - 0, - 0, - 2, - dragged.box.width, - dragged.box.height, - ); - - expect(simulated).toEqual({ x: 4, y: 40 }); -}); - -test("places append ghost on the short second row in a wrapped row layout", () => { - const container = snapshotFixture({ - value: "answer", - direction: "row", - mainAxisAlign: "start", - locked: false, - box: layoutBox( - { x: 0, y: 0, width: 1096, height: 244 }, - {}, - { top: 12, right: 12, bottom: 12, left: 12 }, - { top: 2, right: 2, bottom: 2, left: 2 }, - ), - children: [ - ["彼", 104, 92, 14, 14], - ["すぐ", 136, 92, 122, 14], - ["経歴", 136, 92, 262, 14], - ["に", 104, 92, 402, 14], - ["少年", 136, 92, 510, 14], - ["会社", 136, 92, 650, 14], - ["問い合わせ", 240, 92, 14, 110], - ["しまっ", 168, 92, 258, 110], - ].map(([value, width, height, x, y]) => ({ - value: value as string, - direction: "column" as const, - mainAxisAlign: "start" as const, - locked: false, - box: layoutBox({ - x: x as number, - y: y as number, - width: width as number, - height: height as number, - }), - children: [], - })), - }); - const dragged = snapshotFixture({ - value: "を", - direction: "column", - mainAxisAlign: "start", - locked: false, - box: layoutBox({ x: 0, y: 0, width: 104, height: 92 }), - children: [], - }); - const origin = contentRect(container.box); - const appendGhost = virtualInsertionPosition( - container, - dragged, - origin.x, - origin.y, - container.children.length, - dragged.box.width, - dragged.box.height, - ); - - expect(appendGhost).toBeTruthy(); - expect( - appendGhost!.y, - "append slot should remain on the second visual row", - ).toBeGreaterThan(container.children[0].box.y); - expect(appendGhost!.y).toBe(container.children[6].box.y); -}); - -test("scores a wrapped-row destination by its canonical insertion gap-line center", () => { - const items = [ - mockSnapSortItem("彼", { x: 14, y: 14, width: 53.6, height: 47.8 }), - mockSnapSortItem("の", { x: 71.6, y: 14, width: 53.6, height: 47.8 }), - mockSnapSortItem("経歴", { - x: 129.2, - y: 14, - width: 71.2, - height: 47.8, - }), - mockSnapSortItem("を", { - x: 204.4, - y: 14, - width: 53.6, - height: 47.8, - }), - mockSnapSortItem("会社", { - x: 262, - y: 14, - width: 71.2, - height: 47.8, - }), - mockSnapSortItem("に", { - x: 337.2, - y: 14, - width: 53.6, - height: 47.8, - }), - mockSnapSortItem("問い合わせ", { - x: 14, - y: 65.8, - width: 124, - height: 47.8, - }), - mockSnapSortItem("た", { - x: 142, - y: 65.8, - width: 53.6, - height: 47.8, - }), - ]; - const container = mockSnapSortContainer( - "answer", - { x: 0, y: 0, width: 488, height: 128 }, - items, - "row", - ); - const dragged = items[6]; - const source = { - container, - containerMetadata: container.metadata, - index: 6, - }; - const session = { - items: [dragged], - sources: [source], - activeSources: [source], - itemSet: new Set([dragged]), - snapshotItemSet: new Set([dragged]), - pointer: { x: 235.6, y: 89.7 }, - }; - - // @ts-expect-error The fixture implements the resolver surface without Item's private fields. - const target = determineInsertionDropTarget(dragged, container, session); - - expect(target?.container).toBe(container); - expect(target?.index).toBe(8); - expect(target?.insertion).toMatchObject({ - gap: { - orientation: "vertical", - x: 195.6, - y: 65.8, - length: 47.8, - }, - previous: { item: items[7] }, - next: null, - isCurrentPlacement: false, - }); -}); - -function horizontalDoubleRowLayoutCases(): LayoutCase[] { - const cases: LayoutCase[] = []; - for (let width = 236; width <= 356; width += 4) { - const seed = width * 17; - const count = 14 + (width % 5); - const itemWidths = Array.from({ length: count }, (_, index) => { - return 42 + ((seed + index * 13) % 42); - }); - const itemHeights = Array.from({ length: count }, (_, index) => { - return 30 + ((seed + index * 7) % 16); - }); - const itemBorders = Array.from({ length: count }, (_, index) => { - return (seed + index * 3) % 4; - }); - cases.push({ - name: `w${width}`, - width, - padding: { - top: (seed % 9) + 1, - right: ((seed >> 1) % 13) + 2, - bottom: ((seed >> 2) % 7) + 1, - left: ((seed >> 3) % 11) + 2, - }, - border: { - top: seed % 5, - right: (seed + 1) % 6, - bottom: (seed + 2) % 5, - left: (seed + 3) % 6, - }, - columnGap: 4 + (seed % 8), - rowGap: 3 + ((seed >> 2) % 9), - itemWidths, - itemHeights, - itemBorders, - }); - } - return cases; -} - -function layoutNodeFromBrowserCase( - browserCase: BrowserLayoutCase, -): ItemSnapshot { - return snapshotFixture({ - value: "container", - direction: "row", - locked: false, - box: browserCase.container, - children: browserCase.items.map((item) => ({ - value: item.id, - direction: "column", - locked: false, - box: item.box, - children: [], - })), - }); -} - -async function measureBrowserLayoutCases( - page: Page, - cases: LayoutCase[], -): Promise { - await page.setContent('
'); - return page.evaluate((layoutCases) => { - type BrowserBox = Box; - type BrowserCase = BrowserLayoutCase; - const fixture = document.querySelector("#layout-fixture") as HTMLElement; - const px = (value: number) => `${value}px`; - const sideCss = (value: { - top: number; - right: number; - bottom: number; - left: number; - }) => - `${px(value.top)} ${px(value.right)} ${px(value.bottom)} ${px(value.left)}`; - const boxOf = (element: HTMLElement): BrowserBox => { - const rect = element.getBoundingClientRect(); - const style = getComputedStyle(element); - const number = (value: string) => parseFloat(value) || 0; - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - screen: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - margin: { - top: number(style.marginTop), - right: number(style.marginRight), - bottom: number(style.marginBottom), - left: number(style.marginLeft), - }, - padding: { - top: number(style.paddingTop), - right: number(style.paddingRight), - bottom: number(style.paddingBottom), - left: number(style.paddingLeft), - }, - border: { - top: number(style.borderTopWidth), - right: number(style.borderRightWidth), - bottom: number(style.borderBottomWidth), - left: number(style.borderLeftWidth), - }, - }; - }; - const makeItem = ( - id: string, - width: number, - height: number, - border: number, - isGhost = false, - ) => { - const item = document.createElement("div"); - item.dataset.itemId = id; - item.textContent = id; - item.style.boxSizing = "border-box"; - item.style.flex = "0 0 auto"; - item.style.width = px(width); - item.style.height = px(height); - item.style.border = `${px(border)} solid ${isGhost ? "#b45309" : "#2563eb"}`; - item.style.padding = `${px((width + height) % 5)} ${px((width + border) % 7)}`; - item.style.background = isGhost ? "#fef3c7" : "#dbeafe"; - return item; - }; - const buildContainer = (entry: LayoutCase) => { - fixture.innerHTML = ""; - const container = document.createElement("section"); - container.style.boxSizing = "border-box"; - container.style.display = "flex"; - container.style.flexDirection = "row"; - container.style.flexWrap = "wrap"; - container.style.alignItems = "flex-start"; - container.style.alignContent = "flex-start"; - container.style.width = px(entry.width); - container.style.padding = sideCss(entry.padding); - container.style.borderStyle = "solid"; - container.style.borderColor = "#111827"; - container.style.borderWidth = sideCss(entry.border); - container.style.columnGap = px(entry.columnGap); - container.style.rowGap = px(entry.rowGap); - container.style.margin = "16px"; - fixture.appendChild(container); - return container; - }; - - return layoutCases.map((entry) => { - const draggedIndex = Math.min(3, entry.itemWidths.length - 1); - const draggedId = `item-${draggedIndex}`; - let container = buildContainer(entry); - const itemElements = entry.itemWidths.map((width, index) => { - const item = makeItem( - `item-${index}`, - width, - entry.itemHeights[index], - entry.itemBorders[index], - ); - container.appendChild(item); - return item; - }); - const containerBox = boxOf(container); - const items = itemElements.map((item) => ({ - id: item.dataset.itemId!, - box: boxOf(item), - })); - const dragged = items[draggedIndex]; - const remaining = items.filter((item) => item.id !== draggedId); - const actualGhosts: BrowserCase["actualGhosts"] = []; - - for (let index = 0; index <= remaining.length; index++) { - container = buildContainer(entry); - for (let i = 0; i <= remaining.length; i++) { - if (i === index) { - container.appendChild( - makeItem( - "ghost", - dragged.box.width, - dragged.box.height, - entry.itemBorders[draggedIndex], - true, - ), - ); - } - const remainingItem = remaining[i]; - if (remainingItem) { - const originalIndex = Number(remainingItem.id.replace("item-", "")); - container.appendChild( - makeItem( - remainingItem.id, - entry.itemWidths[originalIndex], - entry.itemHeights[originalIndex], - entry.itemBorders[originalIndex], - ), - ); - } - } - const ghost = container.querySelector( - '[data-item-id="ghost"]', - ) as HTMLElement; - const rect = ghost.getBoundingClientRect(); - actualGhosts.push({ index, x: rect.x, y: rect.y }); - } - - return { - name: entry.name, - container: containerBox, - items, - draggedId, - ghost: { width: dragged.box.width, height: dragged.box.height }, - actualGhosts, - }; - }); - }, cases); -} - -async function itemRect(item: Locator): Promise { - await item.scrollIntoViewIfNeeded(); - const box = await item.boundingBox(); - if (!box) throw new Error("Expected item to have a bounding box."); - return box; -} - -async function itemByText(page: Page, text: string, index = 0) { - const locator = page - .locator(".snapsort-item") - .filter({ hasText: text }) - .nth(index); - await expect(locator).toBeVisible(); - return locator; -} - -async function demoBoxByHeading(page: Page, heading: string) { - const box = page - .locator(".demo-cell") - .filter({ has: page.getByRole("heading", { name: heading }) }); - await expect(box).toBeVisible(); - return box; -} - -async function websiteCoreDemo(page: Page, demo: string) { - const box = page.locator(`[data-demo="${demo}"]`); - await expect(box).toBeVisible(); - return box; -} - -async function itemByTextIn(parent: Locator, text: string, index = 0) { - const locator = parent - .locator(".snapsort-item") - .filter({ hasText: text }) - .nth(index); - await expect(locator).toBeVisible(); - return locator; -} - -async function componentArrayList(page: Page) { - const list = page.locator(".array-list"); - await expect(list).toBeVisible(); - return list; -} - -async function collectSample( - page: Page, - step: number, - mouse: { x: number; y: number }, - options: { captureFrameRects?: boolean } = {}, -): Promise { - return page.evaluate( - ({ step, mouse, captureFrameRects }) => { - const win = window as unknown as { - __snapsortActiveText?: string; - __snapsortActiveIndex?: number; - __snapsortActiveId?: string; - }; - const rectOf = (element: Element | null) => { - if (!element) return null; - const rect = element.getBoundingClientRect(); - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }; - }; - const describedRectOf = (element: Element | null) => { - const rect = rectOf(element); - if (!rect) return null; - return { - ...rect, - text: element?.textContent?.trim().replace(/\s+/g, " ") ?? "", - }; - }; - const activeId = win.__snapsortActiveId ?? ""; - const draggedElement = document.querySelector( - `[data-engine-id="${activeId}"]`, - ); - const spacerElement = document.querySelector("#spacer"); - const spacerParent = spacerElement?.parentElement ?? null; - const spacerSiblings = spacerParent - ? [...spacerParent.children].filter( - (child) => - child !== draggedElement && - (child.id === "spacer" || - child.classList.contains("snapsort-item") || - child.classList.contains("snapsort-container")), - ) - : []; - const spacerSiblingIndex = spacerElement - ? spacerSiblings.indexOf(spacerElement) - : -1; - const directSiblingTexts = spacerParent - ? [...spacerParent.children] - .filter( - (child) => child.id !== "spacer" && child !== draggedElement, - ) - .map( - (child) => child.textContent?.trim().replace(/\s+/g, " ") ?? "", - ) - : []; - const parentText = directSiblingTexts.join(" | "); - const spacerParentKind = - directSiblingTexts.length === 0 - ? null - : directSiblingTexts.some((text) => /^Item [4-6]$/.test(text)) && - directSiblingTexts.every( - (text) => text === "" || /^Item [4-6]$/.test(text), - ) - ? "website-nested-inner" - : directSiblingTexts.some((text) => /^Item [1-3]$/.test(text)) || - directSiblingTexts.some((text) => - /Item 4 Item 5 Item 6/.test(text), - ) - ? "website-nested-outer" - : directSiblingTexts.every((text) => /^Sub A\d/.test(text)) - ? "nested-inner" - : directSiblingTexts.some((text) => - /Item 1\.5|Item 2|Item 3/.test(text), - ) - ? "nested-outer" - : directSiblingTexts.some((text) => - /Header|Card Grid|Footer/.test(text), - ) - ? "layers-root" - : directSiblingTexts.some((text) => - /Hero Section/.test(text), - ) - ? "layers-hero" - : directSiblingTexts.some((text) => - /Loose Item/.test(text), - ) - ? "drag-root" - : directSiblingTexts.some((text) => - /Group 1 -/.test(text), - ) - ? "drag-group-1" - : directSiblingTexts.some((text) => - /Group 2 -/.test(text), - ) - ? "drag-group-2" - : "other"; - const draggedRect = rectOf(draggedElement); - const dragged = draggedRect - ? { - ...draggedRect, - centerX: draggedRect.x + draggedRect.width / 2, - centerY: draggedRect.y + draggedRect.height / 2, - } - : null; - const draggedSourceColumn = draggedElement?.closest(".basic-column"); - const frameRects = captureFrameRects - ? [ - ...document.querySelectorAll( - ".snapsort-item, .snapsort-container, #spacer", - ), - ].map((element) => { - const htmlElement = element as HTMLElement; - const role = - element.id === "spacer" - ? "ghost" - : element.classList.contains("snapsort-container") - ? "container" - : "item"; - return { - role, - text: element.textContent?.trim().replace(/\s+/g, " ") ?? "", - id: element.getAttribute("data-engine-id"), - transform: htmlElement.style.transform, - rect: rectOf(element)!, - }; - }) - : undefined; - return { - step, - mouse, - spacerCount: document.querySelectorAll("#spacer").length, - spacer: rectOf(spacerElement), - spacerParentId: spacerParent?.getAttribute("data-engine-id") ?? null, - spacerParentKind, - spacerParentText: parentText || null, - spacerIndex: spacerSiblingIndex === -1 ? null : spacerSiblingIndex, - spacerPrevious: - spacerSiblingIndex > 0 - ? describedRectOf(spacerSiblings[spacerSiblingIndex - 1]) - : null, - spacerNext: - spacerSiblingIndex >= 0 && - spacerSiblingIndex < spacerSiblings.length - 1 - ? describedRectOf(spacerSiblings[spacerSiblingIndex + 1]) - : null, - spacerDomPrevious: describedRectOf( - spacerElement?.previousElementSibling ?? null, - ), - spacerDomNext: describedRectOf( - spacerElement?.nextElementSibling ?? null, - ), - dragged, - draggedCenterDelta: dragged - ? Math.hypot(dragged.centerX - mouse.x, dragged.centerY - mouse.y) - : null, - draggedSourceColumnZIndex: draggedSourceColumn - ? getComputedStyle(draggedSourceColumn).zIndex - : null, - draggedAttribute: - draggedElement instanceof HTMLElement - ? draggedElement.dataset.snapsortDragging ?? null - : null, - frameRects, - }; - }, - { step, mouse, captureFrameRects: options.captureFrameRects ?? false }, - ); -} - -async function dragBy( - page: Page, - source: Locator, - text: string, - index: number, - delta: { x: number; y: number }, - options: { - steps?: number; - assertCenter?: boolean; - start?: { x: number; y: number }; - captureFrameRects?: boolean; - } = {}, -): Promise { - const sourceRect = options.start - ? await source.boundingBox() - : await itemRect(source); - if (!sourceRect) { - throw new Error("Expected source item to have a bounding box."); - } - const activeId = await source.getAttribute("data-engine-id"); - const start = options.start ?? center(sourceRect); - const steps = options.steps ?? 160; - await page.evaluate( - ({ text, index, activeId }) => { - const win = window as unknown as { - __snapsortActiveText?: string; - __snapsortActiveIndex?: number; - __snapsortActiveId?: string; - }; - win.__snapsortActiveText = text; - win.__snapsortActiveIndex = index; - win.__snapsortActiveId = activeId ?? ""; - }, - { text, index, activeId }, - ); - - const samples: DragSample[] = []; - let mouseIsDown = false; - try { - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - mouseIsDown = true; - - const dragDistance = Math.hypot(delta.x, delta.y); - const activationRatio = - dragDistance === 0 ? 0 : Math.min(4 / dragDistance, 1); - if (activationRatio > 0) { - await page.mouse.move( - start.x + delta.x * activationRatio, - start.y + delta.y * activationRatio, - ); - await page.waitForTimeout(16); - } - - for (let step = 1; step <= steps; step++) { - const ratio = activationRatio + ((1 - activationRatio) * step) / steps; - const mouse = { - x: start.x + delta.x * ratio, - y: start.y + delta.y * ratio, - }; - await page.mouse.move(mouse.x, mouse.y); - await page.waitForTimeout(8); - samples.push( - await collectSample(page, step, mouse, { - captureFrameRects: options.captureFrameRects, - }), - ); - } - } finally { - if (mouseIsDown) { - await page.mouse.up().catch(() => {}); - } - } - - await page.waitForTimeout(100); - return samples; -} - -async function dragTo( - page: Page, - source: Locator, - text: string, - index: number, - target: Locator, - options: Parameters[5] = {}, -): Promise { - const sourceCenter = center(await itemRect(source)); - const targetCenter = center(await itemRect(target)); - return dragBy( - page, - source, - text, - index, - { - x: targetCenter.x - sourceCenter.x, - y: targetCenter.y - sourceCenter.y, - }, - options, - ); -} - -async function dragToItemFraction( - page: Page, - source: Locator, - text: string, - index: number, - target: Locator, - yRatio: number, - options: Parameters[5] = {}, -): Promise { - const sourceCenter = center(await itemRect(source)); - const targetRect = await itemRect(target); - return dragBy( - page, - source, - text, - index, - { - x: targetRect.x + targetRect.width / 2 - sourceCenter.x, - y: targetRect.y + targetRect.height * yRatio - sourceCenter.y, - }, - options, - ); -} - -async function directSnapSortItemTexts(locator: Locator): Promise { - return locator.evaluate((element) => - [...element.children] - .filter((child) => child.classList.contains("snapsort-item")) - .map((child) => child.textContent?.trim().replace(/\s+/g, " ") ?? ""), - ); -} - -// A nested container's own textContent concatenates its children's text with -// no separator by default; hand-authored templates picked up an incidental -// space from template whitespace between sibling tags, which items-mode's -// internal {#each} doesn't reproduce. Expected strings below reflect the -// no-space (items-mode) DOM shape -- this is a DOM formatting detail, not a -// behavior difference (content and order are unaffected). -async function directSnapSortChildTexts(locator: Locator): Promise { - return locator.evaluate((element) => - [...element.children] - .filter( - (child) => - child.classList.contains("snapsort-item") || - child.classList.contains("snapsort-container"), - ) - .map((child) => child.textContent?.trim().replace(/\s+/g, " ") ?? ""), - ); -} - -async function nestedSnapSortLifecycleState( - page: Page, -): Promise { - return page.evaluate(() => { - const normalizeText = (element: Element | null) => - element?.textContent?.trim().replace(/\s+/g, " ") ?? ""; - const nestedCell = [...document.querySelectorAll(".demo-cell")].find( - (cell) => - cell.querySelector("h2")?.textContent?.trim() === "Nested Container", - ); - const outerContainer = nestedCell?.querySelector(".snapsort-container"); - const draggingElements = [ - ...document.querySelectorAll( - '[data-snapsort-dragging="true"]', - ), - ]; - - return { - spacerCount: document.querySelectorAll("#spacer").length, - draggingTexts: draggingElements.map(normalizeText), - draggingStyles: draggingElements.map((element) => ({ - text: normalizeText(element), - position: element.style.position, - zIndex: element.style.zIndex, - transform: element.style.transform, - })), - nestedOuterChildren: [...(outerContainer?.children ?? [])].map( - (child) => ({ - id: child.id, - classes: [...child.classList], - text: normalizeText(child), - }), - ), - }; - }); -} - -async function releaseStartedDragNearOrigin( - page: Page, - nested: Locator, - itemText: string, - targetText: string, - targetYRatio: number, -) { - const item = await itemByTextIn(nested, itemText); - const target = await itemByTextIn(nested, targetText); - const start = center(await itemRect(item)); - const targetRect = await itemRect(target); - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move( - targetRect.x + targetRect.width / 2, - targetRect.y + targetRect.height * targetYRatio, - { steps: 30 }, - ); - await page.waitForTimeout(80); - await page.mouse.move(start.x + 1, start.y + 1, { steps: 20 }); - await page.waitForTimeout(20); - await page.mouse.up(); - await page.waitForTimeout(120); -} - -async function dragLockedNestedContainerBackground( - page: Page, - nested: Locator, -) { - const childContainer = nested.locator(".snapsort-container").nth(1); - const rect = await itemRect(childContainer); - const start = { - x: rect.x + 4, - y: rect.y + 4, - }; - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x, start.y + 80, { steps: 20 }); - await page.waitForTimeout(50); - await page.mouse.up(); - await page.waitForTimeout(160); -} - -async function nestedContainerSelfInsertProbe( - page: Page, -): Promise { - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; - return page.evaluate( - async ({ coreImportPath }) => { - const { GlobalManager } = await import(coreImportPath); - const containers = - GlobalManager.getInstance().data.dragAndDropContainers ?? []; - const nestedCell = [...document.querySelectorAll(".demo-cell")].find( - (cell) => - cell.querySelector("h2")?.textContent?.trim() === "Nested Container", - ); - const outerElement = nestedCell?.querySelector(".snapsort-container"); - const childElement = nestedCell?.querySelectorAll( - ".snapsort-container", - )[1]; - const outer = containers.find( - (container: any) => container.element === outerElement, - ); - const child = containers.find( - (container: any) => container.element === childElement, - ); - const normalizeText = (element: Element | null) => - element?.textContent?.trim().replace(/\s+/g, " ") ?? ""; - const itemText = (item: any) => normalizeText(item.element); - - if (!outer || !child) { - return { - found: false, - childIndex: null, - duplicateCount: null, - insertEvents: [], - beforeOrder: [], - afterOrder: [], - domChildren: [], - }; - } - - const beforeOrder = outer.itemOrderedList.map(itemText); - const childIndex = outer.itemOrderedList.indexOf(child); - const insertEvents: SelfInsertProbeState["insertEvents"] = []; - const originalInsert = outer.callbacks.onItemInsert; - outer.callbacks = { - ...outer.callbacks, - onItemInsert: (event: any) => { - insertEvents.push({ - index: event.index, - selfBefore: event.beforeElement === event.item.element, - beforeText: normalizeText(event.beforeElement), - }); - originalInsert?.(event); - }, - }; - - outer.insertItemAt(outer, child, childIndex); - outer.callbacks = { ...outer.callbacks, onItemInsert: originalInsert }; - - return { - found: true, - childIndex, - duplicateCount: outer.itemOrderedList.filter( - (item: any) => item === child, - ).length, - insertEvents, - beforeOrder, - afterOrder: outer.itemOrderedList.map(itemText), - domChildren: [...outer.element.children].map((element) => - normalizeText(element), - ), - }; - }, - { coreImportPath }, - ); -} - -async function directLogoSliceOrder(locator: Locator): Promise { - return locator.evaluate((element) => - [...element.children] - .filter((child) => child.classList.contains("snapsort-item")) - .map((child) => - Number(child.querySelector(".logo-slice")?.dataset.slice), - ), - ); -} - -async function writeJson(path: string, value: unknown) { - await mkdir(dirname(path), { recursive: true }); - await writeFile(path, JSON.stringify(value, null, 2)); -} - -async function expectStableDrag( - page: Page, - samples: DragSample[], - consoleMessages: string[], - outputPath: string, - options: { assertCenter?: boolean } = {}, -) { - const trace = await page.evaluate(() => { - const win = window as unknown as { - __snapsortTrace?: { dom: DomTraceEntry[]; mutations: unknown[] }; - }; - return win.__snapsortTrace; - }); - await writeJson(outputPath, { - samples, - trace, - layoutLogs: consoleMessages.filter((message) => - /\[updateDropTarget\]|\[updateGhostElement\]|\[insertItemAt\]|determineDropTarget|chosen|candidate/.test( - message, - ), - ), - errors: consoleMessages.filter((message) => - /error|Missing drag snapshot|Unhandled|TypeError/i.test(message), - ), - }); - - expect(samples, "drag should produce frame samples").not.toHaveLength(0); - expect( - samples.filter((sample) => sample.spacerCount !== 1), - "the spacer should not disappear or duplicate while dragging", - ).toHaveLength(0); - if (options.assertCenter !== false) { - expect( - Math.max(...samples.map((sample) => sample.draggedCenterDelta ?? 999)), - "dragged item center should remain close to the pointer", - ).toBeLessThan(12); - } - expect( - consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test(message), - ), - ).toHaveLength(0); -} - -function expectNoSpacerBacktrack(samples: DragSample[], axis: "x" | "y") { - const positions = samples - .filter((sample) => sample.spacer) - .map((sample) => ({ - step: sample.step, - value: sample.spacer![axis], - })); - - for (let i = 1; i < positions.length; i++) { - expect( - positions[i].value + 8, - `spacer should not jump backward between steps ${positions[i - 1].step} and ${positions[i].step}`, - ).toBeGreaterThanOrEqual(positions[i - 1].value); - } -} - -function expectNoParentReentry( - samples: DragSample[], - innerKind: string, - outerKind: string, - label: string, -) { - const kinds = samples - .map((sample) => sample.spacerParentKind) - .filter((kind): kind is string => kind === innerKind || kind === outerKind); - const firstInner = kinds.indexOf(innerKind); - expect( - firstInner, - `drag should enter the ${label} nested sub-container`, - ).toBeGreaterThanOrEqual(0); - - for (let i = firstInner + 1; i < kinds.length - 1; i++) { - expect( - !(kinds[i] === outerKind && kinds[i + 1] === innerKind), - `spacer should not briefly leave and re-enter the ${label} nested container`, - ).toBe(true); - } -} - -function expectNoNestedParentFlicker(samples: DragSample[]) { - expectNoParentReentry(samples, "nested-inner", "nested-outer", "default"); -} - -function expectNoSpacerOscillation(samples: DragSample[]) { - const keys = samples - .filter((sample) => sample.spacer) - .map( - (sample) => - `${Math.round(sample.spacer!.x)}:${Math.round(sample.spacer!.y)}:${sample.spacerIndex}`, - ); - - for (let i = 2; i < keys.length; i++) { - expect( - !(keys[i] === keys[i - 2] && keys[i] !== keys[i - 1]), - `spacer should not alternate between ${keys[i - 1]} and ${keys[i]} around sample ${i}`, - ).toBe(true); - } -} - -function ghostInsertionTargets(consoleMessages: string[]) { - return consoleMessages.flatMap((message) => { - const match = message.match( - /\[updateGhostElement\] inserting ghost at container=([^\s]+) index=(\d+)/, - ); - return match ? [`${match[1]}[${match[2]}]`] : []; - }); -} - -function expectGhostUpdatesStable( - consoleMessages: string[], - expectedMaxUpdates: number, -) { - const targets = ghostInsertionTargets(consoleMessages); - expect( - targets.length, - `ghost should update only at stable slot transitions; saw ${targets.join(" -> ")}`, - ).toBeLessThanOrEqual(expectedMaxUpdates); - - for (let i = 2; i < targets.length; i++) { - expect( - !(targets[i] === targets[i - 2] && targets[i] !== targets[i - 1]), - `ghost target should not oscillate: ${targets.join(" -> ")}`, - ).toBe(true); - } -} - -function compressedSpacerStates( - samples: DragSample[], - kinds: string[] = ["nested-inner", "nested-outer"], -) { - const states = samples - .filter((sample) => - sample.spacerParentKind ? kinds.includes(sample.spacerParentKind) : false, - ) - .map((sample) => `${sample.spacerParentKind}[${sample.spacerIndex}]`); - - return states.filter( - (state, index) => index === 0 || state !== states[index - 1], - ); -} - -function expectSpacerAlignedAfterPrevious( - samples: DragSample[], - parentKind: string, - previousPattern: RegExp, -) { - const sample = samples.find( - (entry) => - entry.spacer && - entry.spacerParentKind === parentKind && - previousPattern.test(entry.spacerPrevious?.text ?? ""), - ); - expect( - sample, - `expected spacer in ${parentKind} after ${previousPattern}`, - ).toBeTruthy(); - - const previous = sample!.spacerPrevious!; - const delta = Math.abs(sample!.spacer!.y - (previous.y + previous.height)); - expect( - delta, - `spacer should align just below previous sibling; previous=${previous.text} delta=${delta}`, - ).toBeLessThan(24); -} - -function expectSpacerNearDragged( - samples: DragSample[], - parentKind: string, - maxDistance: number, -) { - const candidates = samples.filter( - (sample) => - sample.spacer && sample.dragged && sample.spacerParentKind === parentKind, - ); - expect( - candidates, - `expected spacer samples in ${parentKind}`, - ).not.toHaveLength(0); - - const worst = candidates.reduce( - (current, sample) => { - const spacerCenterY = sample.spacer!.y + sample.spacer!.height / 2; - const delta = Math.abs(spacerCenterY - sample.dragged!.centerY); - return delta > current.delta ? { sample, delta } : current; - }, - { sample: candidates[0], delta: -Infinity }, - ); - - expect( - worst.delta, - `spacer center should track dragged item center in ${parentKind}; worst step=${worst.sample.step}`, - ).toBeLessThan(maxDistance); -} - -test.describe("Snapsort drag-start snapshot layout", () => { - test.beforeEach(async ({ page }) => { - await installSnapsortTrace(page); - }); - - test("matches browser flex ghost positions for horizontal double-row fuzz cases", async ({ - page, - }, testInfo) => { - const cases = horizontalDoubleRowLayoutCases(); - const measuredCases = await measureBrowserLayoutCases(page, cases); - const failures: Array<{ - name: string; - index: number; - expected: { x: number; y: number }; - actual: { x: number; y: number }; - delta: { x: number; y: number }; - }> = []; - - for (const measuredCase of measuredCases) { - const root = layoutNodeFromBrowserCase(measuredCase); - const dragged = root.children.find( - (item) => item.value === measuredCase.draggedId, - ); - expect( - dragged, - `dragged item should exist for ${measuredCase.name}`, - ).toBeTruthy(); - - const origin = contentRect(measuredCase.container); - for (const actual of measuredCase.actualGhosts) { - const simulated = virtualInsertionPosition( - root, - dragged!, - origin.x, - origin.y, - actual.index, - measuredCase.ghost.width, - measuredCase.ghost.height, - ); - expect( - simulated, - `simulated ghost should exist for ${measuredCase.name}[${actual.index}]`, - ).toBeTruthy(); - - const delta = { - x: Math.abs(simulated!.x - actual.x), - y: Math.abs(simulated!.y - actual.y), - }; - if (delta.x > 1.25 || delta.y > 1.25) { - failures.push({ - name: measuredCase.name, - index: actual.index, - expected: { x: actual.x, y: actual.y }, - actual: simulated!, - delta, - }); - } - } - } - - await writeJson( - testInfo.outputPath("horizontal-double-row-layout-fuzz.json"), - { - caseCount: measuredCases.length, - slotCount: measuredCases.reduce( - (count, measuredCase) => count + measuredCase.actualGhosts.length, - 0, - ), - failures, - }, - ); - - expect( - failures.slice(0, 8), - "layout engine ghost positions should match browser flex positions within 1.25px", - ).toHaveLength(0); - }); - - test("keeps a zero-slack hero grid at 4 columns across sub-pixel container widths", async ({ - page, - }, testInfo) => { - // The landing-page hero pad grid is the worst case for wrap prediction: - // 4 columns of calc((100% - 12px) / 4) with a 4px gap sum *exactly* to - // the container width, leaving zero slack for measurement error. Each - // browser quantizes layout differently (Blink/WebKit on a 1/64px grid; - // Gecko in 1/60px app units whose getBoundingClientRect doubles carry - // ~1e-5px conversion noise), which historically over-wrapped the 4th - // column onto the 2nd row at fractional container widths. Sweep integer - // width bases crossed with increasingly granular sub-pixel offsets and - // assert the simulation keeps 4 items per row with a same-size ghost at - // every insertion index. - const bases = [356, 380, 397, 414, 430, 434, 443]; - const offsets = [ - 0, - 0.5, - 0.25, - 0.75, - 0.33, - 0.67, - 1 / 3, - 2 / 3, - 0.1, - 0.2, - 0.4, - 0.6, - 0.8, - 0.9, - 0.125, - 0.375, - 0.625, - 0.875, - 0.0625, - 0.03125, - 0.015625, - 0.0078125, - ]; - const widths = bases.flatMap((base) => - offsets.map((offset) => base + offset), - ); - - await page.setContent('
'); - const measuredGrids = await page.evaluate((caseWidths) => { - const fixture = document.querySelector( - "#hero-grid-fixture", - ) as HTMLElement; - const boxOf = (element: HTMLElement) => { - const rect = element.getBoundingClientRect(); - const style = getComputedStyle(element); - const number = (value: string) => parseFloat(value) || 0; - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - screen: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - margin: { - top: number(style.marginTop), - right: number(style.marginRight), - bottom: number(style.marginBottom), - left: number(style.marginLeft), - }, - padding: { - top: number(style.paddingTop), - right: number(style.paddingRight), - bottom: number(style.paddingBottom), - left: number(style.paddingLeft), - }, - border: { - top: number(style.borderTopWidth), - right: number(style.borderRightWidth), - bottom: number(style.borderBottomWidth), - left: number(style.borderLeftWidth), - }, - }; - }; - return caseWidths.map((width) => { - fixture.innerHTML = ""; - const container = document.createElement("section"); - container.style.cssText = - "box-sizing:border-box;display:flex;flex-direction:row;flex-wrap:wrap;" + - `align-items:flex-start;align-content:flex-start;gap:4px;width:${width}px;`; - fixture.appendChild(container); - for (let index = 0; index < 16; index++) { - const item = document.createElement("div"); - item.style.cssText = - "box-sizing:border-box;width:calc((100% - 12px) / 4);height:40px;" + - "background:#dbeafe;"; - container.appendChild(item); - } - return { - width, - container: boxOf(container), - items: [...container.children].map((element) => - boxOf(element as HTMLElement), - ), - }; - }); - }, widths); - - const failures: Array<{ - width: number; - index: number | null; - rows: number[]; - }> = []; - for (const grid of measuredGrids) { - const root = makeContainerSnapshot( - grid.container as Box, - grid.items.map((box, index) => - makeItemSnapshot(`item-${index}`, box as Box), - ), - ); - const rowStep = root.children[4].box.y - root.children[0].box.y; - // Browser ground truth first: the real flex layout must show 4 rows - // of 4 before the simulation is held to the same shape. - const browserRows = rowCounts( - root.children.map((child) => child.box.y), - rowStep, - ); - if (browserRows.join() !== "4,4,4,4") { - failures.push({ width: grid.width, index: null, rows: browserRows }); - continue; - } - - const dragged = root.children[0]; - for (let index = 0; index <= 15; index++) { - const rows = simulatedRowCounts(root, { - rowStep, - insertion: { - container: root, - index, - entry: { - width: dragged.box.width, - height: dragged.box.height, - margin: dragged.box.margin, - }, - }, - exclude: (node) => node === dragged, - }); - if (rows.join() !== "4,4,4,4") { - failures.push({ width: grid.width, index, rows }); - } - } - } - - await writeJson(testInfo.outputPath("hero-grid-subpixel-matrix.json"), { - widthCount: measuredGrids.length, - insertionChecks: measuredGrids.length * 16, - failures: failures.slice(0, 40), - }); - expect( - failures.slice(0, 8), - "the 4th column must stay in the 4th column (not wrap to the 2nd row) at every sub-pixel width", - ).toHaveLength(0); - }); - - test("matches browser grid placements across template variants (slot layout model)", async ({ - page, - }, testInfo) => { - // Ground truth for the slot layout model: for each grid template - // variant, remove the dragged item from a real `display:grid` DOM, - // insert a real spacer (with the dragged item's explicit size, as - // flow-ghost does) at several indices, and require the slot simulation - // to match the browser's placement of every entry within 1.25px. The - // unequal-track, auto-flow-column, and auto-rows variants are exactly - // the shapes the flow model cannot represent. - const scenarios = [ - { - name: "fixed equal tracks", - container: - "display:grid;grid-template-columns:repeat(4, 88px);gap:4px;width:380px;", - itemHeight: () => 40, - }, - { - name: "fractional tracks", - container: - "display:grid;grid-template-columns:repeat(4, 1fr);gap:4px;width:380.33px;", - itemHeight: () => 40, - }, - { - name: "unequal tracks", - container: - "display:grid;grid-template-columns:60px 140px 80px 88.33px;gap:4px;width:380.33px;", - itemHeight: () => 40, - }, - { - name: "auto-fill minmax", - container: - "display:grid;grid-template-columns:repeat(auto-fill, minmax(80px, 1fr));gap:4px;width:380.33px;", - itemHeight: () => 40, - }, - { - name: "auto-flow column", - container: - "display:grid;grid-auto-flow:column;grid-template-rows:repeat(4, 44px);gap:4px;width:max-content;", - itemHeight: () => 40, - }, - { - name: "auto rows with mixed item heights", - container: - "display:grid;grid-template-columns:repeat(4, 88px);grid-auto-rows:auto;gap:4px;width:380px;align-items:start;", - // item 0 (the dragged one) is tall: removing it shrinks its row in - // the real layout, which only the content-sized row variant tracks. - itemHeight: (index: number) => (index % 5 === 0 ? 80 : 40), - }, - ]; - const spacerIndices = [0, 3, 7, 14]; - const draggedIndex = 0; - - await page.setContent('
'); - const measured = await page.evaluate( - ({ cases, spacerIndices, draggedIndex }) => { - const fixture = document.querySelector( - "#grid-slot-fixture", - ) as HTMLElement; - const boxOf = (element: HTMLElement) => { - const rect = element.getBoundingClientRect(); - const style = getComputedStyle(element); - const number = (value: string) => parseFloat(value) || 0; - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - screen: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - margin: { - top: number(style.marginTop), - right: number(style.marginRight), - bottom: number(style.marginBottom), - left: number(style.marginLeft), - }, - padding: { - top: number(style.paddingTop), - right: number(style.paddingRight), - bottom: number(style.paddingBottom), - left: number(style.paddingLeft), - }, - border: { - top: number(style.borderTopWidth), - right: number(style.borderRightWidth), - bottom: number(style.borderBottomWidth), - left: number(style.borderLeftWidth), - }, - }; - }; - const build = ( - entry: { container: string; itemHeights: number[] }, - spacer: { index: number; width: number; height: number } | null, - ) => { - fixture.innerHTML = ""; - const container = document.createElement("section"); - container.style.cssText = "box-sizing:border-box;" + entry.container; - fixture.appendChild(container); - const nodes: HTMLElement[] = []; - for (let i = 0; i < 16; i++) { - if (spacer && i === draggedIndex) continue; // dragged item lifted - const item = document.createElement("div"); - item.style.cssText = `box-sizing:border-box;background:#dbeafe;height:${entry.itemHeights[i]}px;`; - item.dataset.i = String(i); - nodes.push(item); - } - if (spacer) { - const spacerEl = document.createElement("div"); - spacerEl.id = "spacer"; - spacerEl.style.cssText = `box-sizing:border-box;background:#fecaca;width:${spacer.width}px;height:${spacer.height}px;`; - nodes.splice(Math.min(spacer.index, nodes.length), 0, spacerEl); - } - for (const node of nodes) container.appendChild(node); - return container; - }; - - return cases.map((entry) => { - const pristine = build(entry, null); - const containerBox = boxOf(pristine); - const itemBoxes = [...pristine.children].map((element) => - boxOf(element as HTMLElement), - ); - const dragged = itemBoxes[draggedIndex]; - const truths = spacerIndices.map((index) => { - const container = build(entry, { - index, - width: dragged.width, - height: dragged.height, - }); - let ghost: { x: number; y: number } | null = null; - const items: Array<{ id: string; x: number; y: number }> = []; - for (const element of container.children) { - const rect = element.getBoundingClientRect(); - if (element.id === "spacer") { - ghost = { x: rect.x, y: rect.y }; - } else { - items.push({ - id: (element as HTMLElement).dataset.i!, - x: rect.x, - y: rect.y, - }); - } - } - return { spacerIndex: index, ghost, items }; - }); - return { - name: entry.name, - container: containerBox, - itemBoxes, - truths, - }; - }); - }, - { - cases: scenarios.map((scenario) => ({ - name: scenario.name, - container: scenario.container, - itemHeights: Array.from({ length: 16 }, (_, i) => - scenario.itemHeight(i), - ), - })), - spacerIndices, - draggedIndex, - }, - ); - - const failures: Array<{ - name: string; - spacerIndex: number; - entry: string; - delta: number; - }> = []; - for (const grid of measured) { - const root = makeContainerSnapshot( - grid.container as Box, - grid.itemBoxes.map((box, index) => - makeItemSnapshot(`${index}`, box as Box), - ), - "row", - "start", - "slots", - ); - const dragged = root.children[draggedIndex]; - for (const truth of grid.truths) { - const insertion = { - container: root, - index: truth.spacerIndex, - entry: { - width: dragged.box.width, - height: dragged.box.height, - margin: dragged.box.margin, - }, - }; - const origin = contentRect(root.box); - const result = flowLayoutPositions(root, origin.x, origin.y, { - exclude: (node) => node === dragged, - insertions: [insertion], - }); - const actualById = new Map(truth.items.map((item) => [item.id, item])); - for (const [snapshotItem, position] of result.itemPositions) { - const actual = actualById.get(snapshotItem.value); - if (!actual) continue; - const delta = Math.max( - Math.abs(position.x - actual.x), - Math.abs(position.y - actual.y), - ); - if (delta > 1.25) { - failures.push({ - name: grid.name, - spacerIndex: truth.spacerIndex, - entry: `item-${snapshotItem.value}`, - delta: +delta.toFixed(2), - }); - } - } - const ghost = result.virtualRects.get(insertion); - expect( - ghost, - `ghost position for ${grid.name}[${truth.spacerIndex}]`, - ).toBeTruthy(); - const ghostDelta = truth.ghost - ? Math.max( - Math.abs(ghost!.x - truth.ghost.x), - Math.abs(ghost!.y - truth.ghost.y), - ) - : Infinity; - if (ghostDelta > 1.25) { - failures.push({ - name: grid.name, - spacerIndex: truth.spacerIndex, - entry: "ghost", - delta: +ghostDelta.toFixed(2), - }); - } - } - } - - await writeJson(testInfo.outputPath("grid-slot-model-ground-truth.json"), { - scenarioCount: measured.length, - failures: failures.slice(0, 40), - }); - expect( - failures.slice(0, 8), - "slot layout simulation should match browser grid placement within 1.25px", - ).toHaveLength(0); - }); - - test("layout simulation invariants hold across randomized containers (property fuzz)", async ({ - page, - }, testInfo) => { - // Property-based ground truth: instead of hand-picked scenarios, build - // seeded-random containers and assert invariants that must hold for ANY - // layout the engine claims to support: - // - // - identity: simulating with no exclusions/insertions reproduces the - // browser's measured positions; - // - away-and-back: excluding item k and inserting a same-size ghost at - // index k is a no-op — every other item stays put and the ghost lands - // on item k's measured rect; - // - locality: a ghost at index k never moves an entry before index k - // (compared against the identity simulation, so the bound is exact). - // - // The generator stays inside the engine's stated envelope (uniform gaps, - // no per-item margins, LTR, no spans); failures record their seed for - // deterministic repro. - const TOLERANCE = 1.25; - const caseCount = 36; - - await page.setContent('
'); - const measured = await page.evaluate((caseCount) => { - const fixture = document.querySelector( - "#property-fixture", - ) as HTMLElement; - let seed = 20260708; - const rand = () => { - seed = (seed * 1664525 + 1013904223) % 4294967296; - return seed / 4294967296; - }; - const between = (lo: number, hi: number) => lo + rand() * (hi - lo); - const int = (lo: number, hi: number) => Math.floor(between(lo, hi + 1)); - const boxOf = (element: HTMLElement) => { - const rect = element.getBoundingClientRect(); - const style = getComputedStyle(element); - const number = (value: string) => parseFloat(value) || 0; - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - screen: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - margin: { - top: number(style.marginTop), - right: number(style.marginRight), - bottom: number(style.marginBottom), - left: number(style.marginLeft), - }, - padding: { - top: number(style.paddingTop), - right: number(style.paddingRight), - bottom: number(style.paddingBottom), - left: number(style.paddingLeft), - }, - border: { - top: number(style.borderTopWidth), - right: number(style.borderRightWidth), - bottom: number(style.borderBottomWidth), - left: number(style.borderLeftWidth), - }, - }; - }; - - const cases = []; - for (let index = 0; index < caseCount; index++) { - const caseSeed = seed; - const kind = rand() < 0.6 ? "flow" : "slots"; - const width = between(240, 520); - const gap = int(2, 12); - const pad = int(0, 12); - const border = int(0, 3); - const count = int(8, 16); - - fixture.innerHTML = ""; - const container = document.createElement("section"); - let containerCss = - `box-sizing:border-box;width:${width}px;padding:${pad}px;` + - `border:${border}px solid #111;`; - if (kind === "flow") { - containerCss += - "display:flex;flex-direction:row;flex-wrap:wrap;" + - `align-items:flex-start;align-content:flex-start;gap:${gap}px;`; - } else { - const templates = [ - `repeat(${int(3, 5)}, 1fr)`, - `repeat(auto-fill, minmax(${int(60, 90)}px, 1fr))`, - Array.from({ length: int(3, 4) }, () => `${int(50, 120)}px`).join( - " ", - ), - ]; - containerCss += - `display:grid;grid-template-columns:${templates[int(0, 2)]};` + - `gap:${gap}px;`; - } - container.style.cssText = containerCss; - fixture.appendChild(container); - for (let i = 0; i < count; i++) { - const item = document.createElement("div"); - let itemCss = `box-sizing:border-box;height:${int(24, 64)}px;background:#dbeafe;`; - if (kind === "flow") itemCss += `width:${between(30, 110)}px;`; - item.style.cssText = itemCss; - container.appendChild(item); - } - cases.push({ - caseSeed, - kind, - container: boxOf(container), - items: [...container.children].map((element) => - boxOf(element as HTMLElement), - ), - }); - } - return cases; - }, caseCount); - - const failures: Array<{ - caseSeed: number; - kind: string; - property: string; - detail: string; - delta: number; - }> = []; - const distance = ( - a: { x: number; y: number }, - b: { x: number; y: number }, - ) => Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y)); - - for (const propertyCase of measured) { - const root = makeContainerSnapshot( - propertyCase.container as Box, - propertyCase.items.map((box, index) => - makeItemSnapshot(`${index}`, box as Box), - ), - "row", - "start", - propertyCase.kind as "flow" | "slots", - ); - const origin = contentRect(root.box); - const record = (property: string, detail: string, delta: number) => - failures.push({ - caseSeed: propertyCase.caseSeed, - kind: propertyCase.kind, - property, - detail, - delta: +delta.toFixed(2), - }); - - // Identity: the simulation of the unmodified container must reproduce - // the measured layout. - const identity = flowLayoutPositions(root, origin.x, origin.y); - for (const child of root.children) { - const delta = distance(identity.itemPositions.get(child)!, child.box); - if (delta > TOLERANCE) record("identity", `item-${child.value}`, delta); - } - - const count = root.children.length; - for (const k of [0, Math.floor(count / 2), count - 1]) { - const target = root.children[k]; - - // Away-and-back: excluding item k and inserting an identical ghost - // at index k must be a no-op. - const insertion = { - container: root, - index: k, - entry: { - width: target.box.width, - height: target.box.height, - margin: target.box.margin, - }, - }; - const roundTrip = flowLayoutPositions(root, origin.x, origin.y, { - exclude: (node) => node === target, - insertions: [insertion], - }); - for (const child of root.children) { - if (child === target) continue; - const delta = distance( - roundTrip.itemPositions.get(child)!, - child.box, - ); - if (delta > TOLERANCE) { - record("away-and-back", `k=${k} item-${child.value}`, delta); - } - } - const ghost = roundTrip.virtualRects.get(insertion)!; - const ghostDelta = distance(ghost, target.box); - if (ghostDelta > TOLERANCE) { - record("away-and-back", `k=${k} ghost`, ghostDelta); - } - - // Locality: inserting at index k (no exclusion) must not move any - // entry before k. Compared against the identity simulation, so this - // bound is exact rather than tolerance-based. - const inserted = flowLayoutPositions(root, origin.x, origin.y, { - insertions: [ - { - container: root, - index: k, - entry: { - width: target.box.width, - height: target.box.height, - margin: target.box.margin, - }, - }, - ], - }); - for (let i = 0; i < k; i++) { - const child = root.children[i]; - const delta = distance( - inserted.itemPositions.get(child)!, - identity.itemPositions.get(child)!, - ); - if (delta > 0.01) record("locality", `k=${k} item-${i}`, delta); - } - } - } - - await writeJson(testInfo.outputPath("layout-property-fuzz.json"), { - caseCount: measured.length, - failures: failures.slice(0, 40), - }); - expect( - failures.slice(0, 8), - "identity / away-and-back / locality invariants should hold for every generated container", - ).toHaveLength(0); - }); - - test("drops land where the drag preview predicted (drift oracle)", async ({ - page, - }, testInfo) => { - // The mid-drag preview IS the layout engine's prediction: displaced - // items sit at simulated positions and the spacer marks the dragged - // item's landing slot. After the drop, the framework re-renders and the - // browser performs the real layout — the authoritative ground truth. - // Comparing the settled DOM against the last preview turns any real - // drag into a layout-engine oracle: drift means the simulation and the - // browser disagreed about the committed arrangement. - const TOLERANCE = 1.5; - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); - - const dragWithOracle = async ( - sourceText: string, - target: { x: number; y: number }, - label: string, - ) => { - const source = await itemByTextIn(verticalColumn, sourceText); - const start = center(await itemRect(source)); - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - for (let step = 1; step <= 14; step++) { - await page.mouse.move( - start.x + ((target.x - start.x) * step) / 14, - start.y + ((target.y - start.y) * step) / 14, - ); - await page.waitForTimeout(16); - } - // Let the preview settle so captured rects are the engine's final - // prediction, not a mid-animation frame. - await page.waitForTimeout(350); - - const prediction = await verticalColumn.evaluate((box, dragged) => { - const out: Record = {}; - for (const element of box.querySelectorAll(".snapsort-item")) { - const text = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; - if (element.id === "spacer" || text.includes(dragged)) continue; - const rect = element.getBoundingClientRect(); - out[text] = { x: rect.x, y: rect.y }; - } - const spacer = box.querySelector("#spacer"); - if (spacer) { - const rect = spacer.getBoundingClientRect(); - out["__dragged__"] = { x: rect.x, y: rect.y }; - } - return out; - }, sourceText); - - await page.mouse.up(); - await page.waitForTimeout(500); - - const settled = await verticalColumn.evaluate((box, dragged) => { - const out: Record = {}; - for (const element of box.querySelectorAll(".snapsort-item")) { - const text = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; - const rect = element.getBoundingClientRect(); - out[text.includes(dragged) ? "__dragged__" : text] = { - x: rect.x, - y: rect.y, - }; - } - return out; - }, sourceText); - - const drifts: Array<{ label: string; entry: string; delta: number }> = []; - let compared = 0; - for (const [entry, predicted] of Object.entries(prediction)) { - const actual = settled[entry]; - if (!actual) continue; - compared++; - const delta = Math.max( - Math.abs(predicted.x - actual.x), - Math.abs(predicted.y - actual.y), - ); - if (delta > TOLERANCE) - drifts.push({ label, entry, delta: +delta.toFixed(2) }); - } - // Guard against a vacuous pass: the oracle must have compared the - // dragged item's landing slot plus the displaced items. - expect( - compared, - `oracle should compare several entries for ${label}`, - ).toBeGreaterThanOrEqual(4); - expect( - prediction.__dragged__, - `spacer prediction should exist for ${label}`, - ).toBeTruthy(); - return drifts; - }; - - const item3 = await itemByTextIn(verticalColumn, "Item 3"); - const item3Center = center(await itemRect(item3)); - const item4 = await itemByTextIn(verticalColumn, "Item 4"); - const item4Rect = await itemRect(item4); - - const allDrifts = [ - // Reorder downward past two slots. - ...(await dragWithOracle("Item 1", item3Center, "item1-to-item3")), - // Reach the final slot (past the last item's bottom edge). - ...(await dragWithOracle( - "Item 2", - { - x: item4Rect.x + item4Rect.width / 2, - y: item4Rect.y + item4Rect.height * 1.05, - }, - "item2-to-final-slot", - )), - ]; - - await writeJson(testInfo.outputPath("drop-drift-oracle.json"), { - drifts: allDrifts, - }); - expect( - allDrifts, - "settled post-drop positions should match the drag preview's prediction", - ).toHaveLength(0); - }); - - test("keeps the spacer stable while dragging into a narrower nested container (stretch flicker regression)", async ({ - page, - }, testInfo) => { - // Before `stretchItems`, insertion entries kept the dragged item's - // source-container size everywhere, so nested candidates' ghost rects - // and centers were computed at parent width — candidate scoring - // flip-flopped between parent and nested slots as the pointer moved and - // the spacer visibly oscillated between containers. The Stretch Nested - // demo cell's items are genuinely 100% width and its containers declare - // `stretchItems`, so the spacer host must settle: at most a couple of - // transitions on the way in, ending inside the nested sub-list, with - // the drop committing there. - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const nested = await demoBoxByHeading(page, "Stretch Nested"); - const source = await itemByTextIn(nested, "Task 1"); - const target = await itemByTextIn(nested, "Sub task 2"); - const start = center(await itemRect(source)); - const end = center(await itemRect(target)); - - const spacerHost = () => - nested.evaluate((box) => { - const spacer = box.querySelector("#spacer"); - if (!spacer) return "none"; - const container = spacer.closest(".snapsort-container"); - if (!container) return "unknown"; - return container.classList.contains("stretch-sublist") - ? "nested" - : "parent"; - }); - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - const hosts: string[] = []; - const steps = 24; - for (let step = 1; step <= steps; step++) { - await page.mouse.move( - start.x + ((end.x - start.x) * step) / steps, - start.y + ((end.y - start.y) * step) / steps, - ); - await page.waitForTimeout(16); - hosts.push(await spacerHost()); - } - await page.waitForTimeout(350); - hosts.push(await spacerHost()); - - // The core of the fix: once the spacer is hosted by the narrower - // sublist, it must be re-sized to the sublist's content width (minus - // its own margins) rather than keeping the parent-container width it - // was measured at. - const spacerSizing = await nested.evaluate((box) => { - const spacer = box.querySelector("#spacer") as HTMLElement | null; - const sublist = box.querySelector( - ".stretch-sublist", - ) as HTMLElement | null; - if (!spacer || !sublist) return null; - const spacerRect = spacer.getBoundingClientRect(); - const style = getComputedStyle(sublist); - const spacerStyle = getComputedStyle(spacer); - const number = (value: string) => parseFloat(value) || 0; - const contentWidth = - sublist.getBoundingClientRect().width - - number(style.borderLeftWidth) - - number(style.borderRightWidth) - - number(style.paddingLeft) - - number(style.paddingRight); - const expected = - contentWidth - - number(spacerStyle.marginLeft) - - number(spacerStyle.marginRight); - return { spacerWidth: spacerRect.width, expected }; - }); - expect(spacerSizing, "spacer should be inside the sublist").toBeTruthy(); - expect( - Math.abs(spacerSizing!.spacerWidth - spacerSizing!.expected), - `spacer width ${spacerSizing!.spacerWidth} should match the sublist's content width ${spacerSizing!.expected}`, - ).toBeLessThanOrEqual(1.5); - - // Drift oracle for the nested drop: preview rects just before release - // vs the settled DOM afterward. - const prediction = await nested.evaluate((box) => { - const out: Record = {}; - for (const element of box.querySelectorAll(".snapsort-item")) { - const text = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; - if (element.id === "spacer" || text === "Task 1") continue; - if (!/^Sub task \d$/.test(text)) continue; - const rect = element.getBoundingClientRect(); - out[text] = { x: rect.x, y: rect.y }; - } - const spacer = box.querySelector("#spacer"); - if (spacer) { - const rect = spacer.getBoundingClientRect(); - out["__dragged__"] = { x: rect.x, y: rect.y }; - } - return out; - }); - await page.mouse.up(); - await page.waitForTimeout(500); - const settled = await nested.evaluate((box) => { - const out: Record = {}; - for (const element of box.querySelectorAll(".snapsort-item")) { - const text = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; - const rect = element.getBoundingClientRect(); - if (text === "Task 1") out["__dragged__"] = { x: rect.x, y: rect.y }; - else if (/^Sub task \d$/.test(text)) - out[text] = { x: rect.x, y: rect.y }; - } - return out; - }); - const drifts: Array<{ entry: string; delta: number }> = []; - for (const [entry, predicted] of Object.entries(prediction)) { - const actual = settled[entry]; - if (!actual) continue; - const delta = Math.max( - Math.abs(predicted.x - actual.x), - Math.abs(predicted.y - actual.y), - ); - if (delta > 1.5) drifts.push({ entry, delta: +delta.toFixed(2) }); - } - - const transitions = hosts.filter( - (host, index) => index > 0 && host !== hosts[index - 1], - ).length; - const subGroupTexts = await nested.evaluate((box) => - [...box.querySelectorAll(".stretch-sublist .snapsort-item")].map( - (element) => element.textContent?.trim().replace(/\s+/g, " ") ?? "", - ), - ); - - await writeJson(testInfo.outputPath("nested-stretch-flicker.json"), { - hosts, - transitions, - drifts, - subGroupTexts, - }); - expect( - hosts[hosts.length - 1], - "spacer should end in the nested sub-list", - ).toBe("nested"); - expect( - transitions, - "spacer host must not oscillate between parent and nested containers", - ).toBeLessThanOrEqual(2); - expect( - drifts, - "nested drop should land where the preview predicted", - ).toHaveLength(0); - expect( - subGroupTexts.some((text) => text.includes("Task 1")), - "the dragged item should commit into the nested sub-list", - ).toBe(true); - }); - - test("stretch entry sizing matches a real width-100% spacer (ground truth)", async ({ - page, - }) => { - // A stretchItems container's simulated entry must match what the browser - // does with an unsized (stretch) flex child: fill the content box minus - // the entry's own margins — including fractional container widths, - // padding, and borders. - await page.setContent('
'); - const measured = await page.evaluate(() => { - const fixture = document.querySelector("#stretch-fixture") as HTMLElement; - const boxOf = (element: HTMLElement) => { - const rect = element.getBoundingClientRect(); - const style = getComputedStyle(element); - const number = (value: string) => parseFloat(value) || 0; - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - screen: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - margin: { - top: number(style.marginTop), - right: number(style.marginRight), - bottom: number(style.marginBottom), - left: number(style.marginLeft), - }, - padding: { - top: number(style.paddingTop), - right: number(style.paddingRight), - bottom: number(style.paddingBottom), - left: number(style.paddingLeft), - }, - border: { - top: number(style.borderTopWidth), - right: number(style.borderRightWidth), - bottom: number(style.borderBottomWidth), - left: number(style.borderLeftWidth), - }, - }; - }; - const build = (withSpacer: boolean) => { - fixture.innerHTML = ""; - const container = document.createElement("section"); - container.style.cssText = - "box-sizing:border-box;display:flex;flex-direction:column;" + - "width:222.33px;padding:9px;border:2px solid #111;gap:6px;"; - fixture.appendChild(container); - for (let i = 0; i < 3; i++) { - const item = document.createElement("div"); - item.style.cssText = - "box-sizing:border-box;height:40px;background:#dbeafe;"; - item.dataset.i = String(i); - container.appendChild(item); - if (withSpacer && i === 0) { - // Unsized stretch flex child with margins: the browser's own - // notion of a "100% width" entry. - const spacer = document.createElement("div"); - spacer.id = "spacer"; - spacer.style.cssText = - "box-sizing:border-box;height:40px;margin:0 4px;background:#fecaca;"; - container.appendChild(spacer); - } - } - return container; - }; - const pristine = build(false); - const containerBox = boxOf(pristine); - const itemBoxes = [...pristine.children].map((element) => - boxOf(element as HTMLElement), - ); - const truth = build(true); - const spacer = truth.querySelector("#spacer") as HTMLElement; - const spacerRect = spacer.getBoundingClientRect(); - return { - container: containerBox, - itemBoxes, - spacer: { - x: spacerRect.x, - y: spacerRect.y, - width: spacerRect.width, - height: spacerRect.height, - }, - }; - }); - - const root = makeContainerSnapshot( - measured.container as Box, - measured.itemBoxes.map((box, index) => - makeItemSnapshot(`${index}`, box as Box), - ), - "column", - "start", - "flow", - { wrap: "nowrap", stretchItems: true }, - ); - const margin = { top: 0, right: 4, bottom: 0, left: 4 }; - const insertion = { - container: root, - index: 1, - entry: { - // Deliberately oversized base: the source container was wider. - ...virtualEntrySizeFor(root, { width: 500, height: 40, margin }), - margin, - }, - }; - const origin = contentRect(root.box); - const result = flowLayoutPositions(root, origin.x, origin.y, { - insertions: [insertion], - }); - const rect = result.virtualRects.get(insertion)!; - expect(Math.abs(rect.width - measured.spacer.width)).toBeLessThanOrEqual( - 1.25, - ); - expect(Math.abs(rect.y - measured.spacer.y)).toBeLessThanOrEqual(1.25); - }); - - // Documented-unsupported layout shapes, encoded as expected failures so - // the boundary is visible in the test report and any accidental fix or - // regression flips the result. Each builds a real DOM, inserts a real - // spacer, and counts entries where the simulation misses the browser's - // placement by more than 1.25px. - async function unsupportedShapeMismatches( - page: Page, - config: { - containerCss: string; - itemCss: string[]; - itemInnerHeights?: number[]; - layoutModel: "flow" | "slots"; - spacerIndices: number[]; - }, - ): Promise { - await page.setContent('
'); - const measured = await page.evaluate((cfg) => { - const fixture = document.querySelector( - "#unsupported-fixture", - ) as HTMLElement; - const boxOf = (element: HTMLElement) => { - const rect = element.getBoundingClientRect(); - const style = getComputedStyle(element); - const number = (value: string) => parseFloat(value) || 0; - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - screen: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - margin: { - top: number(style.marginTop), - right: number(style.marginRight), - bottom: number(style.marginBottom), - left: number(style.marginLeft), - }, - padding: { - top: number(style.paddingTop), - right: number(style.paddingRight), - bottom: number(style.paddingBottom), - left: number(style.paddingLeft), - }, - border: { - top: number(style.borderTopWidth), - right: number(style.borderRightWidth), - bottom: number(style.borderBottomWidth), - left: number(style.borderLeftWidth), - }, - }; - }; - const build = ( - spacer: { index: number; width: number; height: number } | null, - ) => { - fixture.innerHTML = ""; - const container = document.createElement("section"); - container.style.cssText = "box-sizing:border-box;" + cfg.containerCss; - fixture.appendChild(container); - const nodes: HTMLElement[] = []; - for (let i = 0; i < cfg.itemCss.length; i++) { - if (spacer && i === 0) continue; // dragged item lifted - const item = document.createElement("div"); - item.style.cssText = - "box-sizing:border-box;background:#dbeafe;" + cfg.itemCss[i]; - item.dataset.i = String(i); - const innerHeight = cfg.itemInnerHeights?.[i]; - if (innerHeight != null) { - const inner = document.createElement("div"); - inner.style.cssText = `height:${innerHeight}px;`; - item.appendChild(inner); - } - nodes.push(item); - } - if (spacer) { - const spacerEl = document.createElement("div"); - spacerEl.id = "spacer"; - spacerEl.style.cssText = `box-sizing:border-box;background:#fecaca;width:${spacer.width}px;height:${spacer.height}px;`; - nodes.splice(Math.min(spacer.index, nodes.length), 0, spacerEl); - } - for (const node of nodes) container.appendChild(node); - return container; - }; - - const pristine = build(null); - const containerBox = boxOf(pristine); - const itemBoxes = [...pristine.children].map((element) => - boxOf(element as HTMLElement), - ); - const dragged = itemBoxes[0]; - const truths = cfg.spacerIndices.map((index) => { - const container = build({ - index, - width: dragged.width, - height: dragged.height, - }); - let ghost: { x: number; y: number } | null = null; - const items: Array<{ id: string; x: number; y: number }> = []; - for (const element of container.children) { - const rect = element.getBoundingClientRect(); - if (element.id === "spacer") ghost = { x: rect.x, y: rect.y }; - else { - items.push({ - id: (element as HTMLElement).dataset.i!, - x: rect.x, - y: rect.y, - }); - } - } - return { spacerIndex: index, ghost, items }; - }); - return { container: containerBox, itemBoxes, truths }; - }, config); - - const root = makeContainerSnapshot( - measured.container as Box, - measured.itemBoxes.map((box, index) => - makeItemSnapshot(`${index}`, box as Box), - ), - "row", - "start", - config.layoutModel, - ); - const dragged = root.children[0]; - let mismatches = 0; - for (const truth of measured.truths) { - const insertion = { - container: root, - index: truth.spacerIndex, - entry: { - width: dragged.box.width, - height: dragged.box.height, - margin: dragged.box.margin, - }, - }; - const origin = contentRect(root.box); - const result = flowLayoutPositions(root, origin.x, origin.y, { - exclude: (node) => node === dragged, - insertions: [insertion], - }); - const actualById = new Map(truth.items.map((item) => [item.id, item])); - for (const [snapshotItem, position] of result.itemPositions) { - const actual = actualById.get(snapshotItem.value); - if (!actual) continue; - if ( - Math.max( - Math.abs(position.x - actual.x), - Math.abs(position.y - actual.y), - ) > 1.25 - ) { - mismatches++; - } - } - const ghost = result.virtualRects.get(insertion); - if ( - !ghost || - !truth.ghost || - Math.max( - Math.abs(ghost.x - truth.ghost.x), - Math.abs(ghost.y - truth.ghost.y), - ) > 1.25 - ) { - mismatches++; - } - } - return mismatches; - } - - test("documents unsupported: RTL flex containers", async ({ page }) => { - test.fail( - true, - "The flow model assumes LTR main-axis growth: RTL offsets regress per item, so line detection and positions are mirrored. Slot mode covers RTL grids; RTL flex is out of scope.", - ); - const mismatches = await unsupportedShapeMismatches(page, { - containerCss: - "display:flex;flex-wrap:wrap;direction:rtl;width:380.33px;gap:4px;" + - "align-items:flex-start;align-content:flex-start;", - itemCss: Array.from( - { length: 16 }, - () => "width:calc((100% - 12px)/4);height:40px;", - ), - layoutModel: "flow", - spacerIndices: [0, 3, 7], - }); - expect(mismatches).toBe(0); - }); - - test("documents unsupported: grid items spanning multiple tracks", async ({ - page, - }) => { - test.fail( - true, - "Slot mode assumes one entry per slot: a span-2 item makes slot geometry depend on placement, which reordering invalidates.", - ); - const mismatches = await unsupportedShapeMismatches(page, { - containerCss: - "display:grid;grid-template-columns:repeat(4, 88px);gap:4px;width:380px;", - itemCss: Array.from({ length: 14 }, (_, i) => - i === 5 ? "height:40px;grid-column:span 2;" : "height:40px;", - ), - layoutModel: "slots", - spacerIndices: [0, 3, 7], - }); - expect(mismatches).toBe(0); - }); - - test("documents unsupported: stretch items with intrinsic heights across content-sized rows", async ({ - page, - }) => { - test.fail( - true, - "Items with align-self:stretch and no explicit height measure at their row's height, not their intrinsic height; when displaced across content-sized rows the simulation carries the stale stretched height. Predicting the true height would require intrinsic sizing per destination track.", - ); - const mismatches = await unsupportedShapeMismatches(page, { - containerCss: - "display:grid;grid-template-columns:repeat(3, 110px);grid-auto-rows:auto;gap:4px;width:346px;", - // No explicit item heights: each stretches to its row. Item 0's inner - // content is 90px tall, making row 1's track 90 and stretching its - // short siblings to 90 as measured. Removing item 0 shrinks row 1 to - // 30 in the real layout; the simulation keeps the stale 90. - itemCss: Array.from({ length: 9 }, () => ""), - itemInnerHeights: Array.from({ length: 9 }, (_, i) => - i === 0 ? 90 : 30, - ), - layoutModel: "slots", - spacerIndices: [8], - }); - expect(mismatches).toBe(0); - }); - - test("does not crash when drag movement arrives before snapshot capture", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); - const item = await itemByTextIn(verticalColumn, "Item 1"); - const itemCenter = center(await itemRect(item)); - - await page.mouse.move(itemCenter.x, itemCenter.y); - await page.mouse.down(); - for (let step = 1; step <= 24; step++) { - await page.mouse.move(itemCenter.x, itemCenter.y + step * 4); - } - await page.mouse.up(); - await page.waitForTimeout(100); - - await writeJson(testInfo.outputPath("snapshot-readiness-trace.json"), { - errors: consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - snapshotWaits: consoleMessages.filter((message) => - /waiting for drag snapshot/.test(message), - ), - }); - - expect( - consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - ).toHaveLength(0); - }); - - test("cleans up drag state when a started drag releases back inside the threshold", async ({ - page, - }, testInfo) => { - // Regression: a drag that starts (crosses the threshold) and then returns - // near its origin before release must still fire dragEnd and commit/clean - // up. Previously dragEnd was gated on the pointer's final distance from - // the start, so an away-and-back "drop it in the same place" gesture was - // misclassified as a click and left the drag session uncommitted. - // Fixed in src/input.ts #finishPointer by gating on the drag gesture state. - const consoleMessages: string[] = []; - const pageErrors: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - page.on("pageerror", (error) => pageErrors.push(String(error))); - await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - await releaseStartedDragNearOrigin(page, nested, "Item 1.5", "Sub A1", 0.2); - const state = await nestedSnapSortLifecycleState(page); - - await writeJson( - testInfo.outputPath("threshold-release-cleanup-repro.json"), - { - state, - errors: [ - ...pageErrors, - ...consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - ], - }, - ); - - expect(state.spacerCount, "released drag should remove its ghost").toBe(0); - expect( - state.draggingTexts, - "released drag should clear the dragging marker", - ).toEqual([]); - }); - - test("does not let a locked container drag consume leaked root ghost state", async ({ - page, - }, testInfo) => { - test.fail( - true, - "Known repro: drag/dragEnd still run after locked dragStart returns, so a locked container can consume leaked root drag state.", - ); - const consoleMessages: string[] = []; - const pageErrors: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - page.on("pageerror", (error) => pageErrors.push(String(error))); - await page.goto( - "/?demo=drop_snap_nested&disableNestedFlip=1&lockNestedChild=1", - { - waitUntil: "networkidle", - }, - ); - - const nested = await demoBoxByHeading(page, "Nested Container"); - await releaseStartedDragNearOrigin(page, nested, "Item 1.5", "Sub A1", 0.2); - const beforeLockedDrag = await nestedSnapSortLifecycleState(page); - await dragLockedNestedContainerBackground(page, nested); - const afterLockedDrag = await nestedSnapSortLifecycleState(page); - - await writeJson( - testInfo.outputPath("locked-container-leak-adoption-repro.json"), - { - beforeLockedDrag, - afterLockedDrag, - adapterWarnings: consoleMessages.filter((message) => - /adapter did not place/.test(message), - ), - errors: [ - ...pageErrors, - ...consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - ], - }, - ); - - expect( - beforeLockedDrag.spacerCount, - "precondition should expose the leaked ghost", - ).toBe(1); - expect( - afterLockedDrag.spacerCount, - "a locked container drag should not consume another drag's leaked ghost", - ).toBe(1); - }); - - test("does not self-reference beforeElement when reinserting an existing nested container", async ({ - page, - }, testInfo) => { - await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { - waitUntil: "networkidle", - }); - - const probe = await nestedContainerSelfInsertProbe(page); - await writeJson( - testInfo.outputPath("nested-container-self-insert-repro.json"), - { - probe, - }, - ); - - expect(probe.found, "expected to find the nested container objects").toBe( - true, - ); - expect( - probe.insertEvents.some((event) => event.selfBefore), - `adapter should never receive the dropped item as beforeElement; events=${JSON.stringify(probe.insertEvents)}`, - ).toBe(false); - expect( - probe.duplicateCount, - `re-inserting an existing child should not duplicate the itemOrderedList; order=${probe.afterOrder.join(" | ")}`, - ).toBe(1); - }); - - test("does not throw when a released dragged item is grabbed again", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - const pageErrors: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - page.on("pageerror", (error) => pageErrors.push(String(error))); - await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - await releaseStartedDragNearOrigin(page, nested, "Item 1.5", "Sub A1", 0.2); - const releasedItem = await itemByTextIn(nested, "Item 1.5"); - const releasedRect = await itemRect(releasedItem); - const releasedCenter = center(releasedRect); - - await page.mouse.move(releasedCenter.x, releasedCenter.y); - await page.mouse.down(); - await page.mouse.move(releasedCenter.x + 20, releasedCenter.y + 20, { - steps: 10, - }); - await page.waitForTimeout(100); - await page.mouse.up(); - await page.waitForTimeout(200); - - const state = await nestedSnapSortLifecycleState(page); - await writeJson(testInfo.outputPath("released-item-regrab.json"), { - state, - pageErrors, - consoleErrors: consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - }); - - expect(pageErrors).toHaveLength(0); - expect( - consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - ).toHaveLength(0); - expect(state.spacerCount).toBe(0); - expect(state.draggingTexts).toEqual([]); - }); - - test("animates displaced items when the ghost reorders", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); - const item1 = await itemByTextIn(verticalColumn, "Item 1"); - const item4 = await itemByTextIn(verticalColumn, "Item 4"); - const item1Center = center(await itemRect(item1)); - const item4Center = center(await itemRect(item4)); - - await page.mouse.move(item1Center.x, item1Center.y); - await page.mouse.down(); - - // Arm a style-attribute observer before the reorder: polling for the - // inline transform can miss a FLIP that starts and settles between polls - // (WebKit clears the transform quickly on fast machines). - await page.evaluate(() => { - const win = window as unknown as { - __sawDisplacedTransform?: boolean; - __displacedObserver?: MutationObserver; - }; - win.__sawDisplacedTransform = false; - const isDisplaced = (element: Element) => - element.id !== "spacer" && !/Item 1/.test(element.textContent ?? ""); - const check = (element: Element) => { - if ( - isDisplaced(element) && - /^translate3d\(/.test((element as HTMLElement).style.transform) - ) { - win.__sawDisplacedTransform = true; - } - }; - const observer = new MutationObserver((mutations) => { - for (const mutation of mutations) check(mutation.target as Element); - }); - for (const element of document.querySelectorAll(".snapsort-item")) { - observer.observe(element, { - attributes: true, - attributeFilter: ["style"], - }); - check(element); - } - win.__displacedObserver = observer; - }); - - // Pace the moves like a human drag: a single burst of interpolated moves - // can be delivered entirely before the drag session finishes activating - // (observed on WebKit), leaving no post-activation pointermove and thus - // no reorder to animate. - for (let step = 1; step <= 12; step++) { - await page.mouse.move( - item1Center.x, - item1Center.y + ((item4Center.y - item1Center.y) * step) / 12, - ); - await page.waitForTimeout(16); - } - - const animated = await page.waitForFunction( - () => - (window as unknown as { __sawDisplacedTransform?: boolean }) - .__sawDisplacedTransform === true, - ); - await page.mouse.up(); - await page.waitForTimeout(120); - - await writeJson(testInfo.outputPath("reorder-animation-trace.json"), { - animated: await animated.jsonValue(), - errors: consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - }); - - expect(await animated.jsonValue()).toBe(true); - expect( - consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - ).toHaveLength(0); - }); - - test("animates siblings when a flow ghost leaves and re-enters a valid container", async ({ - page, - }, testInfo) => { - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(String(error))); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const multipleAreas = await demoBoxByHeading(page, "Multiple Drop Areas"); - const itemA = await itemByTextIn(multipleAreas, "Item A"); - const itemY = await itemByTextIn(multipleAreas, "Item Y"); - const containers = multipleAreas.locator(".snapsort-container"); - const area1 = containers.nth(1); - const area2 = containers.nth(2); - const targetSpacers = area2.locator( - '[data-snapsort-ghost-entry="target-spacer"]', - ); - const sourceBox = await itemRect(itemA); - const start = center(sourceBox); - const initialTarget = center(await itemRect(itemY)); - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - for (let step = 1; step <= 14; step++) { - await page.mouse.move( - start.x + ((initialTarget.x - start.x) * step) / 14, - start.y + ((initialTarget.y - start.y) * step) / 14, - ); - await page.waitForTimeout(16); - } - await expect(targetSpacers).toHaveCount(1); - await expect - .poll(() => - area2 - .locator(".snapsort-item") - .evaluateAll((elements) => - elements.every( - (element) => !(element as HTMLElement).style.transform, - ), - ), - ) - .toBe(true); - - await area2.evaluate((container) => { - type Phase = "idle" | "removal" | "insertion"; - interface FlowGhostFlipTrace { - phase: Phase; - removal: string[]; - insertion: string[]; - } - const win = window as unknown as { - __flowGhostFlipTrace?: FlowGhostFlipTrace; - __flowGhostFlipObserver?: MutationObserver; - }; - const trace: FlowGhostFlipTrace = { - phase: "idle", - removal: [], - insertion: [], - }; - const check = (element: Element) => { - const transform = (element as HTMLElement).style.transform; - if (!/^translate3d\(/.test(transform)) return; - const hasSpacer = Boolean( - container.querySelector( - '[data-snapsort-ghost-entry="target-spacer"]', - ), - ); - const label = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; - if (trace.phase === "removal" && !hasSpacer) { - trace.removal.push(`${label}: ${transform}`); - } else if (trace.phase === "insertion" && hasSpacer) { - trace.insertion.push(`${label}: ${transform}`); - } - }; - const observer = new MutationObserver((mutations) => { - for (const mutation of mutations) check(mutation.target as Element); - }); - for (const element of container.querySelectorAll(".snapsort-item")) { - observer.observe(element, { - attributes: true, - attributeFilter: ["style"], - }); - } - win.__flowGhostFlipTrace = trace; - win.__flowGhostFlipObserver = observer; - }); - - const setTracePhase = async (phase: "idle" | "removal" | "insertion") => - page.evaluate((nextPhase) => { - const trace = ( - window as unknown as { - __flowGhostFlipTrace?: { phase: typeof nextPhase }; - } - ).__flowGhostFlipTrace; - if (!trace) throw new Error("Missing flow ghost FLIP trace."); - trace.phase = nextPhase; - }, phase); - const traceCounts = () => - page.evaluate(() => { - const trace = ( - window as unknown as { - __flowGhostFlipTrace?: { - removal: string[]; - insertion: string[]; - }; - } - ).__flowGhostFlipTrace; - return { - removal: trace?.removal.length ?? 0, - insertion: trace?.insertion.length ?? 0, - }; - }); - - const [area1Box, area2Box] = await Promise.all([ - area1.boundingBox(), - area2.boundingBox(), - ]); - if (!area1Box || !area2Box) { - throw new Error("Expected visible drop areas."); - } - const invalidPoint = { - x: area2Box.x + area2Box.width / 2, - // Progressive candidates expand their broad-phase main-axis band by - // twice the dragged height, so leave a second full band of clearance. - y: Math.min(area1Box.y, area2Box.y) - sourceBox.height * 4, - }; - - await setTracePhase("removal"); - await page.mouse.move(invalidPoint.x, invalidPoint.y); - await expect(targetSpacers).toHaveCount(0); - await expect - .poll(async () => (await traceCounts()).removal) - .toBeGreaterThan(0); - await expect - .poll(() => - area2 - .locator(".snapsort-item") - .evaluateAll((elements) => - elements.every( - (element) => !(element as HTMLElement).style.transform, - ), - ), - ) - .toBe(true); - - const reentryTarget = center(await itemRect(itemY)); - await setTracePhase("insertion"); - await page.mouse.move(reentryTarget.x, reentryTarget.y); - await expect(targetSpacers).toHaveCount(1); - await expect - .poll(async () => (await traceCounts()).insertion) - .toBeGreaterThan(0); - - await setTracePhase("idle"); - await page.mouse.up(); - await expect( - page.locator('[data-snapsort-ghost-entry="target-spacer"]'), - ).toHaveCount(0); - const trace = await page.evaluate(() => { - const win = window as unknown as { - __flowGhostFlipTrace?: { - removal: string[]; - insertion: string[]; - }; - __flowGhostFlipObserver?: MutationObserver; - }; - win.__flowGhostFlipObserver?.disconnect(); - return win.__flowGhostFlipTrace ?? { removal: [], insertion: [] }; - }); - await writeJson(testInfo.outputPath("flow-ghost-frame-flip.json"), { - invalidPoint, - trace, - pageErrors, - }); - - expect(trace.removal.length).toBeGreaterThan(0); - expect(trace.insertion.length).toBeGreaterThan(0); - expect(pageErrors).toHaveLength(0); - }); - - test("animates displaced items when the ghost reorders upward", async ({ - page, - }, testInfo) => { - // Mirror of the downward test above. Upward reorders place the ghost - // BEFORE the displaced items in FLIP snapshot order, so a failure while - // animating the ghost entry silently kills every displaced-item - // animation — a class of bug the downward drag cannot catch. - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); - const item1 = await itemByTextIn(verticalColumn, "Item 1"); - const item4 = await itemByTextIn(verticalColumn, "Item 4"); - const item1Center = center(await itemRect(item1)); - const item4Center = center(await itemRect(item4)); - - await page.mouse.move(item4Center.x, item4Center.y); - await page.mouse.down(); - - await page.evaluate(() => { - const win = window as unknown as { - __sawDisplacedTransform?: boolean; - __displacedObserver?: MutationObserver; - }; - win.__sawDisplacedTransform = false; - const isDisplaced = (element: Element) => - element.id !== "spacer" && !/Item 4/.test(element.textContent ?? ""); - const check = (element: Element) => { - if ( - isDisplaced(element) && - /^translate3d\(/.test((element as HTMLElement).style.transform) - ) { - win.__sawDisplacedTransform = true; - } - }; - const observer = new MutationObserver((mutations) => { - for (const mutation of mutations) check(mutation.target as Element); - }); - for (const element of document.querySelectorAll(".snapsort-item")) { - observer.observe(element, { - attributes: true, - attributeFilter: ["style"], - }); - check(element); - } - win.__displacedObserver = observer; - }); - - for (let step = 1; step <= 12; step++) { - await page.mouse.move( - item4Center.x, - item4Center.y + ((item1Center.y - item4Center.y) * step) / 12, - ); - await page.waitForTimeout(16); - } - - const animated = await page.waitForFunction( - () => - (window as unknown as { __sawDisplacedTransform?: boolean }) - .__sawDisplacedTransform === true, - ); - await page.mouse.up(); - await page.waitForTimeout(120); - - await writeJson( - testInfo.outputPath("reorder-animation-upward-trace.json"), - { - animated: await animated.jsonValue(), - errors: consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - }, - ); - - expect(await animated.jsonValue()).toBe(true); - expect( - consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - ).toHaveLength(0); - }); - - test("keeps the final slot reachable in a plain vertical list", async ({ - page, - }) => { - await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { - waitUntil: "networkidle", - }); - - const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); - const container = verticalColumn.locator(".snapsort-container").first(); - const item = await itemByTextIn(verticalColumn, "Item 1"); - const target = await itemByTextIn(verticalColumn, "Item 4"); - - await dragToItemFraction(page, item, "Item 1", 0, target, 1.05, { - steps: 80, - }); - - await expect - .poll(() => directSnapSortItemTexts(container)) - .toEqual(["Item 2", "Item 3", "Item 4", "Item 1"]); - }); - - test("reproduces website sideways list final-slot placement", async ({ - page, - }) => { - await page.goto("/?demo=snapsort_website_core", { - waitUntil: "networkidle", - }); - - const card = await websiteCoreDemo(page, "sideways-list"); - const container = card.locator(".sideways-list"); - await expect - .poll(() => directLogoSliceOrder(container)) - .toEqual([3, 0, 5, 1, 4, 2]); - - const source = container.locator(".snapsort-item").first(); - const last = container.locator(".snapsort-item").last(); - const sourceRect = await itemRect(source); - const sourceCenter = center(sourceRect); - const lastRect = await itemRect(last); - const target = { - x: lastRect.x + lastRect.width + sourceRect.width / 2 + 24, - y: lastRect.y + lastRect.height / 2, - }; - - await dragBy( - page, - source, - "TypeScript slice 3", - 0, - { - x: target.x - sourceCenter.x, - y: target.y - sourceCenter.y, - }, - { steps: 140 }, - ); - - await expect - .poll(() => directLogoSliceOrder(container)) - .toEqual([0, 5, 1, 4, 2, 3]); - }); - - test("reproduces website nested bottom-slot stability", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=snapsort_website_core", { - waitUntil: "networkidle", - }); - - const card = await websiteCoreDemo(page, "nested-list"); - const source = await itemByTextIn(card, "Item 1"); - const target = await itemByTextIn(card, "Item 6"); - const handle = source.locator(".demo-row-handle").first(); - const start = center(await itemRect(handle)); - const targetRect = await itemRect(target); - const targetPoint = { - x: targetRect.x + targetRect.width / 2, - y: targetRect.y + targetRect.height * 1.15, - }; - const samples = await dragBy( - page, - source, - "Item 1", - 0, - { - x: targetPoint.x - start.x, - y: targetPoint.y - start.y, - }, - { - start, - steps: 240, - }, - ); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("website-nested-bottom-slot-trace.json"), - { assertCenter: false }, - ); - expectNoParentReentry( - samples, - "website-nested-inner", - "website-nested-outer", - "website core", - ); - - const states = compressedSpacerStates(samples, [ - "website-nested-inner", - "website-nested-outer", - ]); - await writeJson( - testInfo.outputPath("website-nested-bottom-slot-states.json"), - { - states, - ghostTargets: ghostInsertionTargets(consoleMessages), - }, - ); - expect( - states, - `ghost should reach the bottom slot of the website nested list; observed ${states.join(" -> ")}`, - ).toContain("website-nested-inner[3]"); - - const innerContainer = card.locator(".nested-list"); - await expect - .poll(() => directSnapSortItemTexts(innerContainer)) - .toEqual(["Item 4", "Item 5", "Item 6", "Item 1"]); - }); - - test("reproduces website 321px multi-container row layout parity", async ({ - page, - }, testInfo) => { - await page.goto("/?demo=snapsort_website_core", { - waitUntil: "networkidle", - }); - - const card = await websiteCoreDemo(page, "multiple-containers"); - const board = card.locator(".multi-container-board"); - await expect(board).toBeVisible(); - - const measured = await board.evaluate((element) => { - const number = (value: string) => Number.parseFloat(value) || 0; - const boxOf = (node: Element): Box => { - const rect = node.getBoundingClientRect(); - const style = getComputedStyle(node); - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - screen: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - margin: { - top: number(style.marginTop), - right: number(style.marginRight), - bottom: number(style.marginBottom), - left: number(style.marginLeft), - }, - padding: { - top: number(style.paddingTop), - right: number(style.paddingRight), - bottom: number(style.paddingBottom), - left: number(style.paddingLeft), - }, - border: { - top: number(style.borderTopWidth), - right: number(style.borderRightWidth), - bottom: number(style.borderBottomWidth), - left: number(style.borderLeftWidth), - }, - }; - }; - const columns = [...element.children].filter((child) => - child.classList.contains("basic-column"), - ); - const columnBoxes = columns.map((column, index) => ({ - id: `column-${index}`, - box: boxOf(column), - })); - return { - board: boxOf(element), - columns: columnBoxes, - domSameRow: - columnBoxes.length === 2 && - Math.abs(columnBoxes[0].box.y - columnBoxes[1].box.y) < 1, - }; - }); - - expect(measured.columns).toHaveLength(2); - expect( - measured.domSameRow, - "the browser DOM should keep both columns on one row", - ).toBe(true); - - const boardSnapshot = snapshotFixture({ - value: "website-multi-container-board", - direction: "row", - locked: true, - box: measured.board, - children: measured.columns.map((column) => ({ - value: column.id, - direction: "column", - locked: true, - box: column.box, - children: [], - })), - }); - const origin = contentRect(measured.board); - const layout = flowLayoutPositions(boardSnapshot, origin.x, origin.y); - const simulated = boardSnapshot.children.map((child) => { - const position = layout.itemPositions.get(child); - if (!position) { - throw new Error(`Missing simulated position for ${child.value}`); - } - return { id: child.value, ...position }; - }); - - await writeJson( - testInfo.outputPath("website-321px-multi-container-layout.json"), - { - measured, - simulated, - }, - ); - - expect( - Math.abs(simulated[0].y - simulated[1].y), - `layout engine should not wrap the second 321px column when the DOM stays on one row; simulated=${JSON.stringify(simulated)}`, - ).toBeLessThan(1); - - const source = await itemByTextIn(card, "Spec"); - const target = await itemByTextIn(card, "Ship"); - const sourceCenter = center(await itemRect(source)); - const targetRect = await itemRect(target); - const samples = await dragBy( - page, - source, - "Spec", - 0, - { - x: targetRect.x + targetRect.width / 2 - sourceCenter.x, - y: targetRect.y + targetRect.height * 1.15 - sourceCenter.y, - }, - { - captureFrameRects: true, - steps: 160, - }, - ); - const wrappedFrames = samples.flatMap((sample) => { - const columns = - sample.frameRects?.filter( - (entry) => - entry.role === "container" && - (/^Left\b/.test(entry.text) || /^Right\b/.test(entry.text)), - ) ?? []; - if (columns.length !== 2) return []; - - const deltaY = Math.abs(columns[0].rect.y - columns[1].rect.y); - return deltaY > 1 ? [{ step: sample.step, deltaY, columns }] : []; - }); - - await writeJson( - testInfo.outputPath("website-321px-multi-container-drag.json"), - { - wrappedFrames, - samples, - }, - ); - - expect( - wrappedFrames, - "left and right containers should stay on one visual row during the 321px drag", - ).toHaveLength(0); - }); - - test("keeps website multi-container dragged item above both columns", async ({ - page, - }) => { - await page.goto("/?demo=snapsort_website_core", { - waitUntil: "networkidle", - }); - - const card = await websiteCoreDemo(page, "multiple-containers"); - const source = await itemByTextIn(card, "Spec"); - const target = await itemByTextIn(card, "Ship"); - await target.scrollIntoViewIfNeeded(); - const sourceRect = await source.boundingBox(); - const targetRect = await target.boundingBox(); - if (!sourceRect || !targetRect) { - throw new Error("Expected multi-container items to have bounding boxes."); - } - const startPoint = { - x: sourceRect.x + sourceRect.width * 0.25, - y: sourceRect.y + sourceRect.height / 2, - }; - const hoverPoint = { - x: targetRect.x + Math.min(48, targetRect.width / 2), - y: targetRect.y + targetRect.height / 2, - }; - - const samples = await dragBy( - page, - source, - "Spec", - 0, - { - x: hoverPoint.x - startPoint.x, - y: hoverPoint.y - startPoint.y, - }, - { - start: startPoint, - steps: 80, - }, - ); - - const overRightColumn = samples.filter( - (sample) => - sample.mouse.x >= targetRect.x && - sample.mouse.x <= targetRect.x + targetRect.width && - sample.mouse.y >= targetRect.y && - sample.mouse.y <= targetRect.y + targetRect.height, - ); - - expect( - overRightColumn, - "drag should move over the right column", - ).not.toHaveLength(0); - const recentSamples = JSON.stringify(overRightColumn.slice(-4)); - expect( - overRightColumn.some( - (sample) => - sample.draggedAttribute === "true" && - sample.draggedSourceColumnZIndex === "2" && - !!sample.dragged && - sample.dragged.x < targetRect.x + targetRect.width && - sample.dragged.x + sample.dragged.width > targetRect.x && - sample.dragged.y < targetRect.y + targetRect.height && - sample.dragged.y + sample.dragged.height > targetRect.y, - ), - `dragged item should overlap the right column from an elevated source column; observed ${recentSamples}`, - ).toBe(true); - - await expect - .poll(() => - card - .locator(".basic-column") - .first() - .evaluate((element) => (element as HTMLElement).style.zIndex), - ) - .toBe(""); - }); - - test("keeps dragged item aligned while entering a slowly animating nested container", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const item = await itemByTextIn(nested, "Item 1"); - const target = await itemByTextIn(nested, "Sub A3"); - const samples = await dragTo(page, item, "Item 1", 0, target, { - captureFrameRects: true, - }); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("nested-slow-animation-drag-trace.json"), - ); - expectNoNestedParentFlicker(samples); - expectGhostUpdatesStable(consoleMessages, 6); - }); - - test("keeps the drop animation visible while a reorder animation is still active", async ({ - page, - }, testInfo) => { - await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const innerContainer = nested.locator(".snapsort-container").nth(1); - const source = await itemByTextIn(innerContainer, "Sub A1"); - const target = await itemByTextIn(innerContainer, "Sub A3"); - const sourceRect = await itemRect(source); - const targetRect = await itemRect(target); - const start = center(sourceRect); - const releasePoint = { - x: targetRect.x + targetRect.width / 2 + 18, - y: targetRect.y + targetRect.height * 0.85, - }; - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x + 5, start.y); - await page.waitForTimeout(16); - for (let step = 1; step <= 14; step++) { - await page.mouse.move( - start.x + ((releasePoint.x - start.x) * step) / 14, - start.y + ((releasePoint.y - start.y) * step) / 14, - ); - await page.waitForTimeout(12); - } - - // Prove the release happens during the condition that caused the bug: - // at least one displaced sibling still has a reorder FLIP transform. - await expect - .poll( - () => - innerContainer - .locator(".snapsort-item") - .evaluateAll((nodes) => - nodes.some( - (node) => - !node.textContent?.includes("Sub A1") && - (node as HTMLElement).style.transform !== "", - ), - ), - { intervals: [10, 20, 40], timeout: 300 }, - ) - .toBe(true); - - const releaseRect = await itemRect(source); - await page.evaluate(() => { - type DropFrame = { - time: number; - rect: Rect; - inlineTransform: string; - computedTransform: string; - dragging: boolean; - displacedTransformCount: number; - }; - type StyleMutation = { - time: number; - oldValue: string | null; - currentValue: string; - }; - const win = window as unknown as { - __dropContinuityTrace?: { - done: boolean; - frames: DropFrame[]; - styleMutations: StyleMutation[]; - }; - }; - const trace = { - done: false, - frames: [] as DropFrame[], - styleMutations: [] as StyleMutation[], - }; - win.__dropContinuityTrace = trace; - - const nested = [...document.querySelectorAll(".demo-cell")].find( - (element) => - element.querySelector("h2")?.textContent?.trim() === - "Nested Container", - ); - if (!nested) throw new Error("Nested Container fixture was not found."); - const itemText = (element: Element) => - element.querySelector(":scope > p")?.textContent?.trim() ?? ""; - const findDraggedItem = () => - [...nested.querySelectorAll(".snapsort-item")].find( - (element) => itemText(element) === "Sub A1", - ) as HTMLElement | undefined; - const rectOf = (element: Element): Rect => { - const rect = element.getBoundingClientRect(); - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }; - }; - const startedAt = performance.now(); - const observer = new MutationObserver((mutations) => { - for (const mutation of mutations) { - if ( - mutation.target instanceof Element && - mutation.target.classList.contains("snapsort-item") && - itemText(mutation.target) === "Sub A1" - ) { - trace.styleMutations.push({ - time: performance.now() - startedAt, - oldValue: mutation.oldValue, - currentValue: - (mutation.target as HTMLElement).getAttribute("style") ?? "", - }); - } - } - }); - observer.observe(nested, { - attributes: true, - attributeFilter: ["style"], - attributeOldValue: true, - subtree: true, - }); - - const sample = () => { - const item = findDraggedItem(); - if (item) { - trace.frames.push({ - time: performance.now() - startedAt, - rect: rectOf(item), - inlineTransform: item.style.transform, - computedTransform: getComputedStyle(item).transform, - dragging: item.dataset.snapsortDragging === "true", - displacedTransformCount: [ - ...nested.querySelectorAll(".snapsort-item"), - ].filter( - (element) => - element !== item && - !element.id.includes("spacer") && - element.style.transform !== "", - ).length, - }); - } - if (performance.now() - startedAt < 1_050) { - requestAnimationFrame(sample); - return; - } - observer.disconnect(); - trace.done = true; - }; - requestAnimationFrame(sample); - }); - - await page.mouse.up(); - await expect - .poll( - () => - page.evaluate( - () => - ( - window as unknown as { - __dropContinuityTrace?: { done: boolean }; - } - ).__dropContinuityTrace?.done ?? false, - ), - { timeout: 2_000 }, - ) - .toBe(true); - - const trace = await page.evaluate( - () => - ( - window as unknown as { - __dropContinuityTrace: { - done: boolean; - frames: Array<{ - time: number; - rect: Rect; - inlineTransform: string; - computedTransform: string; - dragging: boolean; - displacedTransformCount: number; - }>; - styleMutations: Array<{ - time: number; - oldValue: string | null; - currentValue: string; - }>; - }; - } - ).__dropContinuityTrace, - ); - await writeJson( - testInfo.outputPath("drop-animation-continuity-trace.json"), - { releaseRect, ...trace }, - ); - - const postDropFrames = trace.frames.filter((frame) => !frame.dragging); - expect(postDropFrames.length).toBeGreaterThan(20); - const finalFrame = postDropFrames.at(-1)!; - const centerDistance = (a: Rect, b: Rect) => { - const aCenter = center(a); - const bCenter = center(b); - return Math.hypot(aCenter.x - bCenter.x, aCenter.y - bCenter.y); - }; - const travel = centerDistance(releaseRect, finalFrame.rect); - expect(travel).toBeGreaterThan(12); - - const firstPaintedDropFrame = postDropFrames[0]; - expect( - centerDistance(firstPaintedDropFrame.rect, releaseRect), - "the first painted drop frame should remain at the pointer release position", - ).toBeLessThan(Math.max(4, travel * 0.15)); - expect( - postDropFrames.some((frame) => frame.inlineTransform !== ""), - "the drop FLIP transform should remain visible after release", - ).toBe(true); - - const distancesToFinal = postDropFrames.map((frame) => - centerDistance(frame.rect, finalFrame.rect), - ); - const firstSettledFrame = distancesToFinal.findIndex( - (distance) => distance <= 1, - ); - if (firstSettledFrame !== -1) { - expect( - Math.max(...distancesToFinal.slice(firstSettledFrame)), - "the item must not reach its slot and then bounce away again", - ).toBeLessThanOrEqual(2); - } - - expect(finalFrame.inlineTransform).toBe(""); - await expect(source).not.toHaveAttribute("data-snapsort-dragging"); - await expect - .poll(() => directSnapSortItemTexts(innerContainer)) - .toEqual(["Sub A2", "Sub A3", "Sub A1"]); - }); - - test("keeps nested dragged item aligned while moving in and out of its container", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const innerContainer = nested.locator(".snapsort-container").nth(1); - const item = await itemByTextIn(nested, "Sub A1"); - const activeId = await item.getAttribute("data-engine-id"); - const start = center(await itemRect(item)); - const innerRect = await itemRect(innerContainer); - const leftOutside = { - x: innerRect.x - 28, - y: start.y, - }; - const innerCenter = { - x: innerRect.x + innerRect.width / 2, - y: start.y, - }; - const path = [leftOutside, innerCenter, leftOutside, innerCenter]; - const samples: DragSample[] = []; - let previous = start; - - await page.evaluate( - ({ activeId }) => { - const win = window as unknown as { - __snapsortActiveText?: string; - __snapsortActiveIndex?: number; - __snapsortActiveId?: string; - }; - win.__snapsortActiveText = "Sub A1"; - win.__snapsortActiveIndex = 0; - win.__snapsortActiveId = activeId ?? ""; - }, - { activeId }, - ); - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x + 4, start.y); - await page.waitForTimeout(16); - - for (const point of path) { - for (let step = 1; step <= 24; step++) { - const ratio = step / 24; - const mouse = { - x: previous.x + (point.x - previous.x) * ratio, - y: previous.y + (point.y - previous.y) * ratio, - }; - await page.mouse.move(mouse.x, mouse.y); - await page.waitForTimeout(8); - samples.push( - await collectSample(page, samples.length + 1, mouse, { - captureFrameRects: true, - }), - ); - } - previous = point; - } - - await page.mouse.up(); - await page.waitForTimeout(100); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("nested-in-out-drag-trace.json"), - ); - }); - - test("drops at the pending nested index after a quick same-container slot change", async ({ - page, - }) => { - await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const item = await itemByTextIn(nested, "Item 1"); - const subA1 = await itemByTextIn(nested, "Sub A1"); - const subA3 = await itemByTextIn(nested, "Sub A3"); - const itemCenter = center(await itemRect(item)); - const subA1Center = center(await itemRect(subA1)); - const subA3Rect = await itemRect(subA3); - const subA3AfterPoint = { - x: subA3Rect.x + subA3Rect.width / 2, - y: subA3Rect.y + subA3Rect.height * 0.85, - }; - - await page.mouse.move(itemCenter.x, itemCenter.y); - await page.mouse.down(); - await page.mouse.move(itemCenter.x, itemCenter.y + 6); - await page.waitForTimeout(16); - await page.mouse.move(subA1Center.x, subA1Center.y); - await page.waitForTimeout(24); - await page.mouse.move(subA3AfterPoint.x, subA3AfterPoint.y); - await page.mouse.up(); - await page.waitForTimeout(200); - - const innerContainer = nested.locator(".snapsort-container").nth(1); - await expect(innerContainer).toBeVisible(); - await expect - .poll(() => directSnapSortItemTexts(innerContainer)) - .toEqual(["Sub A1", "Sub A2", "Sub A3", "Item 1"]); - }); - - test("commits the hovered nested slot without animation", async ({ - page, - }) => { - await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const item = await itemByTextIn(nested, "Item 1"); - const subA1 = await itemByTextIn(nested, "Sub A1"); - const target = await itemByTextIn(nested, "Sub A3"); - const itemCenter = center(await itemRect(item)); - const subA1Center = center(await itemRect(subA1)); - - await page.mouse.move(itemCenter.x, itemCenter.y); - await page.mouse.down(); - await page.mouse.move(itemCenter.x, itemCenter.y + 6); - await page.waitForTimeout(16); - await page.mouse.move(subA1Center.x, subA1Center.y); - await page.waitForTimeout(120); - - const movedTargetRect = await itemRect(target); - await page.mouse.move( - movedTargetRect.x + movedTargetRect.width / 2, - movedTargetRect.y + movedTargetRect.height * 0.85, - ); - await page.mouse.up(); - await page.waitForTimeout(200); - - const innerContainer = nested.locator(".snapsort-container").nth(1); - await expect(innerContainer).toBeVisible(); - await expect - .poll(() => directSnapSortItemTexts(innerContainer)) - .toEqual(["Sub A1", "Sub A2", "Sub A3", "Item 1"]); - }); - - test("commits the hovered slot in a compact nested list", async ({ - page, - }) => { - await page.goto( - "/?demo=drop_snap_nested&disableNestedFlip=1&compactNested=1", - { - waitUntil: "networkidle", - }, - ); - - const nested = await demoBoxByHeading(page, "Compact Nested List"); - const item = await itemByTextIn(nested, "Overview"); - const target = await itemByTextIn(nested, "Container"); - await dragToItemFraction(page, item, "Overview", 0, target, 0.5, { - steps: 20, - }); - - const innerContainer = nested.locator(".snapsort-container").nth(1); - await expect(innerContainer).toBeVisible(); - await expect - .poll(() => directSnapSortItemTexts(innerContainer)) - .toEqual(["Container", "Overview", "Item", "Handle"]); - }); - - test("moves a nested item to the parent slot above its nested container", async ({ - page, - }) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const outerContainer = nested.locator(".snapsort-container").first(); - const innerContainer = nested.locator(".snapsort-container").nth(1); - const item = await itemByTextIn(nested, "Sub A1"); - const itemCenter = center(await itemRect(item)); - const innerRect = await itemRect(innerContainer); - const targetPoint = { - x: itemCenter.x - 12, - y: innerRect.y - 2, - }; - await dragBy( - page, - item, - "Sub A1", - 0, - { - x: targetPoint.x - itemCenter.x, - y: targetPoint.y - itemCenter.y, - }, - { steps: 120 }, - ); - - await expect - .poll(() => directSnapSortChildTexts(outerContainer)) - .toEqual([ - "Item 1", - "Item 1.5", - "Sub A1", - "Sub A2Sub A3", - "Item 2", - "Item 3", - ]); - expect( - consoleMessages.filter((message) => - /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( - message, - ), - ), - ).toHaveLength(0); - }); - - test("commits the hovered slot inside a locked nested container without animation", async ({ - page, - }) => { - await page.goto( - "/?demo=drop_snap_nested&disableNestedFlip=1&lockNestedChild=1", - { - waitUntil: "networkidle", - }, - ); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const item = await itemByTextIn(nested, "Item 1"); - const target = await itemByTextIn(nested, "Sub A3"); - await dragToItemFraction(page, item, "Item 1", 0, target, 0.85); - - const innerContainer = nested.locator(".snapsort-container").nth(1); - await expect(innerContainer).toBeVisible(); - await expect - .poll(() => directSnapSortItemTexts(innerContainer)) - .toEqual(["Sub A1", "Sub A2", "Sub A3", "Item 1"]); - }); - - test("places an item below a projected locked nested container without entering it", async ({ - page, - }) => { - await page.goto( - "/?demo=drop_snap_nested&disableNestedFlip=1&lockNestedChild=1", - { - waitUntil: "networkidle", - }, - ); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const outerContainer = nested.locator(".snapsort-container").first(); - const item = await itemByTextIn(nested, "Item 1"); - const target = await itemByTextIn(nested, "Item 2"); - await dragToItemFraction(page, item, "Item 1", 0, target, 0.5, { - steps: 70, - }); - - await expect - .poll(() => directSnapSortChildTexts(outerContainer)) - .toEqual([ - "Item 1.5", - "Sub A1Sub A2Sub A3", - "Item 2", - "Item 1", - "Item 3", - ]); - }); - - test("commits the first nested item slot without animation", async ({ - page, - }) => { - await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const item = await itemByTextIn(nested, "Item 1"); - const target = await itemByTextIn(nested, "Sub A1"); - await dragToItemFraction(page, item, "Item 1", 0, target, 1.05, { - steps: 70, - }); - - const innerContainer = nested.locator(".snapsort-container").nth(1); - await expect(innerContainer).toBeVisible(); - await expect - .poll(() => directSnapSortItemTexts(innerContainer)) - .toEqual(["Sub A1", "Item 1", "Sub A2", "Sub A3"]); - }); - - test("commits the hovered nested slot while animation moves the container", async ({ - page, - }) => { - await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { - waitUntil: "networkidle", - }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const item = await itemByTextIn(nested, "Item 1"); - const target = await itemByTextIn(nested, "Sub A3"); - await dragToItemFraction(page, item, "Item 1", 0, target, 0.85); - - const innerContainer = nested.locator(".snapsort-container").nth(1); - await expect(innerContainer).toBeVisible(); - await expect - .poll(() => directSnapSortItemTexts(innerContainer)) - .toEqual(["Sub A1", "Sub A2", "Sub A3", "Item 1"]); - }); - - test("updates framework state when SnapSort move callbacks reorder an array list", async ({ - page, - }) => { - await page.goto("/?demo=snapsort_components", { - waitUntil: "networkidle", - }); - - const list = await componentArrayList(page); - const kanbanPanel = page.locator(".kanban-panel"); - await expect(page.locator(".demo-header p")).toHaveText( - "6 Euclidean cards plus Progressive sentence demos", - ); - - await kanbanPanel.getByRole("button", { name: "Add Item" }).click(); - await expect(page.locator(".demo-header p")).toHaveText( - "7 Euclidean cards plus Progressive sentence demos", - ); - await expect(list.locator(".task-card")).toHaveCount(5); - - const deleteButton = page.getByRole("button", { name: "Delete Task 7" }); - await deleteButton.click(); - await expect(page.locator(".demo-header p")).toHaveText( - "6 Euclidean cards plus Progressive sentence demos", - ); - await expect(list.locator(".task-card")).toHaveCount(4); - - const upwardItem = await itemByTextIn(list, "Search filters"); - const upwardItemRect = await itemRect(upwardItem); - const upwardItemCenter = center(upwardItemRect); - const upwardTarget = await itemByTextIn(list, "Invite flow"); - const upwardTargetCenter = center(await itemRect(upwardTarget)); - - await dragBy( - page, - upwardItem, - "Search filters", - 0, - { - x: 0, - y: upwardTargetCenter.y - upwardItemCenter.y - 24, - }, - { - start: { - x: upwardItemRect.x + 24, - y: upwardItemCenter.y, - }, - }, - ); - - await expect(list.locator(".task-card .task-main strong")).toHaveText([ - "Profile fields", - "Search filters", - "Invite flow", - "Audit log", - ]); - - await kanbanPanel.getByRole("button", { name: "Reset" }).click(); - await expect(page.locator(".demo-header p")).toHaveText( - "6 Euclidean cards plus Progressive sentence demos", - ); - - const item = await itemByTextIn(list, "Profile fields"); - const itemRectValue = await itemRect(item); - const itemCenter = center(itemRectValue); - const target = await itemByTextIn(list, "Search filters"); - const targetCenter = center(await itemRect(target)); - - await dragBy( - page, - item, - "Profile fields", - 0, - { - x: 0, - y: targetCenter.y - itemCenter.y + 16, - }, - { - start: { - x: itemRectValue.x + 24, - y: itemCenter.y, - }, - }, - ); - - await expect( - page.locator(".task-card").filter({ hasText: "Profile fields" }), - ).toHaveCount(1); - - await expect(page.locator(".demo-header p")).toHaveText( - "6 Euclidean cards plus Progressive sentence demos", - ); - await expect(list.locator(".task-card .task-main strong")).toHaveText([ - "Invite flow", - "Audit log", - "Search filters", - "Profile fields", - ]); - }); - - test("animates a component card moving between columns with SnapEngine FLIP", async ({ - page, - }) => { - await page.goto("/?demo=snapsort_components", { - waitUntil: "networkidle", - }); - - await page.evaluate(() => { - const win = window as typeof window & { - __snapsortMoveComponentItem?: ( - itemId: string, - direction: -1 | 1, - ) => void; - }; - win.__snapsortMoveComponentItem?.("item-1", 1); - }); - - const animated = await page.evaluate(async () => { - for (let frame = 0; frame < 10; frame++) { - await new Promise((resolve) => requestAnimationFrame(resolve)); - const animatedCard = [...document.querySelectorAll(".task-card")].find( - (element) => - /^translate3d\(-?\d/.test((element as HTMLElement).style.transform), - ); - if (animatedCard) { - return true; - } - } - return false; - }); - - expect(animated).toBe(true); - - const panels = page.locator(".list-panel"); - await expect( - panels.nth(0).locator(".task-card .task-main strong"), - ).toHaveText(["Invite flow", "Audit log", "Search filters"]); - await expect( - panels.nth(1).locator(".task-card .task-main strong"), - ).toHaveText(["Profile fields", "Board polish"]); - }); - - test("animates framework-owned programmatic removal but not direct state deletion", async ({ - page, - }) => { - const observesTransform = async () => - page.evaluate(async () => { - for (let frame = 0; frame < 10; frame++) { - await new Promise((resolve) => requestAnimationFrame(resolve)); - const animatedCard = [ - ...document.querySelectorAll(".array-list .task-card"), - ].find((element) => - /^translate3d\(-?\d/.test((element as HTMLElement).style.transform), - ); - if (animatedCard) return true; - } - return false; - }); - - await page.goto("/?demo=snapsort_components&slowFlip=1", { - waitUntil: "networkidle", - }); - await page.evaluate(() => { - const demoWindow = window as typeof window & { - __snapsortDeleteComponentItem?: (itemId: string) => void; - }; - demoWindow.__snapsortDeleteComponentItem?.("item-1"); - }); - expect(await observesTransform()).toBe(false); - - await page.goto("/?demo=snapsort_components&slowFlip=1", { - waitUntil: "networkidle", - }); - const accepted = await page.evaluate(() => { - const demoWindow = window as typeof window & { - __snapsortRemoveComponentItem?: (itemId: string) => boolean; - }; - return demoWindow.__snapsortRemoveComponentItem?.("item-1") ?? false; - }); - expect(accepted).toBe(true); - expect(await observesTransform()).toBe(true); - await expect( - page.locator(".array-list .task-card .task-main strong"), - ).toHaveText(["Invite flow", "Audit log", "Search filters"]); - }); - - test("resets pooled animation variables before a channel is reused", async ({ - page, - }) => { - await page.goto("/?demo=snapsort_components", { - waitUntil: "networkidle", - }); - - const animationModuleUrl = `/@fs${process.cwd()}/src/animation.ts`; - const result = await page.evaluate(async (moduleUrl) => { - const { AnimationObject } = await import(/* @vite-ignore */ moduleUrl); - const target = document.createElement("div"); - document.body.appendChild(target); - - const first = new AnimationObject( - target, - { $value: [0, 1] }, - { duration: 40 }, - ); - first.play(); - for (let frame = 0; frame < 20 && !first.requestDelete; frame++) { - await new Promise((resolve) => - requestAnimationFrame(() => resolve()), - ); - } - - const propertiesAfterFinish = Array.from(target.style).filter((name) => - name.startsWith("--snap-var-"), - ); - const samples: number[] = []; - const second = new AnimationObject( - target, - { $value: [0.25, 0.75] }, - { - duration: 800, - tick: (values: Record) => samples.push(values.$value), - }, - ); - const acquiredProperties = Array.from(target.style) - .filter((name) => name.startsWith("--snap-var-")) - .map((name) => target.style.getPropertyValue(name)); - second.play(); - second.progress = 0; - second.calculateFrame(performance.now()); - second.cancel(); - target.remove(); - - return { - acquiredProperties, - firstSample: samples[0] ?? null, - propertiesAfterFinish, - }; - }, animationModuleUrl); - - expect(result.propertiesAfterFinish).toEqual([]); - expect(result.acquiredProperties).toHaveLength(1); - expect(Number(result.acquiredProperties[0])).toBeCloseTo(0.25); - expect(result.firstSample).toBeCloseTo(0.25); - }); - - test("installs the drop inverse before the first post-release paint", async ({ - page, - }) => { - await page.goto("/?demo=snapsort_components&slowFlip=1", { - waitUntil: "networkidle", - }); - - const moveComponentItem = async (direction: -1 | 1) => { - await page.evaluate((nextDirection) => { - const win = window as typeof window & { - __snapsortMoveComponentItem?: ( - itemId: string, - direction: -1 | 1, - ) => void; - }; - win.__snapsortMoveComponentItem?.("item-1", nextDirection); - }, direction); - }; - await moveComponentItem(1); - await page.waitForTimeout(900); - await moveComponentItem(-1); - await page.waitForTimeout(900); - - const card = page - .locator(".task-card:not(.snapsort-ghost)") - .filter({ hasText: "Profile fields" }); - const target = page - .locator(".task-card:not(.snapsort-ghost)") - .filter({ hasText: "Board polish" }); - const start = center(await itemRect(card.locator(".task-drag-handle"))); - const targetRect = await itemRect(target); - const releasePoint = { - x: targetRect.x + targetRect.width / 2, - y: targetRect.y + targetRect.height * 0.8, - }; - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x + 5, start.y); - await page.waitForTimeout(16); - await page.mouse.move(releasePoint.x, releasePoint.y, { steps: 24 }); - await page.waitForTimeout(80); - const releaseRect = await itemRect(card); - - await page.evaluate(() => { - const win = window as typeof window & { - __dropFlipSamples?: Array<{ - column: string; - transform: string; - x: number; - y: number; - }>; - }; - win.__dropFlipSamples = []; - window.addEventListener( - "pointerup", - () => { - let frame = 0; - const sample = () => { - const card = [ - ...document.querySelectorAll( - ".task-card:not(.snapsort-ghost)", - ), - ].find((element) => - element.textContent?.includes("Profile fields"), - ); - if (card) { - const rect = card.getBoundingClientRect(); - win.__dropFlipSamples?.push({ - column: - card - .closest(".list-panel") - ?.querySelector("h2") - ?.textContent?.trim() ?? "", - transform: card.style.transform, - x: rect.x, - y: rect.y, - }); - } - frame++; - if (frame < 12) requestAnimationFrame(sample); - }; - requestAnimationFrame(sample); - }, - { capture: true, once: true }, - ); - }); - - await page.mouse.up(); - await page.waitForTimeout(250); - const samples = await page.evaluate(() => { - const win = window as typeof window & { - __dropFlipSamples?: Array<{ - column: string; - transform: string; - x: number; - y: number; - }>; - }; - return win.__dropFlipSamples ?? []; - }); - await page.waitForTimeout(700); - const finalRect = await itemRect(card); - const activeSamples = samples.filter( - (sample) => sample.column === "Active", - ); - expect(activeSamples.length).toBeGreaterThan(1); - expect(activeSamples[0].transform).toMatch(/^translate3d\(/); - - const distanceTo = (sample: { x: number; y: number }, rect: Rect) => - Math.hypot(sample.x - rect.x, sample.y - rect.y); - expect(distanceTo(activeSamples[0], releaseRect)).toBeLessThan(8); - expect(distanceTo(activeSamples[0], finalRect)).toBeGreaterThan(12); - - const distancesToFinal = activeSamples.map((sample) => - distanceTo(sample, finalRect), - ); - for (let index = 1; index < distancesToFinal.length; index++) { - expect(distancesToFinal[index]).toBeLessThanOrEqual( - distancesToFinal[index - 1] + 3, - ); - } - }); - - test("does not flicker the spacer backward while dragging down a vertical column", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); - const item = await itemByTextIn(verticalColumn, "Item 1"); - const target = await itemByTextIn(verticalColumn, "Item 4"); - const itemCenter = center(await itemRect(item)); - const targetCenter = center(await itemRect(target)); - const samples = await dragBy(page, item, "Item 1", 0, { - x: 0, - y: targetCenter.y - itemCenter.y + 48, - }); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("vertical-column-flicker-trace.json"), - ); - expectNoSpacerBacktrack(samples, "y"); - expectNoSpacerOscillation(samples); - expectGhostUpdatesStable(consoleMessages, 5); - }); - - test("does not flicker the spacer upward while dragging into a wrapped horizontal row", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const horizontalRow = await demoBoxByHeading(page, "Horizontal Row"); - const item = await itemByTextIn(horizontalRow, "Item 1"); - const target = await itemByTextIn(horizontalRow, "Item 4"); - const itemCenter = center(await itemRect(item)); - const targetCenter = center(await itemRect(target)); - const samples = await dragBy(page, item, "Item 1", 0, { - x: 0, - y: targetCenter.y - itemCenter.y, - }); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("horizontal-row-wrap-flicker-trace.json"), - ); - expectNoSpacerBacktrack(samples, "y"); - expectNoSpacerOscillation(samples); - expectGhostUpdatesStable(consoleMessages, 3); - }); - - test("does not flicker out of a nested column after entering it", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const item = await itemByTextIn(nested, "Item 1"); - const target = await itemByTextIn(nested, "Sub A3"); - const samples = await dragTo(page, item, "Item 1", 0, target); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("nested-container-flicker-trace.json"), - { assertCenter: false }, - ); - expectNoNestedParentFlicker(samples); - expectGhostUpdatesStable(consoleMessages, 6); - }); - - test("can reach nested column boundary slots while dragging root item downward", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const nested = await demoBoxByHeading(page, "Nested Container"); - const item = await itemByTextIn(nested, "Item 1"); - const item3 = await itemByTextIn(nested, "Item 3"); - const itemCenter = center(await itemRect(item)); - const item3Center = center(await itemRect(item3)); - const samples = await dragBy( - page, - item, - "Item 1", - 0, - { - x: 0, - y: item3Center.y - itemCenter.y + 96, - }, - { steps: 240 }, - ); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("nested-boundary-slots-trace.json"), - { assertCenter: false }, - ); - - const states = compressedSpacerStates(samples); - const ghostTargets = ghostInsertionTargets(consoleMessages); - await writeJson(testInfo.outputPath("nested-boundary-slots-states.json"), { - states, - ghostTargets, - }); - - expect( - states, - `ghost should visit nested container boundary slots; observed ${states.join(" -> ")}`, - ).toEqual(expect.arrayContaining(["nested-inner[0]", "nested-inner[3]"])); - }); - - test("creates a spacer when dragging a sub-container as an item", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const cell = await demoBoxByHeading(page, "Draggable Sub-Containers"); - const source = cell - .locator(".snapsort-container .snapsort-container") - .filter({ hasText: "Group 1 - A" }) - .first(); - await expect(source).toBeVisible(); - const target = await itemByTextIn(cell, "Loose Item"); - const sourceRect = await itemRect(source); - const targetCenter = center(await itemRect(target)); - const start = { x: sourceRect.x + 8, y: sourceRect.y + 8 }; - const samples = await dragBy( - page, - source, - "Group 1", - 0, - { - x: targetCenter.x - start.x, - y: targetCenter.y - start.y, - }, - { start, assertCenter: false }, - ); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("drag-container-trace.json"), - { assertCenter: false }, - ); - expect( - samples.some((sample) => sample.spacerCount === 1 && sample.spacer), - "dragging a sub-container should create and move a spacer", - ).toBe(true); - }); - - test("keeps layer-panel ghost aligned below a labeled sub-container", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const layers = await demoBoxByHeading(page, "Layers Panel"); - const header = await itemByTextIn(layers, "Header"); - const hero = layers - .locator(".snapsort-container") - .filter({ hasText: "Hero Section" }) - .nth(1); - await expect(hero).toBeVisible(); - const headerRect = await itemRect(header); - const headerCenter = center(headerRect); - const heroRect = await itemRect(hero); - const targetCenterY = - heroRect.y + heroRect.height + headerRect.height / 2 + 12; - const samples = await dragBy( - page, - header, - "Header", - 0, - { - x: 0, - y: targetCenterY - headerCenter.y, - }, - { steps: 240 }, - ); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("layers-panel-offset-trace.json"), - { assertCenter: false }, - ); - expectSpacerAlignedAfterPrevious(samples, "layers-root", /Hero Section/); - expectSpacerNearDragged(samples, "layers-root", 48); - }); - - test("keeps draggable sub-container ghost aligned after resized groups", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - - const cell = await demoBoxByHeading(page, "Draggable Sub-Containers"); - const group1B = await itemByTextIn(cell, "Group 1 - B"); - const group2 = cell - .locator(".snapsort-container") - .filter({ hasText: "Group 2 - A" }) - .nth(1); - await expect(group2).toBeVisible(); - const group1BRect = await itemRect(group1B); - const group1BCenter = center(group1BRect); - const group2Rect = await itemRect(group2); - const targetCenterY = - group2Rect.y + group2Rect.height + group1BRect.height / 2 + 12; - const samples = await dragBy( - page, - group1B, - "Group 1 - B", - 0, - { - x: 0, - y: targetCenterY - group1BCenter.y, - }, - { steps: 240 }, - ); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("drag-subcontainer-offset-trace.json"), - { assertCenter: false }, - ); - expectSpacerAlignedAfterPrevious(samples, "drag-root", /Group 2 - A/); - expectSpacerNearDragged(samples, "drag-root", 48); - }); - - test("keeps one stable spacer while reordering a flat nested-items list", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - await page.screenshot({ - path: testInfo.outputPath("nested-flat-before.png"), - fullPage: true, - }); - - const item = await itemByText(page, "Item B"); - const samples = await dragBy(page, item, "Item B", 0, { x: 0, y: 110 }); - await page.screenshot({ - path: testInfo.outputPath("nested-flat-after.png"), - fullPage: true, - }); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("nested-flat-trace.json"), - ); - }); - - test("keeps nested container drop prediction stable for padded sub-items", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - await page.screenshot({ - path: testInfo.outputPath("nested-subitem-before.png"), - fullPage: true, - }); - - const item = await itemByText(page, "Sub A2"); - const samples = await dragBy(page, item, "Sub A2", 0, { x: 0, y: 95 }); - await page.screenshot({ - path: testInfo.outputPath("nested-subitem-after.png"), - fullPage: true, - }); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("nested-subitem-trace.json"), - ); - }); - - test("resolves multiple-drop-area container conflicts without spacer flicker", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - await page.screenshot({ - path: testInfo.outputPath("multi-area-before.png"), - fullPage: true, - }); - - const item = await itemByText(page, "Item B"); - const target = await itemByText(page, "Item Y"); - const samples = await dragTo(page, item, "Item B", 0, target); - await page.screenshot({ - path: testInfo.outputPath("multi-area-after.png"), - fullPage: true, - }); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("multi-area-trace.json"), - ); - }); - - test("keeps wrapped row indices aligned beyond the first row", async ({ - page, - }, testInfo) => { - const consoleMessages: string[] = []; - page.on("console", (message) => consoleMessages.push(message.text())); - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - const doubleRow = await demoBoxByHeading(page, "Horizontal Double Row"); - await page.screenshot({ - path: testInfo.outputPath("wrapped-row-before.png"), - fullPage: true, - }); - - const item = await itemByTextIn(doubleRow, "Item 1"); - const target = await itemByTextIn(doubleRow, "Item 9"); - const samples = await dragTo(page, item, "Item 1", 0, target); - await page.screenshot({ - path: testInfo.outputPath("wrapped-row-after.png"), - fullPage: true, - }); - - await expectStableDrag( - page, - samples, - consoleMessages, - testInfo.outputPath("wrapped-row-trace.json"), - ); - - const order = await doubleRow - .locator(".snapsort-item") - .evaluateAll((elements) => - elements.map((element) => element.textContent?.trim()), - ); - expect(order.slice(0, 10)).toEqual([ - "Item 2", - "Item 3", - "Item 4", - "Item 5", - "Item 6", - "Item 7", - "Item 8", - "Item 9", - "Item 1", - "Item 10", - ]); - }); - - test("renders one ghost per member (not a merged group ghost) during a multi-item drag", async ({ - page, - }) => { - await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); - const column = await demoBoxByHeading(page, "Vertical Column"); - - // Multi-select Item 2 + Item 3 (cmd/ctrl-click), then drag the pair down. - const item2 = await itemByTextIn(column, "Item 2"); - const item3 = await itemByTextIn(column, "Item 3"); - await item2.click(); - await item3.click({ modifiers: ["Meta"] }); - - const start = center(await itemRect(item2)); - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x + 4, start.y + 4); - await page.waitForTimeout(60); - - let ghostCountMidDrag = 0; - for (let step = 1; step <= 14; step++) { - await page.mouse.move(start.x, start.y + 120 * (step / 14)); - await page.waitForTimeout(20); - ghostCountMidDrag = await page.evaluate( - () => document.querySelectorAll("#spacer").length, - ); - } - - // The two dragged members must each get their own ghost anchor — the core - // no longer collapses the group into a single merged spacer. - expect(ghostCountMidDrag).toBe(2); - - await page.mouse.up(); - await page.waitForTimeout(300); - - // Ghosts are cleaned up and the pair lands as a contiguous run. - expect( - await page.evaluate(() => document.querySelectorAll("#spacer").length), - ).toBe(0); - const order = await column - .locator(".snapsort-item") - .evaluateAll((elements) => - elements.map((element) => element.textContent?.trim()), - ); - expect(order).toEqual(["Item 1", "Item 4", "Item 2", "Item 3"]); - }); -}); diff --git a/tests/e2e/snapsort-examples-features.spec.ts b/tests/e2e/snapsort-examples-features.spec.ts deleted file mode 100644 index 71ea11c9..00000000 --- a/tests/e2e/snapsort-examples-features.spec.ts +++ /dev/null @@ -1,888 +0,0 @@ -import { expect, test, type Locator, type Page } from "@playwright/test"; -import type { DragStartEvent } from "@snap-engine/snapsort"; - -async function gotoCompleteExamples(page: Page) { - await page.goto("/docs/snapsort/examples/complete-interfaces", { - waitUntil: "networkidle", - }); -} - -async function rect(locator: Locator) { - const box = await locator.boundingBox(); - if (!box) throw new Error("Expected locator to have a bounding box."); - return box; -} - -function center(box: { x: number; y: number; width: number; height: number }) { - return { x: box.x + box.width / 2, y: box.y + box.height / 2 }; -} - -function centerDistance( - a: { x: number; y: number; width: number; height: number }, - b: { x: number; y: number; width: number; height: number }, -) { - const aCenter = center(a); - const bCenter = center(b); - return Math.hypot(aCenter.x - bCenter.x, aCenter.y - bCenter.y); -} - -async function overrideDragVisual( - page: Page, - selector: string, - dragVisual: "item" | "preview" | "none", -) { - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; - await page.evaluate( - async ({ coreImportPath, selector, dragVisual }) => { - const { GlobalManager } = await import(coreImportPath); - const element = document.querySelector(selector); - const containers = - GlobalManager.getInstance().data.dragAndDropContainers ?? []; - const container = containers.find( - (candidate) => candidate.element === element, - ); - if (!container) { - throw new Error(`Could not find SnapSort container ${selector}.`); - } - const callbacks = container.callbacks; - const original = callbacks.onDragStart; - container.callbacks = { - ...callbacks, - onDragStart: (event: DragStartEvent) => { - const result = original?.(event); - if (result === false) return false; - event.session.dragVisual = dragVisual; - return result; - }, - }; - }, - { coreImportPath, selector, dragVisual }, - ); -} - -/** - * Drag `source` onto `target`, using a real pointer-move sequence (not a - * single jump) so SnapSort's drag-threshold and per-move drop-target - * resolution both get a chance to run, matching how a real user drags. - */ -async function dragOnto( - page: Page, - source: Locator, - target: Locator, - options: { - steps?: number; - xOffset?: number; - yOffset?: number; - targetPoint?: (box: { - x: number; - y: number; - width: number; - height: number; - }) => { x: number; y: number }; - beforeDrop?: () => Promise; - afterDrop?: () => Promise; - } = {}, -) { - const sourceBox = await rect(source); - const start = center(sourceBox); - const steps = options.steps ?? 24; - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x + 6, start.y + 6); - await page.waitForTimeout(60); - - const targetBox = await rect(target); - const end = options.targetPoint?.(targetBox) ?? { - x: targetBox.x + targetBox.width / 2 + (options.xOffset ?? 0), - y: targetBox.y + targetBox.height / 2 + (options.yOffset ?? 0), - }; - - for (let step = 1; step <= steps; step++) { - const t = step / steps; - await page.mouse.move( - start.x + (end.x - start.x) * t, - start.y + (end.y - start.y) * t, - ); - await page.waitForTimeout(16); - } - - await page.waitForTimeout(80); - await options.beforeDrop?.(); - await page.mouse.up(); - await options.afterDrop?.(); - await page.waitForTimeout(250); -} - -test.describe("SnapSort complete-interface examples", () => { - test.beforeEach(async ({ page }) => { - await gotoCompleteExamples(page); - }); - - test("complete interfaces expose all eight demos and stay usable on mobile", async ({ - page, - }) => { - await expect(page.locator("[data-demo-code-tabs]")).toHaveCount(8); - await expect(page.locator("[data-snapsort-example]")).toHaveCount(8); - await expect(page.getByRole("tab", { name: "Svelte source" })).toHaveCount( - 8, - ); - - await page.setViewportSize({ width: 390, height: 844 }); - const kanban = page.locator('[data-snapsort-example="kanban-board"]'); - await kanban.scrollIntoViewIfNeeded(); - await expect(kanban).toBeVisible(); - await expect(kanban.locator(".kanban-column")).toHaveCount(3); - const viewportWidth = await page.locator("html").evaluate((element) => ({ - clientWidth: element.clientWidth, - scrollWidth: element.scrollWidth, - })); - expect(viewportWidth.scrollWidth).toBeLessThanOrEqual( - viewportWidth.clientWidth, - ); - }); - - test("TODO List reorders through its drag handle", async ({ page }) => { - const example = page.locator('[data-snapsort-example="todo-list"]'); - await example.scrollIntoViewIfNeeded(); - const cards = example.locator(".project-card"); - - await expect( - example.getByRole("checkbox", { name: "Plan the grocery run" }), - ).toHaveAccessibleName("Plan the grocery run"); - await expect( - example.getByRole("checkbox", { name: "Take an evening walk" }), - ).toBeChecked(); - - await dragOnto( - page, - cards.first().locator(".project-drag-handle"), - cards.nth(3), - { - targetPoint: (box) => ({ - x: box.x + 28, - y: box.y + box.height * 0.82, - }), - }, - ); - - await expect(example.locator(".project-text").first()).not.toHaveText( - "Plan the grocery run", - ); - }); - - test("none visual still animates a flow-mode drop", async ({ page }) => { - const example = page.locator('[data-snapsort-example="todo-list"]'); - await example.scrollIntoViewIfNeeded(); - await overrideDragVisual( - page, - '[data-snapsort-example="todo-list"] .snapsort-container', - "none", - ); - - const items = example.locator(".snapsort-item"); - const dragged = items.first(); - const draggedId = await dragged.getAttribute("data-snapsort-item-id"); - expect(draggedId).toBeTruthy(); - if (!draggedId) throw new Error("Expected the dragged item to have an ID."); - const movedItem = page.locator(`[data-snapsort-item-id="${draggedId}"]`); - await dragOnto( - page, - dragged.locator(".project-drag-handle"), - items.nth(3), - { - targetPoint: (box) => ({ - x: box.x + 28, - y: box.y + box.height * 0.82, - }), - beforeDrop: async () => { - await expect( - page.locator('[data-snapsort-ghost="pointer"]'), - ).toHaveCount(0); - }, - afterDrop: async () => { - await expect - .poll( - () => - movedItem.evaluate( - (node) => getComputedStyle(node).transform !== "none", - ), - { intervals: [10, 20, 40], timeout: 500 }, - ) - .toBe(true); - }, - }, - ); - - await expect(example.locator(".project-text").first()).not.toHaveText( - "Plan the grocery run", - ); - }); - - test("Kanban Board moves a card between columns", async ({ page }) => { - const example = page.locator('[data-snapsort-example="kanban-board"]'); - await example.scrollIntoViewIfNeeded(); - const columns = example.locator(".kanban-column"); - - await dragOnto( - page, - columns.first().locator(".kanban-card").first(), - columns.nth(1), - { - targetPoint: (box) => ({ - x: box.x + box.width / 2, - y: box.y + box.height - 90, - }), - }, - ); - - await expect(columns.nth(1)).toContainText("Fix Bug #12"); - }); - - test("File Explorer moves a file into a nested folder", async ({ page }) => { - const example = page.locator('[data-snapsort-example="file-explorer"]'); - await example.scrollIntoViewIfNeeded(); - const source = example - .locator(".tree-row.file-row") - .filter({ hasText: "package.json" }); - const target = example.locator(".tree-folder").filter({ hasText: "docs" }); - - await dragOnto(page, source, target, { - targetPoint: (box) => ({ - x: box.x + box.width * 0.8, - y: box.y + box.height - 14, - }), - }); - - await expect(target).toContainText("package.json"); - }); - - test("File Explorer exposes separate keyboard controls for disclosure and selection", async ({ - page, - }) => { - const example = page.locator('[data-snapsort-example="file-explorer"]'); - await example.scrollIntoViewIfNeeded(); - const selectSource = example.getByRole("button", { - name: "Select src", - exact: true, - }); - const selectPackage = example.getByRole("button", { - name: "Select package.json", - exact: true, - }); - - await expect(example.locator(".folder-row button button")).toHaveCount(0); - await expect(selectSource).toHaveAttribute("aria-pressed", "false"); - - const collapseSource = example.getByRole("button", { - name: "Collapse src", - exact: true, - }); - await collapseSource.focus(); - await page.keyboard.press("Enter"); - const expandSource = example.getByRole("button", { - name: "Expand src", - exact: true, - }); - await expect(expandSource).toBeFocused(); - await expect(selectSource).toHaveAttribute("aria-pressed", "false"); - - await page.keyboard.press("Space"); - await expect(collapseSource).toBeFocused(); - - await selectSource.focus(); - await page.keyboard.press("Space"); - await expect(selectSource).toHaveAttribute("aria-pressed", "true"); - - await selectPackage.focus(); - await page.keyboard.press("Enter"); - await expect(selectPackage).toHaveAttribute("aria-pressed", "true"); - await expect(selectSource).toHaveAttribute("aria-pressed", "false"); - }); - - test("sentence builder renders incorrect and correct application feedback", async ({ - page, - }) => { - const example = page.locator('[data-snapsort-example="sentence-builder"]'); - await example.scrollIntoViewIfNeeded(); - - await example.getByRole("button", { name: "Check" }).click(); - await expect(example.getByText("Incorrect, try again.")).toBeVisible(); - - for (const word of ["多く", "の", "用途", "が", "あり", "ます"]) { - await example - .getByRole("button", { name: `Move ${word} to answer` }) - .click(); - } - await example.getByRole("button", { name: "Check" }).click(); - await expect(example.getByText("Correct!")).toBeVisible(); - }); - - test("form editor adds and edits fields through application controls", async ({ - page, - }) => { - const example = page.locator('[data-snapsort-example="form-editor"]'); - await example.scrollIntoViewIfNeeded(); - - const fields = example.locator(".editor-field"); - await expect(fields).toHaveCount(3); - await example.getByRole("button", { name: "Long text" }).click(); - await expect(fields).toHaveCount(4); - - const addedQuestion = example - .getByRole("textbox", { - name: "Question text", - }) - .last(); - await addedQuestion.fill("Release notes"); - await expect(addedQuestion).toHaveValue("Release notes"); - - await example.getByRole("button", { name: "Multiple choice" }).click(); - await expect(fields).toHaveCount(5); - const newestField = fields.last(); - await expect( - newestField.getByRole("textbox", { name: "Option text" }), - ).toHaveCount(2); - await newestField.getByRole("button", { name: "Add option" }).click(); - await expect( - newestField.getByRole("textbox", { name: "Option text" }), - ).toHaveCount(3); - }); - - test.describe("Template Palette (move and backfill)", () => { - test("dragging a template moves its stable id to the canvas and backfills the palette", async ({ - page, - }) => { - const exhibit = page.locator('[data-snapsort-example="clone-palette"]'); - await exhibit.scrollIntoViewIfNeeded(); - - const palette = exhibit.locator(".clone-palette"); - const canvas = exhibit.locator(".clone-canvas"); - const buttonTemplate = palette - .locator(".snapsort-item") - .filter({ hasText: "Button" }); - const originalButtonId = await buttonTemplate.getAttribute( - "data-snapsort-item-id", - ); - expect(originalButtonId).toBeTruthy(); - if (!originalButtonId) { - throw new Error("Expected the Button template to have an item ID."); - } - - await expect(palette.locator(".snapsort-item")).toHaveCount(4); - await expect(canvas.locator(".clone-canvas-block")).toHaveCount(0); - - await dragOnto(page, buttonTemplate, canvas); - - // The palette still exposes the same template, but it is a freshly - // minted replacement. The original stable id is what moved. - await expect(palette.locator(".snapsort-item")).toHaveCount(4); - const replacementButton = palette - .locator(".snapsort-item") - .filter({ hasText: "Button" }); - await expect(replacementButton).toHaveCount(1); - await expect(replacementButton).not.toHaveAttribute( - "data-snapsort-item-id", - originalButtonId, - ); - - // The canvas gained the original item under its original stable id. - await expect(canvas.locator(".clone-canvas-block")).toHaveCount(1); - await expect(canvas.locator(".clone-canvas-block")).toContainText( - "Button", - ); - await expect( - canvas.locator(`[data-snapsort-item-id="${originalButtonId}"]`), - ).toHaveCount(1); - - // Dragging a second, different block clones onto the canvas too. - const imageTemplate = palette - .locator(".snapsort-item") - .filter({ hasText: "Image" }); - await dragOnto(page, imageTemplate, canvas, { yOffset: 40 }); - await expect(canvas.locator(".clone-canvas-block")).toHaveCount(2); - await expect(palette.locator(".snapsort-item")).toHaveCount(4); - - // Reordering an already-placed canvas block is a plain move, with no - // source backfill because it did not originate in the palette. - const canvasItems = canvas.locator(".snapsort-item"); - await dragOnto(page, canvasItems.nth(1), canvasItems.nth(0)); - await expect(canvas.locator(".clone-canvas-block")).toHaveCount(2); - await expect(canvas.locator(".clone-canvas-block").first()).toContainText( - "Image", - ); - - // Click-to-remove takes a placed block back out of the canvas. - const firstBlock = canvas.locator(".clone-canvas-block").first(); - await firstBlock.locator(".clone-block-remove").click(); - await expect(canvas.locator(".clone-canvas-block")).toHaveCount(1); - }); - - test("preview drag leaves templates in layout and cleans up when dropped outside a drop zone", async ({ - page, - }) => { - const exhibit = page.locator('[data-snapsort-example="clone-palette"]'); - await exhibit.scrollIntoViewIfNeeded(); - const palette = exhibit.locator(".clone-palette"); - const canvas = exhibit.locator(".clone-canvas"); - - const dividerTemplate = palette - .locator(".snapsort-item") - .filter({ hasText: "Divider" }); - - // Drag a palette block toward the canvas. `dragVisual = "preview"` - // leaves the real template in layout and represents the gesture with a - // pointer-role Ghost. - const src = await rect(dividerTemplate); - const dst = await rect(canvas); - const start = { x: src.x + src.width / 2, y: src.y + src.height / 2 }; - const end = { x: dst.x + dst.width / 2, y: dst.y + dst.height / 2 }; - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x + 6, start.y + 6); - await page.waitForTimeout(60); - let maxPaletteTargetGhosts = 0; - let sawPointerPreview = false; - for (let step = 1; step <= 16; step++) { - const t = step / 16; - await page.mouse.move( - start.x + (end.x - start.x) * t, - start.y + (end.y - start.y) * t, - ); - await page.waitForTimeout(20); - maxPaletteTargetGhosts = Math.max( - maxPaletteTargetGhosts, - await palette.evaluate( - (el) => - el.querySelectorAll('[data-snapsort-ghost-entry$="-spacer"]') - .length, - ), - ); - sawPointerPreview ||= - (await page.locator('[data-snapsort-ghost="pointer"]').count()) === 1; - } - await page.mouse.up(); - await page.waitForTimeout(250); - - expect(maxPaletteTargetGhosts).toBe(0); - expect(sawPointerPreview).toBe(true); - await expect(page.locator('[data-snapsort-ghost="pointer"]')).toHaveCount( - 0, - ); - await expect(palette.locator(".snapsort-item")).toHaveCount(4); - await expect(canvas.locator(".clone-canvas-block")).toHaveCount(1); - - // Now drag another block but release back over the palette (a rejected - // zone): no mutation commits and the preview is discarded. - const spacerTemplate = palette - .locator(".snapsort-item") - .filter({ hasText: "Spacer" }); - const spacerBox = await rect(spacerTemplate); - const spacerStart = { - x: spacerBox.x + spacerBox.width / 2, - y: spacerBox.y + spacerBox.height / 2, - }; - await page.mouse.move(spacerStart.x, spacerStart.y); - await page.mouse.down(); - await page.mouse.move(spacerStart.x, spacerStart.y + 40); - await page.waitForTimeout(60); - await page.mouse.move(spacerStart.x, spacerStart.y); - await page.waitForTimeout(60); - await page.mouse.up(); - await page.waitForTimeout(250); - - await expect(canvas.locator(".clone-canvas-block")).toHaveCount(1); - await expect(palette.locator(".snapsort-item")).toHaveCount(4); - await expect(page.locator('[data-snapsort-ghost="pointer"]')).toHaveCount( - 0, - ); - }); - }); - - test.describe("Trash It (none effect)", () => { - test("dropping a task on the trash removes it; other drags still reorder normally", async ({ - page, - }) => { - const exhibit = page.locator('[data-snapsort-example="trash-it"]'); - await exhibit.scrollIntoViewIfNeeded(); - - const list = exhibit.locator(".trash-list"); - const trashZone = exhibit.locator(".trash-drop-target"); - - await expect(list.locator(".trash-task")).toHaveCount(5); - const firstTaskText = ( - await list.locator(".trash-task").first().textContent() - )?.trim(); - const secondTaskText = ( - await list.locator(".trash-task").nth(1).textContent() - )?.trim(); - - // Reordering within the list (default move effect) still works. - const firstTask = list.locator(".snapsort-item").first(); - await dragOnto(page, firstTask, list.locator(".snapsort-item").nth(2)); - await expect(list.locator(".trash-task")).toHaveCount(5); - await expect(list.locator(".trash-task").first()).not.toContainText( - firstTaskText ?? "__never__", - ); - - // Dragging a task onto the trash deletes it instead of moving it there. - const taskToDelete = list - .locator(".snapsort-item") - .filter({ hasText: secondTaskText ?? "" }); - await dragOnto(page, taskToDelete, trashZone); - - await expect(list.locator(".trash-task")).toHaveCount(4); - await expect( - list.locator(".trash-task", { hasText: secondTaskText ?? "__never__" }), - ).toHaveCount(0); - // Nothing should have actually landed inside the trash container itself. - await expect(trashZone.locator(".trash-task")).toHaveCount(0); - }); - }); - - test.describe("Swap Grid (swap mode)", () => { - test("dragging a tile onto another swaps their positions and nothing else moves", async ({ - page, - }) => { - const exhibit = page.locator('[data-snapsort-example="swap-grid"]'); - await exhibit.scrollIntoViewIfNeeded(); - - const grid = exhibit.locator(".swap-grid"); - const tiles = grid.locator(".snapsort-item"); - await expect(tiles).toHaveCount(9); - - const beforeOrder = await grid - .locator(".swap-tile") - .evaluateAll((nodes) => - nodes.map((node) => node.textContent?.trim() ?? ""), - ); - expect(beforeOrder).toEqual([ - "A1", - "A2", - "A3", - "B1", - "B2", - "B3", - "C1", - "C2", - "C3", - ]); - - const tileA1 = tiles.filter({ hasText: "A1" }); - const tileB2 = tiles.filter({ hasText: "B2" }); - const sourceStart = await rect(tileA1); - const targetStart = await rect(tileB2); - let ghostRelease: Awaited> | null = null; - await dragOnto(page, tileA1, tileB2, { - xOffset: 32, - yOffset: -24, - beforeDrop: async () => { - const sourceTile = tileA1.locator(".swap-tile"); - const pointerGhost = page.locator('[data-snapsort-ghost="pointer"]'); - - await expect(pointerGhost).toBeVisible(); - await expect(pointerGhost).toContainText("A1"); - await expect(pointerGhost.locator(".swap-tile-grip i")).toHaveCount( - 6, - ); - - const appearances = await Promise.all( - [sourceTile, pointerGhost].map((locator) => - locator.evaluate((element) => { - const style = getComputedStyle(element); - return { - backgroundColor: style.backgroundColor, - borderRadius: style.borderRadius, - boxShadow: style.boxShadow, - fontFamily: style.fontFamily, - }; - }), - ), - ); - expect(appearances[1]).toEqual(appearances[0]); - ghostRelease = await rect(pointerGhost); - const expectedPointer = { - x: center(targetStart).x + 32, - y: center(targetStart).y - 24, - }; - expect( - Math.hypot( - center(ghostRelease).x - expectedPointer.x, - center(ghostRelease).y - expectedPointer.y, - ), - ).toBeLessThan(3); - expect(centerDistance(ghostRelease, sourceStart)).toBeGreaterThan(50); - }, - afterDrop: async () => { - await expect - .poll( - () => - grid - .locator(".snapsort-item") - .evaluateAll( - (nodes) => - nodes.filter( - (node) => getComputedStyle(node).transform !== "none", - ).length, - ), - { intervals: [10, 20, 40], timeout: 500 }, - ) - .toBeGreaterThanOrEqual(2); - - expect(ghostRelease).not.toBeNull(); - if (!ghostRelease) { - throw new Error( - "Expected the released pointer ghost to have bounds.", - ); - } - const expectedDraggedDelta = { - x: center(ghostRelease).x - center(targetStart).x, - y: center(ghostRelease).y - center(targetStart).y, - }; - const expectedDisplacedDelta = { - x: center(targetStart).x - center(sourceStart).x, - y: center(targetStart).y - center(sourceStart).y, - }; - const [draggedTransform, displacedTransform] = await Promise.all( - [tileA1, tileB2].map((locator) => - locator.evaluate((node) => { - const matrix = new DOMMatrixReadOnly( - getComputedStyle(node).transform, - ); - return { x: matrix.m41, y: matrix.m42 }; - }), - ), - ); - - expect(Math.sign(draggedTransform.x)).toBe( - Math.sign(expectedDraggedDelta.x), - ); - expect(Math.sign(draggedTransform.y)).toBe( - Math.sign(expectedDraggedDelta.y), - ); - expect(Math.abs(draggedTransform.x)).toBeLessThanOrEqual( - Math.abs(expectedDraggedDelta.x) + 1, - ); - expect(Math.abs(draggedTransform.y)).toBeLessThanOrEqual( - Math.abs(expectedDraggedDelta.y) + 1, - ); - expect(Math.sign(displacedTransform.x)).toBe( - Math.sign(expectedDisplacedDelta.x), - ); - expect(Math.sign(displacedTransform.y)).toBe( - Math.sign(expectedDisplacedDelta.y), - ); - expect(Math.abs(displacedTransform.x)).toBeLessThanOrEqual( - Math.abs(expectedDisplacedDelta.x) + 1, - ); - expect(Math.abs(displacedTransform.y)).toBeLessThanOrEqual( - Math.abs(expectedDisplacedDelta.y) + 1, - ); - }, - }); - - const afterOrder = await grid - .locator(".swap-tile") - .evaluateAll((nodes) => - nodes.map((node) => node.textContent?.trim() ?? ""), - ); - - // Only the two dragged/targeted slots change; everything else stays put. - expect(afterOrder).toEqual([ - "B2", - "A2", - "A3", - "B1", - "A1", - "B3", - "C1", - "C2", - "C3", - ]); - await expect(tiles).toHaveCount(9); - await expect(grid.locator('[data-snapsort-dragging="true"]')).toHaveCount( - 0, - ); - const tileOpacities = await grid - .locator(".swap-tile") - .evaluateAll((nodes) => - nodes.map((node) => getComputedStyle(node).opacity), - ); - expect(tileOpacities).toEqual(Array(9).fill("1")); - }); - - test("item visual hoists the real tile, keeps a source spacer, and still swaps", async ({ - page, - }) => { - const exhibit = page.locator('[data-snapsort-example="swap-grid"]'); - await exhibit.scrollIntoViewIfNeeded(); - await overrideDragVisual( - page, - '[data-snapsort-example="swap-grid"] .swap-grid', - "item", - ); - - const grid = exhibit.locator(".swap-grid"); - const tileA1 = grid.locator(".snapsort-item").filter({ hasText: "A1" }); - const tileB2 = grid.locator(".snapsort-item").filter({ hasText: "B2" }); - const start = await rect(tileA1); - const target = await rect(tileB2); - - await dragOnto(page, tileA1, tileB2, { - beforeDrop: async () => { - await expect(tileA1).toHaveCSS("position", "absolute"); - await expect( - grid.locator('[data-snapsort-ghost-entry$="-spacer"]'), - ).toHaveCount(1); - await expect( - page.locator('[data-snapsort-ghost="pointer"]'), - ).toHaveCount(0); - const live = await rect(tileA1); - expect(centerDistance(live, start)).toBeGreaterThan(40); - expect(centerDistance(live, target)).toBeLessThan(12); - }, - }); - - await expect(grid.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); - const order = await grid - .locator(".swap-tile") - .evaluateAll((nodes) => - nodes.map((node) => node.textContent?.trim() ?? ""), - ); - expect(order).toEqual([ - "B2", - "A2", - "A3", - "B1", - "A1", - "B3", - "C1", - "C2", - "C3", - ]); - }); - - test("none visual renders no pointer representation while hover targeting still swaps", async ({ - page, - }) => { - const exhibit = page.locator('[data-snapsort-example="swap-grid"]'); - await exhibit.scrollIntoViewIfNeeded(); - await overrideDragVisual( - page, - '[data-snapsort-example="swap-grid"] .swap-grid', - "none", - ); - - const grid = exhibit.locator(".swap-grid"); - const tileA1 = grid.locator(".snapsort-item").filter({ hasText: "A1" }); - const tileB2 = grid.locator(".snapsort-item").filter({ hasText: "B2" }); - await dragOnto(page, tileA1, tileB2, { - beforeDrop: async () => { - await expect(tileA1).not.toHaveCSS("position", "absolute"); - await expect(page.locator("[data-snapsort-ghost-entry]")).toHaveCount( - 0, - ); - await expect(tileB2.locator(".swap-tile")).toHaveClass( - /swap-tile-hovered/, - ); - }, - afterDrop: async () => { - await expect - .poll( - () => - tileA1.evaluate( - (node) => getComputedStyle(node).transform !== "none", - ), - { intervals: [10, 20, 40], timeout: 500 }, - ) - .toBe(true); - }, - }); - - const order = await grid - .locator(".swap-tile") - .evaluateAll((nodes) => - nodes.map((node) => node.textContent?.trim() ?? ""), - ); - expect(order).toEqual([ - "B2", - "A2", - "A3", - "B1", - "A1", - "B3", - "C1", - "C2", - "C3", - ]); - await expect(page.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); - }); - - test("dropping outside the grid animates the dragged tile back home", async ({ - page, - }) => { - const exhibit = page.locator('[data-snapsort-example="swap-grid"]'); - await exhibit.scrollIntoViewIfNeeded(); - - const grid = exhibit.locator(".swap-grid"); - const tileA2 = grid.locator(".snapsort-item").filter({ hasText: "A2" }); - const sourceStart = await rect(tileA2); - let ghostRelease: Awaited> | null = null; - - const exampleHeader = page.locator( - '[data-demo-code-tabs="swap-grid"] .demo-code-tabs-header', - ); - await dragOnto(page, tileA2, exampleHeader, { - beforeDrop: async () => { - ghostRelease = await rect( - page.locator('[data-snapsort-ghost="pointer"]'), - ); - }, - afterDrop: async () => { - await expect - .poll( - () => - tileA2.evaluate( - (node) => getComputedStyle(node).transform !== "none", - ), - { intervals: [10, 20, 40], timeout: 500 }, - ) - .toBe(true); - - expect(ghostRelease).not.toBeNull(); - if (!ghostRelease) { - throw new Error( - "Expected the released pointer ghost to have bounds.", - ); - } - const returningVisual = await rect(tileA2); - expect(centerDistance(returningVisual, ghostRelease)).toBeLessThan( - centerDistance(returningVisual, sourceStart), - ); - }, - }); - - const order = await grid - .locator(".swap-tile") - .evaluateAll((nodes) => - nodes.map((node) => node.textContent?.trim() ?? ""), - ); - expect(order).toEqual([ - "A1", - "A2", - "A3", - "B1", - "B2", - "B3", - "C1", - "C2", - "C3", - ]); - await expect(grid.locator('[data-snapsort-dragging="true"]')).toHaveCount( - 0, - ); - await expect(tileA2).toHaveCSS("transform", "none"); - await expect(tileA2.locator(".swap-tile")).toHaveCSS("opacity", "1"); - }); - }); -}); diff --git a/tests/e2e/snapsort-examples.playwright.config.ts b/tests/e2e/snapsort-examples.playwright.config.ts deleted file mode 100644 index a434b52c..00000000 --- a/tests/e2e/snapsort-examples.playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { defineConfig, devices } from "@playwright/test"; -import { dirname, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; - -const websitePort = Number(process.env.SNAPSORT_WEBSITE_TEST_PORT ?? 4317); -const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); - -export default defineConfig({ - testDir: ".", - testMatch: ["snapsort-examples-features.spec.ts"], - fullyParallel: false, - workers: 1, - reporter: [["list"]], - use: { - ...devices["Desktop Chrome"], - baseURL: `http://127.0.0.1:${websitePort}`, - screenshot: "only-on-failure", - trace: "retain-on-failure", - viewport: { width: 1400, height: 950 }, - }, - webServer: { - cwd: resolve(repoRoot, "website"), - command: `npx vite dev --host 127.0.0.1 --port ${websitePort} --strictPort`, - url: `http://127.0.0.1:${websitePort}/docs/snapsort/examples/complete-interfaces`, - reuseExistingServer: false, - timeout: 60_000, - }, -}); diff --git a/tests/e2e/snapsort-landing-regression.spec.ts b/tests/e2e/snapsort-landing-regression.spec.ts deleted file mode 100644 index 1925cfb5..00000000 --- a/tests/e2e/snapsort-landing-regression.spec.ts +++ /dev/null @@ -1,363 +0,0 @@ -import { expect, test, type Locator, type Page } from "@playwright/test"; - -async function directItemKeys(container: Locator): Promise { - return container.evaluate((element) => - Array.from(element.children) - .filter( - (child): child is HTMLElement => - child instanceof HTMLElement && - child.classList.contains("snapsort-item"), - ) - .map( - (child) => - child.dataset.snapsortItemId ?? - child.innerText.replace(/\s+/g, " ").trim(), - ), - ); -} - -async function expectFrameworkOrder(container: Locator, order: string[]) { - const frameworkOrder = await container.getAttribute("data-order"); - if (frameworkOrder !== null) { - expect(order).toEqual(frameworkOrder ? frameworkOrder.split(",") : []); - } -} - -async function box(locator: Locator) { - const value = await locator.boundingBox(); - if (!value) throw new Error("Expected a visible drag target."); - return value; -} - -function watchSnapSortProblems(page: Page): string[] { - const problems: string[] = []; - page.on("pageerror", (error) => problems.push(error.message)); - page.on("console", (message) => { - if ( - (message.type() === "error" || message.type() === "warning") && - message.text().includes("SnapSort") - ) { - problems.push(message.text()); - } - }); - return problems; -} - -async function reorderDirectItems( - page: Page, - container: Locator, - sourceIndex: number, - targetIndex: number, - options: { handle?: string; settleMs?: number } = {}, -): Promise { - const before = await directItemKeys(container); - const items = container.locator(":scope > .snapsort-item"); - const sourceItem = items.nth(sourceIndex); - const pointerTarget = options.handle - ? sourceItem.locator(options.handle).first() - : sourceItem; - const targetItem = items.nth(targetIndex); - const sourceBox = await box(pointerTarget); - const targetBox = await box(targetItem); - const start = { - x: sourceBox.x + sourceBox.width / 2, - y: sourceBox.y + sourceBox.height / 2, - }; - const movingDown = targetIndex > sourceIndex; - const end = { - x: targetBox.x + targetBox.width / 2, - y: targetBox.y + targetBox.height * (movingDown ? 0.82 : 0.18), - }; - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - await page.mouse.move(start.x + 7, start.y + 7); - - const ghost = container.locator( - ':scope > [data-snapsort-ghost-entry$="-spacer"]', - ); - await expect(ghost).toHaveCount(1); - - // Creating the next framework-owned ghost must never reconcile the list - // back to an older source-array order. - expect(await directItemKeys(container)).toEqual(before); - await expectFrameworkOrder(container, before); - - const dragging = page.locator("[data-snapsort-dragging]"); - await expect(dragging).toHaveCount(1); - await expect(dragging).toHaveCSS("position", "absolute"); - await expect(dragging).toHaveCSS("z-index", "1000"); - - const sampledCenters: Array<{ x: number; y: number }> = []; - for (let step = 1; step <= 14; step++) { - const t = step / 14; - await page.mouse.move( - start.x + (end.x - start.x) * t, - start.y + (end.y - start.y) * t, - ); - if (step % 4 === 0) { - const current = await box(dragging); - sampledCenters.push({ - x: current.x + current.width / 2, - y: current.y + current.height / 2, - }); - } - } - - expect(sampledCenters.length).toBeGreaterThan(1); - for (let index = 1; index < sampledCenters.length; index++) { - const previous = sampledCenters[index - 1]; - const current = sampledCenters[index]; - expect( - Math.hypot(current.x - previous.x, current.y - previous.y), - ).toBeGreaterThan(4); - } - - await page.mouse.up(); - await page.waitForTimeout(options.settleMs ?? 140); - await expect(ghost).toHaveCount(0); - await expect(page.locator("[data-snapsort-dragging]")).toHaveCount(0); - - const after = await directItemKeys(container); - expect(after).not.toEqual(before); - await expectFrameworkOrder(container, after); - return after; -} - -test.describe("SnapSort landing repeated-drag ownership", () => { - test("keeps the homepage Euclidean pad-grid drop and FLIP positions aligned", async ({ - page, - }) => { - const problems = watchSnapSortProblems(page); - await page.goto("/", { waitUntil: "networkidle" }); - - const bed = page.locator(".hero-button-bed"); - const grid = page.locator(".hero-button-grid .snapsort-container"); - await expect(grid).toHaveClass(/snapsort-mode-euclidean/); - const items = grid.locator(":scope > .snapsort-item"); - await expect(items).toHaveCount(16); - - const ghost = grid.locator( - ':scope > [data-snapsort-ghost-entry$="-spacer"]', - ); - let expected = await directItemKeys(grid); - - for (let drag = 0; drag < 12; drag++) { - const sourceIndex = drag % 2 === 0 ? 0 : 8; - const targetIndex = drag % 2 === 0 ? 8 : 0; - const source = items.nth(sourceIndex); - const target = items.nth(targetIndex); - const sourceBox = await box(source); - const targetBox = await box(target); - const start = { - x: sourceBox.x + sourceBox.width / 2, - y: sourceBox.y + sourceBox.height / 2, - }; - const end = { - x: targetBox.x + targetBox.width / 2, - y: targetBox.y + targetBox.height / 2, - }; - - await page.mouse.move(start.x, start.y); - await page.mouse.down(); - if (drag === 0) { - await page.waitForTimeout(60); - await expect( - source.locator(".hero-synth-button.is-active"), - ).toHaveCount(0); - } - await page.mouse.move(start.x + 8, start.y + 8); - await page.mouse.move(end.x, end.y, { steps: 12 }); - await expect(ghost).toHaveCount(1); - // WebKit may briefly release capture when Svelte inserts the initial - // framework-owned ghost. Send the final position again after the ghost - // exists to exercise capture recovery and the intended target update. - await page.mouse.move(end.x + 0.5, end.y + 0.5); - - const currentGhostIndex = () => - grid.evaluate((element) => { - let index = 0; - for (const child of element.children) { - if ( - child instanceof HTMLElement && - child.dataset.snapsortGhostEntry === "target-spacer" - ) { - return index; - } - if ( - child instanceof HTMLElement && - child.classList.contains("snapsort-item") && - child.dataset.snapsortDragging !== "true" - ) { - index++; - } - } - return -1; - }); - await expect - .poll(currentGhostIndex, { - message: `drag ${drag} should place the ghost at index ${targetIndex}`, - }) - .toBe(targetIndex); - - const bedBox = await box(bed); - const sourceId = expected[sourceIndex]; - const stationaryBoxes = await items.evaluateAll((elements) => - elements.map((element) => { - const rect = element.getBoundingClientRect(); - return { - id: element.dataset.snapsortItemId, - x: rect.x, - y: rect.y, - right: rect.right, - bottom: rect.bottom, - }; - }), - ); - for (const rect of stationaryBoxes) { - if (rect.id === sourceId) continue; - expect(rect.x).toBeGreaterThanOrEqual(bedBox.x - 1); - expect(rect.y).toBeGreaterThanOrEqual(bedBox.y - 1); - expect(rect.right).toBeLessThanOrEqual(bedBox.x + bedBox.width + 1); - expect(rect.bottom).toBeLessThanOrEqual(bedBox.y + bedBox.height + 1); - } - - await page.mouse.up(); - - const visualTrace = await page.evaluate( - async ({ itemId, duration }) => { - const samples: Array<{ - x: number; - y: number; - right: number; - bottom: number; - }> = []; - const start = performance.now(); - await new Promise((resolve) => { - const sample = () => { - const element = document.querySelector( - `.hero-button-grid .snapsort-item[data-snapsort-item-id="${itemId}"]`, - ); - if (element) { - const rect = element.getBoundingClientRect(); - samples.push({ - x: rect.x, - y: rect.y, - right: rect.right, - bottom: rect.bottom, - }); - } - if (performance.now() - start >= duration) { - resolve(); - } else { - requestAnimationFrame(sample); - } - }; - requestAnimationFrame(sample); - }); - return samples; - }, - { itemId: sourceId, duration: 24 }, - ); - await expect(ghost).toHaveCount(0); - await expect(page.locator("[data-snapsort-dragging]")).toHaveCount(0); - - const [moved] = expected.splice(sourceIndex, 1); - expected.splice(targetIndex, 0, moved); - await expect.poll(() => directItemKeys(grid)).toEqual(expected); - - const settledTargetBox = await box(items.nth(targetIndex)); - for (const rect of visualTrace) { - expect(rect.x).toBeGreaterThanOrEqual(bedBox.x - 1); - expect(rect.y).toBeGreaterThanOrEqual(bedBox.y - 1); - expect(rect.right).toBeLessThanOrEqual(bedBox.x + bedBox.width + 1); - expect(rect.bottom).toBeLessThanOrEqual(bedBox.y + bedBox.height + 1); - } - const finalVisual = visualTrace.at(-1); - expect(finalVisual).toBeDefined(); - expect(finalVisual!.x).toBeCloseTo(settledTargetBox.x, 0); - expect(finalVisual!.y).toBeCloseTo(settledTargetBox.y, 0); - } - - await page.waitForTimeout(140); - expect(problems).toEqual([]); - }); - - test("keeps the sortable list responsive and ordered through repeated drags", async ({ - page, - }) => { - const problems = watchSnapSortProblems(page); - await page.goto("/snapsort", { waitUntil: "networkidle" }); - const list = page.locator(".sortable-list"); - await list.scrollIntoViewIfNeeded(); - await expect(list.locator(":scope > .snapsort-item")).toHaveCount(6); - - for (let drag = 0; drag < 5; drag++) { - const down = drag % 2 === 0; - await reorderDirectItems(page, list, down ? 0 : 5, down ? 5 : 0, { - // Start the next gesture immediately after the configured 100ms FLIP - // window to exercise cleanup without hiding it behind long waits. - settleMs: 105, - }); - } - expect(problems).toEqual([]); - }); - - test("keeps the hero framework order authoritative on every gesture", async ({ - page, - }) => { - const problems = watchSnapSortProblems(page); - await page.goto("/snapsort", { waitUntil: "networkidle" }); - const hero = page.locator(".hero-stack").first(); - await expect(hero.locator(":scope > .snapsort-item")).toHaveCount(3); - - for (let drag = 0; drag < 4; drag++) { - const down = drag % 2 === 0; - await reorderDirectItems(page, hero, down ? 0 : 2, down ? 2 : 0, { - handle: ".hero-row-handle", - settleMs: 105, - }); - } - expect(problems).toEqual([]); - }); - - test("keeps each themed mini-list interactive with independent state", async ({ - page, - }) => { - const problems = watchSnapSortProblems(page); - await page.goto("/snapsort", { waitUntil: "networkidle" }); - const customizable = page.locator(".customizable-demo"); - await customizable.scrollIntoViewIfNeeded(); - await customizable.evaluate((element) => { - const rail = element.querySelector( - ".customizable-theme-rail", - ); - rail?.style.setProperty("transform", "translateX(0)", "important"); - for (const frame of element.querySelectorAll( - ".customizable-motion-frame", - )) { - frame.style.setProperty("transform", "translateY(0)", "important"); - frame.style.setProperty("transition", "none", "important"); - } - }); - - const retroList = page.locator( - '.customizable-surface[data-theme="retro"] .customizable-mini-list', - ); - const defaultList = page.locator( - '.customizable-surface[data-theme="default"] .customizable-mini-list', - ); - await retroList.scrollIntoViewIfNeeded(); - const defaultBefore = await directItemKeys(defaultList); - - for (let drag = 0; drag < 3; drag++) { - const down = drag % 2 === 0; - await reorderDirectItems(page, retroList, down ? 0 : 2, down ? 2 : 0, { - settleMs: 105, - }); - } - - expect(await directItemKeys(defaultList)).toEqual(defaultBefore); - expect(problems).toEqual([]); - }); -}); diff --git a/tests/e2e/snapsort-layout.playwright.config.ts b/tests/e2e/snapsort-layout.playwright.config.ts deleted file mode 100644 index 354b5fa4..00000000 --- a/tests/e2e/snapsort-layout.playwright.config.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Layout-engine test suite: unit tests for the pure flow-layout simulation -// (tests/ut/core-layout.spec.ts) plus the drag-snapshot layout e2e spec across -// chromium, firefox, and webkit. Cross-browser coverage matters here more -// than anywhere else in the repo: the layout engine reconciles simulated -// sums with browser-measured geometry, and each engine quantizes layout -// differently (Blink/WebKit 1/64px; Gecko 1/60px app units with ~1e-5px -// getBoundingClientRect conversion noise). -// -// Run with: npm run test:layout -import { defineConfig } from "@playwright/test"; -import { - frameworkBrowserProjects, - frameworkWebServers, -} from "./playwright-matrix"; - -export default defineConfig({ - testDir: "..", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - projects: [ - { - name: "layout-ut", - testMatch: ["ut/core-layout.spec.ts"], - }, - ...frameworkBrowserProjects({ - frameworks: ["svelte"], - browsers: ["chromium", "firefox", "webkit"], - testMatch: ["e2e/snapsort-drag-snapshot.spec.ts"], - }), - ], - webServer: frameworkWebServers(["svelte"]), -}); diff --git a/tests/e2e/snapsort.playwright.config.ts b/tests/e2e/snapsort.playwright.config.ts deleted file mode 100644 index 65b9565e..00000000 --- a/tests/e2e/snapsort.playwright.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { defineConfig } from "@playwright/test"; -import { - frameworkBrowserProjects, - frameworkWebServers, -} from "./playwright-matrix"; - -// Firefox and WebKit stay out of this broad suite to keep local runs fast; -// the layout suite (snapsort-layout.playwright.config.ts) runs the layout -// spec on all three browsers. -const frameworks = ["svelte", "react"] as const; -const testMatch = [ - "snapsort-drag-snapshot.spec.ts", - "snapsort-duolingo.spec.ts", - "snapsort-adapter-ghosts.spec.ts", - "snapsort-fail-safe.spec.ts", - "snapsort-insertion-copy.spec.ts", - "snapsort-item-api.spec.ts", - "snapsort-callback-ledger.spec.ts", -]; - -const keyboardDemoProjects = frameworkBrowserProjects({ - frameworks: ["svelte"], - browsers: ["chromium"], - testMatch: ["snapsort-keyboard-demo.spec.ts", "snapsort-camera.spec.ts"], -}).map((project) => ({ - ...project, - name: `${project.name}-keyboard`, -})); - -export default defineConfig({ - testDir: ".", - fullyParallel: false, - workers: 1, - reporter: [["list"]], - projects: [ - ...frameworkBrowserProjects({ - frameworks, - browsers: ["chromium"], - testMatch, - }), - ...keyboardDemoProjects, - ], - webServer: frameworkWebServers(frameworks), -}); diff --git a/tests/e2e/snapsort/_support/drag-harness.ts b/tests/e2e/snapsort/_support/drag-harness.ts new file mode 100644 index 00000000..501d3eb1 --- /dev/null +++ b/tests/e2e/snapsort/_support/drag-harness.ts @@ -0,0 +1,806 @@ +// Pointer-drag harness for the SnapSort demo suites: the in-page lifecycle +// trace, drag drivers that sample every frame, and stability assertions. +import { expect, type Locator, type Page } from "@playwright/test"; +import { mkdir, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import { type Rect } from "../../../../src/geometry"; +import { center } from "../../../helpers/snapsort-fixtures"; + +export type DragSample = { + step: number; + mouse: { x: number; y: number }; + spacerCount: number; + spacer: Rect | null; + spacerParentId: string | null; + spacerParentKind: string | null; + spacerParentText: string | null; + spacerIndex: number | null; + spacerPrevious: (Rect & { text: string }) | null; + spacerNext: (Rect & { text: string }) | null; + spacerDomPrevious: (Rect & { text: string }) | null; + spacerDomNext: (Rect & { text: string }) | null; + dragged: (Rect & { centerX: number; centerY: number }) | null; + draggedCenterDelta: number | null; + frameRects?: Array<{ + role: string; + text: string; + id: string | null; + transform: string; + rect: Rect; + }>; +}; + +export type DomTraceEntry = { + type: string; + target: string; + parent?: string; + before?: string | null; + time: number; +}; + +export type SnapSortLifecycleState = { + spacerCount: number; + draggingTexts: string[]; + draggingStyles: Array<{ + text: string; + position: string; + zIndex: string; + transform: string; + }>; + nestedOuterChildren: Array<{ + id: string; + classes: string[]; + text: string; + }>; +}; + +export async function installSnapsortTrace(page: Page) { + await page.addInitScript(() => { + const win = window as unknown as { + __snapsortTrace: { + dom: DomTraceEntry[]; + mutations: Array<{ + type: string; + target: string; + attr: string | null; + time: number; + }>; + }; + __snapsortActiveText?: string; + __snapsortActiveIndex?: number; + __snapsortActiveId?: string; + }; + + const trace = { + dom: [] as DomTraceEntry[], + mutations: [] as Array<{ + type: string; + target: string; + attr: string | null; + time: number; + }>, + }; + win.__snapsortTrace = trace; + + const describe = (node: unknown) => { + if (!(node instanceof Element)) return String(node); + const text = node.textContent?.trim().replace(/\s+/g, " ").slice(0, 40); + const id = node.id ? `#${node.id}` : ""; + const classes = [...node.classList].slice(0, 4).join("."); + return `${node.tagName.toLowerCase()}${id}${classes ? `.${classes}` : ""}${text ? ` "${text}"` : ""}`; + }; + + const shouldTrace = (node: unknown) => + node instanceof Element && + (node.id === "spacer" || + node.classList.contains("snapsort-item") || + node.classList.contains("snapsort-item-wrapper") || + node.classList.contains("snapsort-container") || + node.closest?.(".snapsort-container") != null); + + const originalAppendChild = Node.prototype.appendChild; + Node.prototype.appendChild = function (child: T): T { + if (shouldTrace(child) || shouldTrace(this)) { + trace.dom.push({ + type: "appendChild", + target: describe(child), + parent: describe(this), + time: performance.now(), + }); + } + return originalAppendChild.call(this, child) as T; + }; + + const originalInsertBefore = Node.prototype.insertBefore; + Node.prototype.insertBefore = function ( + child: T, + before: Node | null, + ): T { + if (shouldTrace(child) || shouldTrace(this)) { + trace.dom.push({ + type: "insertBefore", + target: describe(child), + parent: describe(this), + before: before ? describe(before) : null, + time: performance.now(), + }); + } + return originalInsertBefore.call(this, child, before) as T; + }; + + const originalRemove = Element.prototype.remove; + Element.prototype.remove = function () { + if (shouldTrace(this)) { + trace.dom.push({ + type: "remove", + target: describe(this), + parent: describe(this.parentElement), + time: performance.now(), + }); + } + return originalRemove.call(this); + }; + + const mutationObserver = new MutationObserver((mutations) => { + for (const mutation of mutations) { + if (shouldTrace(mutation.target)) { + trace.mutations.push({ + type: mutation.type, + target: describe(mutation.target), + attr: mutation.attributeName, + time: performance.now(), + }); + } + } + }); + + const observeDocument = () => { + const documentElement = document.documentElement; + if (!documentElement) return; + mutationObserver.observe(documentElement, { + attributes: true, + attributeFilter: ["class", "style", "data-engine-id"], + childList: true, + subtree: true, + }); + }; + if (document.documentElement) observeDocument(); + else { + document.addEventListener("DOMContentLoaded", observeDocument, { + once: true, + }); + } + }); +} + +export async function itemRect(item: Locator): Promise { + await item.scrollIntoViewIfNeeded(); + const box = await item.boundingBox(); + if (!box) throw new Error("Expected item to have a bounding box."); + return box; +} + +export async function itemByText(page: Page, text: string, index = 0) { + const locator = page + .locator(".snapsort-item") + .filter({ hasText: text }) + .nth(index); + await expect(locator).toBeVisible(); + return locator; +} + +export async function demoBoxByHeading(page: Page, heading: string) { + const box = page + .locator(".demo-cell") + .filter({ has: page.getByRole("heading", { name: heading }) }); + await expect(box).toBeVisible(); + return box; +} + +export async function websiteCoreDemo(page: Page, demo: string) { + const box = page.locator(`[data-demo="${demo}"]`); + await expect(box).toBeVisible(); + return box; +} + +export async function itemByTextIn(parent: Locator, text: string, index = 0) { + const locator = parent + .locator(".snapsort-item") + .filter({ hasText: text }) + .nth(index); + await expect(locator).toBeVisible(); + return locator; +} + +export async function componentArrayList(page: Page) { + const list = page.locator(".array-list"); + await expect(list).toBeVisible(); + return list; +} + +export async function collectSample( + page: Page, + step: number, + mouse: { x: number; y: number }, + options: { captureFrameRects?: boolean } = {}, +): Promise { + return page.evaluate( + ({ step, mouse, captureFrameRects }) => { + const win = window as unknown as { + __snapsortActiveText?: string; + __snapsortActiveIndex?: number; + __snapsortActiveId?: string; + }; + const rectOf = (element: Element | null) => { + if (!element) return null; + const rect = element.getBoundingClientRect(); + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }; + }; + const describedRectOf = (element: Element | null) => { + const rect = rectOf(element); + if (!rect) return null; + return { + ...rect, + text: element?.textContent?.trim().replace(/\s+/g, " ") ?? "", + }; + }; + const activeId = win.__snapsortActiveId ?? ""; + const draggedElement = document.querySelector( + `[data-engine-id="${activeId}"]`, + ); + const spacerElement = document.querySelector("#spacer"); + const spacerParent = spacerElement?.parentElement ?? null; + const spacerSiblings = spacerParent + ? [...spacerParent.children].filter( + (child) => + child !== draggedElement && + (child.id === "spacer" || + child.classList.contains("snapsort-item") || + child.classList.contains("snapsort-container")), + ) + : []; + const spacerSiblingIndex = spacerElement + ? spacerSiblings.indexOf(spacerElement) + : -1; + const directSiblingTexts = spacerParent + ? [...spacerParent.children] + .filter( + (child) => child.id !== "spacer" && child !== draggedElement, + ) + .map( + (child) => child.textContent?.trim().replace(/\s+/g, " ") ?? "", + ) + : []; + const parentText = directSiblingTexts.join(" | "); + const spacerParentKind = + directSiblingTexts.length === 0 + ? null + : directSiblingTexts.some((text) => /^Item [4-6]$/.test(text)) && + directSiblingTexts.every( + (text) => text === "" || /^Item [4-6]$/.test(text), + ) + ? "website-nested-inner" + : directSiblingTexts.some((text) => /^Item [1-3]$/.test(text)) || + directSiblingTexts.some((text) => + /Item 4 Item 5 Item 6/.test(text), + ) + ? "website-nested-outer" + : directSiblingTexts.every((text) => /^Sub A\d/.test(text)) + ? "nested-inner" + : directSiblingTexts.some((text) => + /Item 1\.5|Item 2|Item 3/.test(text), + ) + ? "nested-outer" + : directSiblingTexts.some((text) => + /Header|Card Grid|Footer/.test(text), + ) + ? "layers-root" + : directSiblingTexts.some((text) => + /Hero Section/.test(text), + ) + ? "layers-hero" + : directSiblingTexts.some((text) => + /Loose Item/.test(text), + ) + ? "drag-root" + : directSiblingTexts.some((text) => + /Group 1 -/.test(text), + ) + ? "drag-group-1" + : directSiblingTexts.some((text) => + /Group 2 -/.test(text), + ) + ? "drag-group-2" + : "other"; + const draggedRect = rectOf(draggedElement); + const dragged = draggedRect + ? { + ...draggedRect, + centerX: draggedRect.x + draggedRect.width / 2, + centerY: draggedRect.y + draggedRect.height / 2, + } + : null; + const frameRects = captureFrameRects + ? [ + ...document.querySelectorAll( + ".snapsort-item, .snapsort-container, #spacer", + ), + ].map((element) => { + const htmlElement = element as HTMLElement; + const role = + element.id === "spacer" + ? "ghost" + : element.classList.contains("snapsort-container") + ? "container" + : "item"; + return { + role, + text: element.textContent?.trim().replace(/\s+/g, " ") ?? "", + id: element.getAttribute("data-engine-id"), + transform: htmlElement.style.transform, + rect: rectOf(element)!, + }; + }) + : undefined; + return { + step, + mouse, + spacerCount: document.querySelectorAll("#spacer").length, + spacer: rectOf(spacerElement), + spacerParentId: spacerParent?.getAttribute("data-engine-id") ?? null, + spacerParentKind, + spacerParentText: parentText || null, + spacerIndex: spacerSiblingIndex === -1 ? null : spacerSiblingIndex, + spacerPrevious: + spacerSiblingIndex > 0 + ? describedRectOf(spacerSiblings[spacerSiblingIndex - 1]) + : null, + spacerNext: + spacerSiblingIndex >= 0 && + spacerSiblingIndex < spacerSiblings.length - 1 + ? describedRectOf(spacerSiblings[spacerSiblingIndex + 1]) + : null, + spacerDomPrevious: describedRectOf( + spacerElement?.previousElementSibling ?? null, + ), + spacerDomNext: describedRectOf( + spacerElement?.nextElementSibling ?? null, + ), + dragged, + draggedCenterDelta: dragged + ? Math.hypot(dragged.centerX - mouse.x, dragged.centerY - mouse.y) + : null, + frameRects, + }; + }, + { step, mouse, captureFrameRects: options.captureFrameRects ?? false }, + ); +} + +export async function dragBy( + page: Page, + source: Locator, + text: string, + index: number, + delta: { x: number; y: number }, + options: { + steps?: number; + assertCenter?: boolean; + start?: { x: number; y: number }; + captureFrameRects?: boolean; + } = {}, +): Promise { + const sourceRect = options.start + ? await source.boundingBox() + : await itemRect(source); + if (!sourceRect) { + throw new Error("Expected source item to have a bounding box."); + } + const activeId = await source.getAttribute("data-engine-id"); + const start = options.start ?? center(sourceRect); + const steps = options.steps ?? 160; + await page.evaluate( + ({ text, index, activeId }) => { + const win = window as unknown as { + __snapsortActiveText?: string; + __snapsortActiveIndex?: number; + __snapsortActiveId?: string; + }; + win.__snapsortActiveText = text; + win.__snapsortActiveIndex = index; + win.__snapsortActiveId = activeId ?? ""; + }, + { text, index, activeId }, + ); + + const samples: DragSample[] = []; + let mouseIsDown = false; + try { + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + mouseIsDown = true; + + const dragDistance = Math.hypot(delta.x, delta.y); + const activationRatio = + dragDistance === 0 ? 0 : Math.min(4 / dragDistance, 1); + if (activationRatio > 0) { + await page.mouse.move( + start.x + delta.x * activationRatio, + start.y + delta.y * activationRatio, + ); + await page.waitForTimeout(16); + } + + for (let step = 1; step <= steps; step++) { + const ratio = activationRatio + ((1 - activationRatio) * step) / steps; + const mouse = { + x: start.x + delta.x * ratio, + y: start.y + delta.y * ratio, + }; + await page.mouse.move(mouse.x, mouse.y); + await page.waitForTimeout(8); + samples.push( + await collectSample(page, step, mouse, { + captureFrameRects: options.captureFrameRects, + }), + ); + } + } finally { + if (mouseIsDown) { + await page.mouse.up().catch(() => {}); + } + } + + await page.waitForTimeout(100); + return samples; +} + +export async function dragTo( + page: Page, + source: Locator, + text: string, + index: number, + target: Locator, + options: Parameters[5] = {}, +): Promise { + const sourceCenter = center(await itemRect(source)); + const targetCenter = center(await itemRect(target)); + return dragBy( + page, + source, + text, + index, + { + x: targetCenter.x - sourceCenter.x, + y: targetCenter.y - sourceCenter.y, + }, + options, + ); +} + +export async function dragToItemFraction( + page: Page, + source: Locator, + text: string, + index: number, + target: Locator, + yRatio: number, + options: Parameters[5] = {}, +): Promise { + const sourceCenter = center(await itemRect(source)); + const targetRect = await itemRect(target); + return dragBy( + page, + source, + text, + index, + { + x: targetRect.x + targetRect.width / 2 - sourceCenter.x, + y: targetRect.y + targetRect.height * yRatio - sourceCenter.y, + }, + options, + ); +} + +export async function directSnapSortItemTexts( + locator: Locator, +): Promise { + return locator.evaluate((element) => + [...element.children] + .filter((child) => child.classList.contains("snapsort-item")) + .map((child) => child.textContent?.trim().replace(/\s+/g, " ") ?? ""), + ); +} + +// A nested container's own textContent concatenates its children's text with +// no separator by default; hand-authored templates picked up an incidental +// space from template whitespace between sibling tags, which items-mode's +// internal {#each} doesn't reproduce. Expected strings below reflect the +// no-space (items-mode) DOM shape -- this is a DOM formatting detail, not a +// behavior difference (content and order are unaffected). +export async function directSnapSortChildTexts( + locator: Locator, +): Promise { + return locator.evaluate((element) => + [...element.children] + .filter( + (child) => + child.classList.contains("snapsort-item") || + child.classList.contains("snapsort-container"), + ) + .map((child) => child.textContent?.trim().replace(/\s+/g, " ") ?? ""), + ); +} + +export async function nestedSnapSortLifecycleState( + page: Page, +): Promise { + return page.evaluate(() => { + const normalizeText = (element: Element | null) => + element?.textContent?.trim().replace(/\s+/g, " ") ?? ""; + const nestedCell = [...document.querySelectorAll(".demo-cell")].find( + (cell) => + cell.querySelector("h2")?.textContent?.trim() === "Nested Container", + ); + const outerContainer = nestedCell?.querySelector(".snapsort-container"); + const draggingElements = [ + ...document.querySelectorAll( + '[data-snapsort-dragging="true"]', + ), + ]; + + return { + spacerCount: document.querySelectorAll("#spacer").length, + draggingTexts: draggingElements.map(normalizeText), + draggingStyles: draggingElements.map((element) => ({ + text: normalizeText(element), + position: element.style.position, + zIndex: element.style.zIndex, + transform: element.style.transform, + })), + nestedOuterChildren: [...(outerContainer?.children ?? [])].map( + (child) => ({ + id: child.id, + classes: [...child.classList], + text: normalizeText(child), + }), + ), + }; + }); +} + +export async function releaseStartedDragNearOrigin( + page: Page, + nested: Locator, + itemText: string, + targetText: string, + targetYRatio: number, +) { + const item = await itemByTextIn(nested, itemText); + const target = await itemByTextIn(nested, targetText); + const start = center(await itemRect(item)); + const targetRect = await itemRect(target); + + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move( + targetRect.x + targetRect.width / 2, + targetRect.y + targetRect.height * targetYRatio, + { steps: 30 }, + ); + await page.waitForTimeout(80); + await page.mouse.move(start.x + 1, start.y + 1, { steps: 20 }); + await page.waitForTimeout(20); + await page.mouse.up(); + await page.waitForTimeout(120); +} + +export async function dragLockedNestedContainerBackground( + page: Page, + nested: Locator, +) { + const childContainer = nested.locator(".snapsort-container").nth(1); + const rect = await itemRect(childContainer); + const start = { + x: rect.x + 4, + y: rect.y + 4, + }; + + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move(start.x, start.y + 80, { steps: 20 }); + await page.waitForTimeout(50); + await page.mouse.up(); + await page.waitForTimeout(160); +} + +export async function directLogoSliceOrder( + locator: Locator, +): Promise { + return locator.evaluate((element) => + [...element.children] + .filter((child) => child.classList.contains("snapsort-item")) + .map((child) => + Number(child.querySelector(".logo-slice")?.dataset.slice), + ), + ); +} + +export async function writeJson(path: string, value: unknown) { + await mkdir(dirname(path), { recursive: true }); + await writeFile(path, JSON.stringify(value, null, 2)); +} + +export async function expectStableDrag( + page: Page, + samples: DragSample[], + consoleMessages: string[], + outputPath: string, + options: { assertCenter?: boolean } = {}, +) { + const trace = await page.evaluate(() => { + const win = window as unknown as { + __snapsortTrace?: { dom: DomTraceEntry[]; mutations: unknown[] }; + }; + return win.__snapsortTrace; + }); + await writeJson(outputPath, { + samples, + trace, + errors: consoleMessages.filter((message) => + /error|Missing drag snapshot|Unhandled|TypeError/i.test(message), + ), + }); + + expect(samples, "drag should produce frame samples").not.toHaveLength(0); + expect( + samples.filter((sample) => sample.spacerCount !== 1), + "the spacer should not disappear or duplicate while dragging", + ).toHaveLength(0); + if (options.assertCenter !== false) { + expect( + Math.max(...samples.map((sample) => sample.draggedCenterDelta ?? 999)), + "dragged item center should remain close to the pointer", + ).toBeLessThan(12); + } + expect( + consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test(message), + ), + ).toHaveLength(0); +} + +export function expectNoSpacerBacktrack( + samples: DragSample[], + axis: "x" | "y", +) { + const positions = samples + .filter((sample) => sample.spacer) + .map((sample) => ({ + step: sample.step, + value: sample.spacer![axis], + })); + + for (let i = 1; i < positions.length; i++) { + expect( + positions[i].value + 8, + `spacer should not jump backward between steps ${positions[i - 1].step} and ${positions[i].step}`, + ).toBeGreaterThanOrEqual(positions[i - 1].value); + } +} + +export function expectNoParentReentry( + samples: DragSample[], + innerKind: string, + outerKind: string, + label: string, +) { + const kinds = samples + .map((sample) => sample.spacerParentKind) + .filter((kind): kind is string => kind === innerKind || kind === outerKind); + const firstInner = kinds.indexOf(innerKind); + expect( + firstInner, + `drag should enter the ${label} nested sub-container`, + ).toBeGreaterThanOrEqual(0); + + for (let i = firstInner + 1; i < kinds.length - 1; i++) { + expect( + !(kinds[i] === outerKind && kinds[i + 1] === innerKind), + `spacer should not briefly leave and re-enter the ${label} nested container`, + ).toBe(true); + } +} + +export function expectNoNestedParentFlicker(samples: DragSample[]) { + expectNoParentReentry(samples, "nested-inner", "nested-outer", "default"); +} + +export function expectNoSpacerOscillation(samples: DragSample[]) { + const keys = samples + .filter((sample) => sample.spacer) + .map( + (sample) => + `${Math.round(sample.spacer!.x)}:${Math.round(sample.spacer!.y)}:${sample.spacerIndex}`, + ); + + for (let i = 2; i < keys.length; i++) { + expect( + !(keys[i] === keys[i - 2] && keys[i] !== keys[i - 1]), + `spacer should not alternate between ${keys[i - 1]} and ${keys[i]} around sample ${i}`, + ).toBe(true); + } +} + +export function compressedSpacerStates( + samples: DragSample[], + kinds: string[] = ["nested-inner", "nested-outer"], +) { + const states = samples + .filter((sample) => + sample.spacerParentKind ? kinds.includes(sample.spacerParentKind) : false, + ) + .map((sample) => `${sample.spacerParentKind}[${sample.spacerIndex}]`); + + return states.filter( + (state, index) => index === 0 || state !== states[index - 1], + ); +} + +export function expectSpacerAlignedAfterPrevious( + samples: DragSample[], + parentKind: string, + previousPattern: RegExp, +) { + const sample = samples.find( + (entry) => + entry.spacer && + entry.spacerParentKind === parentKind && + previousPattern.test(entry.spacerPrevious?.text ?? ""), + ); + expect( + sample, + `expected spacer in ${parentKind} after ${previousPattern}`, + ).toBeTruthy(); + + const previous = sample!.spacerPrevious!; + const delta = Math.abs(sample!.spacer!.y - (previous.y + previous.height)); + expect( + delta, + `spacer should align just below previous sibling; previous=${previous.text} delta=${delta}`, + ).toBeLessThan(24); +} + +export function expectSpacerNearDragged( + samples: DragSample[], + parentKind: string, + maxDistance: number, +) { + const candidates = samples.filter( + (sample) => + sample.spacer && sample.dragged && sample.spacerParentKind === parentKind, + ); + expect( + candidates, + `expected spacer samples in ${parentKind}`, + ).not.toHaveLength(0); + + const worst = candidates.reduce( + (current, sample) => { + const spacerCenterY = sample.spacer!.y + sample.spacer!.height / 2; + const delta = Math.abs(spacerCenterY - sample.dragged!.centerY); + return delta > current.delta ? { sample, delta } : current; + }, + { sample: candidates[0], delta: -Infinity }, + ); + + expect( + worst.delta, + `spacer center should track dragged item center in ${parentKind}; worst step=${worst.sample.step}`, + ).toBeLessThan(maxDistance); +} diff --git a/tests/e2e/snapsort/_support/layout-parity.ts b/tests/e2e/snapsort/_support/layout-parity.ts new file mode 100644 index 00000000..01d9b033 --- /dev/null +++ b/tests/e2e/snapsort/_support/layout-parity.ts @@ -0,0 +1,244 @@ +// Browser-vs-simulation layout parity: builds real flex/grid DOM through +// page.setContent and converts the measured boxes into layout snapshots. +import { type Page } from "@playwright/test"; +import { type ItemSnapshot } from "../../../../assets/snapsort/src/snapshot"; +import { type Box, snapshotFixture } from "../../../helpers/snapsort-fixtures"; + +export type LayoutCase = { + name: string; + width: number; + padding: { top: number; right: number; bottom: number; left: number }; + border: { top: number; right: number; bottom: number; left: number }; + columnGap: number; + rowGap: number; + itemWidths: number[]; + itemHeights: number[]; + itemBorders: number[]; +}; + +export type BrowserLayoutCase = { + name: string; + container: Box; + items: Array<{ id: string; box: Box }>; + draggedId: string; + ghost: { width: number; height: number }; + actualGhosts: Array<{ index: number; x: number; y: number }>; +}; + +export function horizontalDoubleRowLayoutCases(): LayoutCase[] { + const cases: LayoutCase[] = []; + for (let width = 236; width <= 356; width += 4) { + const seed = width * 17; + const count = 14 + (width % 5); + const itemWidths = Array.from({ length: count }, (_, index) => { + return 42 + ((seed + index * 13) % 42); + }); + const itemHeights = Array.from({ length: count }, (_, index) => { + return 30 + ((seed + index * 7) % 16); + }); + const itemBorders = Array.from({ length: count }, (_, index) => { + return (seed + index * 3) % 4; + }); + cases.push({ + name: `w${width}`, + width, + padding: { + top: (seed % 9) + 1, + right: ((seed >> 1) % 13) + 2, + bottom: ((seed >> 2) % 7) + 1, + left: ((seed >> 3) % 11) + 2, + }, + border: { + top: seed % 5, + right: (seed + 1) % 6, + bottom: (seed + 2) % 5, + left: (seed + 3) % 6, + }, + columnGap: 4 + (seed % 8), + rowGap: 3 + ((seed >> 2) % 9), + itemWidths, + itemHeights, + itemBorders, + }); + } + return cases; +} + +export function layoutNodeFromBrowserCase( + browserCase: BrowserLayoutCase, +): ItemSnapshot { + return snapshotFixture({ + value: "container", + direction: "row", + locked: false, + box: browserCase.container, + children: browserCase.items.map((item) => ({ + value: item.id, + direction: "column", + locked: false, + box: item.box, + children: [], + })), + }); +} + +export async function measureBrowserLayoutCases( + page: Page, + cases: LayoutCase[], +): Promise { + await page.setContent('
'); + return page.evaluate((layoutCases) => { + type BrowserBox = Box; + type BrowserCase = BrowserLayoutCase; + const fixture = document.querySelector("#layout-fixture") as HTMLElement; + const px = (value: number) => `${value}px`; + const sideCss = (value: { + top: number; + right: number; + bottom: number; + left: number; + }) => + `${px(value.top)} ${px(value.right)} ${px(value.bottom)} ${px(value.left)}`; + const boxOf = (element: HTMLElement): BrowserBox => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const number = (value: string) => parseFloat(value) || 0; + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + screen: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }, + margin: { + top: number(style.marginTop), + right: number(style.marginRight), + bottom: number(style.marginBottom), + left: number(style.marginLeft), + }, + padding: { + top: number(style.paddingTop), + right: number(style.paddingRight), + bottom: number(style.paddingBottom), + left: number(style.paddingLeft), + }, + border: { + top: number(style.borderTopWidth), + right: number(style.borderRightWidth), + bottom: number(style.borderBottomWidth), + left: number(style.borderLeftWidth), + }, + }; + }; + const makeItem = ( + id: string, + width: number, + height: number, + border: number, + isGhost = false, + ) => { + const item = document.createElement("div"); + item.dataset.itemId = id; + item.textContent = id; + item.style.boxSizing = "border-box"; + item.style.flex = "0 0 auto"; + item.style.width = px(width); + item.style.height = px(height); + item.style.border = `${px(border)} solid ${isGhost ? "#b45309" : "#2563eb"}`; + item.style.padding = `${px((width + height) % 5)} ${px((width + border) % 7)}`; + item.style.background = isGhost ? "#fef3c7" : "#dbeafe"; + return item; + }; + const buildContainer = (entry: LayoutCase) => { + fixture.innerHTML = ""; + const container = document.createElement("section"); + container.style.boxSizing = "border-box"; + container.style.display = "flex"; + container.style.flexDirection = "row"; + container.style.flexWrap = "wrap"; + container.style.alignItems = "flex-start"; + container.style.alignContent = "flex-start"; + container.style.width = px(entry.width); + container.style.padding = sideCss(entry.padding); + container.style.borderStyle = "solid"; + container.style.borderColor = "#111827"; + container.style.borderWidth = sideCss(entry.border); + container.style.columnGap = px(entry.columnGap); + container.style.rowGap = px(entry.rowGap); + container.style.margin = "16px"; + fixture.appendChild(container); + return container; + }; + + return layoutCases.map((entry) => { + const draggedIndex = Math.min(3, entry.itemWidths.length - 1); + const draggedId = `item-${draggedIndex}`; + let container = buildContainer(entry); + const itemElements = entry.itemWidths.map((width, index) => { + const item = makeItem( + `item-${index}`, + width, + entry.itemHeights[index], + entry.itemBorders[index], + ); + container.appendChild(item); + return item; + }); + const containerBox = boxOf(container); + const items = itemElements.map((item) => ({ + id: item.dataset.itemId!, + box: boxOf(item), + })); + const dragged = items[draggedIndex]; + const remaining = items.filter((item) => item.id !== draggedId); + const actualGhosts: BrowserCase["actualGhosts"] = []; + + for (let index = 0; index <= remaining.length; index++) { + container = buildContainer(entry); + for (let i = 0; i <= remaining.length; i++) { + if (i === index) { + container.appendChild( + makeItem( + "ghost", + dragged.box.width, + dragged.box.height, + entry.itemBorders[draggedIndex], + true, + ), + ); + } + const remainingItem = remaining[i]; + if (remainingItem) { + const originalIndex = Number(remainingItem.id.replace("item-", "")); + container.appendChild( + makeItem( + remainingItem.id, + entry.itemWidths[originalIndex], + entry.itemHeights[originalIndex], + entry.itemBorders[originalIndex], + ), + ); + } + } + const ghost = container.querySelector( + '[data-item-id="ghost"]', + ) as HTMLElement; + const rect = ghost.getBoundingClientRect(); + actualGhosts.push({ index, x: rect.x, y: rect.y }); + } + + return { + name: entry.name, + container: containerBox, + items, + draggedId, + ghost: { width: dragged.box.width, height: dragged.box.height }, + actualGhosts, + }; + }); + }, cases); +} diff --git a/tests/e2e/snapsort/animation/reorder-flip.spec.ts b/tests/e2e/snapsort/animation/reorder-flip.spec.ts new file mode 100644 index 00000000..c59e0d26 --- /dev/null +++ b/tests/e2e/snapsort/animation/reorder-flip.spec.ts @@ -0,0 +1,368 @@ +import { expect, test } from "@playwright/test"; +import { center } from "../../../helpers/snapsort-fixtures"; +import { + demoBoxByHeading, + installSnapsortTrace, + itemByTextIn, + itemRect, + writeJson, +} from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test.beforeEach(async ({ page }) => { + await installSnapsortTrace(page); + }); + + test("animates displaced items when the ghost reorders", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); + const item1 = await itemByTextIn(verticalColumn, "Item 1"); + const item4 = await itemByTextIn(verticalColumn, "Item 4"); + const item1Center = center(await itemRect(item1)); + const item4Center = center(await itemRect(item4)); + + await page.mouse.move(item1Center.x, item1Center.y); + await page.mouse.down(); + + // Arm a style-attribute observer before the reorder: polling for the + // inline transform can miss a FLIP that starts and settles between polls + // (WebKit clears the transform quickly on fast machines). + await page.evaluate(() => { + const win = window as unknown as { + __sawDisplacedTransform?: boolean; + __displacedObserver?: MutationObserver; + }; + win.__sawDisplacedTransform = false; + const isDisplaced = (element: Element) => + element.id !== "spacer" && !/Item 1/.test(element.textContent ?? ""); + const check = (element: Element) => { + if ( + isDisplaced(element) && + /^translate3d\(/.test((element as HTMLElement).style.transform) + ) { + win.__sawDisplacedTransform = true; + } + }; + const observer = new MutationObserver((mutations) => { + for (const mutation of mutations) check(mutation.target as Element); + }); + for (const element of document.querySelectorAll(".snapsort-item")) { + observer.observe(element, { + attributes: true, + attributeFilter: ["style"], + }); + check(element); + } + win.__displacedObserver = observer; + }); + + // Pace the moves like a human drag: a single burst of interpolated moves + // can be delivered entirely before the drag session finishes activating + // (observed on WebKit), leaving no post-activation pointermove and thus + // no reorder to animate. + for (let step = 1; step <= 12; step++) { + await page.mouse.move( + item1Center.x, + item1Center.y + ((item4Center.y - item1Center.y) * step) / 12, + ); + await page.waitForTimeout(16); + } + + const animated = await page.waitForFunction( + () => + (window as unknown as { __sawDisplacedTransform?: boolean }) + .__sawDisplacedTransform === true, + ); + await page.mouse.up(); + await page.waitForTimeout(120); + + await writeJson(testInfo.outputPath("reorder-animation-trace.json"), { + animated: await animated.jsonValue(), + errors: consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + }); + + expect(await animated.jsonValue()).toBe(true); + expect( + consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + ).toHaveLength(0); + }); + + test("animates siblings when a flow ghost leaves and re-enters a valid container", async ({ + page, + }, testInfo) => { + const pageErrors: string[] = []; + page.on("pageerror", (error) => pageErrors.push(String(error))); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const multipleAreas = await demoBoxByHeading(page, "Multiple Drop Areas"); + const itemA = await itemByTextIn(multipleAreas, "Item A"); + const itemY = await itemByTextIn(multipleAreas, "Item Y"); + const containers = multipleAreas.locator(".snapsort-container"); + const area1 = containers.nth(1); + const area2 = containers.nth(2); + const targetSpacers = area2.locator( + '[data-snapsort-ghost-entry="target-spacer"]', + ); + const sourceBox = await itemRect(itemA); + const start = center(sourceBox); + const initialTarget = center(await itemRect(itemY)); + + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + for (let step = 1; step <= 14; step++) { + await page.mouse.move( + start.x + ((initialTarget.x - start.x) * step) / 14, + start.y + ((initialTarget.y - start.y) * step) / 14, + ); + await page.waitForTimeout(16); + } + await expect(targetSpacers).toHaveCount(1); + await expect + .poll(() => + area2 + .locator(".snapsort-item") + .evaluateAll((elements) => + elements.every( + (element) => !(element as HTMLElement).style.transform, + ), + ), + ) + .toBe(true); + + await area2.evaluate((container) => { + type Phase = "idle" | "removal" | "insertion"; + interface FlowGhostFlipTrace { + phase: Phase; + removal: string[]; + insertion: string[]; + } + const win = window as unknown as { + __flowGhostFlipTrace?: FlowGhostFlipTrace; + __flowGhostFlipObserver?: MutationObserver; + }; + const trace: FlowGhostFlipTrace = { + phase: "idle", + removal: [], + insertion: [], + }; + const check = (element: Element) => { + const transform = (element as HTMLElement).style.transform; + if (!/^translate3d\(/.test(transform)) return; + const hasSpacer = Boolean( + container.querySelector( + '[data-snapsort-ghost-entry="target-spacer"]', + ), + ); + const label = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; + if (trace.phase === "removal" && !hasSpacer) { + trace.removal.push(`${label}: ${transform}`); + } else if (trace.phase === "insertion" && hasSpacer) { + trace.insertion.push(`${label}: ${transform}`); + } + }; + const observer = new MutationObserver((mutations) => { + for (const mutation of mutations) check(mutation.target as Element); + }); + for (const element of container.querySelectorAll(".snapsort-item")) { + observer.observe(element, { + attributes: true, + attributeFilter: ["style"], + }); + } + win.__flowGhostFlipTrace = trace; + win.__flowGhostFlipObserver = observer; + }); + + const setTracePhase = async (phase: "idle" | "removal" | "insertion") => + page.evaluate((nextPhase) => { + const trace = ( + window as unknown as { + __flowGhostFlipTrace?: { phase: typeof nextPhase }; + } + ).__flowGhostFlipTrace; + if (!trace) throw new Error("Missing flow ghost FLIP trace."); + trace.phase = nextPhase; + }, phase); + const traceCounts = () => + page.evaluate(() => { + const trace = ( + window as unknown as { + __flowGhostFlipTrace?: { + removal: string[]; + insertion: string[]; + }; + } + ).__flowGhostFlipTrace; + return { + removal: trace?.removal.length ?? 0, + insertion: trace?.insertion.length ?? 0, + }; + }); + + const [area1Box, area2Box] = await Promise.all([ + area1.boundingBox(), + area2.boundingBox(), + ]); + if (!area1Box || !area2Box) { + throw new Error("Expected visible drop areas."); + } + const invalidPoint = { + x: area2Box.x + area2Box.width / 2, + // Progressive candidates expand their broad-phase main-axis band by + // twice the dragged height, so leave a second full band of clearance. + y: Math.min(area1Box.y, area2Box.y) - sourceBox.height * 4, + }; + + await setTracePhase("removal"); + await page.mouse.move(invalidPoint.x, invalidPoint.y); + await expect(targetSpacers).toHaveCount(0); + await expect + .poll(async () => (await traceCounts()).removal) + .toBeGreaterThan(0); + await expect + .poll(() => + area2 + .locator(".snapsort-item") + .evaluateAll((elements) => + elements.every( + (element) => !(element as HTMLElement).style.transform, + ), + ), + ) + .toBe(true); + + const reentryTarget = center(await itemRect(itemY)); + await setTracePhase("insertion"); + await page.mouse.move(reentryTarget.x, reentryTarget.y); + await expect(targetSpacers).toHaveCount(1); + await expect + .poll(async () => (await traceCounts()).insertion) + .toBeGreaterThan(0); + + await setTracePhase("idle"); + await page.mouse.up(); + await expect( + page.locator('[data-snapsort-ghost-entry="target-spacer"]'), + ).toHaveCount(0); + const trace = await page.evaluate(() => { + const win = window as unknown as { + __flowGhostFlipTrace?: { + removal: string[]; + insertion: string[]; + }; + __flowGhostFlipObserver?: MutationObserver; + }; + win.__flowGhostFlipObserver?.disconnect(); + return win.__flowGhostFlipTrace ?? { removal: [], insertion: [] }; + }); + await writeJson(testInfo.outputPath("flow-ghost-frame-flip.json"), { + invalidPoint, + trace, + pageErrors, + }); + + expect(trace.removal.length).toBeGreaterThan(0); + expect(trace.insertion.length).toBeGreaterThan(0); + expect(pageErrors).toHaveLength(0); + }); + + test("animates displaced items when the ghost reorders upward", async ({ + page, + }, testInfo) => { + // Mirror of the downward test above. Upward reorders place the ghost + // BEFORE the displaced items in FLIP snapshot order, so a failure while + // animating the ghost entry silently kills every displaced-item + // animation — a class of bug the downward drag cannot catch. + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); + const item1 = await itemByTextIn(verticalColumn, "Item 1"); + const item4 = await itemByTextIn(verticalColumn, "Item 4"); + const item1Center = center(await itemRect(item1)); + const item4Center = center(await itemRect(item4)); + + await page.mouse.move(item4Center.x, item4Center.y); + await page.mouse.down(); + + await page.evaluate(() => { + const win = window as unknown as { + __sawDisplacedTransform?: boolean; + __displacedObserver?: MutationObserver; + }; + win.__sawDisplacedTransform = false; + const isDisplaced = (element: Element) => + element.id !== "spacer" && !/Item 4/.test(element.textContent ?? ""); + const check = (element: Element) => { + if ( + isDisplaced(element) && + /^translate3d\(/.test((element as HTMLElement).style.transform) + ) { + win.__sawDisplacedTransform = true; + } + }; + const observer = new MutationObserver((mutations) => { + for (const mutation of mutations) check(mutation.target as Element); + }); + for (const element of document.querySelectorAll(".snapsort-item")) { + observer.observe(element, { + attributes: true, + attributeFilter: ["style"], + }); + check(element); + } + win.__displacedObserver = observer; + }); + + for (let step = 1; step <= 12; step++) { + await page.mouse.move( + item4Center.x, + item4Center.y + ((item1Center.y - item4Center.y) * step) / 12, + ); + await page.waitForTimeout(16); + } + + const animated = await page.waitForFunction( + () => + (window as unknown as { __sawDisplacedTransform?: boolean }) + .__sawDisplacedTransform === true, + ); + await page.mouse.up(); + await page.waitForTimeout(120); + + await writeJson( + testInfo.outputPath("reorder-animation-upward-trace.json"), + { + animated: await animated.jsonValue(), + errors: consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + }, + ); + + expect(await animated.jsonValue()).toBe(true); + expect( + consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + ).toHaveLength(0); + }); +}); diff --git a/tests/e2e/snapsort-camera.spec.ts b/tests/e2e/snapsort/camera/camera-zoom.svelte.spec.ts similarity index 100% rename from tests/e2e/snapsort-camera.spec.ts rename to tests/e2e/snapsort/camera/camera-zoom.svelte.spec.ts diff --git a/tests/e2e/snapsort-duolingo.spec.ts b/tests/e2e/snapsort/components/duolingo.spec.ts similarity index 92% rename from tests/e2e/snapsort-duolingo.spec.ts rename to tests/e2e/snapsort/components/duolingo.spec.ts index 8402b4a3..48f3212a 100644 --- a/tests/e2e/snapsort-duolingo.spec.ts +++ b/tests/e2e/snapsort/components/duolingo.spec.ts @@ -359,41 +359,6 @@ test.describe("SnapSort Kiokun sentence builder demo", () => { ); }); - test("builds and grades the full answer after repeated cross-container moves", async ({ - page, - }, testInfo) => { - const consoleEntries: ConsoleEntry[] = []; - const pageErrors = installConsoleCapture(page, consoleEntries); - await gotoDemo(page); - - const answer = page.locator(".answer-box"); - const bank = page.locator(".tile-bank"); - for (const text of ["私", "は", "毎朝", "水", "を", "飲みます"]) { - await bank.getByRole("button", { name: text }).click(); - } - - await expect(answer.locator(".tile")).toHaveText([ - "私", - "は", - "毎朝", - "水", - "を", - "飲みます", - ]); - await page.getByRole("button", { name: "Check", exact: true }).click(); - await expect(page.locator(".result.correct")).toBeVisible(); - - await expectCleanConsole( - consoleEntries, - pageErrors, - testInfo.outputPath("full-answer-console.json"), - { - answerTexts: await tileTexts(answer), - bankTexts: await tileTexts(bank), - }, - ); - }); - test("reorders a non-last answer tile without dropping it at the end", async ({ page, }, testInfo) => { diff --git a/tests/e2e/snapsort/components/framework-state.spec.ts b/tests/e2e/snapsort/components/framework-state.spec.ts new file mode 100644 index 00000000..e16fed42 --- /dev/null +++ b/tests/e2e/snapsort/components/framework-state.spec.ts @@ -0,0 +1,325 @@ +import { expect, test } from "@playwright/test"; +import { type Rect } from "../../../../src/geometry"; +import { center } from "../../../helpers/snapsort-fixtures"; +import { + componentArrayList, + dragBy, + installSnapsortTrace, + itemByTextIn, + itemRect, +} from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test.beforeEach(async ({ page }) => { + await installSnapsortTrace(page); + }); + + test("updates framework state when SnapSort move callbacks reorder an array list", async ({ + page, + }) => { + await page.goto("/?demo=snapsort_components", { + waitUntil: "networkidle", + }); + + const list = await componentArrayList(page); + const kanbanPanel = page.locator(".kanban-panel"); + await expect(page.locator(".demo-header p")).toHaveText( + "6 Euclidean cards plus Progressive sentence demos", + ); + + await kanbanPanel.getByRole("button", { name: "Add Item" }).click(); + await expect(page.locator(".demo-header p")).toHaveText( + "7 Euclidean cards plus Progressive sentence demos", + ); + await expect(list.locator(".task-card")).toHaveCount(5); + + const deleteButton = page.getByRole("button", { name: "Delete Task 7" }); + await deleteButton.click(); + await expect(page.locator(".demo-header p")).toHaveText( + "6 Euclidean cards plus Progressive sentence demos", + ); + await expect(list.locator(".task-card")).toHaveCount(4); + + const upwardItem = await itemByTextIn(list, "Search filters"); + const upwardItemRect = await itemRect(upwardItem); + const upwardItemCenter = center(upwardItemRect); + const upwardTarget = await itemByTextIn(list, "Invite flow"); + const upwardTargetCenter = center(await itemRect(upwardTarget)); + + await dragBy( + page, + upwardItem, + "Search filters", + 0, + { + x: 0, + y: upwardTargetCenter.y - upwardItemCenter.y - 24, + }, + { + start: { + x: upwardItemRect.x + 24, + y: upwardItemCenter.y, + }, + }, + ); + + await expect(list.locator(".task-card .task-main strong")).toHaveText([ + "Profile fields", + "Search filters", + "Invite flow", + "Audit log", + ]); + + await kanbanPanel.getByRole("button", { name: "Reset" }).click(); + await expect(page.locator(".demo-header p")).toHaveText( + "6 Euclidean cards plus Progressive sentence demos", + ); + + const item = await itemByTextIn(list, "Profile fields"); + const itemRectValue = await itemRect(item); + const itemCenter = center(itemRectValue); + const target = await itemByTextIn(list, "Search filters"); + const targetCenter = center(await itemRect(target)); + + await dragBy( + page, + item, + "Profile fields", + 0, + { + x: 0, + y: targetCenter.y - itemCenter.y + 16, + }, + { + start: { + x: itemRectValue.x + 24, + y: itemCenter.y, + }, + }, + ); + + await expect( + page.locator(".task-card").filter({ hasText: "Profile fields" }), + ).toHaveCount(1); + + await expect(page.locator(".demo-header p")).toHaveText( + "6 Euclidean cards plus Progressive sentence demos", + ); + await expect(list.locator(".task-card .task-main strong")).toHaveText([ + "Invite flow", + "Audit log", + "Search filters", + "Profile fields", + ]); + }); + + test("animates a component card moving between columns with SnapEngine FLIP", async ({ + page, + }) => { + await page.goto("/?demo=snapsort_components", { + waitUntil: "networkidle", + }); + + await page.evaluate(() => { + const win = window as typeof window & { + __snapsortMoveComponentItem?: ( + itemId: string, + direction: -1 | 1, + ) => void; + }; + win.__snapsortMoveComponentItem?.("item-1", 1); + }); + + const animated = await page.evaluate(async () => { + for (let frame = 0; frame < 10; frame++) { + await new Promise((resolve) => requestAnimationFrame(resolve)); + const animatedCard = [...document.querySelectorAll(".task-card")].find( + (element) => + /^translate3d\(-?\d/.test((element as HTMLElement).style.transform), + ); + if (animatedCard) { + return true; + } + } + return false; + }); + + expect(animated).toBe(true); + + const panels = page.locator(".list-panel"); + await expect( + panels.nth(0).locator(".task-card .task-main strong"), + ).toHaveText(["Invite flow", "Audit log", "Search filters"]); + await expect( + panels.nth(1).locator(".task-card .task-main strong"), + ).toHaveText(["Profile fields", "Board polish"]); + }); + + test("animates framework-owned programmatic removal but not direct state deletion", async ({ + page, + }) => { + const observesTransform = async () => + page.evaluate(async () => { + for (let frame = 0; frame < 10; frame++) { + await new Promise((resolve) => requestAnimationFrame(resolve)); + const animatedCard = [ + ...document.querySelectorAll(".array-list .task-card"), + ].find((element) => + /^translate3d\(-?\d/.test((element as HTMLElement).style.transform), + ); + if (animatedCard) return true; + } + return false; + }); + + await page.goto("/?demo=snapsort_components&slowFlip=1", { + waitUntil: "networkidle", + }); + await page.evaluate(() => { + const demoWindow = window as typeof window & { + __snapsortDeleteComponentItem?: (itemId: string) => void; + }; + demoWindow.__snapsortDeleteComponentItem?.("item-1"); + }); + expect(await observesTransform()).toBe(false); + + await page.goto("/?demo=snapsort_components&slowFlip=1", { + waitUntil: "networkidle", + }); + const accepted = await page.evaluate(() => { + const demoWindow = window as typeof window & { + __snapsortRemoveComponentItem?: (itemId: string) => boolean; + }; + return demoWindow.__snapsortRemoveComponentItem?.("item-1") ?? false; + }); + expect(accepted).toBe(true); + expect(await observesTransform()).toBe(true); + await expect( + page.locator(".array-list .task-card .task-main strong"), + ).toHaveText(["Invite flow", "Audit log", "Search filters"]); + }); + + test("installs the drop inverse before the first post-release paint", async ({ + page, + }) => { + await page.goto("/?demo=snapsort_components&slowFlip=1", { + waitUntil: "networkidle", + }); + + const moveComponentItem = async (direction: -1 | 1) => { + await page.evaluate((nextDirection) => { + const win = window as typeof window & { + __snapsortMoveComponentItem?: ( + itemId: string, + direction: -1 | 1, + ) => void; + }; + win.__snapsortMoveComponentItem?.("item-1", nextDirection); + }, direction); + }; + await moveComponentItem(1); + await page.waitForTimeout(900); + await moveComponentItem(-1); + await page.waitForTimeout(900); + + const card = page + .locator(".task-card:not(.snapsort-ghost)") + .filter({ hasText: "Profile fields" }); + const target = page + .locator(".task-card:not(.snapsort-ghost)") + .filter({ hasText: "Board polish" }); + const start = center(await itemRect(card.locator(".task-drag-handle"))); + const targetRect = await itemRect(target); + const releasePoint = { + x: targetRect.x + targetRect.width / 2, + y: targetRect.y + targetRect.height * 0.8, + }; + + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move(start.x + 5, start.y); + await page.waitForTimeout(16); + await page.mouse.move(releasePoint.x, releasePoint.y, { steps: 24 }); + await page.waitForTimeout(80); + const releaseRect = await itemRect(card); + + await page.evaluate(() => { + const win = window as typeof window & { + __dropFlipSamples?: Array<{ + column: string; + transform: string; + x: number; + y: number; + }>; + }; + win.__dropFlipSamples = []; + window.addEventListener( + "pointerup", + () => { + let frame = 0; + const sample = () => { + const card = [ + ...document.querySelectorAll( + ".task-card:not(.snapsort-ghost)", + ), + ].find((element) => + element.textContent?.includes("Profile fields"), + ); + if (card) { + const rect = card.getBoundingClientRect(); + win.__dropFlipSamples?.push({ + column: + card + .closest(".list-panel") + ?.querySelector("h2") + ?.textContent?.trim() ?? "", + transform: card.style.transform, + x: rect.x, + y: rect.y, + }); + } + frame++; + if (frame < 12) requestAnimationFrame(sample); + }; + requestAnimationFrame(sample); + }, + { capture: true, once: true }, + ); + }); + + await page.mouse.up(); + await page.waitForTimeout(250); + const samples = await page.evaluate(() => { + const win = window as typeof window & { + __dropFlipSamples?: Array<{ + column: string; + transform: string; + x: number; + y: number; + }>; + }; + return win.__dropFlipSamples ?? []; + }); + await page.waitForTimeout(700); + const finalRect = await itemRect(card); + const activeSamples = samples.filter( + (sample) => sample.column === "Active", + ); + expect(activeSamples.length).toBeGreaterThan(1); + expect(activeSamples[0].transform).toMatch(/^translate3d\(/); + + const distanceTo = (sample: { x: number; y: number }, rect: Rect) => + Math.hypot(sample.x - rect.x, sample.y - rect.y); + expect(distanceTo(activeSamples[0], releaseRect)).toBeLessThan(8); + expect(distanceTo(activeSamples[0], finalRect)).toBeGreaterThan(12); + + const distancesToFinal = activeSamples.map((sample) => + distanceTo(sample, finalRect), + ); + for (let index = 1; index < distancesToFinal.length; index++) { + expect(distancesToFinal[index]).toBeLessThanOrEqual( + distancesToFinal[index - 1] + 3, + ); + } + }); +}); diff --git a/tests/e2e/snapsort-item-api.spec.ts b/tests/e2e/snapsort/components/item-api.spec.ts similarity index 100% rename from tests/e2e/snapsort-item-api.spec.ts rename to tests/e2e/snapsort/components/item-api.spec.ts diff --git a/tests/e2e/snapsort/drag/drop-prediction.spec.ts b/tests/e2e/snapsort/drag/drop-prediction.spec.ts new file mode 100644 index 00000000..af9f75c3 --- /dev/null +++ b/tests/e2e/snapsort/drag/drop-prediction.spec.ts @@ -0,0 +1,289 @@ +import { expect, test } from "@playwright/test"; +import { center } from "../../../helpers/snapsort-fixtures"; +import { + demoBoxByHeading, + installSnapsortTrace, + itemByTextIn, + itemRect, + writeJson, +} from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test.beforeEach(async ({ page }) => { + await installSnapsortTrace(page); + }); + + test("drops land where the drag preview predicted (drift oracle)", async ({ + page, + }, testInfo) => { + // The mid-drag preview IS the layout engine's prediction: displaced + // items sit at simulated positions and the spacer marks the dragged + // item's landing slot. After the drop, the framework re-renders and the + // browser performs the real layout — the authoritative ground truth. + // Comparing the settled DOM against the last preview turns any real + // drag into a layout-engine oracle: drift means the simulation and the + // browser disagreed about the committed arrangement. + const TOLERANCE = 1.5; + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); + + const dragWithOracle = async ( + sourceText: string, + target: { x: number; y: number }, + label: string, + ) => { + const source = await itemByTextIn(verticalColumn, sourceText); + const start = center(await itemRect(source)); + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + for (let step = 1; step <= 14; step++) { + await page.mouse.move( + start.x + ((target.x - start.x) * step) / 14, + start.y + ((target.y - start.y) * step) / 14, + ); + await page.waitForTimeout(16); + } + // Let the preview settle so captured rects are the engine's final + // prediction, not a mid-animation frame. + await page.waitForTimeout(350); + + const prediction = await verticalColumn.evaluate((box, dragged) => { + const out: Record = {}; + for (const element of box.querySelectorAll(".snapsort-item")) { + const text = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; + if (element.id === "spacer" || text.includes(dragged)) continue; + const rect = element.getBoundingClientRect(); + out[text] = { x: rect.x, y: rect.y }; + } + const spacer = box.querySelector("#spacer"); + if (spacer) { + const rect = spacer.getBoundingClientRect(); + out["__dragged__"] = { x: rect.x, y: rect.y }; + } + return out; + }, sourceText); + + await page.mouse.up(); + await page.waitForTimeout(500); + + const settled = await verticalColumn.evaluate((box, dragged) => { + const out: Record = {}; + for (const element of box.querySelectorAll(".snapsort-item")) { + const text = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; + const rect = element.getBoundingClientRect(); + out[text.includes(dragged) ? "__dragged__" : text] = { + x: rect.x, + y: rect.y, + }; + } + return out; + }, sourceText); + + const drifts: Array<{ label: string; entry: string; delta: number }> = []; + let compared = 0; + for (const [entry, predicted] of Object.entries(prediction)) { + const actual = settled[entry]; + if (!actual) continue; + compared++; + const delta = Math.max( + Math.abs(predicted.x - actual.x), + Math.abs(predicted.y - actual.y), + ); + if (delta > TOLERANCE) + drifts.push({ label, entry, delta: +delta.toFixed(2) }); + } + // Guard against a vacuous pass: the oracle must have compared the + // dragged item's landing slot plus the displaced items. + expect( + compared, + `oracle should compare several entries for ${label}`, + ).toBeGreaterThanOrEqual(4); + expect( + prediction.__dragged__, + `spacer prediction should exist for ${label}`, + ).toBeTruthy(); + return drifts; + }; + + const item3 = await itemByTextIn(verticalColumn, "Item 3"); + const item3Center = center(await itemRect(item3)); + const item4 = await itemByTextIn(verticalColumn, "Item 4"); + const item4Rect = await itemRect(item4); + + const allDrifts = [ + // Reorder downward past two slots. + ...(await dragWithOracle("Item 1", item3Center, "item1-to-item3")), + // Reach the final slot (past the last item's bottom edge). + ...(await dragWithOracle( + "Item 2", + { + x: item4Rect.x + item4Rect.width / 2, + y: item4Rect.y + item4Rect.height * 1.05, + }, + "item2-to-final-slot", + )), + ]; + + await writeJson(testInfo.outputPath("drop-drift-oracle.json"), { + drifts: allDrifts, + }); + expect( + allDrifts, + "settled post-drop positions should match the drag preview's prediction", + ).toHaveLength(0); + }); + + test("keeps the spacer stable while dragging into a narrower nested container (stretch flicker regression)", async ({ + page, + }, testInfo) => { + // Before `stretchItems`, insertion entries kept the dragged item's + // source-container size everywhere, so nested candidates' ghost rects + // and centers were computed at parent width — candidate scoring + // flip-flopped between parent and nested slots as the pointer moved and + // the spacer visibly oscillated between containers. The Stretch Nested + // demo cell's items are genuinely 100% width and its containers declare + // `stretchItems`, so the spacer host must settle: at most a couple of + // transitions on the way in, ending inside the nested sub-list, with + // the drop committing there. + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const nested = await demoBoxByHeading(page, "Stretch Nested"); + const source = await itemByTextIn(nested, "Task 1"); + const target = await itemByTextIn(nested, "Sub task 2"); + const start = center(await itemRect(source)); + const end = center(await itemRect(target)); + + const spacerHost = () => + nested.evaluate((box) => { + const spacer = box.querySelector("#spacer"); + if (!spacer) return "none"; + const container = spacer.closest(".snapsort-container"); + if (!container) return "unknown"; + return container.classList.contains("stretch-sublist") + ? "nested" + : "parent"; + }); + + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + const hosts: string[] = []; + const steps = 24; + for (let step = 1; step <= steps; step++) { + await page.mouse.move( + start.x + ((end.x - start.x) * step) / steps, + start.y + ((end.y - start.y) * step) / steps, + ); + await page.waitForTimeout(16); + hosts.push(await spacerHost()); + } + await page.waitForTimeout(350); + hosts.push(await spacerHost()); + + // The core of the fix: once the spacer is hosted by the narrower + // sublist, it must be re-sized to the sublist's content width (minus + // its own margins) rather than keeping the parent-container width it + // was measured at. + const spacerSizing = await nested.evaluate((box) => { + const spacer = box.querySelector("#spacer") as HTMLElement | null; + const sublist = box.querySelector( + ".stretch-sublist", + ) as HTMLElement | null; + if (!spacer || !sublist) return null; + const spacerRect = spacer.getBoundingClientRect(); + const style = getComputedStyle(sublist); + const spacerStyle = getComputedStyle(spacer); + const number = (value: string) => parseFloat(value) || 0; + const contentWidth = + sublist.getBoundingClientRect().width - + number(style.borderLeftWidth) - + number(style.borderRightWidth) - + number(style.paddingLeft) - + number(style.paddingRight); + const expected = + contentWidth - + number(spacerStyle.marginLeft) - + number(spacerStyle.marginRight); + return { spacerWidth: spacerRect.width, expected }; + }); + expect(spacerSizing, "spacer should be inside the sublist").toBeTruthy(); + expect( + Math.abs(spacerSizing!.spacerWidth - spacerSizing!.expected), + `spacer width ${spacerSizing!.spacerWidth} should match the sublist's content width ${spacerSizing!.expected}`, + ).toBeLessThanOrEqual(1.5); + + // Drift oracle for the nested drop: preview rects just before release + // vs the settled DOM afterward. + const prediction = await nested.evaluate((box) => { + const out: Record = {}; + for (const element of box.querySelectorAll(".snapsort-item")) { + const text = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; + if (element.id === "spacer" || text === "Task 1") continue; + if (!/^Sub task \d$/.test(text)) continue; + const rect = element.getBoundingClientRect(); + out[text] = { x: rect.x, y: rect.y }; + } + const spacer = box.querySelector("#spacer"); + if (spacer) { + const rect = spacer.getBoundingClientRect(); + out["__dragged__"] = { x: rect.x, y: rect.y }; + } + return out; + }); + await page.mouse.up(); + await page.waitForTimeout(500); + const settled = await nested.evaluate((box) => { + const out: Record = {}; + for (const element of box.querySelectorAll(".snapsort-item")) { + const text = element.textContent?.trim().replace(/\s+/g, " ") ?? ""; + const rect = element.getBoundingClientRect(); + if (text === "Task 1") out["__dragged__"] = { x: rect.x, y: rect.y }; + else if (/^Sub task \d$/.test(text)) + out[text] = { x: rect.x, y: rect.y }; + } + return out; + }); + const drifts: Array<{ entry: string; delta: number }> = []; + for (const [entry, predicted] of Object.entries(prediction)) { + const actual = settled[entry]; + if (!actual) continue; + const delta = Math.max( + Math.abs(predicted.x - actual.x), + Math.abs(predicted.y - actual.y), + ); + if (delta > 1.5) drifts.push({ entry, delta: +delta.toFixed(2) }); + } + + const transitions = hosts.filter( + (host, index) => index > 0 && host !== hosts[index - 1], + ).length; + const subGroupTexts = await nested.evaluate((box) => + [...box.querySelectorAll(".stretch-sublist .snapsort-item")].map( + (element) => element.textContent?.trim().replace(/\s+/g, " ") ?? "", + ), + ); + + await writeJson(testInfo.outputPath("nested-stretch-flicker.json"), { + hosts, + transitions, + drifts, + subGroupTexts, + }); + expect( + hosts[hosts.length - 1], + "spacer should end in the nested sub-list", + ).toBe("nested"); + expect( + transitions, + "spacer host must not oscillate between parent and nested containers", + ).toBeLessThanOrEqual(2); + expect( + drifts, + "nested drop should land where the preview predicted", + ).toHaveLength(0); + expect( + subGroupTexts.some((text) => text.includes("Task 1")), + "the dragged item should commit into the nested sub-list", + ).toBe(true); + }); +}); diff --git a/tests/e2e/snapsort/drag/lifecycle-robustness.spec.ts b/tests/e2e/snapsort/drag/lifecycle-robustness.spec.ts new file mode 100644 index 00000000..bf14eb72 --- /dev/null +++ b/tests/e2e/snapsort/drag/lifecycle-robustness.spec.ts @@ -0,0 +1,169 @@ +import { expect, test } from "@playwright/test"; +import { center } from "../../../helpers/snapsort-fixtures"; +import { + demoBoxByHeading, + dragLockedNestedContainerBackground, + installSnapsortTrace, + itemByTextIn, + itemRect, + nestedSnapSortLifecycleState, + releaseStartedDragNearOrigin, + writeJson, +} from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test.beforeEach(async ({ page }) => { + await installSnapsortTrace(page); + }); + + test("does not crash when drag movement arrives before snapshot capture", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); + const item = await itemByTextIn(verticalColumn, "Item 1"); + const itemCenter = center(await itemRect(item)); + + await page.mouse.move(itemCenter.x, itemCenter.y); + await page.mouse.down(); + for (let step = 1; step <= 24; step++) { + await page.mouse.move(itemCenter.x, itemCenter.y + step * 4); + } + await page.mouse.up(); + await page.waitForTimeout(100); + + await writeJson(testInfo.outputPath("snapshot-readiness-trace.json"), { + errors: consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + }); + + expect( + consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + ).toHaveLength(0); + }); + + // Regression for a leak where a released drag left a root ghost behind and + // a later locked-container drag adopted it. The input layer now finishes + // the released pointer, so neither gesture may leave drag state behind. + test("leaves no drag state behind when a locked container drag follows a released drag", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + const pageErrors: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + page.on("pageerror", (error) => pageErrors.push(String(error))); + await page.goto( + "/?demo=drop_snap_nested&disableNestedFlip=1&lockNestedChild=1", + { + waitUntil: "networkidle", + }, + ); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const initialState = await nestedSnapSortLifecycleState(page); + await releaseStartedDragNearOrigin(page, nested, "Item 1.5", "Sub A1", 0.2); + const beforeLockedDrag = await nestedSnapSortLifecycleState(page); + await dragLockedNestedContainerBackground(page, nested); + const afterLockedDrag = await nestedSnapSortLifecycleState(page); + const errors = [ + ...pageErrors, + ...consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + ]; + + await writeJson(testInfo.outputPath("locked-container-drag-state.json"), { + initialState, + beforeLockedDrag, + afterLockedDrag, + errors, + }); + + for (const state of [beforeLockedDrag, afterLockedDrag]) { + expect(state.spacerCount).toBe(0); + expect(state.draggingTexts).toEqual([]); + } + expect(afterLockedDrag.nestedOuterChildren).toEqual( + initialState.nestedOuterChildren, + ); + expect(errors).toEqual([]); + }); + + test("cleans up a drag released back inside the threshold and regrabs it", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + const pageErrors: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + page.on("pageerror", (error) => pageErrors.push(String(error))); + await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { + waitUntil: "networkidle", + }); + + // Regression: a drag that starts (crosses the threshold) and then returns + // near its origin before release must still fire dragEnd and commit/clean + // up. Previously dragEnd was gated on the pointer's final distance from + // the start, so an away-and-back "drop it in the same place" gesture was + // misclassified as a click and left the drag session uncommitted. + // Fixed in src/input.ts #finishPointer by gating on the drag gesture state. + const nested = await demoBoxByHeading(page, "Nested Container"); + await releaseStartedDragNearOrigin(page, nested, "Item 1.5", "Sub A1", 0.2); + const releasedState = await nestedSnapSortLifecycleState(page); + expect( + releasedState.spacerCount, + "released drag should remove its ghost", + ).toBe(0); + expect( + releasedState.draggingTexts, + "released drag should clear the dragging marker", + ).toEqual([]); + + // Grabbing the released item again must not throw. + const releasedItem = await itemByTextIn(nested, "Item 1.5"); + const releasedRect = await itemRect(releasedItem); + const releasedCenter = center(releasedRect); + + await page.mouse.move(releasedCenter.x, releasedCenter.y); + await page.mouse.down(); + await page.mouse.move(releasedCenter.x + 20, releasedCenter.y + 20, { + steps: 10, + }); + await page.waitForTimeout(100); + await page.mouse.up(); + await page.waitForTimeout(200); + + const state = await nestedSnapSortLifecycleState(page); + await writeJson(testInfo.outputPath("released-item-regrab.json"), { + state, + pageErrors, + consoleErrors: consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + }); + + expect(pageErrors).toHaveLength(0); + expect( + consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + ).toHaveLength(0); + expect(state.spacerCount).toBe(0); + expect(state.draggingTexts).toEqual([]); + }); +}); diff --git a/tests/e2e/snapsort/drag/spacer-stability.spec.ts b/tests/e2e/snapsort/drag/spacer-stability.spec.ts new file mode 100644 index 00000000..35cfba3e --- /dev/null +++ b/tests/e2e/snapsort/drag/spacer-stability.spec.ts @@ -0,0 +1,322 @@ +import { expect, test } from "@playwright/test"; +import { center } from "../../../helpers/snapsort-fixtures"; +import { + compressedSpacerStates, + demoBoxByHeading, + dragBy, + dragTo, + expectNoSpacerBacktrack, + expectNoSpacerOscillation, + expectSpacerAlignedAfterPrevious, + expectSpacerNearDragged, + expectStableDrag, + installSnapsortTrace, + itemByText, + itemByTextIn, + itemRect, + writeJson, +} from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test.beforeEach(async ({ page }) => { + await installSnapsortTrace(page); + }); + + test("does not flicker the spacer backward while dragging down a vertical column", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); + const item = await itemByTextIn(verticalColumn, "Item 1"); + const target = await itemByTextIn(verticalColumn, "Item 4"); + const itemCenter = center(await itemRect(item)); + const targetCenter = center(await itemRect(target)); + const samples = await dragBy(page, item, "Item 1", 0, { + x: 0, + y: targetCenter.y - itemCenter.y + 48, + }); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("vertical-column-flicker-trace.json"), + ); + expectNoSpacerBacktrack(samples, "y"); + expectNoSpacerOscillation(samples); + }); + + test("does not flicker the spacer upward while dragging into a wrapped horizontal row", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const horizontalRow = await demoBoxByHeading(page, "Horizontal Row"); + const item = await itemByTextIn(horizontalRow, "Item 1"); + const target = await itemByTextIn(horizontalRow, "Item 4"); + const itemCenter = center(await itemRect(item)); + const targetCenter = center(await itemRect(target)); + const samples = await dragBy(page, item, "Item 1", 0, { + x: 0, + y: targetCenter.y - itemCenter.y, + }); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("horizontal-row-wrap-flicker-trace.json"), + ); + expectNoSpacerBacktrack(samples, "y"); + expectNoSpacerOscillation(samples); + }); + + test("can reach nested column boundary slots while dragging root item downward", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const item = await itemByTextIn(nested, "Item 1"); + const item3 = await itemByTextIn(nested, "Item 3"); + const itemCenter = center(await itemRect(item)); + const item3Center = center(await itemRect(item3)); + const samples = await dragBy( + page, + item, + "Item 1", + 0, + { + x: 0, + y: item3Center.y - itemCenter.y + 96, + }, + { steps: 240 }, + ); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("nested-boundary-slots-trace.json"), + { assertCenter: false }, + ); + + const states = compressedSpacerStates(samples); + await writeJson(testInfo.outputPath("nested-boundary-slots-states.json"), { + states, + }); + + expect( + states, + `ghost should visit nested container boundary slots; observed ${states.join(" -> ")}`, + ).toEqual(expect.arrayContaining(["nested-inner[0]", "nested-inner[3]"])); + }); + + test("creates a spacer when dragging a sub-container as an item", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const cell = await demoBoxByHeading(page, "Draggable Sub-Containers"); + const source = cell + .locator(".snapsort-container .snapsort-container") + .filter({ hasText: "Group 1 - A" }) + .first(); + await expect(source).toBeVisible(); + const target = await itemByTextIn(cell, "Loose Item"); + const sourceRect = await itemRect(source); + const targetCenter = center(await itemRect(target)); + const start = { x: sourceRect.x + 8, y: sourceRect.y + 8 }; + const samples = await dragBy( + page, + source, + "Group 1", + 0, + { + x: targetCenter.x - start.x, + y: targetCenter.y - start.y, + }, + { start, assertCenter: false }, + ); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("drag-container-trace.json"), + { assertCenter: false }, + ); + expect( + samples.some((sample) => sample.spacerCount === 1 && sample.spacer), + "dragging a sub-container should create and move a spacer", + ).toBe(true); + }); + + test("keeps layer-panel ghost aligned below a labeled sub-container", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const layers = await demoBoxByHeading(page, "Layers Panel"); + const header = await itemByTextIn(layers, "Header"); + const hero = layers + .locator(".snapsort-container") + .filter({ hasText: "Hero Section" }) + .nth(1); + await expect(hero).toBeVisible(); + const headerRect = await itemRect(header); + const headerCenter = center(headerRect); + const heroRect = await itemRect(hero); + const targetCenterY = + heroRect.y + heroRect.height + headerRect.height / 2 + 12; + const samples = await dragBy( + page, + header, + "Header", + 0, + { + x: 0, + y: targetCenterY - headerCenter.y, + }, + { steps: 240 }, + ); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("layers-panel-offset-trace.json"), + { assertCenter: false }, + ); + expectSpacerAlignedAfterPrevious(samples, "layers-root", /Hero Section/); + expectSpacerNearDragged(samples, "layers-root", 48); + }); + + test("keeps draggable sub-container ghost aligned after resized groups", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const cell = await demoBoxByHeading(page, "Draggable Sub-Containers"); + const group1B = await itemByTextIn(cell, "Group 1 - B"); + const group2 = cell + .locator(".snapsort-container") + .filter({ hasText: "Group 2 - A" }) + .nth(1); + await expect(group2).toBeVisible(); + const group1BRect = await itemRect(group1B); + const group1BCenter = center(group1BRect); + const group2Rect = await itemRect(group2); + const targetCenterY = + group2Rect.y + group2Rect.height + group1BRect.height / 2 + 12; + const samples = await dragBy( + page, + group1B, + "Group 1 - B", + 0, + { + x: 0, + y: targetCenterY - group1BCenter.y, + }, + { steps: 240 }, + ); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("drag-subcontainer-offset-trace.json"), + { assertCenter: false }, + ); + expectSpacerAlignedAfterPrevious(samples, "drag-root", /Group 2 - A/); + expectSpacerNearDragged(samples, "drag-root", 48); + }); + + test("keeps nested container drop prediction stable for padded sub-items", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const item = await itemByText(page, "Sub A2"); + const samples = await dragBy(page, item, "Sub A2", 0, { x: 0, y: 95 }); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("nested-subitem-trace.json"), + ); + }); + + test("resolves multiple-drop-area container conflicts without spacer flicker", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + + const item = await itemByText(page, "Item B"); + const target = await itemByText(page, "Item Y"); + const samples = await dragTo(page, item, "Item B", 0, target); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("multi-area-trace.json"), + ); + }); + + test("keeps wrapped row indices aligned beyond the first row", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested", { waitUntil: "networkidle" }); + const doubleRow = await demoBoxByHeading(page, "Horizontal Double Row"); + + const item = await itemByTextIn(doubleRow, "Item 1"); + const target = await itemByTextIn(doubleRow, "Item 9"); + const samples = await dragTo(page, item, "Item 1", 0, target); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("wrapped-row-trace.json"), + ); + + const order = await doubleRow + .locator(".snapsort-item") + .evaluateAll((elements) => + elements.map((element) => element.textContent?.trim()), + ); + expect(order.slice(0, 10)).toEqual([ + "Item 2", + "Item 3", + "Item 4", + "Item 5", + "Item 6", + "Item 7", + "Item 8", + "Item 9", + "Item 1", + "Item 10", + ]); + }); +}); diff --git a/tests/e2e/snapsort/drag/website-core-repros.spec.ts b/tests/e2e/snapsort/drag/website-core-repros.spec.ts new file mode 100644 index 00000000..ee737980 --- /dev/null +++ b/tests/e2e/snapsort/drag/website-core-repros.spec.ts @@ -0,0 +1,309 @@ +import { expect, test } from "@playwright/test"; +import { contentRect } from "../../../../src/geometry"; +import { flowLayoutPositions } from "../../../helpers/layout-grid"; +import { + type Box, + center, + snapshotFixture, +} from "../../../helpers/snapsort-fixtures"; +import { + compressedSpacerStates, + demoBoxByHeading, + directLogoSliceOrder, + directSnapSortItemTexts, + dragBy, + dragToItemFraction, + expectNoParentReentry, + expectStableDrag, + installSnapsortTrace, + itemByTextIn, + itemRect, + websiteCoreDemo, + writeJson, +} from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test.beforeEach(async ({ page }) => { + await installSnapsortTrace(page); + }); + + test("keeps the final slot reachable in a plain vertical list", async ({ + page, + }) => { + await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { + waitUntil: "networkidle", + }); + + const verticalColumn = await demoBoxByHeading(page, "Vertical Column"); + const container = verticalColumn.locator(".snapsort-container").first(); + const item = await itemByTextIn(verticalColumn, "Item 1"); + const target = await itemByTextIn(verticalColumn, "Item 4"); + + await dragToItemFraction(page, item, "Item 1", 0, target, 1.05, { + steps: 80, + }); + + await expect + .poll(() => directSnapSortItemTexts(container)) + .toEqual(["Item 2", "Item 3", "Item 4", "Item 1"]); + }); + + test("reproduces website sideways list final-slot placement", async ({ + page, + }) => { + await page.goto("/?demo=snapsort_website_core", { + waitUntil: "networkidle", + }); + + const card = await websiteCoreDemo(page, "sideways-list"); + const container = card.locator(".sideways-list"); + await expect + .poll(() => directLogoSliceOrder(container)) + .toEqual([3, 0, 5, 1, 4, 2]); + + const source = container.locator(".snapsort-item").first(); + const last = container.locator(".snapsort-item").last(); + const sourceRect = await itemRect(source); + const sourceCenter = center(sourceRect); + const lastRect = await itemRect(last); + const target = { + x: lastRect.x + lastRect.width + sourceRect.width / 2 + 24, + y: lastRect.y + lastRect.height / 2, + }; + + await dragBy( + page, + source, + "TypeScript slice 3", + 0, + { + x: target.x - sourceCenter.x, + y: target.y - sourceCenter.y, + }, + { steps: 140 }, + ); + + await expect + .poll(() => directLogoSliceOrder(container)) + .toEqual([0, 5, 1, 4, 2, 3]); + }); + + test("reproduces website nested bottom-slot stability", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=snapsort_website_core", { + waitUntil: "networkidle", + }); + + const card = await websiteCoreDemo(page, "nested-list"); + const source = await itemByTextIn(card, "Item 1"); + const target = await itemByTextIn(card, "Item 6"); + const handle = source.locator(".demo-row-handle").first(); + const start = center(await itemRect(handle)); + const targetRect = await itemRect(target); + const targetPoint = { + x: targetRect.x + targetRect.width / 2, + y: targetRect.y + targetRect.height * 1.15, + }; + const samples = await dragBy( + page, + source, + "Item 1", + 0, + { + x: targetPoint.x - start.x, + y: targetPoint.y - start.y, + }, + { + start, + steps: 240, + }, + ); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("website-nested-bottom-slot-trace.json"), + { assertCenter: false }, + ); + expectNoParentReentry( + samples, + "website-nested-inner", + "website-nested-outer", + "website core", + ); + + const states = compressedSpacerStates(samples, [ + "website-nested-inner", + "website-nested-outer", + ]); + await writeJson( + testInfo.outputPath("website-nested-bottom-slot-states.json"), + { + states, + }, + ); + expect( + states, + `ghost should reach the bottom slot of the website nested list; observed ${states.join(" -> ")}`, + ).toContain("website-nested-inner[3]"); + + const innerContainer = card.locator(".nested-list"); + await expect + .poll(() => directSnapSortItemTexts(innerContainer)) + .toEqual(["Item 4", "Item 5", "Item 6", "Item 1"]); + }); + + test("reproduces website 321px multi-container row layout parity", async ({ + page, + }, testInfo) => { + await page.goto("/?demo=snapsort_website_core", { + waitUntil: "networkidle", + }); + + const card = await websiteCoreDemo(page, "multiple-containers"); + const board = card.locator(".multi-container-board"); + await expect(board).toBeVisible(); + + const measured = await board.evaluate((element) => { + const number = (value: string) => Number.parseFloat(value) || 0; + const boxOf = (node: Element): Box => { + const rect = node.getBoundingClientRect(); + const style = getComputedStyle(node); + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + screen: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }, + margin: { + top: number(style.marginTop), + right: number(style.marginRight), + bottom: number(style.marginBottom), + left: number(style.marginLeft), + }, + padding: { + top: number(style.paddingTop), + right: number(style.paddingRight), + bottom: number(style.paddingBottom), + left: number(style.paddingLeft), + }, + border: { + top: number(style.borderTopWidth), + right: number(style.borderRightWidth), + bottom: number(style.borderBottomWidth), + left: number(style.borderLeftWidth), + }, + }; + }; + const columns = [...element.children].filter((child) => + child.classList.contains("basic-column"), + ); + const columnBoxes = columns.map((column, index) => ({ + id: `column-${index}`, + box: boxOf(column), + })); + return { + board: boxOf(element), + columns: columnBoxes, + domSameRow: + columnBoxes.length === 2 && + Math.abs(columnBoxes[0].box.y - columnBoxes[1].box.y) < 1, + }; + }); + + expect(measured.columns).toHaveLength(2); + expect( + measured.domSameRow, + "the browser DOM should keep both columns on one row", + ).toBe(true); + + const boardSnapshot = snapshotFixture({ + value: "website-multi-container-board", + direction: "row", + locked: true, + box: measured.board, + children: measured.columns.map((column) => ({ + value: column.id, + direction: "column", + locked: true, + box: column.box, + children: [], + })), + }); + const origin = contentRect(measured.board); + const layout = flowLayoutPositions(boardSnapshot, origin.x, origin.y); + const simulated = boardSnapshot.children.map((child) => { + const position = layout.itemPositions.get(child); + if (!position) { + throw new Error(`Missing simulated position for ${child.value}`); + } + return { id: child.value, ...position }; + }); + + await writeJson( + testInfo.outputPath("website-321px-multi-container-layout.json"), + { + measured, + simulated, + }, + ); + + expect( + Math.abs(simulated[0].y - simulated[1].y), + `layout engine should not wrap the second 321px column when the DOM stays on one row; simulated=${JSON.stringify(simulated)}`, + ).toBeLessThan(1); + + const source = await itemByTextIn(card, "Spec"); + const target = await itemByTextIn(card, "Ship"); + const sourceCenter = center(await itemRect(source)); + const targetRect = await itemRect(target); + const samples = await dragBy( + page, + source, + "Spec", + 0, + { + x: targetRect.x + targetRect.width / 2 - sourceCenter.x, + y: targetRect.y + targetRect.height * 1.15 - sourceCenter.y, + }, + { + captureFrameRects: true, + steps: 160, + }, + ); + const wrappedFrames = samples.flatMap((sample) => { + const columns = + sample.frameRects?.filter( + (entry) => + entry.role === "container" && + (/^Left\b/.test(entry.text) || /^Right\b/.test(entry.text)), + ) ?? []; + if (columns.length !== 2) return []; + + const deltaY = Math.abs(columns[0].rect.y - columns[1].rect.y); + return deltaY > 1 ? [{ step: sample.step, deltaY, columns }] : []; + }); + + await writeJson( + testInfo.outputPath("website-321px-multi-container-drag.json"), + { + wrappedFrames, + samples, + }, + ); + + expect( + wrappedFrames, + "left and right containers should stay on one visual row during the 321px drag", + ).toHaveLength(0); + }); +}); diff --git a/tests/e2e/snapsort-fail-safe.spec.ts b/tests/e2e/snapsort/errors/fail-safe.spec.ts similarity index 98% rename from tests/e2e/snapsort-fail-safe.spec.ts rename to tests/e2e/snapsort/errors/fail-safe.spec.ts index ff7e70d5..1bc03ca8 100644 --- a/tests/e2e/snapsort-fail-safe.spec.ts +++ b/tests/e2e/snapsort/errors/fail-safe.spec.ts @@ -1,4 +1,5 @@ import { expect, test, type Locator, type Page } from "@playwright/test"; +import { coreImportPath } from "../../shared/servers"; async function rect(locator: Locator) { const box = await locator.boundingBox(); @@ -19,7 +20,6 @@ async function verticalColumn(page: Page): Promise { } async function setGhostRemoveAvailable(page: Page, available: boolean) { - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; await page.evaluate( async ({ coreImportPath, available }) => { const { GlobalManager } = await import(coreImportPath); @@ -58,7 +58,6 @@ async function setGhostRemoveAvailable(page: Page, available: boolean) { } async function setItemMoveFailure(page: Page, enabled: boolean) { - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; await page.evaluate( async ({ coreImportPath, enabled }) => { const { GlobalManager } = await import(coreImportPath); @@ -138,7 +137,6 @@ async function setItemMoveFailure(page: Page, enabled: boolean) { } async function verticalColumnSessionStatus(page: Page): Promise { - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; return page.evaluate( async ({ coreImportPath }) => { const { GlobalManager } = await import(coreImportPath); diff --git a/tests/e2e/snapsort-adapter-ghosts.spec.ts b/tests/e2e/snapsort/ghosts/adapter-ghosts.svelte.spec.ts similarity index 96% rename from tests/e2e/snapsort-adapter-ghosts.spec.ts rename to tests/e2e/snapsort/ghosts/adapter-ghosts.svelte.spec.ts index be8a7593..d539d5dd 100644 --- a/tests/e2e/snapsort-adapter-ghosts.spec.ts +++ b/tests/e2e/snapsort/ghosts/adapter-ghosts.svelte.spec.ts @@ -1,15 +1,8 @@ import { expect, test, type Locator, type Page } from "@playwright/test"; +import { coreImportPath } from "../../shared/servers"; -// This spec asserts on Svelte-adapter-specific implementation details -// (`data-snapsort-ghost-entry`, emitted by the framework-owned Ghost -// component) — it has no React-adapter equivalent yet, so it only runs under -// the svelte project. -test.beforeEach(async ({}, testInfo) => { - test.skip( - !testInfo.project.name.startsWith("svelte"), - "Svelte-adapter-specific ghost ownership marker", - ); -}); +// Svelte-only because the React demo has no multi-item pointer-preview +// fixture; the other ghost-entry tests here also pass on React. async function rect(locator: Locator) { const box = await locator.boundingBox(); @@ -131,6 +124,11 @@ test.describe("SnapSort adapter-rendered ghost entries", () => { await page.mouse.up(); await page.waitForTimeout(250); await expect(column.locator("[data-snapsort-ghost-entry]")).toHaveCount(0); + // The pair lands as a contiguous run. + const order = await column + .locator(".snapsort-item") + .evaluateAll((els) => els.map((el) => el.textContent?.trim())); + expect(order).toEqual(["Item 1", "Item 4", "Item 2", "Item 3"]); }); test("a multi-item preview uses one pointer Ghost while flow feedback keeps its target run", async ({ @@ -145,7 +143,6 @@ test.describe("SnapSort adapter-rendered ghost entries", () => { // Install the override after selection updates settle because Svelte's // adapter refreshes its callback wrapper when reactive config reruns. - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; await page.evaluate( async ({ coreImportPath }) => { const { GlobalManager } = await import(coreImportPath); @@ -187,6 +184,7 @@ test.describe("SnapSort adapter-rendered ghost entries", () => { const result = originalDragStart?.(event); if (result === false) return false; event.session.dragVisual = "preview"; + return undefined; }, }; }, diff --git a/tests/e2e/snapsort-insertion-copy.spec.ts b/tests/e2e/snapsort/insertion/insertion-copy.spec.ts similarity index 99% rename from tests/e2e/snapsort-insertion-copy.spec.ts rename to tests/e2e/snapsort/insertion/insertion-copy.spec.ts index b16ee1c5..386ce17b 100644 --- a/tests/e2e/snapsort-insertion-copy.spec.ts +++ b/tests/e2e/snapsort/insertion/insertion-copy.spec.ts @@ -1,4 +1,5 @@ import { expect, test, type Locator, type Page } from "@playwright/test"; +import { coreImportPath } from "../../shared/servers"; async function rect(locator: Locator) { const box = await locator.boundingBox(); @@ -20,7 +21,6 @@ async function overrideInsertionDragVisual( page: Page, dragVisual: "item" | "preview" | "none", ) { - const coreImportPath = `/@fs${process.cwd()}/src/index.ts`; await page.evaluate( async ({ coreImportPath, dragVisual }) => { const { GlobalManager } = await import(coreImportPath); @@ -51,6 +51,7 @@ async function overrideInsertionDragVisual( const result = originalDragStart?.(event); if (result === false) return false; event.session.dragVisual = dragVisual; + return undefined; }, }; }, diff --git a/tests/e2e/snapsort/insertion/insertion-marker.spec.ts b/tests/e2e/snapsort/insertion/insertion-marker.spec.ts new file mode 100644 index 00000000..a6513b8f --- /dev/null +++ b/tests/e2e/snapsort/insertion/insertion-marker.spec.ts @@ -0,0 +1,106 @@ +import { expect, test } from "@playwright/test"; +import { center } from "../../../helpers/snapsort-fixtures"; +import { itemRect } from "../_support/drag-harness"; + +test.describe("SnapSort insertion marker strategy", () => { + test("keeps insertion marker absolute and does not displace siblings during hover", async ({ + page, + }) => { + await page.goto("/snapsort-insertion", { waitUntil: "networkidle" }); + + const firstList = page.locator(".insertion-list").first(); + const firstCard = firstList.locator(".insertion-card").first(); + const secondCard = firstList.locator(".insertion-card").nth(1); + + const firstRect = await itemRect(firstCard); + const secondBefore = await itemRect(secondCard); + const start = center(firstRect); + + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move(start.x, start.y + firstRect.height + 18); + await page.waitForTimeout(120); + + const marker = page.locator('[data-snapsort-ghost="insertion"]').first(); + await expect(marker).toHaveCount(1); + + const markerState = await marker.evaluate((element) => { + const style = window.getComputedStyle(element); + const rect = element.getBoundingClientRect(); + return { + position: style.position, + inlineHeight: element.style.height, + computedHeight: style.height, + borderTopWidth: style.borderTopWidth, + rectHeight: rect.height, + }; + }); + expect(markerState.position).toBe("absolute"); + expect(markerState.inlineHeight).toBe("3px"); + expect(markerState.computedHeight).toBe("3px"); + expect(markerState.borderTopWidth).toBe("0px"); + expect(markerState.rectHeight).toBeCloseTo(3, 1); + + const secondDuring = await itemRect(secondCard); + expect(Math.abs(secondDuring.x - secondBefore.x)).toBeLessThan(1); + expect(Math.abs(secondDuring.y - secondBefore.y)).toBeLessThan(1); + + await page.mouse.up(); + }); + + test("moves one stable marker between both outer edges of the current item", async ({ + page, + }) => { + await page.goto("/snapsort-insertion", { waitUntil: "networkidle" }); + + const firstList = page.locator(".insertion-list").first(); + const cards = firstList.locator(".insertion-card"); + const dragged = cards.nth(1); + const beforeOrder = await cards.locator("strong").allTextContents(); + const firstBefore = await itemRect(cards.first()); + const draggedBefore = await itemRect(dragged); + const thirdBefore = await itemRect(cards.nth(2)); + const start = center(draggedBefore); + + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + // The move that crosses the drag threshold only starts the session; its + // position is not resolved. Start the drag first so the next move is the + // first one that places the marker. + await page.mouse.move(start.x + 6, start.y); + await page.waitForTimeout(60); + await page.mouse.move(start.x, draggedBefore.y + 4); + await page.waitForTimeout(120); + + const marker = page.locator('[data-snapsort-ghost="insertion"]'); + await expect(marker).toHaveCount(1); + const leadingRect = await itemRect(marker); + await marker.evaluate((element) => { + element.setAttribute("data-test-marker-identity", "stable"); + }); + + await page.mouse.move(start.x, draggedBefore.y + draggedBefore.height - 4); + await page.waitForTimeout(120); + + await expect(marker).toHaveCount(1); + await expect( + page.locator('[data-test-marker-identity="stable"]'), + ).toHaveCount(1); + const trailingRect = await itemRect(marker); + expect(trailingRect.y - leadingRect.y).toBeGreaterThan( + draggedBefore.height / 2, + ); + + for (const [current, before] of [ + [await itemRect(cards.first()), firstBefore], + [await itemRect(cards.nth(2)), thirdBefore], + ]) { + expect(Math.abs(current.x - before.x)).toBeLessThan(1); + expect(Math.abs(current.y - before.y)).toBeLessThan(1); + } + + await page.mouse.up(); + await expect(marker).toHaveCount(0); + await expect(cards.locator("strong")).toHaveText(beforeOrder); + }); +}); diff --git a/tests/e2e/snapsort-keyboard-demo.spec.ts b/tests/e2e/snapsort/keyboard/keyboard-demo.svelte.spec.ts similarity index 82% rename from tests/e2e/snapsort-keyboard-demo.spec.ts rename to tests/e2e/snapsort/keyboard/keyboard-demo.svelte.spec.ts index 01bd0f9c..45221dd1 100644 --- a/tests/e2e/snapsort-keyboard-demo.spec.ts +++ b/tests/e2e/snapsort/keyboard/keyboard-demo.svelte.spec.ts @@ -72,6 +72,9 @@ test("direct movement animates the active item between candidate slots", async ( const item = page.locator('[data-task-id="outline"]'); await outline.focus(); await page.keyboard.press("Enter"); + // Trace the move only once the lift is active; an arrow pressed while the + // lift is still activating is consumed without moving (covered below). + await expect(item).toHaveAttribute("data-snapsort-dragging", "true"); const source = await item.evaluate((element) => { const rect = element.getBoundingClientRect(); return { @@ -101,6 +104,34 @@ test("direct movement animates the active item between candidate slots", async ( await page.keyboard.press("Escape"); }); +test("an arrow pressed while the lift activates never scrolls the page", async ({ + page, +}) => { + await page.goto("/snapsort-keyboard", { waitUntil: "networkidle" }); + await page.locator('[data-keyboard-handle="outline"]').focus(); + + // Enter and ArrowDown in the same task: the ArrowDown reaches the + // controller before the lift has activated its candidates, so there is no + // target to move yet — but the key must still be consumed. + const arrowPrevented = await page.evaluate(() => { + const target = document.activeElement!; + const keydown = (key: string) => { + const event = new KeyboardEvent("keydown", { + key, + bubbles: true, + cancelable: true, + }); + target.dispatchEvent(event); + return event.defaultPrevented; + }; + keydown("Enter"); + return keydown("ArrowDown"); + }); + + expect(arrowPrevented).toBe(true); + await page.keyboard.press("Escape"); +}); + test("direct movement interpolates destination width and height", async ({ page, }) => { diff --git a/tests/e2e/snapsort/layout.playwright.config.ts b/tests/e2e/snapsort/layout.playwright.config.ts new file mode 100644 index 00000000..563b944b --- /dev/null +++ b/tests/e2e/snapsort/layout.playwright.config.ts @@ -0,0 +1,56 @@ +// SnapSort layout-engine suite across Chromium, Firefox, and WebKit. Cross- +// browser coverage matters most here: the layout engine reconciles simulated +// sums with browser-measured geometry, and each engine quantizes layout +// differently (Blink/WebKit 1/64px; Gecko 1/60px app units with ~1e-5px +// getBoundingClientRect conversion noise). Also runs the pure layout-engine +// unit tests from tests/ut/core-layout.spec.ts. +// +// Run with: npm run test:layout +import { defineConfig } from "@playwright/test"; +import { resolve } from "node:path"; +import { + BROWSERS, + PORTS, + baseURL, + demoServer, + repoRoot, + sharedUse, +} from "../shared/servers"; + +/** + * Specs whose outcome depends on browser layout: simulation-vs-DOM parity and + * drags whose drop targets come from measured geometry. Pure lifecycle and + * framework-state specs run once, on Chromium, in playwright.config.ts. + */ +const layoutSpecs = [ + "layout/**/*.spec.ts", + "drag/drop-prediction.spec.ts", + "drag/spacer-stability.spec.ts", + "drag/website-core-repros.spec.ts", + "nested/**/*.spec.ts", +]; + +export default defineConfig({ + testDir: ".", + fullyParallel: false, + workers: 1, + reporter: [["list"]], + projects: [ + { + name: "layout-ut", + testDir: resolve(repoRoot, "tests/ut"), + testMatch: ["core-layout.spec.ts"], + }, + ...(["chromium", "firefox", "webkit"] as const).map((browser) => ({ + name: `svelte-${browser}`, + testMatch: layoutSpecs, + use: { + ...BROWSERS[browser], + ...sharedUse, + viewport: { width: 1400, height: 950 }, + baseURL: baseURL(PORTS.snapsortLayout), + }, + })), + ], + webServer: demoServer("svelte", PORTS.snapsortLayout), +}); diff --git a/tests/e2e/snapsort/layout/flex-double-row-fuzz.spec.ts b/tests/e2e/snapsort/layout/flex-double-row-fuzz.spec.ts new file mode 100644 index 00000000..63aa92d3 --- /dev/null +++ b/tests/e2e/snapsort/layout/flex-double-row-fuzz.spec.ts @@ -0,0 +1,84 @@ +import { expect, test } from "@playwright/test"; +import { contentRect } from "../../../../src/geometry"; +import { virtualInsertionPosition } from "../../../helpers/snapsort-fixtures"; +import { + horizontalDoubleRowLayoutCases, + layoutNodeFromBrowserCase, + measureBrowserLayoutCases, +} from "../_support/layout-parity"; +import { writeJson } from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test("matches browser flex ghost positions for horizontal double-row fuzz cases", async ({ + page, + }, testInfo) => { + const cases = horizontalDoubleRowLayoutCases(); + const measuredCases = await measureBrowserLayoutCases(page, cases); + const failures: Array<{ + name: string; + index: number; + expected: { x: number; y: number }; + actual: { x: number; y: number }; + delta: { x: number; y: number }; + }> = []; + + for (const measuredCase of measuredCases) { + const root = layoutNodeFromBrowserCase(measuredCase); + const dragged = root.children.find( + (item) => item.value === measuredCase.draggedId, + ); + expect( + dragged, + `dragged item should exist for ${measuredCase.name}`, + ).toBeTruthy(); + + const origin = contentRect(measuredCase.container); + for (const actual of measuredCase.actualGhosts) { + const simulated = virtualInsertionPosition( + root, + dragged!, + origin.x, + origin.y, + actual.index, + measuredCase.ghost.width, + measuredCase.ghost.height, + ); + expect( + simulated, + `simulated ghost should exist for ${measuredCase.name}[${actual.index}]`, + ).toBeTruthy(); + + const delta = { + x: Math.abs(simulated!.x - actual.x), + y: Math.abs(simulated!.y - actual.y), + }; + if (delta.x > 1.25 || delta.y > 1.25) { + failures.push({ + name: measuredCase.name, + index: actual.index, + expected: { x: actual.x, y: actual.y }, + actual: simulated!, + delta, + }); + } + } + } + + await writeJson( + testInfo.outputPath("horizontal-double-row-layout-fuzz.json"), + { + caseCount: measuredCases.length, + slotCount: measuredCases.reduce( + (count, measuredCase) => count + measuredCase.actualGhosts.length, + 0, + ), + failures, + }, + ); + + expect( + failures.slice(0, 8), + "layout engine ghost positions should match browser flex positions within 1.25px", + ).toHaveLength(0); + }); +}); diff --git a/tests/e2e/snapsort/layout/grid-slot-model.spec.ts b/tests/e2e/snapsort/layout/grid-slot-model.spec.ts new file mode 100644 index 00000000..e16e32a5 --- /dev/null +++ b/tests/e2e/snapsort/layout/grid-slot-model.spec.ts @@ -0,0 +1,262 @@ +import { expect, test } from "@playwright/test"; +import { contentRect } from "../../../../src/geometry"; +import { + flowLayoutPositions, + makeContainerSnapshot, + makeItemSnapshot, +} from "../../../helpers/layout-grid"; +import { type Box } from "../../../helpers/snapsort-fixtures"; +import { writeJson } from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test("matches browser grid placements across template variants (slot layout model)", async ({ + page, + }, testInfo) => { + // Ground truth for the slot layout model: for each grid template + // variant, remove the dragged item from a real `display:grid` DOM, + // insert a real spacer (with the dragged item's explicit size, as + // flow-ghost does) at several indices, and require the slot simulation + // to match the browser's placement of every entry within 1.25px. The + // unequal-track, auto-flow-column, and auto-rows variants are exactly + // the shapes the flow model cannot represent. + const scenarios = [ + { + name: "fixed equal tracks", + container: + "display:grid;grid-template-columns:repeat(4, 88px);gap:4px;width:380px;", + itemHeight: () => 40, + }, + { + name: "fractional tracks", + container: + "display:grid;grid-template-columns:repeat(4, 1fr);gap:4px;width:380.33px;", + itemHeight: () => 40, + }, + { + name: "unequal tracks", + container: + "display:grid;grid-template-columns:60px 140px 80px 88.33px;gap:4px;width:380.33px;", + itemHeight: () => 40, + }, + { + name: "auto-fill minmax", + container: + "display:grid;grid-template-columns:repeat(auto-fill, minmax(80px, 1fr));gap:4px;width:380.33px;", + itemHeight: () => 40, + }, + { + name: "auto-flow column", + container: + "display:grid;grid-auto-flow:column;grid-template-rows:repeat(4, 44px);gap:4px;width:max-content;", + itemHeight: () => 40, + }, + { + name: "auto rows with mixed item heights", + container: + "display:grid;grid-template-columns:repeat(4, 88px);grid-auto-rows:auto;gap:4px;width:380px;align-items:start;", + // item 0 (the dragged one) is tall: removing it shrinks its row in + // the real layout, which only the content-sized row variant tracks. + itemHeight: (index: number) => (index % 5 === 0 ? 80 : 40), + }, + ]; + const spacerIndices = [0, 3, 7, 14]; + const draggedIndex = 0; + + await page.setContent('
'); + const measured = await page.evaluate( + ({ cases, spacerIndices, draggedIndex }) => { + const fixture = document.querySelector( + "#grid-slot-fixture", + ) as HTMLElement; + const boxOf = (element: HTMLElement) => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const number = (value: string) => parseFloat(value) || 0; + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + screen: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }, + margin: { + top: number(style.marginTop), + right: number(style.marginRight), + bottom: number(style.marginBottom), + left: number(style.marginLeft), + }, + padding: { + top: number(style.paddingTop), + right: number(style.paddingRight), + bottom: number(style.paddingBottom), + left: number(style.paddingLeft), + }, + border: { + top: number(style.borderTopWidth), + right: number(style.borderRightWidth), + bottom: number(style.borderBottomWidth), + left: number(style.borderLeftWidth), + }, + }; + }; + const build = ( + entry: { container: string; itemHeights: number[] }, + spacer: { index: number; width: number; height: number } | null, + ) => { + fixture.innerHTML = ""; + const container = document.createElement("section"); + container.style.cssText = "box-sizing:border-box;" + entry.container; + fixture.appendChild(container); + const nodes: HTMLElement[] = []; + for (let i = 0; i < 16; i++) { + if (spacer && i === draggedIndex) continue; // dragged item lifted + const item = document.createElement("div"); + item.style.cssText = `box-sizing:border-box;background:#dbeafe;height:${entry.itemHeights[i]}px;`; + item.dataset.i = String(i); + nodes.push(item); + } + if (spacer) { + const spacerEl = document.createElement("div"); + spacerEl.id = "spacer"; + spacerEl.style.cssText = `box-sizing:border-box;background:#fecaca;width:${spacer.width}px;height:${spacer.height}px;`; + nodes.splice(Math.min(spacer.index, nodes.length), 0, spacerEl); + } + for (const node of nodes) container.appendChild(node); + return container; + }; + + return cases.map((entry) => { + const pristine = build(entry, null); + const containerBox = boxOf(pristine); + const itemBoxes = [...pristine.children].map((element) => + boxOf(element as HTMLElement), + ); + const dragged = itemBoxes[draggedIndex]; + const truths = spacerIndices.map((index) => { + const container = build(entry, { + index, + width: dragged.width, + height: dragged.height, + }); + let ghost: { x: number; y: number } | null = null; + const items: Array<{ id: string; x: number; y: number }> = []; + for (const element of container.children) { + const rect = element.getBoundingClientRect(); + if (element.id === "spacer") { + ghost = { x: rect.x, y: rect.y }; + } else { + items.push({ + id: (element as HTMLElement).dataset.i!, + x: rect.x, + y: rect.y, + }); + } + } + return { spacerIndex: index, ghost, items }; + }); + return { + name: entry.name, + container: containerBox, + itemBoxes, + truths, + }; + }); + }, + { + cases: scenarios.map((scenario) => ({ + name: scenario.name, + container: scenario.container, + itemHeights: Array.from({ length: 16 }, (_, i) => + scenario.itemHeight(i), + ), + })), + spacerIndices, + draggedIndex, + }, + ); + + const failures: Array<{ + name: string; + spacerIndex: number; + entry: string; + delta: number; + }> = []; + for (const grid of measured) { + const root = makeContainerSnapshot( + grid.container as Box, + grid.itemBoxes.map((box, index) => + makeItemSnapshot(`${index}`, box as Box), + ), + "row", + "start", + "slots", + ); + const dragged = root.children[draggedIndex]; + for (const truth of grid.truths) { + const insertion = { + container: root, + index: truth.spacerIndex, + entry: { + width: dragged.box.width, + height: dragged.box.height, + margin: dragged.box.margin, + }, + }; + const origin = contentRect(root.box); + const result = flowLayoutPositions(root, origin.x, origin.y, { + exclude: (node) => node === dragged, + insertions: [insertion], + }); + const actualById = new Map(truth.items.map((item) => [item.id, item])); + for (const [snapshotItem, position] of result.itemPositions) { + const actual = actualById.get(snapshotItem.value); + if (!actual) continue; + const delta = Math.max( + Math.abs(position.x - actual.x), + Math.abs(position.y - actual.y), + ); + if (delta > 1.25) { + failures.push({ + name: grid.name, + spacerIndex: truth.spacerIndex, + entry: `item-${snapshotItem.value}`, + delta: +delta.toFixed(2), + }); + } + } + const ghost = result.virtualRects.get(insertion); + expect( + ghost, + `ghost position for ${grid.name}[${truth.spacerIndex}]`, + ).toBeTruthy(); + const ghostDelta = truth.ghost + ? Math.max( + Math.abs(ghost!.x - truth.ghost.x), + Math.abs(ghost!.y - truth.ghost.y), + ) + : Infinity; + if (ghostDelta > 1.25) { + failures.push({ + name: grid.name, + spacerIndex: truth.spacerIndex, + entry: "ghost", + delta: +ghostDelta.toFixed(2), + }); + } + } + } + + await writeJson(testInfo.outputPath("grid-slot-model-ground-truth.json"), { + scenarioCount: measured.length, + failures: failures.slice(0, 40), + }); + expect( + failures.slice(0, 8), + "slot layout simulation should match browser grid placement within 1.25px", + ).toHaveLength(0); + }); +}); diff --git a/tests/e2e/snapsort/layout/hero-grid-wrap-matrix.spec.ts b/tests/e2e/snapsort/layout/hero-grid-wrap-matrix.spec.ts new file mode 100644 index 00000000..c820cd4c --- /dev/null +++ b/tests/e2e/snapsort/layout/hero-grid-wrap-matrix.spec.ts @@ -0,0 +1,173 @@ +import { expect, test } from "@playwright/test"; +import { + makeContainerSnapshot, + makeItemSnapshot, + rowCounts, + simulatedRowCounts, +} from "../../../helpers/layout-grid"; +import { type Box } from "../../../helpers/snapsort-fixtures"; +import { writeJson } from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test("keeps a zero-slack hero grid at 4 columns across sub-pixel container widths", async ({ + page, + }, testInfo) => { + // The landing-page hero pad grid is the worst case for wrap prediction: + // 4 columns of calc((100% - 12px) / 4) with a 4px gap sum *exactly* to + // the container width, leaving zero slack for measurement error. Each + // browser quantizes layout differently (Blink/WebKit on a 1/64px grid; + // Gecko in 1/60px app units whose getBoundingClientRect doubles carry + // ~1e-5px conversion noise), which historically over-wrapped the 4th + // column onto the 2nd row at fractional container widths. Sweep integer + // width bases crossed with increasingly granular sub-pixel offsets and + // assert the simulation keeps 4 items per row with a same-size ghost at + // every insertion index. + const bases = [356, 380, 397, 414, 430, 434, 443]; + const offsets = [ + 0, + 0.5, + 0.25, + 0.75, + 0.33, + 0.67, + 1 / 3, + 2 / 3, + 0.1, + 0.2, + 0.4, + 0.6, + 0.8, + 0.9, + 0.125, + 0.375, + 0.625, + 0.875, + 0.0625, + 0.03125, + 0.015625, + 0.0078125, + ]; + const widths = bases.flatMap((base) => + offsets.map((offset) => base + offset), + ); + + await page.setContent('
'); + const measuredGrids = await page.evaluate((caseWidths) => { + const fixture = document.querySelector( + "#hero-grid-fixture", + ) as HTMLElement; + const boxOf = (element: HTMLElement) => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const number = (value: string) => parseFloat(value) || 0; + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + screen: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }, + margin: { + top: number(style.marginTop), + right: number(style.marginRight), + bottom: number(style.marginBottom), + left: number(style.marginLeft), + }, + padding: { + top: number(style.paddingTop), + right: number(style.paddingRight), + bottom: number(style.paddingBottom), + left: number(style.paddingLeft), + }, + border: { + top: number(style.borderTopWidth), + right: number(style.borderRightWidth), + bottom: number(style.borderBottomWidth), + left: number(style.borderLeftWidth), + }, + }; + }; + return caseWidths.map((width) => { + fixture.innerHTML = ""; + const container = document.createElement("section"); + container.style.cssText = + "box-sizing:border-box;display:flex;flex-direction:row;flex-wrap:wrap;" + + `align-items:flex-start;align-content:flex-start;gap:4px;width:${width}px;`; + fixture.appendChild(container); + for (let index = 0; index < 16; index++) { + const item = document.createElement("div"); + item.style.cssText = + "box-sizing:border-box;width:calc((100% - 12px) / 4);height:40px;" + + "background:#dbeafe;"; + container.appendChild(item); + } + return { + width, + container: boxOf(container), + items: [...container.children].map((element) => + boxOf(element as HTMLElement), + ), + }; + }); + }, widths); + + const failures: Array<{ + width: number; + index: number | null; + rows: number[]; + }> = []; + for (const grid of measuredGrids) { + const root = makeContainerSnapshot( + grid.container as Box, + grid.items.map((box, index) => + makeItemSnapshot(`item-${index}`, box as Box), + ), + ); + const rowStep = root.children[4].box.y - root.children[0].box.y; + // Browser ground truth first: the real flex layout must show 4 rows + // of 4 before the simulation is held to the same shape. + const browserRows = rowCounts( + root.children.map((child) => child.box.y), + rowStep, + ); + if (browserRows.join() !== "4,4,4,4") { + failures.push({ width: grid.width, index: null, rows: browserRows }); + continue; + } + + const dragged = root.children[0]; + for (let index = 0; index <= 15; index++) { + const rows = simulatedRowCounts(root, { + rowStep, + insertion: { + container: root, + index, + entry: { + width: dragged.box.width, + height: dragged.box.height, + margin: dragged.box.margin, + }, + }, + exclude: (node) => node === dragged, + }); + if (rows.join() !== "4,4,4,4") { + failures.push({ width: grid.width, index, rows }); + } + } + } + + await writeJson(testInfo.outputPath("hero-grid-subpixel-matrix.json"), { + widthCount: measuredGrids.length, + insertionChecks: measuredGrids.length * 16, + failures: failures.slice(0, 40), + }); + expect( + failures.slice(0, 8), + "the 4th column must stay in the 4th column (not wrap to the 2nd row) at every sub-pixel width", + ).toHaveLength(0); + }); +}); diff --git a/tests/e2e/snapsort/layout/property-fuzz.spec.ts b/tests/e2e/snapsort/layout/property-fuzz.spec.ts new file mode 100644 index 00000000..e5487c3a --- /dev/null +++ b/tests/e2e/snapsort/layout/property-fuzz.spec.ts @@ -0,0 +1,244 @@ +import { expect, test } from "@playwright/test"; +import { contentRect } from "../../../../src/geometry"; +import { + flowLayoutPositions, + makeContainerSnapshot, + makeItemSnapshot, +} from "../../../helpers/layout-grid"; +import { type Box } from "../../../helpers/snapsort-fixtures"; +import { writeJson } from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test("layout simulation invariants hold across randomized containers (property fuzz)", async ({ + page, + }, testInfo) => { + // Property-based ground truth: instead of hand-picked scenarios, build + // seeded-random containers and assert invariants that must hold for ANY + // layout the engine claims to support: + // + // - identity: simulating with no exclusions/insertions reproduces the + // browser's measured positions; + // - away-and-back: excluding item k and inserting a same-size ghost at + // index k is a no-op — every other item stays put and the ghost lands + // on item k's measured rect; + // - locality: a ghost at index k never moves an entry before index k + // (compared against the identity simulation, so the bound is exact). + // + // The generator stays inside the engine's stated envelope (uniform gaps, + // no per-item margins, LTR, no spans); failures record their seed for + // deterministic repro. + const TOLERANCE = 1.25; + const caseCount = 36; + + await page.setContent('
'); + const measured = await page.evaluate((caseCount) => { + const fixture = document.querySelector( + "#property-fixture", + ) as HTMLElement; + let seed = 20260708; + const rand = () => { + seed = (seed * 1664525 + 1013904223) % 4294967296; + return seed / 4294967296; + }; + const between = (lo: number, hi: number) => lo + rand() * (hi - lo); + const int = (lo: number, hi: number) => Math.floor(between(lo, hi + 1)); + const boxOf = (element: HTMLElement) => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const number = (value: string) => parseFloat(value) || 0; + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + screen: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }, + margin: { + top: number(style.marginTop), + right: number(style.marginRight), + bottom: number(style.marginBottom), + left: number(style.marginLeft), + }, + padding: { + top: number(style.paddingTop), + right: number(style.paddingRight), + bottom: number(style.paddingBottom), + left: number(style.paddingLeft), + }, + border: { + top: number(style.borderTopWidth), + right: number(style.borderRightWidth), + bottom: number(style.borderBottomWidth), + left: number(style.borderLeftWidth), + }, + }; + }; + + const cases = []; + for (let index = 0; index < caseCount; index++) { + const caseSeed = seed; + const kind = rand() < 0.6 ? "flow" : "slots"; + const width = between(240, 520); + const gap = int(2, 12); + const pad = int(0, 12); + const border = int(0, 3); + const count = int(8, 16); + + fixture.innerHTML = ""; + const container = document.createElement("section"); + let containerCss = + `box-sizing:border-box;width:${width}px;padding:${pad}px;` + + `border:${border}px solid #111;`; + if (kind === "flow") { + containerCss += + "display:flex;flex-direction:row;flex-wrap:wrap;" + + `align-items:flex-start;align-content:flex-start;gap:${gap}px;`; + } else { + const templates = [ + `repeat(${int(3, 5)}, 1fr)`, + `repeat(auto-fill, minmax(${int(60, 90)}px, 1fr))`, + Array.from({ length: int(3, 4) }, () => `${int(50, 120)}px`).join( + " ", + ), + ]; + containerCss += + `display:grid;grid-template-columns:${templates[int(0, 2)]};` + + `gap:${gap}px;`; + } + container.style.cssText = containerCss; + fixture.appendChild(container); + for (let i = 0; i < count; i++) { + const item = document.createElement("div"); + let itemCss = `box-sizing:border-box;height:${int(24, 64)}px;background:#dbeafe;`; + if (kind === "flow") itemCss += `width:${between(30, 110)}px;`; + item.style.cssText = itemCss; + container.appendChild(item); + } + cases.push({ + caseSeed, + kind, + container: boxOf(container), + items: [...container.children].map((element) => + boxOf(element as HTMLElement), + ), + }); + } + return cases; + }, caseCount); + + const failures: Array<{ + caseSeed: number; + kind: string; + property: string; + detail: string; + delta: number; + }> = []; + const distance = ( + a: { x: number; y: number }, + b: { x: number; y: number }, + ) => Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y)); + + for (const propertyCase of measured) { + const root = makeContainerSnapshot( + propertyCase.container as Box, + propertyCase.items.map((box, index) => + makeItemSnapshot(`${index}`, box as Box), + ), + "row", + "start", + propertyCase.kind as "flow" | "slots", + ); + const origin = contentRect(root.box); + const record = (property: string, detail: string, delta: number) => + failures.push({ + caseSeed: propertyCase.caseSeed, + kind: propertyCase.kind, + property, + detail, + delta: +delta.toFixed(2), + }); + + // Identity: the simulation of the unmodified container must reproduce + // the measured layout. + const identity = flowLayoutPositions(root, origin.x, origin.y); + for (const child of root.children) { + const delta = distance(identity.itemPositions.get(child)!, child.box); + if (delta > TOLERANCE) record("identity", `item-${child.value}`, delta); + } + + const count = root.children.length; + for (const k of [0, Math.floor(count / 2), count - 1]) { + const target = root.children[k]; + + // Away-and-back: excluding item k and inserting an identical ghost + // at index k must be a no-op. + const insertion = { + container: root, + index: k, + entry: { + width: target.box.width, + height: target.box.height, + margin: target.box.margin, + }, + }; + const roundTrip = flowLayoutPositions(root, origin.x, origin.y, { + exclude: (node) => node === target, + insertions: [insertion], + }); + for (const child of root.children) { + if (child === target) continue; + const delta = distance( + roundTrip.itemPositions.get(child)!, + child.box, + ); + if (delta > TOLERANCE) { + record("away-and-back", `k=${k} item-${child.value}`, delta); + } + } + const ghost = roundTrip.virtualRects.get(insertion)!; + const ghostDelta = distance(ghost, target.box); + if (ghostDelta > TOLERANCE) { + record("away-and-back", `k=${k} ghost`, ghostDelta); + } + + // Locality: inserting at index k (no exclusion) must not move any + // entry before k. Compared against the identity simulation, so this + // bound is exact rather than tolerance-based. + const inserted = flowLayoutPositions(root, origin.x, origin.y, { + insertions: [ + { + container: root, + index: k, + entry: { + width: target.box.width, + height: target.box.height, + margin: target.box.margin, + }, + }, + ], + }); + for (let i = 0; i < k; i++) { + const child = root.children[i]; + const delta = distance( + inserted.itemPositions.get(child)!, + identity.itemPositions.get(child)!, + ); + if (delta > 0.01) record("locality", `k=${k} item-${i}`, delta); + } + } + } + + await writeJson(testInfo.outputPath("layout-property-fuzz.json"), { + caseCount: measured.length, + failures: failures.slice(0, 40), + }); + expect( + failures.slice(0, 8), + "identity / away-and-back / locality invariants should hold for every generated container", + ).toHaveLength(0); + }); +}); diff --git a/tests/e2e/snapsort/layout/stretch-ground-truth.spec.ts b/tests/e2e/snapsort/layout/stretch-ground-truth.spec.ts new file mode 100644 index 00000000..2b74099d --- /dev/null +++ b/tests/e2e/snapsort/layout/stretch-ground-truth.spec.ts @@ -0,0 +1,132 @@ +import { expect, test } from "@playwright/test"; +import { contentRect } from "../../../../src/geometry"; +import { virtualEntrySizeFor } from "../../../../src/layout"; +import { + flowLayoutPositions, + makeContainerSnapshot, + makeItemSnapshot, +} from "../../../helpers/layout-grid"; +import { type Box } from "../../../helpers/snapsort-fixtures"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test("stretch entry sizing matches a real width-100% spacer (ground truth)", async ({ + page, + }) => { + // A stretchItems container's simulated entry must match what the browser + // does with an unsized (stretch) flex child: fill the content box minus + // the entry's own margins — including fractional container widths, + // padding, and borders. + await page.setContent('
'); + const measured = await page.evaluate(() => { + const fixture = document.querySelector("#stretch-fixture") as HTMLElement; + const boxOf = (element: HTMLElement) => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const number = (value: string) => parseFloat(value) || 0; + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + screen: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }, + margin: { + top: number(style.marginTop), + right: number(style.marginRight), + bottom: number(style.marginBottom), + left: number(style.marginLeft), + }, + padding: { + top: number(style.paddingTop), + right: number(style.paddingRight), + bottom: number(style.paddingBottom), + left: number(style.paddingLeft), + }, + border: { + top: number(style.borderTopWidth), + right: number(style.borderRightWidth), + bottom: number(style.borderBottomWidth), + left: number(style.borderLeftWidth), + }, + }; + }; + const build = (withSpacer: boolean) => { + fixture.innerHTML = ""; + const container = document.createElement("section"); + container.style.cssText = + "box-sizing:border-box;display:flex;flex-direction:column;" + + "width:222.33px;padding:9px;border:2px solid #111;gap:6px;"; + fixture.appendChild(container); + for (let i = 0; i < 3; i++) { + const item = document.createElement("div"); + item.style.cssText = + "box-sizing:border-box;height:40px;background:#dbeafe;"; + item.dataset.i = String(i); + container.appendChild(item); + if (withSpacer && i === 0) { + // Unsized stretch flex child with margins: the browser's own + // notion of a "100% width" entry. + const spacer = document.createElement("div"); + spacer.id = "spacer"; + spacer.style.cssText = + "box-sizing:border-box;height:40px;margin:0 4px;background:#fecaca;"; + container.appendChild(spacer); + } + } + return container; + }; + const pristine = build(false); + const containerBox = boxOf(pristine); + const itemBoxes = [...pristine.children].map((element) => + boxOf(element as HTMLElement), + ); + const truth = build(true); + const spacer = truth.querySelector("#spacer") as HTMLElement; + const spacerRect = spacer.getBoundingClientRect(); + return { + container: containerBox, + itemBoxes, + spacer: { + x: spacerRect.x, + y: spacerRect.y, + width: spacerRect.width, + height: spacerRect.height, + }, + }; + }); + + const root = makeContainerSnapshot( + measured.container as Box, + measured.itemBoxes.map((box, index) => + makeItemSnapshot(`${index}`, box as Box), + ), + "column", + "start", + "flow", + { wrap: "nowrap", stretchItems: true }, + ); + const margin = { top: 0, right: 4, bottom: 0, left: 4 }; + const insertion = { + container: root, + index: 1, + entry: { + // Deliberately oversized base: the source container was wider. + ...virtualEntrySizeFor(root, { width: 500, height: 40, margin }), + margin, + }, + }; + const origin = contentRect(root.box); + const result = flowLayoutPositions(root, origin.x, origin.y, { + insertions: [insertion], + }); + const rect = result.virtualRects.get(insertion)!; + expect(Math.abs(rect.width - measured.spacer.width)).toBeLessThanOrEqual( + 1.25, + ); + expect(Math.abs(rect.y - measured.spacer.y)).toBeLessThanOrEqual(1.25); + }); +}); diff --git a/tests/e2e/snapsort/layout/unsupported-shapes.spec.ts b/tests/e2e/snapsort/layout/unsupported-shapes.spec.ts new file mode 100644 index 00000000..87d19c58 --- /dev/null +++ b/tests/e2e/snapsort/layout/unsupported-shapes.spec.ts @@ -0,0 +1,243 @@ +import { expect, test, type Page } from "@playwright/test"; +import { contentRect } from "../../../../src/geometry"; +import { + flowLayoutPositions, + makeContainerSnapshot, + makeItemSnapshot, +} from "../../../helpers/layout-grid"; +import { type Box } from "../../../helpers/snapsort-fixtures"; + +test.describe("Snapsort drag-start snapshot layout", () => { + // Documented-unsupported layout shapes, encoded as expected failures so + // the boundary is visible in the test report and any accidental fix or + // regression flips the result. Each builds a real DOM, inserts a real + // spacer, and counts entries where the simulation misses the browser's + // placement by more than 1.25px. + async function unsupportedShapeMismatches( + page: Page, + config: { + containerCss: string; + itemCss: string[]; + itemInnerHeights?: number[]; + layoutModel: "flow" | "slots"; + spacerIndices: number[]; + }, + ): Promise { + await page.setContent('
'); + const measured = await page.evaluate((cfg) => { + const fixture = document.querySelector( + "#unsupported-fixture", + ) as HTMLElement; + const boxOf = (element: HTMLElement) => { + const rect = element.getBoundingClientRect(); + const style = getComputedStyle(element); + const number = (value: string) => parseFloat(value) || 0; + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + screen: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }, + margin: { + top: number(style.marginTop), + right: number(style.marginRight), + bottom: number(style.marginBottom), + left: number(style.marginLeft), + }, + padding: { + top: number(style.paddingTop), + right: number(style.paddingRight), + bottom: number(style.paddingBottom), + left: number(style.paddingLeft), + }, + border: { + top: number(style.borderTopWidth), + right: number(style.borderRightWidth), + bottom: number(style.borderBottomWidth), + left: number(style.borderLeftWidth), + }, + }; + }; + const build = ( + spacer: { index: number; width: number; height: number } | null, + ) => { + fixture.innerHTML = ""; + const container = document.createElement("section"); + container.style.cssText = "box-sizing:border-box;" + cfg.containerCss; + fixture.appendChild(container); + const nodes: HTMLElement[] = []; + for (let i = 0; i < cfg.itemCss.length; i++) { + if (spacer && i === 0) continue; // dragged item lifted + const item = document.createElement("div"); + item.style.cssText = + "box-sizing:border-box;background:#dbeafe;" + cfg.itemCss[i]; + item.dataset.i = String(i); + const innerHeight = cfg.itemInnerHeights?.[i]; + if (innerHeight != null) { + const inner = document.createElement("div"); + inner.style.cssText = `height:${innerHeight}px;`; + item.appendChild(inner); + } + nodes.push(item); + } + if (spacer) { + const spacerEl = document.createElement("div"); + spacerEl.id = "spacer"; + spacerEl.style.cssText = `box-sizing:border-box;background:#fecaca;width:${spacer.width}px;height:${spacer.height}px;`; + nodes.splice(Math.min(spacer.index, nodes.length), 0, spacerEl); + } + for (const node of nodes) container.appendChild(node); + return container; + }; + + const pristine = build(null); + const containerBox = boxOf(pristine); + const itemBoxes = [...pristine.children].map((element) => + boxOf(element as HTMLElement), + ); + const dragged = itemBoxes[0]; + const truths = cfg.spacerIndices.map((index) => { + const container = build({ + index, + width: dragged.width, + height: dragged.height, + }); + let ghost: { x: number; y: number } | null = null; + const items: Array<{ id: string; x: number; y: number }> = []; + for (const element of container.children) { + const rect = element.getBoundingClientRect(); + if (element.id === "spacer") ghost = { x: rect.x, y: rect.y }; + else { + items.push({ + id: (element as HTMLElement).dataset.i!, + x: rect.x, + y: rect.y, + }); + } + } + return { spacerIndex: index, ghost, items }; + }); + return { container: containerBox, itemBoxes, truths }; + }, config); + + const root = makeContainerSnapshot( + measured.container as Box, + measured.itemBoxes.map((box, index) => + makeItemSnapshot(`${index}`, box as Box), + ), + "row", + "start", + config.layoutModel, + ); + const dragged = root.children[0]; + let mismatches = 0; + for (const truth of measured.truths) { + const insertion = { + container: root, + index: truth.spacerIndex, + entry: { + width: dragged.box.width, + height: dragged.box.height, + margin: dragged.box.margin, + }, + }; + const origin = contentRect(root.box); + const result = flowLayoutPositions(root, origin.x, origin.y, { + exclude: (node) => node === dragged, + insertions: [insertion], + }); + const actualById = new Map(truth.items.map((item) => [item.id, item])); + for (const [snapshotItem, position] of result.itemPositions) { + const actual = actualById.get(snapshotItem.value); + if (!actual) continue; + if ( + Math.max( + Math.abs(position.x - actual.x), + Math.abs(position.y - actual.y), + ) > 1.25 + ) { + mismatches++; + } + } + const ghost = result.virtualRects.get(insertion); + if ( + !ghost || + !truth.ghost || + Math.max( + Math.abs(ghost.x - truth.ghost.x), + Math.abs(ghost.y - truth.ghost.y), + ) > 1.25 + ) { + mismatches++; + } + } + return mismatches; + } + + test("documents unsupported: RTL flex containers", async ({ page }) => { + test.fail( + true, + "The flow model assumes LTR main-axis growth: RTL offsets regress per item, so line detection and positions are mirrored. Slot mode covers RTL grids; RTL flex is out of scope.", + ); + const mismatches = await unsupportedShapeMismatches(page, { + containerCss: + "display:flex;flex-wrap:wrap;direction:rtl;width:380.33px;gap:4px;" + + "align-items:flex-start;align-content:flex-start;", + itemCss: Array.from( + { length: 16 }, + () => "width:calc((100% - 12px)/4);height:40px;", + ), + layoutModel: "flow", + spacerIndices: [0, 3, 7], + }); + expect(mismatches).toBe(0); + }); + + test("documents unsupported: grid items spanning multiple tracks", async ({ + page, + }) => { + test.fail( + true, + "Slot mode assumes one entry per slot: a span-2 item makes slot geometry depend on placement, which reordering invalidates.", + ); + const mismatches = await unsupportedShapeMismatches(page, { + containerCss: + "display:grid;grid-template-columns:repeat(4, 88px);gap:4px;width:380px;", + itemCss: Array.from({ length: 14 }, (_, i) => + i === 5 ? "height:40px;grid-column:span 2;" : "height:40px;", + ), + layoutModel: "slots", + spacerIndices: [0, 3, 7], + }); + expect(mismatches).toBe(0); + }); + + test("documents unsupported: stretch items with intrinsic heights across content-sized rows", async ({ + page, + }) => { + test.fail( + true, + "Items with align-self:stretch and no explicit height measure at their row's height, not their intrinsic height; when displaced across content-sized rows the simulation carries the stale stretched height. Predicting the true height would require intrinsic sizing per destination track.", + ); + const mismatches = await unsupportedShapeMismatches(page, { + containerCss: + "display:grid;grid-template-columns:repeat(3, 110px);grid-auto-rows:auto;gap:4px;width:346px;", + // No explicit item heights: each stretches to its row. Item 0's inner + // content is 90px tall, making row 1's track 90 and stretching its + // short siblings to 90 as measured. Removing item 0 shrinks row 1 to + // 30 in the real layout; the simulation keeps the stale 90. + itemCss: Array.from({ length: 9 }, () => ""), + itemInnerHeights: Array.from({ length: 9 }, (_, i) => + i === 0 ? 90 : 30, + ), + layoutModel: "slots", + spacerIndices: [8], + }); + expect(mismatches).toBe(0); + }); +}); diff --git a/tests/e2e/snapsort/nested/nested-commit.spec.ts b/tests/e2e/snapsort/nested/nested-commit.spec.ts new file mode 100644 index 00000000..3d2ef446 --- /dev/null +++ b/tests/e2e/snapsort/nested/nested-commit.spec.ts @@ -0,0 +1,592 @@ +import { expect, test } from "@playwright/test"; +import { type Rect } from "../../../../src/geometry"; +import { center } from "../../../helpers/snapsort-fixtures"; +import { + type DragSample, + collectSample, + demoBoxByHeading, + directSnapSortChildTexts, + directSnapSortItemTexts, + dragBy, + dragTo, + dragToItemFraction, + expectNoNestedParentFlicker, + expectStableDrag, + installSnapsortTrace, + itemByTextIn, + itemRect, + writeJson, +} from "../_support/drag-harness"; + +test.describe("Snapsort drag-start snapshot layout", () => { + test.beforeEach(async ({ page }) => { + await installSnapsortTrace(page); + }); + + test("keeps dragged item aligned while entering a slowly animating nested container", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { + waitUntil: "networkidle", + }); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const item = await itemByTextIn(nested, "Item 1"); + const target = await itemByTextIn(nested, "Sub A3"); + const samples = await dragTo(page, item, "Item 1", 0, target); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("nested-slow-animation-drag-trace.json"), + ); + expectNoNestedParentFlicker(samples); + }); + + test("keeps the drop animation visible while a reorder animation is still active", async ({ + page, + }, testInfo) => { + await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { + waitUntil: "networkidle", + }); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const innerContainer = nested.locator(".snapsort-container").nth(1); + const source = await itemByTextIn(innerContainer, "Sub A1"); + const target = await itemByTextIn(innerContainer, "Sub A3"); + const sourceRect = await itemRect(source); + const targetRect = await itemRect(target); + const start = center(sourceRect); + const releasePoint = { + x: targetRect.x + targetRect.width / 2 + 18, + y: targetRect.y + targetRect.height * 0.85, + }; + + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move(start.x + 5, start.y); + await page.waitForTimeout(16); + for (let step = 1; step <= 14; step++) { + await page.mouse.move( + start.x + ((releasePoint.x - start.x) * step) / 14, + start.y + ((releasePoint.y - start.y) * step) / 14, + ); + await page.waitForTimeout(12); + } + + // Prove the release happens during the condition that caused the bug: + // at least one displaced sibling still has a reorder FLIP transform. + await expect + .poll( + () => + innerContainer + .locator(".snapsort-item") + .evaluateAll((nodes) => + nodes.some( + (node) => + !node.textContent?.includes("Sub A1") && + (node as HTMLElement).style.transform !== "", + ), + ), + { intervals: [10, 20, 40], timeout: 300 }, + ) + .toBe(true); + + const releaseRect = await itemRect(source); + await page.evaluate(() => { + type DropFrame = { + time: number; + rect: Rect; + inlineTransform: string; + computedTransform: string; + dragging: boolean; + displacedTransformCount: number; + }; + type StyleMutation = { + time: number; + oldValue: string | null; + currentValue: string; + }; + const win = window as unknown as { + __dropContinuityTrace?: { + done: boolean; + frames: DropFrame[]; + styleMutations: StyleMutation[]; + }; + }; + const trace = { + done: false, + frames: [] as DropFrame[], + styleMutations: [] as StyleMutation[], + }; + win.__dropContinuityTrace = trace; + + const nested = [...document.querySelectorAll(".demo-cell")].find( + (element) => + element.querySelector("h2")?.textContent?.trim() === + "Nested Container", + ); + if (!nested) throw new Error("Nested Container fixture was not found."); + const itemText = (element: Element) => + element.querySelector(":scope > p")?.textContent?.trim() ?? ""; + const findDraggedItem = () => + [...nested.querySelectorAll(".snapsort-item")].find( + (element) => itemText(element) === "Sub A1", + ) as HTMLElement | undefined; + const rectOf = (element: Element): Rect => { + const rect = element.getBoundingClientRect(); + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }; + }; + const startedAt = performance.now(); + const observer = new MutationObserver((mutations) => { + for (const mutation of mutations) { + if ( + mutation.target instanceof Element && + mutation.target.classList.contains("snapsort-item") && + itemText(mutation.target) === "Sub A1" + ) { + trace.styleMutations.push({ + time: performance.now() - startedAt, + oldValue: mutation.oldValue, + currentValue: + (mutation.target as HTMLElement).getAttribute("style") ?? "", + }); + } + } + }); + observer.observe(nested, { + attributes: true, + attributeFilter: ["style"], + attributeOldValue: true, + subtree: true, + }); + + const sample = () => { + const item = findDraggedItem(); + if (item) { + trace.frames.push({ + time: performance.now() - startedAt, + rect: rectOf(item), + inlineTransform: item.style.transform, + computedTransform: getComputedStyle(item).transform, + dragging: item.dataset.snapsortDragging === "true", + displacedTransformCount: [ + ...nested.querySelectorAll(".snapsort-item"), + ].filter( + (element) => + element !== item && + !element.id.includes("spacer") && + element.style.transform !== "", + ).length, + }); + } + if (performance.now() - startedAt < 1_050) { + requestAnimationFrame(sample); + return; + } + observer.disconnect(); + trace.done = true; + }; + requestAnimationFrame(sample); + }); + + await page.mouse.up(); + await expect + .poll( + () => + page.evaluate( + () => + ( + window as unknown as { + __dropContinuityTrace?: { done: boolean }; + } + ).__dropContinuityTrace?.done ?? false, + ), + { timeout: 2_000 }, + ) + .toBe(true); + + const trace = await page.evaluate( + () => + ( + window as unknown as { + __dropContinuityTrace: { + done: boolean; + frames: Array<{ + time: number; + rect: Rect; + inlineTransform: string; + computedTransform: string; + dragging: boolean; + displacedTransformCount: number; + }>; + styleMutations: Array<{ + time: number; + oldValue: string | null; + currentValue: string; + }>; + }; + } + ).__dropContinuityTrace, + ); + await writeJson( + testInfo.outputPath("drop-animation-continuity-trace.json"), + { releaseRect, ...trace }, + ); + + const postDropFrames = trace.frames.filter((frame) => !frame.dragging); + expect(postDropFrames.length).toBeGreaterThan(20); + const finalFrame = postDropFrames.at(-1)!; + const centerDistance = (a: Rect, b: Rect) => { + const aCenter = center(a); + const bCenter = center(b); + return Math.hypot(aCenter.x - bCenter.x, aCenter.y - bCenter.y); + }; + const travel = centerDistance(releaseRect, finalFrame.rect); + expect(travel).toBeGreaterThan(12); + + const firstPaintedDropFrame = postDropFrames[0]; + expect( + centerDistance(firstPaintedDropFrame.rect, releaseRect), + "the first painted drop frame should remain at the pointer release position", + ).toBeLessThan(Math.max(4, travel * 0.15)); + expect( + postDropFrames.some((frame) => frame.inlineTransform !== ""), + "the drop FLIP transform should remain visible after release", + ).toBe(true); + + const distancesToFinal = postDropFrames.map((frame) => + centerDistance(frame.rect, finalFrame.rect), + ); + const firstSettledFrame = distancesToFinal.findIndex( + (distance) => distance <= 1, + ); + if (firstSettledFrame !== -1) { + expect( + Math.max(...distancesToFinal.slice(firstSettledFrame)), + "the item must not reach its slot and then bounce away again", + ).toBeLessThanOrEqual(2); + } + + expect(finalFrame.inlineTransform).toBe(""); + await expect(source).not.toHaveAttribute("data-snapsort-dragging"); + await expect + .poll(() => directSnapSortItemTexts(innerContainer)) + .toEqual(["Sub A2", "Sub A3", "Sub A1"]); + }); + + test("keeps nested dragged item aligned while moving in and out of its container", async ({ + page, + }, testInfo) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { + waitUntil: "networkidle", + }); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const innerContainer = nested.locator(".snapsort-container").nth(1); + const item = await itemByTextIn(nested, "Sub A1"); + const activeId = await item.getAttribute("data-engine-id"); + const start = center(await itemRect(item)); + const innerRect = await itemRect(innerContainer); + const leftOutside = { + x: innerRect.x - 28, + y: start.y, + }; + const innerCenter = { + x: innerRect.x + innerRect.width / 2, + y: start.y, + }; + const path = [leftOutside, innerCenter, leftOutside, innerCenter]; + const samples: DragSample[] = []; + let previous = start; + + await page.evaluate( + ({ activeId }) => { + const win = window as unknown as { + __snapsortActiveText?: string; + __snapsortActiveIndex?: number; + __snapsortActiveId?: string; + }; + win.__snapsortActiveText = "Sub A1"; + win.__snapsortActiveIndex = 0; + win.__snapsortActiveId = activeId ?? ""; + }, + { activeId }, + ); + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move(start.x + 4, start.y); + await page.waitForTimeout(16); + + for (const point of path) { + for (let step = 1; step <= 24; step++) { + const ratio = step / 24; + const mouse = { + x: previous.x + (point.x - previous.x) * ratio, + y: previous.y + (point.y - previous.y) * ratio, + }; + await page.mouse.move(mouse.x, mouse.y); + await page.waitForTimeout(8); + samples.push(await collectSample(page, samples.length + 1, mouse)); + } + previous = point; + } + + await page.mouse.up(); + await page.waitForTimeout(100); + + await expectStableDrag( + page, + samples, + consoleMessages, + testInfo.outputPath("nested-in-out-drag-trace.json"), + ); + }); + + test("drops at the pending nested index after a quick same-container slot change", async ({ + page, + }) => { + await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { + waitUntil: "networkidle", + }); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const item = await itemByTextIn(nested, "Item 1"); + const subA1 = await itemByTextIn(nested, "Sub A1"); + const subA3 = await itemByTextIn(nested, "Sub A3"); + const itemCenter = center(await itemRect(item)); + const subA1Center = center(await itemRect(subA1)); + const subA3Rect = await itemRect(subA3); + const subA3AfterPoint = { + x: subA3Rect.x + subA3Rect.width / 2, + y: subA3Rect.y + subA3Rect.height * 0.85, + }; + + await page.mouse.move(itemCenter.x, itemCenter.y); + await page.mouse.down(); + await page.mouse.move(itemCenter.x, itemCenter.y + 6); + await page.waitForTimeout(16); + await page.mouse.move(subA1Center.x, subA1Center.y); + await page.waitForTimeout(24); + await page.mouse.move(subA3AfterPoint.x, subA3AfterPoint.y); + await page.mouse.up(); + await page.waitForTimeout(200); + + const innerContainer = nested.locator(".snapsort-container").nth(1); + await expect(innerContainer).toBeVisible(); + await expect + .poll(() => directSnapSortItemTexts(innerContainer)) + .toEqual(["Sub A1", "Sub A2", "Sub A3", "Item 1"]); + }); + + test("commits the hovered nested slot without animation", async ({ + page, + }) => { + await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { + waitUntil: "networkidle", + }); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const item = await itemByTextIn(nested, "Item 1"); + const subA1 = await itemByTextIn(nested, "Sub A1"); + const target = await itemByTextIn(nested, "Sub A3"); + const itemCenter = center(await itemRect(item)); + const subA1Center = center(await itemRect(subA1)); + + await page.mouse.move(itemCenter.x, itemCenter.y); + await page.mouse.down(); + await page.mouse.move(itemCenter.x, itemCenter.y + 6); + await page.waitForTimeout(16); + await page.mouse.move(subA1Center.x, subA1Center.y); + await page.waitForTimeout(120); + + const movedTargetRect = await itemRect(target); + await page.mouse.move( + movedTargetRect.x + movedTargetRect.width / 2, + movedTargetRect.y + movedTargetRect.height * 0.85, + ); + await page.mouse.up(); + await page.waitForTimeout(200); + + const innerContainer = nested.locator(".snapsort-container").nth(1); + await expect(innerContainer).toBeVisible(); + await expect + .poll(() => directSnapSortItemTexts(innerContainer)) + .toEqual(["Sub A1", "Sub A2", "Sub A3", "Item 1"]); + }); + + test("commits the hovered slot in a compact nested list", async ({ + page, + }) => { + await page.goto( + "/?demo=drop_snap_nested&disableNestedFlip=1&compactNested=1", + { + waitUntil: "networkidle", + }, + ); + + const nested = await demoBoxByHeading(page, "Compact Nested List"); + const item = await itemByTextIn(nested, "Overview"); + const target = await itemByTextIn(nested, "Container"); + await dragToItemFraction(page, item, "Overview", 0, target, 0.5, { + steps: 20, + }); + + const innerContainer = nested.locator(".snapsort-container").nth(1); + await expect(innerContainer).toBeVisible(); + await expect + .poll(() => directSnapSortItemTexts(innerContainer)) + .toEqual(["Container", "Overview", "Item", "Handle"]); + }); + + test("moves a nested item to the parent slot above its nested container", async ({ + page, + }) => { + const consoleMessages: string[] = []; + page.on("console", (message) => consoleMessages.push(message.text())); + await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { + waitUntil: "networkidle", + }); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const outerContainer = nested.locator(".snapsort-container").first(); + const innerContainer = nested.locator(".snapsort-container").nth(1); + const item = await itemByTextIn(nested, "Sub A1"); + const itemCenter = center(await itemRect(item)); + const innerRect = await itemRect(innerContainer); + const targetPoint = { + x: itemCenter.x - 12, + y: innerRect.y - 2, + }; + await dragBy( + page, + item, + "Sub A1", + 0, + { + x: targetPoint.x - itemCenter.x, + y: targetPoint.y - itemCenter.y, + }, + { steps: 120 }, + ); + + await expect + .poll(() => directSnapSortChildTexts(outerContainer)) + .toEqual([ + "Item 1", + "Item 1.5", + "Sub A1", + "Sub A2Sub A3", + "Item 2", + "Item 3", + ]); + expect( + consoleMessages.filter((message) => + /Missing drag snapshot|Unhandled|TypeError|ReferenceError/i.test( + message, + ), + ), + ).toHaveLength(0); + }); + + test("commits the hovered slot inside a locked nested container without animation", async ({ + page, + }) => { + await page.goto( + "/?demo=drop_snap_nested&disableNestedFlip=1&lockNestedChild=1", + { + waitUntil: "networkidle", + }, + ); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const item = await itemByTextIn(nested, "Item 1"); + const target = await itemByTextIn(nested, "Sub A3"); + await dragToItemFraction(page, item, "Item 1", 0, target, 0.85); + + const innerContainer = nested.locator(".snapsort-container").nth(1); + await expect(innerContainer).toBeVisible(); + await expect + .poll(() => directSnapSortItemTexts(innerContainer)) + .toEqual(["Sub A1", "Sub A2", "Sub A3", "Item 1"]); + }); + + test("places an item below a projected locked nested container without entering it", async ({ + page, + }) => { + await page.goto( + "/?demo=drop_snap_nested&disableNestedFlip=1&lockNestedChild=1", + { + waitUntil: "networkidle", + }, + ); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const outerContainer = nested.locator(".snapsort-container").first(); + const item = await itemByTextIn(nested, "Item 1"); + const target = await itemByTextIn(nested, "Item 2"); + await dragToItemFraction(page, item, "Item 1", 0, target, 0.5, { + steps: 70, + }); + + await expect + .poll(() => directSnapSortChildTexts(outerContainer)) + .toEqual([ + "Item 1.5", + "Sub A1Sub A2Sub A3", + "Item 2", + "Item 1", + "Item 3", + ]); + }); + + test("commits the first nested item slot without animation", async ({ + page, + }) => { + await page.goto("/?demo=drop_snap_nested&disableNestedFlip=1", { + waitUntil: "networkidle", + }); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const item = await itemByTextIn(nested, "Item 1"); + const target = await itemByTextIn(nested, "Sub A1"); + await dragToItemFraction(page, item, "Item 1", 0, target, 1.05, { + steps: 70, + }); + + const innerContainer = nested.locator(".snapsort-container").nth(1); + await expect(innerContainer).toBeVisible(); + await expect + .poll(() => directSnapSortItemTexts(innerContainer)) + .toEqual(["Sub A1", "Item 1", "Sub A2", "Sub A3"]); + }); + + test("commits the hovered nested slot while animation moves the container", async ({ + page, + }) => { + await page.goto("/?demo=drop_snap_nested&slowNestedFlip=1", { + waitUntil: "networkidle", + }); + + const nested = await demoBoxByHeading(page, "Nested Container"); + const item = await itemByTextIn(nested, "Item 1"); + const target = await itemByTextIn(nested, "Sub A3"); + await dragToItemFraction(page, item, "Item 1", 0, target, 0.85); + + const innerContainer = nested.locator(".snapsort-container").nth(1); + await expect(innerContainer).toBeVisible(); + await expect + .poll(() => directSnapSortItemTexts(innerContainer)) + .toEqual(["Sub A1", "Sub A2", "Sub A3", "Item 1"]); + }); +}); diff --git a/tests/e2e/snapsort/playwright.config.ts b/tests/e2e/snapsort/playwright.config.ts new file mode 100644 index 00000000..5d513cb8 --- /dev/null +++ b/tests/e2e/snapsort/playwright.config.ts @@ -0,0 +1,44 @@ +// SnapSort suite on Chromium for both framework adapters. Shared specs run +// on Svelte and React; `*.svelte.spec.ts` / `*.react.spec.ts` run only on +// their framework. `layout/**` renders its own markup instead of a demo, so it +// runs only in layout.playwright.config.ts, which also repeats the +// layout-sensitive drag specs cross-browser. +// +// Run with: npm run test:snapsort +import { defineConfig } from "@playwright/test"; +import { + BROWSERS, + PORTS, + baseURL, + demoServer, + sharedUse, +} from "../shared/servers"; + +const use = { + ...BROWSERS.chromium, + ...sharedUse, + viewport: { width: 1400, height: 950 }, +}; + +export default defineConfig({ + testDir: ".", + fullyParallel: false, + workers: 1, + reporter: [["list"]], + projects: [ + { + name: "svelte-chromium", + testIgnore: ["layout/**", "**/*.react.spec.ts"], + use: { ...use, baseURL: baseURL(PORTS.snapsortSvelte) }, + }, + { + name: "react-chromium", + testIgnore: ["layout/**", "**/*.svelte.spec.ts"], + use: { ...use, baseURL: baseURL(PORTS.snapsortReact) }, + }, + ], + webServer: [ + demoServer("svelte", PORTS.snapsortSvelte), + demoServer("react", PORTS.snapsortReact), + ], +}); diff --git a/tests/e2e/snapsort_drag.spec.ts b/tests/e2e/snapsort_drag.spec.ts deleted file mode 100644 index c9c00543..00000000 --- a/tests/e2e/snapsort_drag.spec.ts +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Snapsort drag/drop flicker regression test. - * - * Reproduces the reported bug where, while dragging an item, the drop ghost - * (a) sits far from the cursor and (b) flickers (jumps back and forth) between frames. - * - * Root cause: the drag-start layout snapshot froze each item at its absolute position, - * which still included the gap the dragged item occupied. Once the dragged item is - * removed the real DOM closes that gap and everything below shifts up, so the frozen - * candidate slots were offset by ~one item height and the chosen slot oscillated. - * - * This test drives a real pointer drag down a column, samples the ghost element's - * position every frame, and asserts: - * 1. ghost tracks the cursor — |ghostCenterY - mouseY| stays small throughout; - * 2. no flicker — as the cursor moves monotonically down, the ghost's - * position is (near-)monotonic: few direction reversals. - * - * It also captures the layout engine's per-frame "chosen" decision (from the - * LAYOUT_TRACE console output) and writes a frame-by-frame log + screenshots to - * test-results/ for inspection. - * - * Requires the SVELTE demo server on :3001, e.g.: - * start-server-and-test server:svelte http://localhost:3001 \ - * 'playwright test tests/e2e/snapsort_drag.spec.ts --project=chromium' - */ -import { test, expect, type Page } from "@playwright/test"; -import * as fs from "fs"; -import * as path from "path"; - -const port = 3001; -const OUT_DIR = path.resolve("test-results", "snapsort-drag"); - -interface Frame { - step: number; - mouseY: number; - ghostTop: number | null; - ghostCenterY: number | null; - chosen: string | null; // last layout-engine decision seen before this sample -} - -/** Read the live ghost spacer element's bounding rect from the page. */ -async function readGhost( - page: Page, -): Promise<{ top: number; height: number } | null> { - return page.evaluate(() => { - const el = document.querySelector(".snapsort-ghost") as HTMLElement | null; - if (!el) return null; - const r = el.getBoundingClientRect(); - return { top: r.top, height: r.height }; - }); -} - -test.describe("Snapsort drag ghost should track the cursor without flickering", () => { - test("dragging an item down a column keeps the ghost under the cursor and monotonic", async ({ - page, - }) => { - fs.mkdirSync(OUT_DIR, { recursive: true }); - - // Capture the layout engine's per-frame drop decision from the console trace. - let lastChosen: string | null = null; - const chosenLog: string[] = []; - page.on("console", (msg) => { - const text = msg.text(); - const m = text.match( - /✔ chosen\s+container=(\S+)\s+idx=(\d+)\s+ghost=\(([-\d]+),([-\d]+)\)/, - ); - if (m) { - lastChosen = `container=${m[1]} idx=${m[2]} ghost=(${m[3]},${m[4]})`; - chosenLog.push(lastChosen); - } - }); - - await page.goto(`http://localhost:${port}/?demo=nested_items`); - - // Use the "Flat List" container: a pure column of Item A..D with no sub-containers, - // which isolates the dragged-item-gap reflow that caused the flicker. - const items = page - .locator(".snapsort-container") - .first() - .locator(".snapsort-item"); - await expect(items.first()).toBeVisible(); - const first = items.first(); - const box = await first.boundingBox(); - expect(box).not.toBeNull(); - - const startX = box!.x + box!.width / 2; - const startY = box!.y + box!.height / 2; - - // Drag distance: travel down ~4 item heights so we cross several drop slots. - const travel = box!.height * 4; - // Use a HIGH step count so each frame moves only a few pixels — this simulates a - // smooth, gradual human drag. The flicker only manifests with small per-frame - // movement near a slot boundary; large jumps skip over the oscillation. - const steps = 120; - const pxPerStep = travel / steps; - - await first.hover(); - await page.mouse.down(); - // Small initial nudge to cross the drag-start threshold. - await page.mouse.move(startX, startY + 3, { steps: 2 }); - await page.waitForTimeout(50); - - const frames: Frame[] = []; - const shotAt = new Set([ - 1, - Math.floor(steps / 4), - Math.floor(steps / 2), - Math.floor((3 * steps) / 4), - steps, - ]); - for (let i = 1; i <= steps; i++) { - const mouseY = startY + pxPerStep * i; - // Move in a couple of sub-steps for a smooth pointer path between samples. - await page.mouse.move(startX, mouseY, { steps: 3 }); - // Let the engine process its read/write frame(s) so the ghost DOM settles. - await page.waitForTimeout(25); - const ghost = await readGhost(page); - frames.push({ - step: i, - mouseY, - ghostTop: ghost ? ghost.top : null, - ghostCenterY: ghost ? ghost.top + ghost.height / 2 : null, - chosen: lastChosen, - }); - if (shotAt.has(i)) { - await page.screenshot({ - path: path.join(OUT_DIR, `drag-step-${i}.png`), - }); - } - } - - await page.mouse.up(); - - // Persist the frame log for inspection. - fs.writeFileSync( - path.join(OUT_DIR, "frames.json"), - JSON.stringify({ frames, chosenLog }, null, 2), - ); - - // ---- Assertions ---- - const valid = frames.filter( - (f) => f.ghostCenterY !== null, - ) as Required[]; - // The ghost must exist during the drag. - expect(valid.length).toBeGreaterThan(steps * 0.7); - - const itemH = box!.height; - - // (1) Ghost tracks the cursor: it should never be more than ~1.5 item heights away. - const maxOffset = Math.max( - ...valid.map((f) => Math.abs((f.ghostCenterY as number) - f.mouseY)), - ); - expect - .soft( - maxOffset, - `max |ghostCenterY - mouseY| = ${maxOffset.toFixed(1)}px`, - ) - .toBeLessThan(itemH * 1.5); - - // (2) No flicker: as the cursor moves monotonically down, the ghost center should be - // (near-)monotonic. Count meaningful downward->upward reversals (> 4px to ignore jitter). - let reversals = 0; - for (let i = 1; i < valid.length; i++) { - const dy = - (valid[i].ghostCenterY as number) - - (valid[i - 1].ghostCenterY as number); - if (dy < -4) reversals++; - } - expect - .soft(reversals, `ghost-position reversals across ${valid.length} frames`) - .toBeLessThanOrEqual(2); - - // Surface a compact summary in the report. - test.info().annotations.push({ - type: "drag-summary", - description: `frames=${valid.length} maxOffset=${maxOffset.toFixed(1)}px reversals=${reversals} decisions=${chosenLog.length}`, - }); - }); -}); diff --git a/tests/e2e/website-engine-lifecycle.spec.ts b/tests/e2e/website-engine-lifecycle.spec.ts deleted file mode 100644 index 3c7bd543..00000000 --- a/tests/e2e/website-engine-lifecycle.spec.ts +++ /dev/null @@ -1,364 +0,0 @@ -import { expect, test } from "@playwright/test"; - -test("owned Svelte engines survive page teardown without errors", async ({ - page, -}) => { - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - - await page.goto("/"); - await expect(page.locator("#highlight-animation")).toBeVisible(); - await expect(page.locator("#collision-card-canvas")).toBeVisible(); - - const collisionCanvas = await page - .locator("#collision-card-canvas") - .boundingBox(); - expect(collisionCanvas?.width).toBeGreaterThan(800); - expect(collisionCanvas?.height).toBeGreaterThan(400); - - await page.getByRole("link", { name: "About", exact: true }).first().click(); - await expect(page).toHaveURL(/\/about$/); - - expect(pageErrors).toEqual([]); -}); - -test("marker ghost callbacks do not emit flow-mode warnings", async ({ - page, -}) => { - const ghostWarnings: string[] = []; - page.on("console", (message) => { - if ( - message.type() === "warning" && - message.text().includes("ghost callbacks") - ) { - ghostWarnings.push(message.text()); - } - }); - - await page.goto("/docs/snapsort/examples/complete-interfaces"); - await expect( - page.locator('[data-snapsort-example="swap-grid"] .swap-grid'), - ).toBeVisible(); - - expect(ghostWarnings).toEqual([]); -}); - -test("SnapSort asset preview pans and moves items through the imperative API", async ({ - page, -}) => { - const pageErrors: string[] = []; - page.on("pageerror", (error) => pageErrors.push(error.message)); - - await page.goto("/"); - - const card = page.locator(".drop-snap-card"); - const preview = page.locator( - "#assets-snapsort-preview-engine .preview-mosaic", - ); - const pan = card.locator(".snapsort-preview-pan"); - const scale = card.locator(".snapsort-preview-scale"); - const firstKanbanColumn = card.locator(".preview-kanban-column").first(); - const sentenceAnswer = card.locator(".preview-sentence-zone").first(); - const firstTile = card.locator(".preview-tile-grid > .snapsort-item").first(); - const fileRows = card.locator(".preview-file-tree > .snapsort-item"); - const editorTools = card.locator(".preview-editor-tools"); - const editorCanvas = card.locator(".preview-editor-canvas"); - - await card.scrollIntoViewIfNeeded(); - await expect(preview).toBeVisible(); - await expect(card).toHaveJSProperty("tagName", "ARTICLE"); - await expect(card.getByRole("link", { name: "Learn more" })).toBeVisible(); - await expect(card.locator(".framework-list")).toHaveCount(0); - await expect(card.locator(".slot")).toHaveCount(0); - await expect( - firstKanbanColumn.locator(":scope > .snapsort-item"), - ).toHaveCount(2); - await expect(sentenceAnswer.locator(":scope > .snapsort-item")).toHaveCount( - 2, - ); - await expect(firstTile).toHaveText("01"); - await expect(fileRows).toHaveCount(5); - await expect(editorTools.locator(":scope > .snapsort-item")).toHaveCount(3); - await expect(editorCanvas.locator(":scope > .snapsort-item")).toHaveCount(0); - - const nativeGridMetrics = await preview.evaluate((element) => ({ - layoutWidth: (element as HTMLElement).offsetWidth, - renderedWidth: element.getBoundingClientRect().width, - })); - expect(nativeGridMetrics.layoutWidth).toBe(1084); - expect(nativeGridMetrics.renderedWidth).toBeLessThan(500); - - const exhibitRows = await card.evaluate((element) => ({ - sentence: element - .querySelector(".preview-sentence-panel")! - .getBoundingClientRect().top, - kanban: element - .querySelector(".preview-kanban-panel")! - .getBoundingClientRect().top, - editor: element - .querySelector(".preview-editor-panel")! - .getBoundingClientRect().top, - })); - expect(exhibitRows.kanban).toBeGreaterThan(exhibitRows.sentence); - expect(exhibitRows.kanban).toBeLessThan(exhibitRows.editor); - - const edgeMetrics = await card.evaluate((element) => { - const cardRect = element.getBoundingClientRect(); - const previewRect = element - .querySelector(".snapsort-preview-window")! - .getBoundingClientRect(); - return { - left: previewRect.left - cardRect.left, - right: cardRect.right - previewRect.right, - bottom: cardRect.bottom - previewRect.bottom, - }; - }); - expect(edgeMetrics.left).toBeCloseTo(0, 3); - expect(edgeMetrics.right).toBeCloseTo(0, 3); - expect(edgeMetrics.bottom).toBeCloseTo(0, 3); - - const cardBefore = await card.boundingBox(); - const panBefore = await pan.evaluate( - (element) => getComputedStyle(element).transform, - ); - await expect(scale).toHaveCSS("filter", /grayscale\(1\)/); - - await card.hover(); - await expect(card).toHaveAttribute("data-preview-active", "true"); - await expect(card).toHaveAttribute("data-preview-hovered", "true"); - for (const selector of [ - ".preview-trash-list span:first-child", - ".preview-clone-blocks .heading-block", - ]) { - await expect(card.locator(selector)).toHaveCSS( - "animation-play-state", - "running", - ); - } - await expect - .poll( - () => - card - .locator('[data-preview-entry-id="preview-kanban-motion"]') - .evaluate((element) => - element - .getAnimations() - .some((animation) => animation.playState === "running"), - ), - { timeout: 1500 }, - ) - .toBe(true); - await expect - .poll(() => fileRows.last().textContent()) - .toContain("Card.svelte"); - await expect - .poll(() => - card - .locator('[data-preview-entry-id="preview-file-card"]') - .evaluate((element) => - element - .getAnimations() - .some((animation) => animation.playState === "running"), - ), - ) - .toBe(true); - await expect - .poll(() => firstKanbanColumn.locator(":scope > .snapsort-item").count()) - .toBe(1); - await expect.poll(() => firstTile.textContent()).toBe("02"); - const movedTile = card.locator( - '[data-preview-entry-id="preview-tile-primary"]', - ); - await expect - .poll(() => - movedTile.evaluate((element) => - element - .getAnimations() - .some((animation) => animation.playState === "running"), - ), - ) - .toBe(true); - await expect( - movedTile.locator( - "xpath=ancestor::*[contains(@class, 'snapsort-item')][1]", - ), - ).toHaveCSS("transform", "none"); - await expect - .poll(() => editorCanvas.locator(":scope > .snapsort-item").count()) - .toBe(1); - await expect - .poll(() => - card - .locator('[data-preview-entry-id="preview-editor-text"]') - .evaluate((element) => - element - .getAnimations() - .some((animation) => animation.playState === "running"), - ), - ) - .toBe(true); - await expect - .poll(() => sentenceAnswer.locator(":scope > .snapsort-item").count()) - .toBe(3); - await expect(scale).toHaveCSS("filter", /grayscale\(0\)/); - - const pointerCardBox = await card.boundingBox(); - if (!pointerCardBox) - throw new Error("Expected the SnapSort card to have bounds."); - await page.mouse.move(pointerCardBox.x + 20, pointerCardBox.y + 20); - await page.waitForTimeout(220); - const topPan = await pan.evaluate( - (element) => new DOMMatrix(getComputedStyle(element).transform).m42, - ); - await page.mouse.move( - pointerCardBox.x + pointerCardBox.width - 20, - pointerCardBox.y + pointerCardBox.height - 20, - ); - await page.waitForTimeout(220); - const bottomPan = await pan.evaluate( - (element) => new DOMMatrix(getComputedStyle(element).transform).m42, - ); - expect(bottomPan).toBeLessThan(topPan - 100); - - const panAfter = await pan.evaluate( - (element) => getComputedStyle(element).transform, - ); - expect(panAfter).not.toBe(panBefore); - - const cardAfter = await card.boundingBox(); - expect(cardAfter?.x).toBeCloseTo(cardBefore?.x ?? 0, 3); - expect(cardAfter?.y).toBeCloseTo(cardBefore?.y ?? 0, 3); - expect(cardAfter?.width).toBeCloseTo(cardBefore?.width ?? 0, 3); - expect(cardAfter?.height).toBeCloseTo(cardBefore?.height ?? 0, 3); - - await card.getByRole("link", { name: "Learn more" }).click(); - await expect(page).toHaveURL(/\/snapsort$/); - expect(pageErrors).toEqual([]); -}); - -test("SnapSort asset preview honors reduced motion", async ({ page }) => { - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.goto("/"); - - const card = page.locator(".drop-snap-card"); - const firstKanbanColumn = card.locator(".preview-kanban-column").first(); - await card.scrollIntoViewIfNeeded(); - await expect( - firstKanbanColumn.locator(":scope > .snapsort-item"), - ).toHaveCount(2); - - await card.hover(); - await expect(card).toHaveAttribute("data-preview-active", "false"); - await expect(card).toHaveAttribute("data-preview-hovered", "true"); - await expect(card.locator(".snapsort-preview-scale")).toHaveCSS( - "filter", - /grayscale\(0\)/, - ); - await page.waitForTimeout(1200); - await expect( - firstKanbanColumn.locator(":scope > .snapsort-item"), - ).toHaveCount(2); - await expect(card.locator(".snapsort-preview-pan")).toHaveCSS( - "animation-name", - "none", - ); - const reducedPanBefore = await card - .locator(".snapsort-preview-pan") - .evaluate((element) => getComputedStyle(element).transform); - const cardBox = await card.boundingBox(); - if (!cardBox) throw new Error("Expected the SnapSort card to have bounds."); - await page.mouse.move(cardBox.x + 10, cardBox.y + cardBox.height - 10); - const reducedPanAfter = await card - .locator(".snapsort-preview-pan") - .evaluate((element) => getComputedStyle(element).transform); - expect(reducedPanAfter).toBe(reducedPanBefore); -}); - -test("SnapSort asset preview activates and pans with scroll on touch screens", async ({ - browser, -}) => { - const context = await browser.newContext({ - viewport: { width: 390, height: 844 }, - isMobile: true, - hasTouch: true, - }); - const page = await context.newPage(); - await page.goto("/"); - - const card = page.locator(".drop-snap-card"); - const pan = card.locator(".snapsort-preview-pan"); - const firstKanbanColumn = card.locator(".preview-kanban-column").first(); - await card.scrollIntoViewIfNeeded(); - await expect(card).toHaveAttribute("data-preview-active", "true"); - await expect(card).toHaveAttribute("data-preview-hovered", "true"); - - const panBeforeScroll = await pan.evaluate( - (element) => new DOMMatrix(getComputedStyle(element).transform).m42, - ); - await page.evaluate(() => window.scrollBy(0, 140)); - await expect - .poll(() => - pan.evaluate( - (element) => new DOMMatrix(getComputedStyle(element).transform).m42, - ), - ) - .toBeLessThan(panBeforeScroll - 15); - await expect - .poll(() => firstKanbanColumn.locator(":scope > .snapsort-item").count()) - .toBe(1); - - await context.close(); -}); - -test("camera card reserves modified wheel input for zoom", async ({ page }) => { - await page.goto("/"); - - const card = page.locator(".camera-control-card"); - const camera = page.locator("#snap-camera-control"); - await expect(card).toBeVisible(); - await card.scrollIntoViewIfNeeded(); - await expect(camera).toBeVisible(); - - const movePointerOverCard = async () => { - const box = await card.boundingBox(); - if (!box) throw new Error("Expected camera card to have a bounding box."); - await page.mouse.move( - box.x + box.width / 2, - Math.min(box.y + box.height / 2, 760), - ); - }; - - await movePointerOverCard(); - const scrollBefore = await page.evaluate(() => window.scrollY); - const transformBefore = await camera.evaluate( - (element) => (element as HTMLElement).style.transform, - ); - await page.mouse.wheel(0, 420); - await expect - .poll(() => page.evaluate(() => window.scrollY)) - .toBeGreaterThan(scrollBefore + 100); - expect( - await camera.evaluate( - (element) => (element as HTMLElement).style.transform, - ), - ).toBe(transformBefore); - - await card.scrollIntoViewIfNeeded(); - await movePointerOverCard(); - const modifiedScrollBefore = await page.evaluate(() => window.scrollY); - const modifiedTransformBefore = await camera.evaluate( - (element) => (element as HTMLElement).style.transform, - ); - await page.keyboard.down("Control"); - try { - await page.mouse.wheel(0, -320); - } finally { - await page.keyboard.up("Control"); - } - await expect - .poll(() => - camera.evaluate((element) => (element as HTMLElement).style.transform), - ) - .not.toBe(modifiedTransformBefore); - expect(await page.evaluate(() => window.scrollY)).toBe(modifiedScrollBefore); -}); diff --git a/tests/e2e/website-navigation.spec.ts b/tests/e2e/website-navigation.spec.ts deleted file mode 100644 index d7c4188d..00000000 --- a/tests/e2e/website-navigation.spec.ts +++ /dev/null @@ -1,925 +0,0 @@ -import { expect, test, type Locator, type Page } from "@playwright/test"; - -async function dragBetween(page: Page, source: Locator, target: Locator) { - await source.scrollIntoViewIfNeeded(); - const [sourceBox, targetBox] = await Promise.all([ - source.boundingBox(), - target.boundingBox(), - ]); - if (!sourceBox || !targetBox) { - throw new Error("Gallery 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 page.mouse.up(); - await page.waitForTimeout(200); -} - -async function holdDragToPoint( - page: Page, - source: Locator, - targetPoint: { x: number; y: number }, -) { - await source.scrollIntoViewIfNeeded(); - const sourceBox = await source.boundingBox(); - if (!sourceBox) { - throw new Error("Gallery drag source has no layout box."); - } - - const sourcePoint = { - x: sourceBox.x + sourceBox.width / 2, - y: sourceBox.y + sourceBox.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); -} - -test("uses the arrow as a project selector and the wordmark as a homepage link", async ({ - page, -}) => { - await page.goto("/", { waitUntil: "networkidle" }); - - const primaryNav = page.getByRole("navigation", { - name: "Primary navigation", - }); - const projectTrigger = primaryNav.getByRole("button", { - name: /Switch project\. Current project: SnapEngine/, - }); - const projectMenu = page.locator("#project-nav-menu"); - const docsLink = primaryNav.getByRole("link", { name: "Docs", exact: true }); - const wordmark = primaryNav.locator(".wordmark"); - - await expect(wordmark).toHaveText("SnapEngine"); - await expect(wordmark).toHaveAttribute("href", "/"); - await expect(projectMenu).not.toBeVisible(); - await expect(docsLink).toHaveAttribute( - "href", - "/docs/snapengine/introduction", - ); - await projectTrigger.click(); - await expect(projectTrigger).toHaveAttribute("aria-expanded", "true"); - await expect(projectMenu).toBeVisible(); - await expect(projectMenu.getByRole("link")).toHaveCount(4); - await expect( - projectMenu.getByRole("link", { name: "SnapEngine" }), - ).toHaveAttribute("href", "/"); - await expect( - projectMenu - .getByRole("link", { name: "SnapEngine" }) - .locator(".project-nav-check"), - ).toHaveText("✓"); - await expect( - projectMenu.getByRole("link", { name: "SnapEngine" }), - ).toHaveAttribute("aria-current", "true"); - await expect( - projectMenu.getByRole("link", { name: "SnapSort" }), - ).toHaveAttribute("href", "/snapsort"); - await expect( - projectMenu.getByRole("link", { name: "SnapLine" }), - ).toHaveAttribute("href", "/snapline"); - await expect( - projectMenu.getByRole("link", { name: "SnapDesign" }), - ).toHaveAttribute("href", "/snapdesign"); - await expect(projectMenu.getByRole("link", { name: "SnapZap" })).toHaveCount( - 0, - ); - - await projectMenu.getByRole("link", { name: "SnapSort" }).click(); - await expect(page).toHaveURL(/\/snapsort$/); - await expect(wordmark).toHaveText("SnapSort"); - await expect(wordmark).toHaveAttribute("href", "/snapsort"); - await expect(docsLink).toHaveAttribute("href", "/docs/snapsort/introduction"); - await expect( - primaryNav.getByRole("link", { name: "Examples", exact: true }), - ).toHaveAttribute("href", "/docs/snapsort/examples"); - await expect(primaryNav.getByRole("link", { name: "About" })).toHaveCount(0); - - await page.goto("/docs/snapsort/examples", { waitUntil: "networkidle" }); - await expect(wordmark).toHaveText("SnapSort"); - await expect( - primaryNav.getByRole("link", { name: "Examples", exact: true }), - ).toHaveAttribute("aria-current", "page"); - await expect(docsLink).not.toHaveAttribute("aria-current", "page"); - const docsProjectTrigger = primaryNav.getByRole("button", { - name: /Switch project\. Current project: SnapSort/, - }); - await docsProjectTrigger.click(); - await expect( - projectMenu.getByRole("link", { name: "SnapSort" }), - ).toHaveAttribute("href", "/snapsort"); - await expect( - projectMenu.getByRole("link", { name: "SnapEngine" }), - ).toHaveAttribute("href", "/"); - await expect( - projectMenu.getByRole("link", { name: "SnapDesign" }), - ).toHaveAttribute("href", "/snapdesign"); - - await page.keyboard.press("Escape"); - await expect(docsProjectTrigger).toHaveAttribute("aria-expanded", "false"); - await expect(docsProjectTrigger).toBeFocused(); - - await docsProjectTrigger.click(); - await page.mouse.click(1200, 500); - await expect(docsProjectTrigger).toHaveAttribute("aria-expanded", "false"); - - await wordmark.click(); - await expect(page).toHaveURL(/\/snapsort$/); - await expect(projectMenu).not.toBeVisible(); -}); - -test("uses SnapEngine navigation for global pages", async ({ page }) => { - await page.goto("/about", { waitUntil: "networkidle" }); - - const primaryNav = page.getByRole("navigation", { - name: "Primary navigation", - }); - await expect(primaryNav.locator(".wordmark")).toHaveText("SnapEngine"); - await expect(primaryNav.locator(".wordmark")).toHaveAttribute("href", "/"); - await expect( - primaryNav.getByRole("link", { name: "Docs", exact: true }), - ).toHaveAttribute("href", "/docs/snapengine/introduction"); - await expect( - primaryNav.getByRole("link", { name: "About", exact: true }), - ).toHaveAttribute("aria-current", "page"); - await expect(primaryNav.getByRole("link", { name: "Examples" })).toHaveCount( - 0, - ); -}); - -test("puts project documentation inside the icon-only mobile menu", async ({ - page, -}) => { - await page.setViewportSize({ width: 390, height: 844 }); - await page.goto("/docs/snapline/introduction", { waitUntil: "networkidle" }); - - const primaryNav = page.getByRole("navigation", { - name: "Primary navigation", - }); - const projectTrigger = primaryNav.getByRole("button", { - name: /Switch project\. Current project: SnapLine/, - }); - - await expect(primaryNav.locator(".wordmark")).toHaveText("SnapLine"); - await expect(primaryNav.locator(".wordmark")).toHaveAttribute( - "href", - "/snapline", - ); - await expect(projectTrigger).toBeVisible(); - await projectTrigger.click(); - await expect(page.locator("#project-nav-menu")).toBeVisible(); - await expect( - page.locator("#project-nav-menu").getByRole("link", { name: "SnapSort" }), - ).toHaveAttribute("href", "/snapsort"); - await expect( - page.locator("#project-nav-menu").getByRole("link", { name: "SnapDesign" }), - ).toHaveAttribute("href", "/snapdesign"); - - await page.keyboard.press("Escape"); - await expect( - page.getByRole("button", { name: /Browse .* docs/ }), - ).toHaveCount(0); - - const mobileHeaderTrigger = primaryNav.getByRole("button", { - name: "Toggle navigation", - }); - await expect(mobileHeaderTrigger).toHaveText("≡"); - await mobileHeaderTrigger.click(); - await expect(mobileHeaderTrigger).toHaveAttribute("aria-expanded", "true"); - await expect(mobileHeaderTrigger).toHaveText("×"); - await expect( - primaryNav.getByRole("link", { name: "Docs", exact: true }), - ).toHaveAttribute("href", "/docs/snapline/introduction"); - await expect(primaryNav.getByRole("link", { name: "About" })).toHaveCount(0); - await expect(primaryNav.getByRole("link", { name: "Examples" })).toHaveCount( - 0, - ); - - const mobileDocs = primaryNav.locator(".mobile-doc-navigation"); - await expect(mobileDocs).toBeVisible(); - await expect(mobileDocs).toContainText("SnapLine docs"); - await expect(mobileDocs.getByLabel("Framework")).toBeVisible(); - await expect( - mobileDocs.getByRole("link", { name: "Installation and setup" }), - ).toHaveAttribute("href", "/docs/snapline/introduction/01_setup"); - await expect( - mobileDocs.getByRole("link", { name: "SnapLine", exact: true }), - ).toHaveAttribute("aria-current", "page"); -}); - -test("uses SnapDesign navigation on Guideline and Gallery pages", async ({ - page, -}) => { - await page.goto("/snapdesign", { waitUntil: "networkidle" }); - - const primaryNav = page.getByRole("navigation", { - name: "Primary navigation", - }); - const projectTrigger = primaryNav.getByRole("button", { - name: /Switch project\. Current project: SnapDesign/, - }); - const wordmark = primaryNav.locator(".wordmark"); - const guideline = primaryNav.getByRole("link", { - name: "Guideline", - exact: true, - }); - const gallery = primaryNav.getByRole("link", { - name: "Gallery", - exact: true, - }); - - await expect(wordmark).toHaveText("SnapDesign"); - await expect(wordmark).toHaveAttribute("href", "/snapdesign"); - await expect(projectTrigger).toHaveText(""); - await expect(guideline).toHaveAttribute("href", "/snapdesign"); - await expect(guideline).toHaveAttribute("aria-current", "page"); - await expect(gallery).toHaveAttribute("href", "/snapdesign/gallery"); - await expect(primaryNav.getByRole("link", { name: "Docs" })).toHaveCount(0); - await expect(primaryNav.getByRole("link", { name: "About" })).toHaveCount(0); - await expect( - primaryNav.getByRole("link", { name: "SnapEngine on GitHub" }), - ).toBeVisible(); - - await gallery.click(); - await expect(page).toHaveURL(/\/snapdesign\/gallery$/); - await expect(wordmark).toHaveText("SnapDesign"); - await expect(gallery).toHaveAttribute("aria-current", "page"); - await expect(guideline).not.toHaveAttribute("aria-current", "page"); - - await page.setViewportSize({ width: 390, height: 844 }); - await page.reload({ waitUntil: "networkidle" }); - const mobileHeaderTrigger = primaryNav.getByRole("button", { - name: "Toggle navigation", - }); - await mobileHeaderTrigger.click(); - await expect(guideline).toBeVisible(); - await expect(gallery).toBeVisible(); - await expect( - primaryNav.getByRole("link", { name: "SnapEngine on GitHub" }), - ).toBeVisible(); -}); - -test("serves the interactive Gallery and removes the old photo-op route", async ({ - page, - request, -}) => { - const oldPhotoOp = await request.get("/snapsort/photo-op", { - maxRedirects: 0, - }); - expect(oldPhotoOp.status()).toBe(404); - - await page.goto("/snapdesign", { waitUntil: "networkidle" }); - const guidelineToggleSurface = page - .locator('.toggle[aria-label="Skeuomorphic toggle"] .material-surface.recessed') - .first(); - await guidelineToggleSurface.scrollIntoViewIfNeeded(); - const guidelineToggleRecipe = await guidelineToggleSurface.evaluate( - (surface) => { - const style = getComputedStyle(surface); - return [ - "--material-light-angle", - "--material-rim-width", - "--material-rim-blur", - "--material-shadow-far-blur", - "--material-shadow-far-x", - "--material-shadow-far-y", - "--material-crevice-visibility", - ].map((property) => style.getPropertyValue(property).trim()); - }, - ); - - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - await expect( - page.getByRole("heading", { name: "Gallery", exact: true }), - ).toBeVisible(); - await expect(page.locator("[data-gallery]")).toHaveCount(6); - const stageDimensions = await page.locator(".demo-stage").evaluateAll( - (stages) => - stages.map((stage) => ({ - width: stage.clientWidth, - height: stage.clientHeight, - })), - ); - expect(stageDimensions).toHaveLength(6); - for (const { width, height } of stageDimensions) { - expect(Math.abs(width - height)).toBeLessThanOrEqual(1); - } - await expect(page.locator('link[rel="canonical"]')).toHaveAttribute( - "href", - "https://snapengine.dev/snapdesign/gallery", - ); - await expect(page.locator('meta[name="robots"]')).toHaveCount(0); - - const layersGeometry = await page - .locator('[data-demo="layers-panel"]') - .evaluate((demo) => { - const shell = demo.querySelector(".figma-shell"); - const panel = demo.querySelector( - ".layers-card.material-surface", - ); - const group = demo.querySelector( - '[data-layer-id="header"]', - ); - const child = demo.querySelector( - '[data-layer-id="brand-mark"]', - ); - const rows = [...demo.querySelectorAll(".layers-tree-row")]; - if (!shell || !panel || !group || !child) { - throw new Error("Layers panel geometry targets are missing."); - } - - const demoRect = demo.getBoundingClientRect(); - const shellRect = shell.getBoundingClientRect(); - const panelRect = panel.getBoundingClientRect(); - const groupRect = group.getBoundingClientRect(); - const childRect = child.getBoundingClientRect(); - const rowTops = rows.map((row) => row.getBoundingClientRect().top); - return { - shellTopOffset: shellRect.top - demoRect.top, - shellWidthDelta: shellRect.width - demoRect.width, - shellHeightDelta: shellRect.height - demoRect.height, - panelCenterDelta: - panelRect.left + panelRect.width / 2 - - (demoRect.left + demoRect.width / 2), - panelVerticalCenterDelta: - panelRect.top + panelRect.height / 2 - - (demoRect.top + demoRect.height / 2), - panelWidthRatio: panelRect.width / demoRect.width, - panelHeight: panelRect.height, - childInset: childRect.left - groupRect.left, - childIsNarrower: childRect.width < groupRect.width, - rowGaps: rowTops.slice(1).map((top, index) => top - rowTops[index]), - }; - }); - expect(Math.abs(layersGeometry.shellTopOffset)).toBeLessThanOrEqual(1); - expect(Math.abs(layersGeometry.shellWidthDelta)).toBeLessThanOrEqual(1); - expect(Math.abs(layersGeometry.shellHeightDelta)).toBeLessThanOrEqual(1); - expect(Math.abs(layersGeometry.panelCenterDelta)).toBeLessThanOrEqual(1); - expect( - Math.abs(layersGeometry.panelVerticalCenterDelta), - ).toBeLessThanOrEqual(1); - expect(layersGeometry.panelWidthRatio).toBeGreaterThanOrEqual(0.45); - expect(layersGeometry.panelWidthRatio).toBeLessThanOrEqual(0.47); - expect(Math.abs(layersGeometry.panelHeight - 464)).toBeLessThanOrEqual(1); - expect(layersGeometry.childInset).toBeGreaterThanOrEqual(19); - expect(layersGeometry.childIsNarrower).toBe(true); - for (const gap of layersGeometry.rowGaps) { - expect(Math.abs(gap - 36)).toBeLessThanOrEqual(1); - } - - const todoStage = page.locator('[data-gallery="todo-list"] .todo-stage'); - const todoDemo = todoStage.locator(".todo-demo"); - const todoList = todoStage.locator('[data-demo="todo-list"]'); - const promoTodo = todoStage.locator('[data-todo-id="todo-promo"]'); - await expect(todoStage).toHaveAttribute("inert", ""); - await expect(todoStage).toHaveAttribute("aria-hidden", "true"); - await expect(todoStage).toHaveCSS("pointer-events", "none"); - await expect( - todoStage.locator(".todo-label"), - ).toHaveText([ - "Promo video", - "Support accessibility", - "SSR mode", - "Publish gallery", - ]); - - const galleryToggleRecipe = await todoStage - .locator(".todo-toggle .material-surface.recessed") - .first() - .evaluate((surface) => { - const style = getComputedStyle(surface); - return [ - "--material-light-angle", - "--material-rim-width", - "--material-rim-blur", - "--material-shadow-far-blur", - "--material-shadow-far-x", - "--material-shadow-far-y", - "--material-crevice-visibility", - ].map((property) => style.getPropertyValue(property).trim()); - }); - expect(galleryToggleRecipe).toEqual(guidelineToggleRecipe); - - await todoDemo.scrollIntoViewIfNeeded(); - await expect(todoDemo).toHaveAttribute("data-todo-autoplay-active", "true"); - await expect(promoTodo).toHaveAttribute("data-completed", "true", { - timeout: 5_000, - }); - await expect( - promoTodo.locator('[role="switch"]'), - ).toHaveAttribute("aria-checked", "true"); - await expect(todoList).toHaveAttribute( - "data-todo-order", - "todo-accessibility,todo-ssr,todo-publish,todo-promo", - { timeout: 5_000 }, - ); - await expect(todoList).toHaveAttribute( - "data-todo-order", - "todo-promo,todo-accessibility,todo-ssr,todo-publish", - { timeout: 5_000 }, - ); - await expect(promoTodo).toHaveAttribute("data-completed", "false"); - - const swapItems = page.locator(".swap-grid > .snapsort-item"); - await expect(swapItems).toHaveCount(6); - const swapLabels = () => - swapItems.evaluateAll((items) => - items.map((item) => item.getAttribute("data-swap-label")), - ); - await expect.poll(swapLabels).toEqual(["A", "B", "C", "D", "E", "F"]); - await dragBetween(page, swapItems.nth(0), swapItems.nth(1)); - await expect.poll(swapLabels).toEqual(["B", "A", "C", "D", "E", "F"]); - - await page.setViewportSize({ width: 390, height: 844 }); - await page.reload({ waitUntil: "networkidle" }); - const mobileLayout = await page.evaluate(() => { - const nestedStage = document.querySelector( - '[data-gallery="nested-containers"] .demo-stage', - ); - if (!nestedStage) throw new Error("Nested Gallery stage is missing"); - - return { - documentWidth: document.documentElement.clientWidth, - documentScrollWidth: document.documentElement.scrollWidth, - stageWidth: nestedStage.clientWidth, - stageHeight: nestedStage.clientHeight, - stageScrollHeight: nestedStage.scrollHeight, - }; - }); - expect(mobileLayout.documentScrollWidth).toBe(mobileLayout.documentWidth); - expect(Math.abs(mobileLayout.stageWidth - mobileLayout.stageHeight)).toBeLessThanOrEqual(1); - expect(mobileLayout.stageScrollHeight).toBeLessThanOrEqual( - mobileLayout.stageHeight, - ); - - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.reload({ waitUntil: "networkidle" }); - const reducedTodoDemo = page.locator(".todo-demo"); - await reducedTodoDemo.scrollIntoViewIfNeeded(); - await expect(reducedTodoDemo).toHaveAttribute("data-todo-phase", "reduced"); - await expect(reducedTodoDemo).toHaveAttribute( - "data-todo-autoplay-active", - "false", - ); - await expect( - page.locator('[data-todo-id="todo-promo"]'), - ).toHaveAttribute("data-completed", "true"); - await expect(page.locator('[data-demo="todo-list"]')).toHaveAttribute( - "data-todo-order", - "todo-promo,todo-accessibility,todo-ssr,todo-publish", - ); - - const sitemap = await request.get("/sitemap.xml"); - expect(sitemap.ok()).toBe(true); - const sitemapXml = await sitemap.text(); - expect(sitemapXml).toContain("https://snapengine.dev/snapdesign"); - expect(sitemapXml).toContain("https://snapengine.dev/snapdesign/gallery"); - expect(sitemapXml).not.toContain("/snapsort/photo-op"); -}); - -test("Layers panel nests by main-axis proximity and unnests by leading edge", async ({ - page, -}) => { - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const layersPanel = page.locator('[data-demo="layers-panel"]'); - await layersPanel.scrollIntoViewIfNeeded(); - const group = layersPanel.locator('[data-layer-id="navigation"]'); - const groupRow = group.locator(":scope > .group-row"); - const artwork = layersPanel.locator('[data-layer-id="hero-artwork"]'); - const groupRowBox = await groupRow.boundingBox(); - if (!groupRowBox) { - throw new Error("Layers panel group row has no layout box."); - } - - await holdDragToPoint(page, artwork, { - x: groupRowBox.x + 4, - y: groupRowBox.y + groupRowBox.height + 1, - }); - await expect( - group.locator( - '.insertion-tree-marker[data-tree-marker-hidden="false"]', - ), - ).toBeVisible(); - await page.mouse.up(); - await expect( - group.locator('[data-layer-id="hero-artwork"]'), - ).toHaveCount(1); - await expect - .poll(() => - layersPanel.locator("[data-layer-id]").evaluateAll((elements) => - elements.every( - (element) => !(element as HTMLElement).style.transform, - ), - ), - ) - .toBe(true); - - const [artworkBox, notesBox] = await Promise.all([ - artwork.boundingBox(), - layersPanel.locator('[data-layer-id="prototype-notes"]').boundingBox(), - ]); - if (!artworkBox || !notesBox) { - throw new Error("Layers panel drag target has no layout box."); - } - - await page.mouse.move( - artworkBox.x + artworkBox.width / 2, - artworkBox.y + artworkBox.height / 2, - ); - await page.mouse.down(); - await page.mouse.move( - artworkBox.x + artworkBox.width / 2 + 7, - artworkBox.y + 7, - ); - await page.waitForTimeout(60); - await page.mouse.move(notesBox.x + 4, notesBox.y + notesBox.height / 2, { - steps: 12, - }); - await page.waitForTimeout(120); - await page.mouse.up(); - - await expect( - layersPanel.locator('.layers-tree-root > [data-layer-id="hero-artwork"]'), - ).toHaveCount(1); -}); - -test("Layers panel group FLIP preserves unchanged descendants and animates local changes", async ({ - page, -}) => { - await page.setViewportSize({ width: 1440, height: 1100 }); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const layersPanel = page.locator('[data-demo="layers-panel"]'); - await layersPanel.scrollIntoViewIfNeeded(); - await page.addStyleTag({ - content: ` - [data-demo="layers-panel"] - .layers-tree-root - > [data-layer-id="header"] - > [data-layer-id="brand-mark"] { - margin-left: calc(var(--layers-node-indent) + 12px) !important; - } - `, - }); - const header = layersPanel.locator('[data-layer-id="header"]'); - const notes = layersPanel.locator('[data-layer-id="prototype-notes"]'); - const relations = [ - { childId: "brand-mark", parentId: "header" }, - { childId: "navigation", parentId: "header" }, - { childId: "features", parentId: "navigation" }, - { childId: "pricing", parentId: "navigation" }, - ]; - const baselineOffsets = await layersPanel.evaluate((demo, pairs) => { - return Object.fromEntries( - pairs.map(({ childId, parentId }) => { - const child = demo.querySelector( - `[data-layer-id="${childId}"]`, - ); - const parent = demo.querySelector( - `[data-layer-id="${parentId}"]`, - ); - if (!child || !parent) { - throw new Error("Layers panel FLIP relation is missing."); - } - const childRect = child.getBoundingClientRect(); - const parentRect = parent.getBoundingClientRect(); - return [ - `${childId}:${parentId}`, - { - x: childRect.x - parentRect.x, - y: childRect.y - parentRect.y, - }, - ]; - }), - ); - }, relations); - - const notesBox = await notes.boundingBox(); - if (!notesBox) { - throw new Error("Layers panel root insertion target has no layout box."); - } - await holdDragToPoint(page, header.locator(":scope > .group-row"), { - x: notesBox.x + 4, - y: notesBox.y + notesBox.height / 2, - }); - await page.waitForTimeout(320); - - const frameTrace = layersPanel.evaluate( - (demo, pairs) => - new Promise< - Array<{ - connected: boolean; - transforms: Record; - offsets: Record; - }> - >((resolve) => { - const itemIds = [ - "header", - "brand-mark", - "navigation", - "features", - "pricing", - "feature-cards", - ]; - const frames: Array<{ - connected: boolean; - transforms: Record; - offsets: Record; - }> = []; - const startedAt = performance.now(); - const sample = () => { - const items = new Map( - itemIds.map((itemId) => [ - itemId, - demo.querySelector( - `[data-layer-id="${itemId}"]`, - ), - ]), - ); - const connected = [...items.values()].every(Boolean); - const transforms = Object.fromEntries( - itemIds.map((itemId) => [ - itemId, - items.get(itemId)?.style.transform ?? "", - ]), - ); - const offsets: Record = {}; - for (const { childId, parentId } of pairs) { - const child = items.get(childId); - const parent = items.get(parentId); - if (!child || !parent) continue; - const childRect = child.getBoundingClientRect(); - const parentRect = parent.getBoundingClientRect(); - offsets[`${childId}:${parentId}`] = { - x: childRect.x - parentRect.x, - y: childRect.y - parentRect.y, - }; - } - frames.push({ connected, transforms, offsets }); - - if (performance.now() - startedAt >= 420) { - resolve(frames); - return; - } - requestAnimationFrame(sample); - }; - requestAnimationFrame(sample); - }), - relations, - ); - await page.mouse.up(); - const frames = (await frameTrace).filter((frame) => frame.connected); - - await expect( - layersPanel.locator('.layers-tree-root > [data-layer-id="header"]'), - ).toHaveCount(1); - expect(frames.length).toBeGreaterThan(4); - expect( - frames.some(({ transforms }) => transforms.header !== ""), - ).toBe(true); - expect( - frames.some(({ transforms }) => transforms["feature-cards"] !== ""), - ).toBe(true); - expect( - frames.some(({ transforms }) => transforms["brand-mark"] !== ""), - ).toBe(true); - - for (const frame of frames) { - for (const itemId of ["navigation", "features", "pricing"]) { - expect(frame.transforms[itemId]).toBe(""); - } - for (const [relation, baseline] of Object.entries(baselineOffsets)) { - if (relation === "brand-mark:header") continue; - const offset = frame.offsets[relation]; - expect(offset).toBeDefined(); - expect(Math.abs(offset.x - baseline.x)).toBeLessThanOrEqual(1); - expect(Math.abs(offset.y - baseline.y)).toBeLessThanOrEqual(1); - } - } - - const brandBaseline = baselineOffsets["brand-mark:header"]; - const finalBrandFrame = frames.at(-1); - const finalBrandOffset = finalBrandFrame?.offsets["brand-mark:header"]; - const animatedBrandOffsets = frames - .filter(({ transforms }) => transforms["brand-mark"] !== "") - .map(({ offsets }) => offsets["brand-mark:header"].x - brandBaseline.x); - expect(finalBrandFrame).toBeDefined(); - expect(finalBrandOffset).toBeDefined(); - expect(finalBrandFrame?.transforms["brand-mark"]).toBe(""); - expect(animatedBrandOffsets.some((offset) => offset > 0 && offset < 12)).toBe( - true, - ); - expect( - Math.abs((finalBrandOffset?.x ?? 0) - brandBaseline.x - 12), - ).toBeLessThanOrEqual(1); - expect( - Math.abs((finalBrandOffset?.y ?? 0) - brandBaseline.y), - ).toBeLessThanOrEqual(1); -}); - -test("Layers panel keeps collapsed-group edges available for sibling insertion", async ({ - page, -}) => { - await page.emulateMedia({ reducedMotion: "reduce" }); - await page.goto("/snapdesign/gallery", { waitUntil: "networkidle" }); - - const layersPanel = page.locator('[data-demo="layers-panel"]'); - await layersPanel.scrollIntoViewIfNeeded(); - const desktopHome = layersPanel.locator('[data-layer-id="desktop-home"]'); - const header = layersPanel.locator('[data-layer-id="header"]'); - const featureCards = layersPanel.locator('[data-layer-id="feature-cards"]'); - const notes = layersPanel.locator('[data-layer-id="prototype-notes"]'); - - await header - .getByRole("button", { name: "Collapse Header" }) - .click(); - await featureCards - .getByRole("button", { name: "Collapse Feature cards" }) - .click(); - await expect( - header.getByRole("button", { name: "Expand Header" }), - ).toBeVisible(); - await expect( - featureCards.getByRole("button", { name: "Expand Feature cards" }), - ).toBeVisible(); - - const headerRowBox = await header - .locator(":scope > .group-row") - .boundingBox(); - if (!headerRowBox) { - throw new Error("Collapsed Layers group row has no layout box."); - } - - await holdDragToPoint(page, notes, { - x: headerRowBox.x + headerRowBox.width / 2, - y: headerRowBox.y + headerRowBox.height - 2, - }); - await expect( - desktopHome.locator( - ':scope > .insertion-tree-marker[data-tree-marker-hidden="false"]', - ), - ).toBeVisible(); - await expect( - layersPanel.locator('[data-layer-targeted="true"]'), - ).toHaveCount(0); - await page.mouse.up(); - await page.waitForTimeout(200); - - const desktopLayerIds = () => - desktopHome - .locator(":scope > [data-layer-id]") - .evaluateAll((entries) => - entries.map((entry) => entry.getAttribute("data-layer-id")), - ); - await expect.poll(desktopLayerIds).toEqual([ - "header", - "prototype-notes", - "feature-cards", - "hero-artwork", - ]); - - const featureCardsRowBox = await featureCards - .locator(":scope > .group-row") - .boundingBox(); - if (!featureCardsRowBox) { - throw new Error("Collapsed Layers group row has no layout box."); - } - - await holdDragToPoint(page, notes, { - x: featureCardsRowBox.x + featureCardsRowBox.width / 2, - y: featureCardsRowBox.y + featureCardsRowBox.height / 2, - }); - await expect(featureCards).toHaveAttribute("data-layer-targeted", "true"); - await expect( - desktopHome.locator( - ':scope > .insertion-tree-marker[data-tree-marker-hidden="false"]', - ), - ).toHaveCount(0); - await page.mouse.up(); - await page.waitForTimeout(200); - - await featureCards - .getByRole("button", { name: "Expand Feature cards" }) - .click(); - await expect( - featureCards.locator(':scope > [data-layer-id="prototype-notes"]'), - ).toHaveCount(1); -}); - -test("keeps coming-soon SnapLine pages unlisted but directly accessible", async ({ - page, - request, -}) => { - await page.goto("/", { waitUntil: "networkidle" }); - - const snapLineCard = page.locator("#asset-snapline"); - const snapZapCard = page.locator("#asset-snapzap"); - await expect(snapLineCard).toContainText("Coming soon"); - await expect(snapLineCard.getByRole("link")).toHaveCount(0); - await expect( - snapLineCard.getByRole("button", { name: "Learn more" }), - ).toBeDisabled(); - await expect(snapZapCard).toContainText("Coming soon"); - await expect( - page.locator(".planned-asset-node", { hasText: "SnapLine" }), - ).toContainText("Coming soon"); - await expect( - page.locator("footer").getByText("SnapLine · Coming soon"), - ).toBeVisible(); - - await page.goto("/docs", { waitUntil: "networkidle" }); - await expect(page.locator(".doc-article")).toContainText( - "SnapLine is a planned toolkit", - ); - await expect( - page.locator('.doc-article a[href^="/docs/snapline"]'), - ).toHaveCount(0); - - await page.goto("/snapline", { waitUntil: "networkidle" }); - await expect( - page.getByRole("heading", { name: "Node-based UI primitives" }), - ).toBeVisible(); - await expect(page.locator('meta[name="robots"]')).toHaveAttribute( - "content", - "noindex, nofollow", - ); - await expect( - page.getByRole("link", { - name: /SnapLine docs|Read the docs|Install SnapLine/, - }), - ).toHaveCount(0); - - await page.goto("/docs/snapline/introduction", { waitUntil: "networkidle" }); - await expect(page.locator('meta[name="robots"]')).toHaveAttribute( - "content", - "noindex, nofollow", - ); - await expect( - page.getByRole("heading", { name: "SnapLine", level: 1 }), - ).toBeVisible(); - - const rootLlms = await request.get("/llms.txt"); - expect(rootLlms.ok()).toBe(true); - expect(await rootLlms.text()).not.toContain("SnapLine"); - - const sitemap = await request.get("/sitemap.xml"); - expect(sitemap.ok()).toBe(true); - expect(await sitemap.text()).not.toContain("/snapline"); - - const markdown = await request.get("/docs/snapline/introduction.md"); - expect(markdown.ok()).toBe(true); - expect(markdown.headers()["x-robots-tag"]).toBe("noindex, nofollow"); - - const projectLlms = await request.get("/docs/snapline/llms.txt"); - expect(projectLlms.ok()).toBe(true); - expect(projectLlms.headers()["x-robots-tag"]).toBe("noindex, nofollow"); -}); - -test("uses one reading width for documentation chrome and article content", async ({ - page, -}) => { - await page.goto("/docs/snapengine/reference/engine", { - waitUntil: "networkidle", - }); - - const selectors = [ - ".doc-breadcrumb", - ".doc-header", - ".doc-article > p", - ".doc-article > .display", - ".doc-article > table", - ".doc-pagination", - ]; - const boxes = await Promise.all( - selectors.map((selector) => page.locator(selector).first().boundingBox()), - ); - const measuredBoxes = boxes.filter( - (box): box is NonNullable => box !== null, - ); - - expect(measuredBoxes).toHaveLength(selectors.length); - for (const box of measuredBoxes) { - expect(box.x).toBeCloseTo(measuredBoxes[0].x, 0); - expect(box.width).toBeCloseTo(measuredBoxes[0].width, 0); - } - expect(measuredBoxes[0].width).toBeLessThanOrEqual(700); -}); diff --git a/tests/helpers/layout-grid.ts b/tests/helpers/layout-grid.ts index c5ec7d3a..b44d5938 100644 --- a/tests/helpers/layout-grid.ts +++ b/tests/helpers/layout-grid.ts @@ -1,5 +1,5 @@ // Shared helpers for layout-engine tests (tests/ut/core-layout.spec.ts and the -// wrap-matrix e2e test in tests/e2e/snapsort-drag-snapshot.spec.ts): DOM-free +// wrap-matrix e2e test in tests/e2e/snapsort/layout/): DOM-free // snapshot builders plus the row-shape assertions both suites make. Keeping // the grid construction and row counting here guarantees the unit tests and // the cross-browser e2e matrix judge the layout engine by the same rules. diff --git a/tests/helpers/snapsort-fixtures.ts b/tests/helpers/snapsort-fixtures.ts new file mode 100644 index 00000000..2bd73e64 --- /dev/null +++ b/tests/helpers/snapsort-fixtures.ts @@ -0,0 +1,282 @@ +// DOM-free SnapSort fixtures shared by the drop-resolution unit tests and +// the e2e suites: frozen boxes, item snapshots, and mock items/containers. +import { type ElementBox, type Rect } from "../../src/geometry"; +import { type ItemSnapshot } from "../../assets/snapsort/src/snapshot"; +import { rejectDrop } from "../../assets/snapsort/src/callbacks"; +import { type DropPriorityEvent } from "../../assets/snapsort/src/events"; +import { flowLayoutPositions } from "./layout-grid"; + +export type Box = ElementBox; + +export type MockSnapSortItem = { + id: string; + itemId: string; + metadata: Record; + direction: "row" | "column"; + mainAxisAlign: "start"; + locked: boolean; + isGhost: boolean; + parent?: MockSnapSortItem | null; + callbacks?: { + getDropPriority?: (event: DropPriorityEvent) => number | undefined; + }; + dropPriority?: number; + dragSnapshot: ItemSnapshot; + box: Box; + itemOrderedList: MockSnapSortItem[]; + children: MockSnapSortItem[]; + worldTransform: { x: number; y: number; scaleX: number; scaleY: number }; + dragPositionX: number; + dragPositionY: number; + dragPointerPosition: { x: number; y: number } | null; + depth: number; + name?: string; + config?: Record; + numberOfItems?: number; + getIndexAndContainer?: () => { + container: MockSnapSortItem | null | undefined; + index: number; + }; + addDebugRect: () => void; + addDebugCircle: () => void; + addDebugLine: () => void; + addDebugText: () => void; + clearDebugMarker: () => void; +}; + +export function center(rect: Rect) { + return { + x: rect.x + rect.width / 2, + y: rect.y + rect.height / 2, + }; +} + +export function layoutBox( + rect: Rect, + margin: Partial = {}, + padding: Partial = {}, + border: Partial = {}, +): Box { + return { + ...rect, + screen: { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + }, + margin: { + top: margin.top ?? 0, + right: margin.right ?? 0, + bottom: margin.bottom ?? 0, + left: margin.left ?? 0, + }, + padding: { + top: padding.top ?? 0, + right: padding.right ?? 0, + bottom: padding.bottom ?? 0, + left: padding.left ?? 0, + }, + border: { + top: border.top ?? 0, + right: border.right ?? 0, + bottom: border.bottom ?? 0, + left: border.left ?? 0, + }, + }; +} + +export function itemSnapshot( + value: T, + box: Box, + children: ItemSnapshot[] = [], + direction: "row" | "column" = "column", +): ItemSnapshot { + return { + value, + itemId: String(value), + metadata: {}, + direction, + mainAxisAlign: "start", + layoutModel: "flow", + wrap: "auto", + stretchItems: false, + locked: false, + box, + children, + }; +} + +export type SnapshotFixture = Omit< + ItemSnapshot, + | "itemId" + | "metadata" + | "mainAxisAlign" + | "layoutModel" + | "wrap" + | "stretchItems" + | "children" +> & { + itemId?: string; + metadata?: ItemSnapshot["metadata"]; + mainAxisAlign?: ItemSnapshot["mainAxisAlign"]; + layoutModel?: ItemSnapshot["layoutModel"]; + wrap?: ItemSnapshot["wrap"]; + stretchItems?: ItemSnapshot["stretchItems"]; + children: SnapshotFixture[]; +}; + +export function snapshotFixture( + fixture: SnapshotFixture, +): ItemSnapshot { + return { + ...fixture, + itemId: fixture.itemId ?? String(fixture.value), + metadata: fixture.metadata ?? {}, + mainAxisAlign: fixture.mainAxisAlign ?? "start", + layoutModel: fixture.layoutModel ?? "flow", + wrap: fixture.wrap ?? "auto", + stretchItems: fixture.stretchItems ?? false, + children: fixture.children.map(snapshotFixture), + }; +} + +export function mockSnapSortItem( + id: string, + rect: Rect, + children: MockSnapSortItem[] = [], + direction: "row" | "column" = "column", +): MockSnapSortItem { + const box = layoutBox(rect); + const item: MockSnapSortItem = { + id, + itemId: id, + metadata: {}, + direction, + mainAxisAlign: "start", + locked: false, + isGhost: false, + parent: null, + callbacks: undefined, + dropPriority: 0, + dragSnapshot: null as unknown as ItemSnapshot, + box, + itemOrderedList: children, + children, + worldTransform: { x: rect.x, y: rect.y, scaleX: 1, scaleY: 1 }, + dragPositionX: rect.x, + dragPositionY: rect.y, + dragPointerPosition: null, + depth: 0, + addDebugRect: () => {}, + addDebugCircle: () => {}, + addDebugLine: () => {}, + addDebugText: () => {}, + clearDebugMarker: () => {}, + }; + item.getIndexAndContainer = () => { + const container = item.parent; + return { + container, + index: container ? container.itemOrderedList.indexOf(item) : -1, + }; + }; + Object.defineProperties(item, { + dragPositionX: { + get: () => item.worldTransform.x, + configurable: true, + }, + dragPositionY: { + get: () => item.worldTransform.y, + configurable: true, + }, + dragPointerPosition: { + get: () => null, + configurable: true, + }, + }); + item.dragSnapshot = itemSnapshot( + item, + box, + children.map((child) => child.dragSnapshot), + direction, + ); + for (const child of children) { + child.depth = item.depth + 1; + child.parent = item; + } + return item; +} + +export function mockSnapSortContainer( + id: string, + rect: Rect, + children: MockSnapSortItem[], + direction: "row" | "column", +): MockSnapSortItem { + const item = mockSnapSortItem(id, rect, children, direction); + item.config = {}; + item.name = id; + item.numberOfItems = children.length; + return item; +} + +export function dropPriorityFixture() { + const dragged = mockSnapSortItem("dragged", { + x: 10, + y: 10, + width: 20, + height: 20, + }); + const source = mockSnapSortContainer( + "source", + { x: -100, y: 0, width: 50, height: 50 }, + [dragged], + "column", + ); + const near = mockSnapSortContainer( + "near", + { x: 0, y: 0, width: 100, height: 50 }, + [], + "column", + ); + const far = mockSnapSortContainer( + "far", + { x: 0, y: 65, width: 100, height: 50 }, + [], + "column", + ); + const root = mockSnapSortContainer( + "root", + { x: 0, y: 0, width: 100, height: 115 }, + [near, far], + "column", + ); + root.callbacks = { getDropPriority: rejectDrop }; + return { dragged, source, near, far, root }; +} + +export function virtualInsertionPosition( + container: ItemSnapshot, + dragged: ItemSnapshot, + startX: number, + startY: number, + index: number, + width: number, + height: number, +) { + const insertion = { + container, + index, + entry: { + width, + height, + margin: dragged.box.margin, + }, + }; + const rect = flowLayoutPositions(container, startX, startY, { + exclude: (node) => node === dragged, + insertions: [insertion], + }).virtualRects.get(insertion); + return rect ? { x: rect.x, y: rect.y } : null; +} diff --git a/tests/promo/snapsort-promo.playwright.config.ts b/tests/promo/snapsort-promo.playwright.config.ts index f9cdbb55..6f79cf71 100644 --- a/tests/promo/snapsort-promo.playwright.config.ts +++ b/tests/promo/snapsort-promo.playwright.config.ts @@ -16,7 +16,9 @@ export default defineConfig({ browserName: "chromium", baseURL: `http://127.0.0.1:${websitePort}`, viewport: { width: 1200, height: 1200 }, - screen: { width: 1200, height: 1200 }, + // `screen` is a BrowserContext option with no top-level `use` fixture, so + // it must go through `contextOptions` to reach the browser context. + contextOptions: { screen: { width: 1200, height: 1200 } }, deviceScaleFactor: 1, colorScheme: "light", screenshot: "only-on-failure", diff --git a/tests/types/snapsort-api-contract.ts b/tests/types/snapsort-api-contract.ts index 1b18f2a0..153692a3 100644 --- a/tests/types/snapsort-api-contract.ts +++ b/tests/types/snapsort-api-contract.ts @@ -87,11 +87,6 @@ const dropPolicy = (event: DropPriorityEvent): number | undefined => { }; const policyCallbacks: ContainerCallbacks = { getDropPriority: dropPolicy }; void policyCallbacks; -const removedCanDrop: ContainerCallbacks = { - // @ts-expect-error canDrop was replaced by getDropPriority rejection. - canDrop: () => true, -}; -void removedCanDrop; const itemOptions: ItemOptions = { itemId: "task-1" }; const constructedItem = new Item(engine, null, itemOptions); @@ -229,8 +224,6 @@ const _missingReactItemId: reactBinding.ItemProps = { children: null }; const _missingReactContainerId: reactBinding.ContainerProps = {}; // @ts-expect-error application identity is immutable. item.itemId = "replacement"; -// @ts-expect-error resolvedItemId was replaced by the non-null itemId property. -item.resolvedItemId; const directSession: DragSession | null = item.beginDirectDrag(); @@ -315,28 +308,10 @@ session.ghosts; // @ts-expect-error animation bookkeeping is internal. session.dragVisualStart; -// @ts-expect-error addItem was replaced by attachItem. -container.addItem(item); -// @ts-expect-error configuration was replaced by config. -container.configuration; // @ts-expect-error custom strategy injection is no longer public configuration. config.strategy; -// @ts-expect-error clickMove was replaced by move. -animations.clickMove; -// @ts-expect-error awaitMutation is no longer a callback integration seam. -callbacks.awaitMutation; -// @ts-expect-error framework transaction ownership moved to SnapSortAdapter. -callbacks.flushMutation; // @ts-expect-error renderer adapters are construction-only ContainerOptions. config.adapter; -// @ts-expect-error the old integration boundary was replaced by SnapSortAdapter. -config.integration; -// @ts-expect-error the old integration property was replaced by Container.adapter. -container.integration; -// @ts-expect-error Ghost accepts current GhostState, not mutation events. -ghostProps.event; -// @ts-expect-error Ghost accepts current GhostState, not presentation models. -ghostProps.presentation; // @ts-expect-error insertion markers expose a semantic gap, not a render rectangle. insertionMarker.rect; // @ts-expect-error insertion geometry conversion always requires explicit presentation options. @@ -352,20 +327,10 @@ horizontalGap.length = 200; insertionNeighbor.rect.x = 0; // @ts-expect-error the stock renderer contract is immutable. stockInsertionMarkerRectOptions.thickness = 4; -// @ts-expect-error mutation events no longer expose a phase. -insertEvent.phase; -// @ts-expect-error mutation events no longer expose a phase. -moveEvent.phase; -// @ts-expect-error mutation events no longer expose a phase. -removeEvent.phase; -// @ts-expect-error mutation events no longer expose a phase. -swapEvent.phase; // @ts-expect-error a true insertion cannot materialize an application value. renderTree = reduceRenderTree(renderTree, insertEvent); // @ts-expect-error framework reconciliation keys are application-owned. entries[0].key; -// @ts-expect-error RenderEntry.id was replaced by RenderEntry.itemId. -entries[0].id; const callbacksWithoutLegacyInsertionGeometry: ContainerCallbacks = { // @ts-expect-error insertion targeting geometry is core-owned; this callback was removed. @@ -373,38 +338,12 @@ const callbacksWithoutLegacyInsertionGeometry: ContainerCallbacks = { }; void callbacksWithoutLegacyInsertionGeometry; -// @ts-expect-error MutationPhase is no longer exported from the package root. -import type { MutationPhase as _MutationPhase } from "@snap-engine/snapsort"; // @ts-expect-error SortStrategy is an internal implementation detail. import type { SortStrategy as _SortStrategy } from "@snap-engine/snapsort"; // @ts-expect-error DropTargetStrategy is an internal implementation detail. import type { DropTargetStrategy as _DropTargetStrategy } from "@snap-engine/snapsort"; // @ts-expect-error DragLifecycleStrategy is an internal implementation detail. import type { DragLifecycleStrategy as _DragLifecycleStrategy } from "@snap-engine/snapsort"; -// @ts-expect-error FrameworkIntegration was replaced by SnapSortAdapter. -import type { FrameworkIntegration as _FrameworkIntegration } from "@snap-engine/snapsort"; -// @ts-expect-error GhostPresentation was replaced by GhostState. -import type { GhostPresentation as _GhostPresentation } from "@snap-engine/snapsort"; -// @ts-expect-error InsertionMarkerRectEvent was removed with getInsertionMarkerRect. -import type { InsertionMarkerRectEvent as _InsertionMarkerRectEvent } from "@snap-engine/snapsort"; -// @ts-expect-error RenderKey is no longer part of the public API. -import type { RenderKey as _RenderKey } from "@snap-engine/snapsort"; -// @ts-expect-error renderKey is no longer part of the public API. -import { renderKey as _renderKey } from "@snap-engine/snapsort"; -// @ts-expect-error container-local ghost state was replaced by RenderTree. -import { reduceContainerGhosts as _reduceContainerGhosts } from "@snap-engine/snapsort"; -// @ts-expect-error render composition was replaced by RenderTree state. -import { composeRenderEntries as _composeRenderEntries } from "@snap-engine/snapsort"; -// @ts-expect-error container-local reduction replaced the flat insert reducer. -import { insertGhostState as _insertGhostState } from "@snap-engine/snapsort"; -// @ts-expect-error container-local reduction replaced the flat move reducer. -import { moveGhostState as _moveGhostState } from "@snap-engine/snapsort"; -// @ts-expect-error container-local reduction replaced the flat remove reducer. -import { removeGhostState as _removeGhostState } from "@snap-engine/snapsort"; -// @ts-expect-error the deprecated React helper is no longer exported. -import { useSnapSortAwaitMutation as _useSnapSortAwaitMutation } from "@snap-engine/snapsort/react"; -// @ts-expect-error the deprecated React helper has no package subpath. -import { useSnapSortAwaitMutation as _deepHelper } from "@snap-engine/snapsort/react/useSnapSortAwaitMutation"; // @ts-expect-error GhostRect was replaced by core's geometry Rect. import type { GhostRect as _GhostRect } from "@snap-engine/snapsort"; // @ts-expect-error ContainerLocalRect was replaced by core's geometry Rect. diff --git a/tests/ut/core-geometry.spec.ts b/tests/ut/core-geometry.spec.ts index 3c397aa3..676b0251 100644 --- a/tests/ut/core-geometry.spec.ts +++ b/tests/ut/core-geometry.spec.ts @@ -7,6 +7,7 @@ import { contentRect, distance, edgesToCss, + freezePoint, freezeRect, insetRect, lerpRect, @@ -77,6 +78,12 @@ test.describe("rect helpers", () => { expect(boundingRect([])).toBeNull(); }); + test("freezePoint copies only point fields", () => { + const point = freezePoint({ x: 1, y: 2, ...{ extra: true } }); + expect(point).toEqual({ x: 1, y: 2 }); + expect(Object.isFrozen(point)).toBe(true); + }); + test("freeze and bounds copy only rectangle fields", () => { const frozen = freezeRect(box); expect(frozen).toEqual({ x: 10, y: 20, width: 100, height: 60 }); diff --git a/tests/ut/input-headless-owner.spec.ts b/tests/ut/core-input-headless-owner.spec.ts similarity index 93% rename from tests/ut/input-headless-owner.spec.ts rename to tests/ut/core-input-headless-owner.spec.ts index 8b4e5fda..baa06bc5 100644 --- a/tests/ut/input-headless-owner.spec.ts +++ b/tests/ut/core-input-headless-owner.spec.ts @@ -1,7 +1,11 @@ import { expect, test } from "@playwright/test"; import { JSDOM } from "jsdom"; import { InputControl } from "../../src/input"; -import { BaseObject, ElementObject } from "../../src/object"; +import { + BaseObject, + ElementObject, + type DomElement, +} from "../../src/object"; type InstalledGlobal = { key: "window" | "document" | "HTMLElement" | "Node" | "AbortController"; @@ -1323,7 +1327,7 @@ test("keydown exposes the focused input-alias owner through targeted bubbling an const deliveries: Array<{ scope: string; - focusedObject: ElementObject | null; + focusedObject: ElementObject | null; event: KeyboardEvent; }> = []; focusedObject.event.input.keyDown = (prop) => { @@ -1384,7 +1388,7 @@ test("global keydown receives null when the focused element has no registered ow if (!focusElement) throw new Error("Missing keyboard input element"); try { - const deliveries: Array = []; + const deliveries: Array | null> = []; harness.input.event.keyDown = ({ focusedObject }) => { deliveries.push(focusedObject); }; @@ -1402,3 +1406,96 @@ test("global keydown receives null when the focused element has no registered ow harness.cleanup(); } }); + +// A consumer handler that throws must not unwind the input dispatch. The +// pointer record deleted at the end of #finishPointer is what releases the +// pointer's claim, and a claim that outlives its gesture suppresses every +// later global pointerMove for that pointer id — which is how a throwing +// dragEnd once left the resize cursor stuck until the next click. +test("a throwing dragEnd handler does not strand the pointer's claim", () => { + const harness = createInputHarness(""); + const { container, dom, engine, input } = harness; + + // The engine reports consumer errors through globalThis.reportError; capture + // it so a deliberately thrown error doesn't fail the run. + const reported: unknown[] = []; + const previousReportError = Object.getOwnPropertyDescriptor( + globalThis, + "reportError", + ); + Object.defineProperty(globalThis, "reportError", { + configurable: true, + writable: true, + value: (error: unknown) => reported.push(error), + }); + + try { + const owner = new ElementObject(engine); + input.registerObjectElement(owner, container); + + owner.event.input.pointerDown = ({ event }) => { + // Same shape as a resize gesture: claim from the first pointer event. + input.claimPointer(event.pointerId); + }; + owner.event.input.dragEnd = () => { + throw new Error("consumer dragEnd failure"); + }; + + container.dispatchEvent( + pointerEvent(dom.window, "pointerdown", { + x: 10, + y: 10, + buttons: 1, + pointerId: 7, + }), + ); + container.dispatchEvent( + pointerEvent(dom.window, "pointermove", { + x: 40, + y: 10, + buttons: 1, + pointerId: 7, + }), + ); + dom.window.document.dispatchEvent( + pointerEvent(dom.window, "pointerup", { + x: 40, + y: 10, + buttons: 0, + pointerId: 7, + }), + ); + + expect(reported).toHaveLength(1); + + // The claim died with the gesture, so hover-style global dispatch resumes. + // This is the channel ResizeHoverController listens on to recompute the + // cursor, so a leaked claim is exactly what pins it. + const globalMoves: number[] = []; + input.subscribeGlobalCursorEvent( + "pointerMove", + "test-hover", + () => { + globalMoves.push(1); + }, + engine, + ); + container.dispatchEvent( + pointerEvent(dom.window, "pointermove", { + x: 55, + y: 22, + buttons: 0, + pointerId: 7, + }), + ); + + expect(globalMoves).toHaveLength(1); + } finally { + if (previousReportError) { + Object.defineProperty(globalThis, "reportError", previousReportError); + } else { + delete (globalThis as Record).reportError; + } + harness.cleanup(); + } +}); diff --git a/tests/ut/core-layout.spec.ts b/tests/ut/core-layout.spec.ts index f76ff3ae..8cd7e16f 100644 --- a/tests/ut/core-layout.spec.ts +++ b/tests/ut/core-layout.spec.ts @@ -221,18 +221,6 @@ test.describe("flowLayoutPositions wrap decisions", () => { } }); - test("wraps a genuinely oversized ghost insertion", () => { - const grid = makeGrid({ rows: 2, cols: 4, itemW: 93, itemH: 93, gap: 4 }); - const dragged = grid.children[0]; - // Ghost twice as wide as a slot: only 3 fit per line alongside it. - const counts = simulatedRowCounts(grid, { - rowStep: 97, - insertion: ghostInsertion(grid, 0, { width: 190, height: 93 }), - exclude: (node) => node.value === dragged.value, - }); - expect(counts[0]).toBeLessThan(4); - }); - test("column containers with a single measured line never wrap", () => { const children = [0, 1, 2].map((i) => makeItemSnapshot( diff --git a/tests/ut/frame-controller.spec.ts b/tests/ut/frame-controller.spec.ts index f7c08d25..649cfd5a 100644 --- a/tests/ut/frame-controller.spec.ts +++ b/tests/ut/frame-controller.spec.ts @@ -94,7 +94,9 @@ test("frame controllers run before every engine READ_1 with the shared rAF times order.push(`frame:first:${firstEngine.global?.currentStage}`); timestamps.push(frame.timestamp); frames.push(frame); - firstObject.schedule(() => order.push("read:first"), { + firstObject.schedule(() => { + order.push("read:first"); + }, { stage: "READ_1", }); }); @@ -102,7 +104,9 @@ test("frame controllers run before every engine READ_1 with the shared rAF times order.push(`frame:second:${secondEngine.global?.currentStage}`); timestamps.push(frame.timestamp); frames.push(frame); - secondObject.schedule(() => order.push("read:second"), { + secondObject.schedule(() => { + order.push("read:second"); + }, { stage: "READ_1", }); }); diff --git a/tests/ut/input-error-isolation.spec.ts b/tests/ut/input-error-isolation.spec.ts deleted file mode 100644 index 594a0dd6..00000000 --- a/tests/ut/input-error-isolation.spec.ts +++ /dev/null @@ -1,203 +0,0 @@ -import { expect, test } from "@playwright/test"; -import { JSDOM } from "jsdom"; -import { InputControl } from "../../src/input"; -import { ElementObject } from "../../src/object"; - -// A consumer handler that throws must not unwind the input dispatch. The -// pointer record deleted at the end of #finishPointer is what releases the -// pointer's claim, and a claim that outlives its gesture suppresses every -// later global pointerMove for that pointer id — which is how a throwing -// dragEnd once left the resize cursor stuck until the next click. - -type InstalledGlobal = { - key: "window" | "document" | "HTMLElement" | "Node" | "AbortController"; - descriptor: PropertyDescriptor | undefined; -}; - -function installDomGlobals(window: JSDOM["window"]): () => void { - const values = { - window, - document: window.document, - HTMLElement: window.HTMLElement, - Node: window.Node, - AbortController: window.AbortController, - }; - const installed: InstalledGlobal[] = []; - - for (const [key, value] of Object.entries(values) as Array< - [InstalledGlobal["key"], unknown] - >) { - installed.push({ - key, - descriptor: Object.getOwnPropertyDescriptor(globalThis, key), - }); - Object.defineProperty(globalThis, key, { - configurable: true, - writable: true, - value, - }); - } - - return () => { - for (const { key, descriptor } of installed) { - if (descriptor) { - Object.defineProperty(globalThis, key, descriptor); - } else { - delete (globalThis as Record)[key]; - } - } - }; -} - -function pointerEvent( - window: JSDOM["window"], - type: string, - { - x, - y, - buttons, - pointerId, - }: { x: number; y: number; buttons: number; pointerId: number }, -): Event { - const event = new window.MouseEvent(type, { - bubbles: true, - cancelable: true, - clientX: x, - clientY: y, - buttons, - }); - Object.defineProperty(event, "pointerId", { value: pointerId }); - return event; -} - -test("a throwing dragEnd handler does not strand the pointer's claim", () => { - const dom = new JSDOM( - "
", - ); - const restoreGlobals = installDomGlobals(dom.window); - const container = dom.window.document.querySelector("#engine"); - if (!container) throw new Error("Missing test container"); - - // The engine reports consumer errors through globalThis.reportError; capture - // it so a deliberately thrown error doesn't fail the run. - const reported: unknown[] = []; - const previousReportError = Object.getOwnPropertyDescriptor( - globalThis, - "reportError", - ); - Object.defineProperty(globalThis, "reportError", { - configurable: true, - writable: true, - value: (error: unknown) => reported.push(error), - }); - - let nextId = 0; - const objectTable: Record = {}; - const queue = { - READ_1: new Map(), - WRITE_1: new Map(), - READ_2: new Map(), - WRITE_2: new Map(), - READ_3: new Map(), - WRITE_3: new Map(), - }; - const engine: any = { - camera: null, - containerBounds: null, - global: null, - input: null, - }; - const global: any = { - currentStage: "IDLE", - data: {}, - queue, - createId: () => `${++nextId}`, - getEngineObjectTable: (candidate: unknown) => { - if (candidate !== engine) throw new Error("Unexpected engine"); - return objectTable; - }, - registerObject: (object: ElementObject) => { - objectTable[object.id] = object; - }, - unregisterObject: (object: ElementObject) => { - delete objectTable[object.id]; - }, - }; - - try { - engine.global = global; - const input = new InputControl(global, engine); - engine.input = input; - input.bindContainer(container); - - const owner = new ElementObject(engine); - input.registerObjectElement(owner, container); - - owner.event.input.pointerDown = ({ event }) => { - // Same shape as a resize gesture: claim from the first pointer event. - input.claimPointer(event.pointerId); - }; - owner.event.input.dragEnd = () => { - throw new Error("consumer dragEnd failure"); - }; - - container.dispatchEvent( - pointerEvent(dom.window, "pointerdown", { - x: 10, - y: 10, - buttons: 1, - pointerId: 7, - }), - ); - container.dispatchEvent( - pointerEvent(dom.window, "pointermove", { - x: 40, - y: 10, - buttons: 1, - pointerId: 7, - }), - ); - dom.window.document.dispatchEvent( - pointerEvent(dom.window, "pointerup", { - x: 40, - y: 10, - buttons: 0, - pointerId: 7, - }), - ); - - expect(reported).toHaveLength(1); - - // The claim died with the gesture, so hover-style global dispatch resumes. - // This is the channel ResizeHoverController listens on to recompute the - // cursor, so a leaked claim is exactly what pins it. - const globalMoves: number[] = []; - input.subscribeGlobalCursorEvent( - "pointerMove", - "test-hover", - () => { - globalMoves.push(1); - }, - engine, - ); - container.dispatchEvent( - pointerEvent(dom.window, "pointermove", { - x: 55, - y: 22, - buttons: 0, - pointerId: 7, - }), - ); - - expect(globalMoves).toHaveLength(1); - input.destroy(); - } finally { - if (previousReportError) { - Object.defineProperty(globalThis, "reportError", previousReportError); - } else { - delete (globalThis as Record).reportError; - } - restoreGlobals(); - dom.window.close(); - } -}); diff --git a/tests/ut/input.spec.ts b/tests/ut/input.spec.ts deleted file mode 100644 index edfd3a94..00000000 --- a/tests/ut/input.spec.ts +++ /dev/null @@ -1,467 +0,0 @@ -import { expect, test } from "@playwright/test"; -import SnapLine from "../../src/index"; -import { InputControl, cursorState } from "../../src/input"; -import { JSDOM } from "jsdom"; -const port = 3001; - -function initInputControl() { - const dom = new JSDOM( - ` - -
- - `, - { - url: `http://localhost:${port}`, - contentType: "text/html", - }, - ); - const window = dom.window; - const document = dom.window.document; - const target = document.querySelector("#target"); - const inputControl = new InputControl(target, document); - - return [inputControl, window, document, target]; -} - -test.describe("Test mouse input handler", () => { - test("Mousedown event", async ({ page }) => { - const [inputControl, window, document, target] = initInputControl(); - // Create a mock event - const event = new window.MouseEvent("mousedown", { - bubbles: true, - cancelable: true, - clientX: 100, - clientY: 100, - button: 0, - }); - - let called: boolean = false; - inputControl._onCursorDown = (e, callbackTarget, button, x, y) => { - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(button).toBe(cursorState.mouseLeft); - expect(x).toBe(100); - expect(y).toBe(100); - called = true; - }; - - target.dispatchEvent(event); - expect(called).toBe(true); - }); - - test("Mousemove event", async ({ page }) => { - const [inputControl, window, document, target] = initInputControl(); - document.elementFromPoint = () => { - return target; - }; - // Create a mock event - const event = new window.MouseEvent("mousemove", { - bubbles: true, - cancelable: true, - clientX: 100, - clientY: 100, - }); - - let called: boolean = false; - inputControl._onCursorMove = (e, callbackTarget, state, x, y) => { - called = true; - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(x).toBe(100); - expect(y).toBe(100); - }; - - target.dispatchEvent(event); - expect(called).toBe(true); - }); - - test("Mouseup event", async ({ page }) => { - const [inputControl, window, document, target] = initInputControl(); - // Create a mock event - const event = new window.MouseEvent("mouseup", { - bubbles: true, - cancelable: true, - clientX: 100, - clientY: 100, - button: 0, - }); - - let called: boolean = false; - inputControl._onCursorUp = (e, callbackTarget, button, x, y) => { - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(button).toBe(cursorState.mouseLeft); - expect(x).toBe(100); - expect(y).toBe(100); - called = true; - }; - - target.dispatchEvent(event); - expect(called).toBe(true); - }); - - test("Mousewheel event", async ({ page }) => { - const [inputControl, window, document, target] = initInputControl(); - // Create a mock event - const event = new window.WheelEvent("wheel", { - bubbles: true, - cancelable: true, - clientX: 100, - clientY: 100, - deltaY: 200, - }); - - let called: boolean = false; - inputControl._onScroll = ( - e, - callbackTarget, - state, - clientX, - clientY, - deltaY, - ) => { - called = true; - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(clientX).toBe(100); - expect(clientY).toBe(100); - expect(deltaY).toBe(200); - }; - - target.dispatchEvent(event); - expect(called).toBe(true); - }); -}); - -type touchEntry = { - clientX: number; - clientY: number; - identifier: number; -}; - -class MockTouch { - identifier: number; - clientX: number; - clientY: number; - target: Element; - constructor( - identifier: number, - clientX: number, - clientY: number, - target: Element, - ) { - this.identifier = identifier; - this.clientX = clientX; - this.clientY = clientY; - this.target = target; - } -} - -class MockTouchList extends Array { - constructor(private touches: MockTouch[] = []) { - super(...touches); - } - item(index: number): MockTouch | null { - return this.touches[index] || null; - } -} - -function initTouchEvent( - window: any, - eventName: string, - target: Element, - touches: touchEntry[], - changedTouches: touchEntry[] = [], -) { - const touchList: MockTouchList = new MockTouchList(); - for (const touch of touches) { - touchList.push( - new MockTouch(touch.identifier, touch.clientX, touch.clientY, target), - ); - } - const changedTouchList: MockTouchList = new MockTouchList(); - for (const touch of changedTouches) { - changedTouchList.push( - new MockTouch(touch.identifier, touch.clientX, touch.clientY, target), - ); - } - return new window.TouchEvent(eventName, { - bubbles: true, - cancelable: true, - touches: touchList, - changedTouches: changedTouchList, - }); -} - -test.describe("Test touch input handler", () => { - test("Pressing a single touch point", async ({ page }) => { - const [inputControl, window, document, target] = initInputControl(); - const event = initTouchEvent( - window, - "touchstart", - target, - [], - [ - { - clientX: 100, - clientY: 100, - identifier: 1, - }, - ], - ); - - let called: boolean = false; - inputControl._onCursorDown = (e, callbackTarget, button, x, y) => { - called = true; - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(x).toBe(100); - expect(y).toBe(100); - }; - - target.dispatchEvent(event); - expect(called).toBe(true); - }); - - test("When two touches are started simultaneously, it should be treated as a middle mouse button click", async ({ - page, - }) => { - page.on("console", (msg) => console.log(msg.text())); - const [inputControl, window, document, target] = initInputControl(); - const eventStart = initTouchEvent( - window, - "touchstart", - target, - [], - [ - { - clientX: 100, - clientY: 100, - identifier: 1, - }, - { - clientX: 200, - clientY: 200, - identifier: 2, - }, - ], - ); - - let called: boolean = false; - inputControl._onCursorDown = (e, callbackTarget, button, x, y) => { - called = true; - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(button).toBe(cursorState.mouseMiddle); - expect(x).toBe(150); - expect(y).toBe(150); - }; - - target.dispatchEvent(eventStart); - expect(called).toBe(true); - }); - - test("Touchmove event with a single touch", async ({ page }) => { - const [inputControl, window, document, target] = initInputControl(); - const downTouches = [ - { - clientX: 100, - clientY: 100, - identifier: 1, - }, - ]; - const moveTouches = [ - { - clientX: 101, - clientY: 101, - identifier: 1, - }, - ]; - - const touchStart = initTouchEvent( - window, - "touchstart", - target, - downTouches, - downTouches, - ); - const touchMove = initTouchEvent( - window, - "touchmove", - target, - moveTouches, - [], - ); - - let called: boolean = false; - inputControl._onCursorMove = (e, callbackTarget, button, x, y) => { - called = true; - // Moving a touch point should be treated as dragging a mouse while holding the left button - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(button).toBe(cursorState.mouseLeft); - expect(x).toBe(101); - expect(y).toBe(101); - }; - - target.dispatchEvent(touchStart); - target.dispatchEvent(touchMove); - expect(called).toBe(true); - }); - - test("Touchmove event with multiple simultaneous touches", async ({ - page, - }) => { - const [inputControl, window, document, target] = initInputControl(); - const downTouches = [ - { - clientX: 100, - clientY: 100, - identifier: 1, - }, - { - clientX: 200, - clientY: 200, - identifier: 2, - }, - ]; - const moveTouches = [ - { - clientX: 101, - clientY: 101, - identifier: 1, - }, - { - clientX: 201, - clientY: 201, - identifier: 2, - }, - ]; - const eventDown = initTouchEvent( - window, - "touchstart", - target, - downTouches, - downTouches, - ); - const eventMove = initTouchEvent( - window, - "touchmove", - target, - moveTouches, - [], - ); - - let called: boolean = false; - inputControl._onCursorMove = (e, callbackTarget, button, x, y) => { - called = true; - // Moving two touch points should be treated as dragging a mouse while holding the middle button - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(button).toBe(cursorState.mouseMiddle); - expect(x).toBe(151); - expect(y).toBe(151); - }; - - target.dispatchEvent(eventDown); - target.dispatchEvent(eventMove); - expect(called).toBe(true); - }); - - test("Touchmove event for pan and pinch zoom", async ({ page }) => { - const [inputControl, window, document, target] = initInputControl(); - const downTouches = [ - { - clientX: 0, - clientY: 100, - identifier: 1, - }, - { - clientX: 0, - clientY: -100, - identifier: 2, - }, - ]; - const moveTouches_0 = [ - { - clientX: 0, - clientY: 100, - identifier: 1, - }, - { - clientX: 0, - clientY: -100, - identifier: 2, - }, - ]; - const moveTouches_1 = [ - { - clientX: 30, - clientY: 50, - identifier: 1, - }, - { - clientX: 30, - clientY: -50, - identifier: 2, - }, - ]; - - const touchStart = initTouchEvent( - window, - "touchstart", - target, - downTouches, - downTouches, - ); - const touchMove_0 = initTouchEvent( - window, - "touchmove", - target, - moveTouches_0, - [], - ); - const touchMove_1 = initTouchEvent( - window, - "touchmove", - target, - moveTouches_1, - [], - ); - - target.dispatchEvent(touchStart); - target.dispatchEvent(touchMove_0); - - let scrollCalled: boolean = false; - let moveCalled: boolean = false; - inputControl._onScroll = ( - e, - callbackTarget, - button, - clientX, - clientY, - deltaY, - ) => { - scrollCalled = true; - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(clientX).toBe(30); - expect(clientY).toBe(0); - expect(deltaY).toBe(-100); - }; - inputControl._onCursorMove = (e, callbackTarget, button, x, y) => { - moveCalled = true; - expect(e).toBeDefined(); - expect(callbackTarget).toBe(target); - expect(button).toBe(cursorState.mouseMiddle); - expect(x).toBe(30); - expect(y).toBe(0); - }; - - target.dispatchEvent(touchMove_1); - // expect(inputControl._zoom).toBe(0.5); - expect(scrollCalled).toBe(true); - expect(moveCalled).toBe(true); - }); -}); diff --git a/tests/ut/snapline-geometry.spec.ts b/tests/ut/snapline-geometry.spec.ts index 1db03179..741f625e 100644 --- a/tests/ut/snapline-geometry.spec.ts +++ b/tests/ut/snapline-geometry.spec.ts @@ -105,3 +105,39 @@ test("outside a gesture, a measurement still reconciles the collision box", () = node.destroy(false); restoreObservers(); }); + +test("a scaled node's collision box keeps its unscaled local size", () => { + const restoreObservers = installObserverStubs(); + const { engine, global } = createEngineHarness(); + // A real DOM read: core measures the rendered rect and computed style. + const windowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window"); + Object.defineProperty(globalThis, "window", { + configurable: true, + value: { + getComputedStyle: () => ({ transformOrigin: "0px 0px" }), + }, + }); + const node = new NodeMirror(engine, null); + // 180x100 in CSS, rendered at 2x by the node's own transform. + const element = { + style: { transform: "translate3d(0px, 0px, 0px) scale(2, 2)" }, + getBoundingClientRect: () => ({ left: 0, top: 0, width: 360, height: 200 }), + }; + node.element = element as unknown as HTMLElement; + node.worldTransform = { x: 0, y: 0, scaleX: 2, scaleY: 2 }; + + node.remeasureDomGeometry(); + drain(global, "READ_1"); + + // The collider scales with its node, so its local size must be unscaled. + expect([node.hitBox.width, node.hitBox.height]).toEqual([180, 100]); + expect([node.hitBox.worldWidth, node.hitBox.worldHeight]).toEqual([360, 200]); + + node.destroy(false); + if (windowDescriptor) { + Object.defineProperty(globalThis, "window", windowDescriptor); + } else { + delete (globalThis as Record).window; + } + restoreObservers(); +}); diff --git a/tests/ut/snapline-line-reconciler.spec.ts b/tests/ut/snapline-line-reconciler.spec.ts index 84324b56..640997a9 100644 --- a/tests/ut/snapline-line-reconciler.spec.ts +++ b/tests/ut/snapline-line-reconciler.spec.ts @@ -207,7 +207,7 @@ function gestureHarness() { return { ...base, source, target }; } -function dragFrom(connector: ConnectorMirror, dropX: number, pointerId = 7) { +function dragFrom(connector: ConnectorMirror, pointerId = 7) { const event = { button: 0, pointerId } as any; connector.onCursorDown({ position: pos(0, 0), event } as any); } @@ -230,7 +230,7 @@ test("a controlled connect stages, proposes one atomic request, and settles in p const { engine, handle, requests, source, target } = gestureHarness(); const mirror = getGraphRegistry(engine); - dragFrom(source, 100); + dragFrom(source); driveDrop(source, 100); expect(requests).toHaveLength(1); @@ -269,7 +269,7 @@ test("rejection-by-inaction discards the staged line on the decisive pass", () = const { engine, handle, requests, source } = gestureHarness(); const mirror = getGraphRegistry(engine); - dragFrom(source, 100); + dragFrom(source); driveDrop(source, 100); expect(requests).toHaveLength(1); expect(source.outgoingLines).toHaveLength(1); @@ -301,7 +301,7 @@ test("a full replace-oldest target yields one atomic replace request with no loc handle.flush(); const existing = mirror.line("line-a")!; - dragFrom(source, 100); + dragFrom(source); driveDrop(source, 100); expect(requests).toHaveLength(1); const request = requests[0]; @@ -378,7 +378,11 @@ test("controlled graphs on sibling engines are fully isolated, gestures included const sibling = createSiblingEngine(global); const siblingRequests: LineChangeRequest[] = []; const siblingHandle = attachControlledGraph(sibling, { - onLineChangeRequest: (request) => siblingRequests.push(request), + onLineChangeRequest: (request) => { + siblingRequests.push(request); + // The sibling document is never seeded, so it stays empty. + return []; + }, }); // Same connector ids on both engines: no conflict, independent settles. diff --git a/tests/ut/snapline-perf.spec.ts b/tests/ut/snapline-perf.spec.ts deleted file mode 100644 index f3b04c08..00000000 --- a/tests/ut/snapline-perf.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { test } from "@playwright/test"; -import { - ConnectorMirror, - NodeMirror, - type LineRecord, -} from "../../assets/snapline/src"; -import { getGraphRegistry } from "../../assets/snapline/src"; -import { - createControlledHarness, - nearTargetStrategy, -} from "../helpers/snapline-harness"; - -// Informational only — no assertions on timings. Logs the hot paths so a -// pathological regression (accidental O(n²), per-pointer-move scans) is -// visible in test output before it reaches an application. -test("perf: reconcile, candidate discovery, and bulk load on a 200-node graph", () => { - const { engine, handle } = createControlledHarness(); - const mirror = getGraphRegistry(engine); - - const NODES = 200; - const LINES = 150; - const sources: ConnectorMirror[] = []; - for (let index = 0; index < NODES; index += 1) { - const node = new NodeMirror(engine, null, { id: `n${index}` }); - sources.push( - new ConnectorMirror(engine, node, { - id: `n${index}:out`, - name: "out", - rules: { maxIncoming: 0 }, - }), - ); - new ConnectorMirror(engine, node, { - id: `n${index}:in`, - name: "in", - rules: { maxOutgoing: 0 }, - surfaceStrategies: [nearTargetStrategy], - }); - } - const records: LineRecord[] = []; - for (let index = 0; index < LINES; index += 1) { - records.push({ - id: `l${index}`, - fromConnectorId: `n${index}:out`, - toConnectorId: `n${(index + 1) % NODES}:in`, - }); - } - - const coldStart = performance.now(); - handle.setCanonicalGraph({ lines: records }); - handle.flush(); - const cold = performance.now() - coldStart; - - const warmStart = performance.now(); - handle.flush(); - const warm = performance.now() - warmStart; - - // Candidate discovery is the per-pointer-move hot path during a drag. - const probeStart = performance.now(); - const PROBES = 100; - for (let index = 0; index < PROBES; index += 1) { - sources[0].findCandidateAtPoint({ x: 100 + (index % 50), y: 10 }); - } - const probe = (performance.now() - probeStart) / PROBES; - - // Bulk load: fresh records over a cleared document inside one batch. - handle.setCanonicalGraph({ lines: [] }); - handle.flush(); - const bulkStart = performance.now(); - const batch = mirror.beginBatch(); - handle.setCanonicalGraph({ lines: records }); - batch.end(); - mirror.flush(); - const bulk = performance.now() - bulkStart; - - console.log( - `[snapline-perf] ${NODES} nodes / ${LINES} lines — ` + - `cold reconcile ${cold.toFixed(1)}ms, warm ${warm.toFixed(1)}ms, ` + - `candidate probe ${probe.toFixed(3)}ms/move, bulk load ${bulk.toFixed(1)}ms`, - ); -}); diff --git a/tests/ut/snapsort-algorithm.spec.ts b/tests/ut/snapsort-algorithm.spec.ts index 5da7fe3f..4471d36a 100644 --- a/tests/ut/snapsort-algorithm.spec.ts +++ b/tests/ut/snapsort-algorithm.spec.ts @@ -149,7 +149,11 @@ function requireInsertionTarget( if (!target?.insertion) { throw new Error("Expected an insertion-marker drop target."); } - return target; + // The guard above proved `insertion` is present; optional chaining on + // `target` does not narrow the property type for the return. + return target as ResolvedDropTarget & { + insertion: InsertionMarkerPresentation; + }; } function flowTargets( @@ -1089,36 +1093,6 @@ test("drop resolution performs no debug work until a renderer is enabled", () => expect(disabledChild.debugCounters.addDebugRect).toBeGreaterThan(0); }); -test("drop policy exposes one complete frozen event per container", () => { - const calls: string[] = []; - let priorityEvent: MockItem | null = null; - const child = mockItem("child", { x: 0, y: 0, width: 100, height: 20 }); - const root = mockItem( - "root", - { x: 0, y: 0, width: 120, height: 60 }, - { children: [child], container: true }, - ); - root.callbacks = { - getDropPriority: (event: MockItem) => { - calls.push("getDropPriority"); - priorityEvent = event; - return undefined; - }, - }; - const dragged = mockItem("dragged", { - x: 0, - y: 30, - width: 20, - height: 20, - }); - - determineDropTarget(dragged as never, root as never); - - expect(calls).toEqual(["getDropPriority"]); - expect(Object.isFrozen(priorityEvent!.containerRect)).toBe(true); - expect(Object.isFrozen(priorityEvent!.dragRect)).toBe(true); -}); - test("hover rectangle and circle boundaries remain edge-inclusive", () => { const dragged = mockItem("dragged", { x: 30, y: 30, width: 10, height: 10 }); const target = mockItem("target", { x: 0, y: 0, width: 10, height: 10 }); diff --git a/tests/e2e/snapsort-callback-ledger.spec.ts b/tests/ut/snapsort-callback-ledger.spec.ts similarity index 97% rename from tests/e2e/snapsort-callback-ledger.spec.ts rename to tests/ut/snapsort-callback-ledger.spec.ts index 3f63cb2f..151d95eb 100644 --- a/tests/e2e/snapsort-callback-ledger.spec.ts +++ b/tests/ut/snapsort-callback-ledger.spec.ts @@ -1,6 +1,7 @@ import { expect, test } from "@playwright/test"; import { JSDOM } from "jsdom"; import type { dragProp, dragStartProp } from "@snap-engine/core"; +import type { PointerPosition } from "../../src/geometry"; import { Container } from "../../assets/snapsort/src/container"; import { buildGhostSlotLocation } from "../../assets/snapsort/src/event-builders"; import type { DragLifecycleStrategy } from "../../assets/snapsort/src/drag/lifecycle"; @@ -182,11 +183,16 @@ function location(item: Item) { return { container, containerMetadata: container.metadata, index }; } +/** A pointer position with identical world, camera, and screen coordinates. */ +function pointerAt(x: number, y: number): PointerPosition { + return { x, y, camera: { x, y }, screen: { x, y } }; +} + function dragStartFor(item: Item, pointerId = 1): dragStartProp { return { objectId: item.id, pointerId, - start: { x: 20, y: 20 }, + start: pointerAt(20, 20), button: 0, isWithinEngine: true, handoffTo() {}, @@ -197,9 +203,9 @@ function dragMoveFor(item: Item, x: number, y: number): dragProp { return { objectId: item.id, pointerId: 1, - start: { x: 20, y: 20 }, - position: { x, y }, - delta: { x: x - 20, y: y - 20 }, + start: pointerAt(20, 20), + position: pointerAt(x, y), + delta: pointerAt(x - 20, y - 20), button: 0, handoffTo() {}, }; @@ -296,8 +302,12 @@ test("activation and veto callbacks remain direct and preserve order", async () let observedHandle: unknown = null; const lifecycle: DragLifecycleStrategy = { placementOccupiesFlowSlots: true, - validateStart: () => activationLedger.push("validate"), - dragStart: () => activationLedger.push("activate"), + validateStart: () => { + activationLedger.push("validate"); + }, + dragStart: () => { + activationLedger.push("activate"); + }, dragMove() {}, currentPlacement: () => null, placementIndexFor: (_session, target) => target.index, @@ -306,10 +316,10 @@ test("activation and veto callbacks remain direct and preserve order", async () afterPlacementSync() {}, drop() {}, }; - const strategy = { + const strategy: SortStrategy = { + mode: "euclidean", dropTarget: { resolve: () => null }, lifecycle, - defaultDragVisual: "none" as const, }; const root = mountRoot(harness, { onDragStart: (event) => { @@ -640,9 +650,9 @@ test("error finalization skips DOM writes for disconnected participants", async [item], [location(item)], { + mode: "euclidean", dropTarget: { resolve: () => null }, lifecycle, - defaultDragVisual: "item", }, { inputType: "pointer", diff --git a/tests/ut/snapsort-drag-config.spec.ts b/tests/ut/snapsort-drag-config.spec.ts new file mode 100644 index 00000000..f61da69d --- /dev/null +++ b/tests/ut/snapsort-drag-config.spec.ts @@ -0,0 +1,335 @@ +import { expect, test } from "@playwright/test"; +import type { Engine } from "@snap-engine/core"; +import { + Container as SnapSortContainer, + defaultAnimations, +} from "../../assets/snapsort/src/container"; +import { type DragVisual } from "../../assets/snapsort/src/index"; +import { Item as SnapSortItem } from "../../assets/snapsort/src/item"; +import { DragSessionController as DragSession } from "../../assets/snapsort/src/drag/session"; +import { + clearDragSession, + installDragSession, +} from "../../assets/snapsort/src/drag/session-store"; +import { + builtinStrategies, + type SortMode, +} from "../../assets/snapsort/src/drag/drop-strategy"; +import { + assertCanFireItemMove, + assertCanFireItemSwap, +} from "../../assets/snapsort/src/mutation"; + +/** + * The constructors under test only touch `engine.global` and `engine.input`, + * so a minimal stub stands in for a full Engine. + */ +function mockEngine(stub: { global: object; input: object }): Engine { + return stub as unknown as Engine; +} + +test("built-in modes choose composable drag visual defaults that can be overridden before activation", () => { + let nextId = 0; + const engine = mockEngine({ + global: { + data: {}, + queue: {}, + createId: () => `drag-visual-default-${++nextId}`, + registerObject: () => {}, + unregisterObject: () => {}, + }, + input: { + subscribeGlobalCursorEvent: () => {}, + unsubscribeGlobalCursorEvent: () => {}, + }, + }); + const expected = { + euclidean: "item", + progressive: "item", + insertion: "none", + swap: "preview", + } as const satisfies Record; + + for (const mode of Object.keys(expected) as SortMode[]) { + const root = new SnapSortContainer(engine, null, { + itemId: `drag-visual-${mode}-root`, + mode, + }); + const item = new SnapSortItem(engine, root, { + itemId: `drag-visual-${mode}-item`, + }); + const source = { + container: root, + containerMetadata: root.metadata, + index: 0, + }; + const session = new DragSession( + root, + [item], + [source], + builtinStrategies[mode], + { + inputType: "pointer", + prop: { + handoffTo: () => {}, + pointerId: 1, + start: { x: 10, y: 20 }, + } as never, + }, + ); + installDragSession(root, session); + const handle = root.dragSession!; + const nested = new SnapSortContainer(engine, root, { + itemId: `drag-visual-${mode}-nested`, + mode, + }); + + expect(handle).toBe(session); + expect(nested.dragSession).toBeNull(); + expect(Object.isFrozen(handle)).toBe(false); + expect(Object.isFrozen(handle.input)).toBe(true); + expect(Object.isFrozen(handle.items)).toBe(true); + expect(Object.isFrozen(handle.sources)).toBe(true); + expect(Object.isFrozen(handle.sources[0])).toBe(true); + const input = handle.input; + if (input.inputType !== "pointer") { + throw new Error("Expected pointer input"); + } + expect(Object.isFrozen(input.start)).toBe(true); + expect(Object.isFrozen(input.pointer)).toBe(true); + expect("strategy" in handle).toBe(true); + expect("ghosts" in handle).toBe(false); + expect("cancel" in handle).toBe(true); + expect(() => (handle.items as any[]).push(item)).toThrow(); + expect(() => ((handle.sources[0] as any).index = 2)).toThrow(); + expect(() => ((input.pointer as any).x = 30)).toThrow(); + + expect(handle.dragVisual).toBe(expected[mode]); + expect(() => { + (handle as any).dragVisual = "clone"; + }).toThrow(/DragSession\.dragVisual/); + const override = expected[mode] === "preview" ? "none" : "preview"; + handle.dragVisual = override; + expect(handle.dragVisual).toBe(override); + handle.dropEffect = "none"; + expect(handle.dropEffect).toBe("none"); + session.phase = "active"; + expect(() => { + handle.dragVisual = expected[mode]; + }).toThrow(/DragSession\.dragVisual/); + handle.dropEffect = "move"; + expect(() => { + (handle as any).dropEffect = "copy"; + }).toThrow(/DragSession\.dropEffect/); + session.phase = "dropping"; + expect(() => { + handle.dropEffect = "none"; + }).toThrow(/DragSession\.dropEffect/); + session.phase = "ended"; + expect(() => { + handle.dropEffect = "none"; + }).toThrow(/DragSession\.dropEffect/); + expect(handle.dragVisual).toBe(override); + + clearDragSession(root, session); + expect(root.dragSession).toBeNull(); + nested.destroy(false); + item.destroy(false); + root.destroy(false); + } +}); + +test("container animations are opt-in and expose the standard preset", () => { + let nextId = 0; + const engine = mockEngine({ + global: { + data: {}, + queue: {}, + createId: () => `animation-config-test-${++nextId}`, + registerObject: () => {}, + }, + input: { + subscribeGlobalCursorEvent: () => {}, + unsubscribeGlobalCursorEvent: () => {}, + }, + }); + + const immediate = new SnapSortContainer(engine, null, { + itemId: "animation-immediate-root", + }); + const animated = new SnapSortContainer(engine, null, { + itemId: "animation-enabled-root", + animation: defaultAnimations, + }); + const partiallyDisabled = new SnapSortContainer(engine, null, { + itemId: "animation-partially-disabled-root", + animation: { reorder: null, drop: defaultAnimations.drop }, + }); + const disabled = new SnapSortContainer(engine, null, { + itemId: "animation-disabled-root", + animation: null, + }); + + expect(immediate.config.animation).toBeUndefined(); + expect(immediate.reorderAnimationConfig(immediate)).toBeNull(); + expect(immediate.dropAnimationConfig(immediate)).toBeNull(); + expect(defaultAnimations).toEqual({ + reorder: { duration: 100, timing_function: "ease-out" }, + drop: { duration: 100, timing_function: "ease-out" }, + move: { duration: 100, timing_function: "ease-out" }, + }); + expect(animated.reorderAnimationConfig(animated)).toBe( + defaultAnimations.reorder, + ); + expect(animated.dropAnimationConfig(animated)).toBe(defaultAnimations.drop); + expect( + partiallyDisabled.reorderAnimationConfig(partiallyDisabled), + ).toBeNull(); + expect(partiallyDisabled.dropAnimationConfig(partiallyDisabled)).toBe( + defaultAnimations.drop, + ); + expect(disabled.reorderAnimationConfig(disabled)).toBeNull(); + expect(disabled.dropAnimationConfig(disabled)).toBeNull(); +}); + +test("item drag snapshots freeze a shallow copy of current metadata", () => { + let nextId = 0; + const engine = mockEngine({ + global: { + data: {}, + queue: {}, + createId: () => `metadata-snapshot-${++nextId}`, + registerObject: () => {}, + unregisterObject: () => {}, + }, + input: { + subscribeGlobalCursorEvent: () => {}, + unsubscribeGlobalCursorEvent: () => {}, + }, + }); + const item = new SnapSortItem(engine, null, { + itemId: "metadata-item", + }); + const original = { version: 1 }; + item.metadata = original; + + const snapshot = item.captureDragSnapshotTree(); + item.metadata = { version: 2 }; + + expect(snapshot.metadata).not.toBe(original); + expect(snapshot.metadata.version).toBe(1); + expect(Object.isFrozen(snapshot.metadata)).toBe(true); + expect(item.metadata.version).toBe(2); +}); + +test("custom adapters never inherit Vanilla DOM callbacks", () => { + let nextId = 0; + const engine = mockEngine({ + global: { + data: {}, + queue: {}, + createId: () => `ownership-test-${++nextId}`, + registerObject: () => {}, + }, + input: { + subscribeGlobalCursorEvent: () => {}, + unsubscribeGlobalCursorEvent: () => {}, + }, + }); + const onItemMove = () => {}; + + const vanilla = new SnapSortContainer(engine, null, { + itemId: "ownership-vanilla-root", + }); + const framework = new SnapSortContainer(engine, null, { + itemId: "ownership-framework-root", + adapter: { callbacks: {}, commit: (mutation) => mutation() }, + callbacks: { onItemMove }, + }); + const frameworkWithoutMutation = new SnapSortContainer(engine, null, { + itemId: "ownership-framework-without-mutation-root", + adapter: { callbacks: {}, commit: (mutation) => mutation() }, + }); + + expect(vanilla.adapter.callbacks.onItemInsert).toBeDefined(); + expect(vanilla.adapter.callbacks.onGhostInsert).toBeDefined(); + expect(framework.callbacks.onItemMove).toBe(onItemMove); + expect(framework.callbacks.onItemInsert).toBeUndefined(); + expect(framework.callbacks.onItemRemove).toBeUndefined(); + expect(framework.callbacks.onGhostInsert).toBeUndefined(); + expect(framework.callbacks.onGhostMove).toBeUndefined(); + expect(framework.callbacks.onGhostRemove).toBeUndefined(); + expect(() => assertCanFireItemMove(frameworkWithoutMutation)).toThrow( + /requires callbacks\.onItemMove or callbacks\.onItemInsert/, + ); + expect(() => assertCanFireItemSwap(framework)).toThrow( + /requires callbacks\.onItemSwap/, + ); + expect(() => assertCanFireItemSwap(vanilla)).not.toThrow(); +}); + +test("visual geometry invalidations coalesce at the root container", async () => { + let nextId = 0; + const queue = { + READ_1: new Map(), + WRITE_1: new Map(), + READ_2: new Map(), + WRITE_2: new Map(), + READ_3: new Map(), + WRITE_3: new Map(), + }; + const events: Array<{ + items: readonly unknown[]; + reasons: readonly string[]; + }> = []; + const engine = mockEngine({ + global: { + data: {}, + queue, + createId: () => `geometry-test-${++nextId}`, + registerObject: () => {}, + }, + input: { + subscribeGlobalCursorEvent: () => {}, + unsubscribeGlobalCursorEvent: () => {}, + }, + }); + const root = new SnapSortContainer(engine, null, { + itemId: "visual-geometry-root", + adapter: { callbacks: {}, commit: (mutation) => mutation() }, + callbacks: { + onVisualGeometryInvalidated: (event) => { + events.push(event); + if (events.length === 1) { + root.invalidateVisualGeometry([second], "settle"); + } + }, + }, + }); + const child = new SnapSortContainer(engine, root, { + itemId: "visual-geometry-child", + }); + const first = { isGhost: false } as never; + const second = { isGhost: false } as never; + const ghost = { isGhost: true } as never; + + child.invalidateVisualGeometry([first, ghost], "drag"); + root.invalidateVisualGeometry([first, second], "animation"); + + const rootQueue = queue.READ_1.get(root.id); + expect(rootQueue?.size).toBe(1); + const task = [...rootQueue!.values()][0]!; + for (const callback of task.callback ?? []) await callback(); + + expect(events).toHaveLength(1); + expect(events[0]!.items).toEqual([first, second]); + expect(events[0]!.reasons).toEqual(["drag", "animation"]); + expect(queue.READ_1.get(root.id)?.size).toBe(1); + + const nextTask = [...queue.READ_1.get(root.id)!.values()][0]!; + for (const callback of nextTask.callback ?? []) await callback(); + + expect(events).toHaveLength(2); + expect(events[1]!.items).toEqual([second]); + expect(events[1]!.reasons).toEqual(["settle"]); +}); diff --git a/tests/ut/snapsort-drop-priority.spec.ts b/tests/ut/snapsort-drop-priority.spec.ts new file mode 100644 index 00000000..a8c29e67 --- /dev/null +++ b/tests/ut/snapsort-drop-priority.spec.ts @@ -0,0 +1,611 @@ +import { expect, test } from "@playwright/test"; +import { type Rect } from "../../src/geometry"; +import { + determineDropTarget, + determineInsertionDropTarget, + determineProgressiveDropTarget, + determineSwapDropTarget, +} from "../../assets/snapsort/src/algorithm"; +import { BaseObject } from "../../src/object"; +import { + prioritizeIntersectingContainer, + prioritizeNearestContainerEdge, + prioritizePointerContainer, + prioritizeTreeDepth, + rejectDrop, +} from "../../assets/snapsort/src/callbacks"; +import { + DROP_REJECT_PRIORITY, + type DropPriorityEvent, +} from "../../assets/snapsort/src/events"; +import { + dropPriorityFixture, + itemSnapshot, + layoutBox, + mockSnapSortContainer, + mockSnapSortItem, +} from "../helpers/snapsort-fixtures"; + +test.describe("standard SnapSort drop callbacks", () => { + const event = { + pointer: { x: 15, y: 25 }, + dragRect: { x: 5, y: 5, width: 10, height: 10 }, + containerRect: { x: 10, y: 20, width: 30, height: 40 }, + } as DropPriorityEvent; + + test("pointer and drag intersection priorities share core collision semantics", () => { + expect(prioritizePointerContainer(event)).toBe(1); + expect( + prioritizePointerContainer({ + ...event, + pointer: { x: 9, y: 25 }, + }), + ).toBeUndefined(); + expect(prioritizeIntersectingContainer(event)).toBeUndefined(); + expect( + prioritizeIntersectingContainer({ + ...event, + dragRect: { x: 5, y: 25, width: 10, height: 10 }, + }), + ).toBe(1); + expect( + prioritizeIntersectingContainer({ + ...event, + dragRect: { x: 0, y: 20, width: 10, height: 10 }, + }), + ).toBeUndefined(); + }); + + test("nearest-container scoring and unconditional rejection are reusable", () => { + expect(prioritizeNearestContainerEdge(event)).toBe(1); + expect( + prioritizeNearestContainerEdge({ + ...event, + pointer: { x: 7, y: 16 }, + }), + ).toBeCloseTo(1 / 6); + expect( + prioritizeNearestContainerEdge({ + ...event, + pointer: { x: 4, y: 12 }, + }), + ).toBeLessThan(1 / 6); + expect(DROP_REJECT_PRIORITY).toBe(-1); + expect(rejectDrop({} as DropPriorityEvent)).toBe(DROP_REJECT_PRIORITY); + }); + + test("tree depth uses the virtual leading x edge and pointer y", () => { + const treeEvent = { + ...event, + staticPriority: 0, + depth: 3, + containerRect: { x: 10, y: 20, width: 30, height: 40 }, + dragRect: { x: 10, y: 0, width: 80, height: 10 }, + pointer: { x: 100, y: 20 }, + } as DropPriorityEvent; + + expect(prioritizeTreeDepth(treeEvent)).toBe(4); + expect( + prioritizeTreeDepth({ + ...treeEvent, + dragRect: { ...treeEvent.dragRect, x: 40 }, + pointer: { x: 0, y: 60 }, + }), + ).toBe(4); + expect( + prioritizeTreeDepth({ + ...treeEvent, + dragRect: { ...treeEvent.dragRect, x: 9 }, + pointer: { x: 15, y: 25 }, + }), + ).toBe(0); + expect( + prioritizeTreeDepth({ + ...treeEvent, + pointer: { x: 15, y: 61 }, + }), + ).toBe(0); + }); +}); + +test("drop priority filters containers before each placement mode ranks slots", () => { + const { dragged, near, far, root } = dropPriorityFixture(); + + expect(determineDropTarget(dragged as any, root as any)?.container).toBe( + near, + ); + far.dropPriority = 1; + + expect(determineDropTarget(dragged as any, root as any)?.container).toBe(far); + expect( + determineProgressiveDropTarget(dragged as any, root as any)?.container, + ).toBe(far); + expect( + determineInsertionDropTarget(dragged as any, root as any)?.container, + ).toBe(far); + + far.callbacks = { getDropPriority: rejectDrop }; + expect(determineDropTarget(dragged as any, root as any)?.container).toBe( + near, + ); + expect( + determineProgressiveDropTarget(dragged as any, root as any)?.container, + ).toBe(near); + expect( + determineInsertionDropTarget(dragged as any, root as any)?.container, + ).toBe(near); +}); + +test("Euclidean priority resolves mismatched zones before ranking their slots", () => { + const dragged = mockSnapSortItem("dragged", { + x: 300, + y: 170, + width: 20, + height: 20, + }); + const largeZone = mockSnapSortContainer( + "large-zone", + { x: 0, y: 0, width: 400, height: 200 }, + [], + "row", + ); + const smallZone = mockSnapSortContainer( + "small-zone", + { x: 0, y: 200, width: 400, height: 40 }, + [], + "column", + ); + const root = mockSnapSortContainer( + "root", + { x: 0, y: 0, width: 400, height: 240 }, + [largeZone, smallZone], + "column", + ); + root.callbacks = { getDropPriority: rejectDrop }; + + expect(determineDropTarget(dragged as any, root as any)?.container).toBe( + smallZone, + ); + + smallZone.callbacks = { + getDropPriority: prioritizeIntersectingContainer, + }; + largeZone.callbacks = { + getDropPriority: prioritizeIntersectingContainer, + }; + expect(determineDropTarget(dragged as any, root as any)?.container).toBe( + largeZone, + ); +}); + +test("drop priority runs once for a container with multiple candidate slots", () => { + const dragged = mockSnapSortItem("dragged", { + x: 10, + y: 10, + width: 20, + height: 20, + }); + const first = mockSnapSortItem("first", { + x: 0, + y: 0, + width: 100, + height: 20, + }); + const second = mockSnapSortItem("second", { + x: 0, + y: 20, + width: 100, + height: 20, + }); + const target = mockSnapSortContainer( + "target", + { x: 0, y: 0, width: 100, height: 60 }, + [first, second], + "column", + ); + const root = mockSnapSortContainer( + "root", + { x: 0, y: 0, width: 100, height: 60 }, + [target], + "column", + ); + root.callbacks = { getDropPriority: rejectDrop }; + + let priorityCalls = 0; + target.callbacks = { + getDropPriority: () => { + priorityCalls++; + return undefined; + }, + }; + + expect(determineDropTarget(dragged as any, root as any)?.container).toBe( + target, + ); + expect(priorityCalls).toBe(1); +}); + +test("priority supports rejection, fallback, and nonnegative overrides", () => { + const { dragged, near, far, root } = dropPriorityFixture(); + near.dropPriority = DROP_REJECT_PRIORITY; + far.dropPriority = DROP_REJECT_PRIORITY; + + expect(determineDropTarget(dragged as any, root as any)).toBeNull(); + + far.dropPriority = 0.5; + near.callbacks = { getDropPriority: () => undefined }; + + expect(determineDropTarget(dragged as any, root as any)?.container).toBe(far); + + near.callbacks = { getDropPriority: () => 0.75 }; + expect(determineDropTarget(dragged as any, root as any)?.container).toBe( + near, + ); +}); + +test("drop policy events expose source, destination, metadata, and geometry", () => { + const { dragged, source, near, far, root } = dropPriorityFixture(); + dragged.metadata = { kind: "card" }; + source.metadata = { dropGroup: "cards" }; + near.metadata = { dropGroup: "cards" }; + let priorityEvent: DropPriorityEvent | null = null; + near.callbacks = { + getDropPriority: (event) => { + priorityEvent = event; + return undefined; + }, + }; + far.callbacks = { getDropPriority: rejectDrop }; + + determineDropTarget(dragged as any, root as any); + + expect(priorityEvent).toMatchObject({ + itemId: "dragged", + itemMetadata: { kind: "card" }, + source: { + container: source, + containerMetadata: { dropGroup: "cards" }, + index: 0, + }, + sources: [ + { + container: source, + containerMetadata: { dropGroup: "cards" }, + index: 0, + }, + ], + container: near, + containerMetadata: { dropGroup: "cards" }, + index: 0, + }); + expect(priorityEvent).toMatchObject({ + staticPriority: 0, + pointer: { x: 20, y: 20 }, + dragRect: { x: 10, y: 10, width: 20, height: 20 }, + containerRect: { x: 0, y: 0, width: 100, height: 50 }, + containerContentRect: { x: 0, y: 0, width: 100, height: 50 }, + depth: 1, + }); + const event = priorityEvent as DropPriorityEvent | null; + expect(Object.isFrozen(event?.containerRect)).toBe(true); + expect(Object.isFrozen(event?.dragRect)).toBe(true); +}); + +test("applications can replace grouping with source and destination metadata", () => { + const { dragged, source, near, far, root } = dropPriorityFixture(); + source.metadata = { dropGroup: "cards" }; + near.metadata = { dropGroup: "cards" }; + far.metadata = { dropGroup: "files" }; + far.dropPriority = 10; + const prioritizeMatchingGroup = (event: DropPriorityEvent) => + event.source?.containerMetadata.dropGroup === + event.containerMetadata.dropGroup + ? undefined + : rejectDrop(event); + near.callbacks = { getDropPriority: prioritizeMatchingGroup }; + far.callbacks = { getDropPriority: prioritizeMatchingGroup }; + + expect(determineDropTarget(dragged as any, root as any)?.container).toBe( + near, + ); +}); + +test("drop policy events preserve every source in a multi-item drag", () => { + const { dragged, source, near, far, root } = dropPriorityFixture(); + const companion = mockSnapSortItem("companion", { + x: -80, + y: 20, + width: 20, + height: 20, + }); + const companionSource = mockSnapSortContainer( + "companion-source", + { x: -100, y: 0, width: 50, height: 50 }, + [companion], + "column", + ); + dragged.metadata = { order: 1 }; + companion.metadata = { order: 2 }; + source.metadata = { dropGroup: "cards" }; + companionSource.metadata = { dropGroup: "cards" }; + // Asserted (not annotated) so TS does not narrow to `null`: the callback + // assigns it inside a closure that control-flow analysis cannot see. + let event = null as DropPriorityEvent | null; + near.callbacks = { + getDropPriority: (nextEvent) => { + event = nextEvent; + return undefined; + }, + }; + far.callbacks = { getDropPriority: rejectDrop }; + const session = { + items: [dragged, companion], + sources: [ + { + container: source, + containerMetadata: source.metadata, + index: 0, + }, + { + container: companionSource, + containerMetadata: companionSource.metadata, + index: 0, + }, + ], + activeSources: [ + { + container: source, + containerMetadata: source.metadata, + index: 0, + }, + { + container: companionSource, + containerMetadata: companionSource.metadata, + index: 0, + }, + ], + itemSet: new Set([dragged, companion]), + snapshotItemSet: new Set([dragged, companion]), + pointer: { x: 20, y: 20 }, + }; + + determineInsertionDropTarget(dragged as any, root as any, session as any); + + expect(event?.items.map((item) => item.itemId)).toEqual([ + "dragged", + "companion", + ]); + expect(event?.itemsMetadata).toEqual([{ order: 1 }, { order: 2 }]); + expect(event?.source?.container).toBe(source); + expect(event?.sources.map((location) => location?.container)).toEqual([ + source, + companionSource, + ]); +}); + +test("drop priority rejects malformed configured and callback values", () => { + const configured = dropPriorityFixture(); + configured.far.dropPriority = Number.POSITIVE_INFINITY; + expect(() => + determineDropTarget(configured.dragged as any, configured.root as any), + ).toThrow(/dropPriority must be -1 or a finite nonnegative number/); + + for (const value of [-2, -0.5, Number.NEGATIVE_INFINITY, "1", null, {}]) { + const malformed = dropPriorityFixture(); + malformed.far.dropPriority = value as never; + expect(() => + determineDropTarget(malformed.dragged as any, malformed.root as any), + ).toThrow(/dropPriority must be -1 or a finite nonnegative number/); + } + + for (const value of [ + -2, + -0.5, + Number.NEGATIVE_INFINITY, + Number.POSITIVE_INFINITY, + Number.NaN, + "1", + null, + {}, + ]) { + const callback = dropPriorityFixture(); + callback.far.callbacks = { getDropPriority: () => value as never }; + expect(() => + determineDropTarget(callback.dragged as any, callback.root as any), + ).toThrow(/getDropPriority must be -1 or a finite nonnegative number/); + } +}); + +test("a container priority does not propagate to nested containers", () => { + const dragged = mockSnapSortItem("dragged", { + x: 10, + y: 10, + width: 20, + height: 20, + }); + const child = mockSnapSortContainer( + "child", + { x: 0, y: 0, width: 50, height: 50 }, + [], + "column", + ); + const parent = mockSnapSortContainer( + "parent", + { x: 0, y: 0, width: 100, height: 100 }, + [child], + "column", + ); + const root = mockSnapSortContainer( + "root", + { x: 0, y: 0, width: 100, height: 100 }, + [parent], + "column", + ); + root.callbacks = { getDropPriority: rejectDrop }; + parent.dropPriority = 1; + let childStaticPriority: number | null = null; + child.callbacks = { + getDropPriority: (event) => { + childStaticPriority = event.staticPriority; + return undefined; + }, + }; + + const target = determineDropTarget(dragged as any, root as any); + expect(childStaticPriority).toBe(0); + expect(target?.container).toBe(parent); +}); + +test("swap collects every hovered container before applying priority", () => { + let nextId = 0; + const engine = { + global: { + data: {}, + queue: {}, + createId: () => `swap-priority-${++nextId}`, + registerObject: () => {}, + unregisterObject: () => {}, + }, + input: { + subscribeGlobalCursorEvent: () => {}, + unsubscribeGlobalCursorEvent: () => {}, + }, + collisionEngine: null, + animationList: [], + }; + const makeItem = ( + itemId: string, + rect: Rect, + children: BaseObject[] = [], + container = false, + ) => { + const item = new BaseObject(engine as never) as BaseObject & + Record; + const box = layoutBox(rect); + item.itemId = itemId; + item.metadata = {}; + item.direction = "column"; + item.mainAxisAlign = "start"; + item.locked = false; + item.isGhost = false; + item.itemOrderedList = children; + item.children = children; + item.box = box; + item.depth = 0; + item.callbacks = undefined; + item.dropPriority = 0; + item.worldTransform = { x: rect.x, y: rect.y }; + Object.defineProperties(item, { + dragPositionX: { get: () => item.worldTransform.x }, + dragPositionY: { get: () => item.worldTransform.y }, + dragPointerPosition: { get: () => null }, + }); + if (container) { + item.config = {}; + item.name = itemId; + item.numberOfItems = children.length; + } + item.dragSnapshot = itemSnapshot( + item, + box, + children.map((child) => (child as any).dragSnapshot), + "column", + ); + return item; + }; + + const smallTarget = makeItem("small-target", { + x: 0, + y: 0, + width: 20, + height: 20, + }); + const largeTarget = makeItem("large-target", { + x: 0, + y: 0, + width: 60, + height: 60, + }); + const smallContainer = makeItem( + "small-container", + { x: 0, y: 0, width: 50, height: 50 }, + [smallTarget], + true, + ); + const preferredContainer = makeItem( + "preferred-container", + { x: 0, y: 0, width: 100, height: 100 }, + [largeTarget], + true, + ); + smallContainer.depth = 1; + preferredContainer.depth = 1; + preferredContainer.dropPriority = 1; + let smallHitboxOwner: unknown = null; + let preferredHitboxOwner: unknown = null; + smallContainer.callbacks = { + getItemHitbox: (event: any) => { + smallHitboxOwner = event.container; + return { + shape: "rect", + rect: { x: 80, y: 80, width: 10, height: 10 }, + }; + }, + }; + preferredContainer.callbacks = { + getItemHitbox: (event: any) => { + preferredHitboxOwner = event.container; + return { + shape: "circle", + circle: { x: 10, y: 10, radius: 8 }, + }; + }, + }; + const root = makeItem( + "root", + { x: 0, y: 0, width: 120, height: 120 }, + [smallContainer, preferredContainer], + true, + ); + root.callbacks = { getDropPriority: rejectDrop }; + const dragged = makeItem("dragged", { + x: 150, + y: 150, + width: 20, + height: 20, + }); + const session = { + items: [dragged], + sources: [null], + itemSet: new Set([dragged]), + pointer: { x: 10, y: 10 }, + }; + + const target = determineSwapDropTarget( + dragged as never, + root as never, + session as never, + ); + expect(target?.container).toBe(preferredContainer); + expect(target?.index).toBe(0); + expect(smallHitboxOwner).toBe(smallContainer); + expect(preferredHitboxOwner).toBe(preferredContainer); + + preferredContainer.callbacks = { + ...preferredContainer.callbacks, + getDropPriority: rejectDrop, + }; + expect( + determineSwapDropTarget(dragged as never, root as never, session as never), + ).toBeNull(); + + preferredContainer.callbacks = { + getItemHitbox: () => ({ + shape: "rect", + rect: { x: 0, y: 0, width: Number.NaN, height: 10 }, + }), + }; + expect(() => + determineSwapDropTarget(dragged as never, root as never, session as never), + ).toThrow(/getItemHitbox/); +}); diff --git a/tests/ut/snapsort-placement.spec.ts b/tests/ut/snapsort-placement.spec.ts new file mode 100644 index 00000000..b24f45db --- /dev/null +++ b/tests/ut/snapsort-placement.spec.ts @@ -0,0 +1,546 @@ +import { expect, test } from "@playwright/test"; +import { contentRect } from "../../src/geometry"; +import { + determineDropTarget, + determineInsertionDropTarget, + determineProgressiveDropTarget, +} from "../../assets/snapsort/src/algorithm"; +import { + layoutBox, + mockSnapSortContainer, + mockSnapSortItem, + snapshotFixture, + virtualInsertionPosition, +} from "../helpers/snapsort-fixtures"; + +test("progressive placement selects the ghost slot under the dragged center", () => { + const dragged = mockSnapSortItem("dragged", { + x: 0, + y: 0, + width: 50, + height: 40, + }); + const columnItems = [ + mockSnapSortItem("a", { x: 0, y: 0, width: 80, height: 40 }), + mockSnapSortItem("b", { x: 0, y: 48, width: 80, height: 40 }), + mockSnapSortItem("c", { x: 0, y: 96, width: 80, height: 40 }), + ]; + const column = mockSnapSortContainer( + "column", + { x: 0, y: 0, width: 140, height: 180 }, + columnItems, + "column", + ); + dragged.worldTransform = { x: 15, y: 48, scaleX: 1, scaleY: 1 }; + + expect( + determineProgressiveDropTarget(dragged as any, column as any), + ).toMatchObject({ container: column, index: 1 }); + + const rowItems = [ + mockSnapSortItem("a", { x: 0, y: 0, width: 60, height: 40 }), + mockSnapSortItem("b", { x: 68, y: 0, width: 60, height: 40 }), + mockSnapSortItem("c", { x: 136, y: 0, width: 60, height: 40 }), + ]; + const row = mockSnapSortContainer( + "row", + { x: 0, y: 0, width: 240, height: 80 }, + rowItems, + "row", + ); + dragged.worldTransform = { x: 73, y: 0, scaleX: 1, scaleY: 1 }; + + expect( + determineProgressiveDropTarget(dragged as any, row as any), + ).toMatchObject({ container: row, index: 1 }); +}); + +test("euclidean placement keeps parent slots reachable next to nested containers", () => { + const before = mockSnapSortItem("before", { + x: 0, + y: 0, + width: 80, + height: 40, + }); + const dragged = mockSnapSortItem("dragged", { + x: 4, + y: 52, + width: 50, + height: 40, + }); + const nestedItem = mockSnapSortItem("nested-item", { + x: 4, + y: 100, + width: 50, + height: 40, + }); + const nested = mockSnapSortContainer( + "nested", + { x: 0, y: 48, width: 120, height: 96 }, + [dragged, nestedItem], + "column", + ); + const after = mockSnapSortItem("after", { + x: 0, + y: 152, + width: 80, + height: 40, + }); + const root = mockSnapSortContainer( + "root", + { x: 0, y: 0, width: 160, height: 220 }, + [before, nested, after], + "column", + ); + dragged.worldTransform = { x: 1, y: 49, scaleX: 1, scaleY: 1 }; + + const target = determineDropTarget(dragged as any, root as any); + + expect(target?.container).toBe(root); + expect(target?.index).toBe(1); +}); + +test("insertion placement maps a downward same-container gap to the live index", () => { + const itemA = mockSnapSortItem("a", { + x: 0, + y: 0, + width: 120, + height: 40, + }); + const dragged = mockSnapSortItem("dragged", { + x: 0, + y: 48, + width: 120, + height: 40, + }); + const itemB = mockSnapSortItem("b", { + x: 0, + y: 96, + width: 120, + height: 40, + }); + const itemC = mockSnapSortItem("c", { + x: 0, + y: 144, + width: 120, + height: 40, + }); + const container = mockSnapSortContainer( + "container", + { x: 0, y: 0, width: 120, height: 184 }, + [itemA, dragged, itemB, itemC], + "column", + ); + dragged.worldTransform = { x: 0, y: 120, scaleX: 1, scaleY: 1 }; + + const target = determineInsertionDropTarget(dragged as any, container as any); + + expect(target?.container).toBe(container); + expect(target?.index).toBe(3); + expect(target?.insertion).toMatchObject({ + gap: { orientation: "horizontal", x: 0, y: 140, length: 120 }, + previous: { item: itemB }, + next: { item: itemC }, + isCurrentPlacement: false, + }); +}); + +test("insertion placement maps an upward same-container gap to the live index", () => { + const itemA = mockSnapSortItem("a", { + x: 0, + y: 0, + width: 120, + height: 40, + }); + const itemB = mockSnapSortItem("b", { + x: 0, + y: 48, + width: 120, + height: 40, + }); + const dragged = mockSnapSortItem("dragged", { + x: 0, + y: 96, + width: 120, + height: 40, + }); + const itemC = mockSnapSortItem("c", { + x: 0, + y: 144, + width: 120, + height: 40, + }); + const container = mockSnapSortContainer( + "container", + { x: 0, y: 0, width: 120, height: 184 }, + [itemA, itemB, dragged, itemC], + "column", + ); + dragged.worldTransform = { x: 0, y: 32, scaleX: 1, scaleY: 1 }; + + const target = determineInsertionDropTarget(dragged as any, container as any); + + expect(target?.container).toBe(container); + expect(target?.index).toBe(1); + expect(target?.insertion).toMatchObject({ + gap: { orientation: "horizontal", x: 0, y: 44, length: 120 }, + previous: { item: itemA }, + next: { item: itemB }, + isCurrentPlacement: false, + }); +}); + +test("insertion placement keeps the top boundary reachable when dragging the first item", () => { + const dragged = mockSnapSortItem("dragged", { + x: 0, + y: 0, + width: 120, + height: 40, + }); + const itemA = mockSnapSortItem("a", { + x: 0, + y: 48, + width: 120, + height: 40, + }); + const itemB = mockSnapSortItem("b", { + x: 0, + y: 96, + width: 120, + height: 40, + }); + const container = mockSnapSortContainer( + "container", + { x: 0, y: 0, width: 120, height: 136 }, + [dragged, itemA, itemB], + "column", + ); + dragged.worldTransform = { x: 0, y: -22, scaleX: 1, scaleY: 1 }; + + const target = determineInsertionDropTarget(dragged as any, container as any); + + expect(target?.container).toBe(container); + expect(target?.index).toBe(1); + expect(target?.insertion).toMatchObject({ + gap: { orientation: "horizontal", x: 0, y: 0, length: 120 }, + previous: null, + next: { item: dragged }, + isCurrentPlacement: true, + }); +}); + +test("insertion placement keeps the bottom boundary reachable when dragging the last item", () => { + const itemA = mockSnapSortItem("a", { + x: 0, + y: 0, + width: 120, + height: 40, + }); + const itemB = mockSnapSortItem("b", { + x: 0, + y: 48, + width: 120, + height: 40, + }); + const dragged = mockSnapSortItem("dragged", { + x: 0, + y: 96, + width: 120, + height: 40, + }); + const container = mockSnapSortContainer( + "container", + { x: 0, y: 0, width: 120, height: 136 }, + [itemA, itemB, dragged], + "column", + ); + dragged.worldTransform = { x: 0, y: 132, scaleX: 1, scaleY: 1 }; + + const target = determineInsertionDropTarget(dragged as any, container as any); + + expect(target?.container).toBe(container); + expect(target?.index).toBe(3); + expect(target?.insertion).toMatchObject({ + gap: { orientation: "horizontal", x: 0, y: 136, length: 120 }, + previous: { item: dragged }, + next: null, + isCurrentPlacement: true, + }); +}); + +test("insertion placement spans the container content box on the marker cross axis", () => { + const itemA = mockSnapSortItem("a", { + x: 34, + y: 40, + width: 120, + height: 40, + }); + const dragged = mockSnapSortItem("dragged", { + x: 34, + y: 88, + width: 120, + height: 40, + }); + const itemB = mockSnapSortItem("b", { + x: 34, + y: 136, + width: 120, + height: 40, + }); + const container = mockSnapSortContainer( + "container", + { x: 10, y: 20, width: 220, height: 180 }, + [itemA, dragged, itemB], + "column", + ); + const containerBox = layoutBox( + { x: 10, y: 20, width: 220, height: 180 }, + {}, + { top: 8, right: 12, bottom: 8, left: 20 }, + { top: 2, right: 2, bottom: 2, left: 2 }, + ); + container.dragSnapshot = { + ...container.dragSnapshot, + box: containerBox, + }; + container.box = containerBox; + dragged.worldTransform = { x: 34, y: 112, scaleX: 1, scaleY: 1 }; + + const target = determineInsertionDropTarget(dragged as any, container as any); + + expect(target?.container).toBe(container); + expect(target?.insertion?.gap).toEqual({ + orientation: "horizontal", + x: 32, + y: 132, + length: 184, + }); +}); + +test("progressive placement uses the cross-axis line in wrapped rows", () => { + const dragged = mockSnapSortItem("dragged", { + x: 0, + y: 0, + width: 70, + height: 40, + }); + const rowItems = [ + dragged, + mockSnapSortItem("a", { x: 80, y: 0, width: 70, height: 40 }), + mockSnapSortItem("b", { x: 0, y: 48, width: 70, height: 40 }), + mockSnapSortItem("c", { x: 80, y: 48, width: 70, height: 40 }), + ]; + const row = mockSnapSortContainer( + "wrapped-row", + { x: 0, y: 0, width: 160, height: 96 }, + rowItems, + "row", + ); + dragged.worldTransform = { x: 4, y: 48, scaleX: 1, scaleY: 1 }; + + expect( + determineProgressiveDropTarget(dragged as any, row as any), + ).toMatchObject({ container: row, index: 2 }); +}); + +test("wraps a horizontal ghost when its trailing margin exceeds the content width", () => { + const container = snapshotFixture({ + value: "container", + direction: "row", + locked: false, + box: layoutBox({ x: 0, y: 0, width: 313, height: 120 }), + children: [ + { + value: "item-1", + direction: "column", + locked: false, + box: layoutBox( + { x: 4, y: 0, width: 100, height: 40 }, + { left: 4, right: 4 }, + ), + children: [], + }, + { + value: "item-2", + direction: "column", + locked: false, + box: layoutBox( + { x: 112, y: 0, width: 100, height: 40 }, + { left: 4, right: 4 }, + ), + children: [], + }, + ], + }); + const dragged = snapshotFixture({ + value: "dragged", + direction: "column", + locked: false, + box: layoutBox( + { x: 0, y: 0, width: 90, height: 40 }, + { left: 4, right: 4 }, + ), + children: [], + }); + + const simulated = virtualInsertionPosition( + container, + dragged, + 0, + 0, + 2, + dragged.box.width, + dragged.box.height, + ); + + expect(simulated).toEqual({ x: 4, y: 40 }); +}); + +test("places append ghost on the short second row in a wrapped row layout", () => { + const container = snapshotFixture({ + value: "answer", + direction: "row", + mainAxisAlign: "start", + locked: false, + box: layoutBox( + { x: 0, y: 0, width: 1096, height: 244 }, + {}, + { top: 12, right: 12, bottom: 12, left: 12 }, + { top: 2, right: 2, bottom: 2, left: 2 }, + ), + children: [ + ["彼", 104, 92, 14, 14], + ["すぐ", 136, 92, 122, 14], + ["経歴", 136, 92, 262, 14], + ["に", 104, 92, 402, 14], + ["少年", 136, 92, 510, 14], + ["会社", 136, 92, 650, 14], + ["問い合わせ", 240, 92, 14, 110], + ["しまっ", 168, 92, 258, 110], + ].map(([value, width, height, x, y]) => ({ + value: value as string, + direction: "column" as const, + mainAxisAlign: "start" as const, + locked: false, + box: layoutBox({ + x: x as number, + y: y as number, + width: width as number, + height: height as number, + }), + children: [], + })), + }); + const dragged = snapshotFixture({ + value: "を", + direction: "column", + mainAxisAlign: "start", + locked: false, + box: layoutBox({ x: 0, y: 0, width: 104, height: 92 }), + children: [], + }); + const origin = contentRect(container.box); + const appendGhost = virtualInsertionPosition( + container, + dragged, + origin.x, + origin.y, + container.children.length, + dragged.box.width, + dragged.box.height, + ); + + expect(appendGhost).toBeTruthy(); + expect( + appendGhost!.y, + "append slot should remain on the second visual row", + ).toBeGreaterThan(container.children[0].box.y); + expect(appendGhost!.y).toBe(container.children[6].box.y); +}); + +// Insertion ranks gaps by main-axis distance alone (see "Insertion geometry +// ownership" in assets/snapsort/AGENTS.md): in a wrapped row every line's +// gaps compete on pointer X, so a gap on another line can win. This pins +// that documented rule; applications that want line-aware wrapped +// insertion supply their own getDropPriority / layout. +test("ranks wrapped-row insertion gaps by main-axis distance across lines", () => { + const items = [ + mockSnapSortItem("彼", { x: 14, y: 14, width: 53.6, height: 47.8 }), + mockSnapSortItem("の", { x: 71.6, y: 14, width: 53.6, height: 47.8 }), + mockSnapSortItem("経歴", { + x: 129.2, + y: 14, + width: 71.2, + height: 47.8, + }), + mockSnapSortItem("を", { + x: 204.4, + y: 14, + width: 53.6, + height: 47.8, + }), + mockSnapSortItem("会社", { + x: 262, + y: 14, + width: 71.2, + height: 47.8, + }), + mockSnapSortItem("に", { + x: 337.2, + y: 14, + width: 53.6, + height: 47.8, + }), + mockSnapSortItem("問い合わせ", { + x: 14, + y: 65.8, + width: 124, + height: 47.8, + }), + mockSnapSortItem("た", { + x: 142, + y: 65.8, + width: 53.6, + height: 47.8, + }), + ]; + const container = mockSnapSortContainer( + "answer", + { x: 0, y: 0, width: 488, height: 128 }, + items, + "row", + ); + const dragged = items[6]; + const source = { + container, + containerMetadata: container.metadata, + index: 6, + }; + const session = { + items: [dragged], + sources: [source], + activeSources: [source], + itemSet: new Set([dragged]), + snapshotItemSet: new Set([dragged]), + pointer: { x: 235.6, y: 89.7 }, + }; + + // @ts-expect-error The fixture implements the resolver surface without Item's private fields. + const target = determineInsertionDropTarget(dragged, container, session); + + // Pointer X 235.6 is 24.4 from the first line's を|会社 gap (x=260) but + // 40 from the second line's append gap (x=195.6), so the first line wins. + expect(target?.container).toBe(container); + expect(target?.index).toBe(4); + expect(target?.insertion).toMatchObject({ + gap: { + orientation: "vertical", + x: 260, + y: 14, + length: 47.8, + }, + previous: { item: items[3] }, + next: { item: items[4] }, + isCurrentPlacement: false, + }); +}); diff --git a/tests/ut/snapsort-render-tree.spec.ts b/tests/ut/snapsort-render-tree.spec.ts index 60341ecb..e772adde 100644 --- a/tests/ut/snapsort-render-tree.spec.ts +++ b/tests/ut/snapsort-render-tree.spec.ts @@ -14,6 +14,7 @@ import { buildGhostSlotLocation, } from "../../assets/snapsort/src/event-builders"; import type { + DragInputController, DragSession, DragSessionController, } from "../../assets/snapsort/src/drag/session"; @@ -105,15 +106,19 @@ function createRenderTreeHarness(itemIds = ["dragged"]): RenderTreeHarness { const originals = [...items.values()]; const sources = originals.map((_, index) => buildDragLocation(source, index)); const session: DragSession = { - inputType: "pointer", root, - pointerId: 1, + // Render-state never reads the input controller; stub only its public + // pointer fields rather than constructing one against a real session. + input: { + inputType: "pointer", + pointerId: 1, + start: { x: 0, y: 0 }, + pointer: { x: 0, y: 0 }, + } as unknown as DragInputController, items: originals, sources, pressedItem: originals[0], primaryItem: originals[0], - start: { x: 0, y: 0 }, - pointer: { x: 0, y: 0 }, status: "active", dragVisual: "item", dropEffect: "move", @@ -511,7 +516,7 @@ test("same-location insertion marker moves update presentation and replay idempo const rendered = childTree(updated, "destination").entries.find( (entry) => entry.itemId === marker.ghostItemId, ); - if (!rendered?.isGhost) { + if (!rendered?.isGhost || rendered.ghost.type !== "insertion-marker") { throw new Error("Expected the moved insertion marker entry."); } diff --git a/tests/ut/snapsort-state.spec.ts b/tests/ut/snapsort-state.spec.ts index 7f0ea088..9fa4afb4 100644 --- a/tests/ut/snapsort-state.spec.ts +++ b/tests/ut/snapsort-state.spec.ts @@ -1353,7 +1353,9 @@ test("swap lifecycle reconciles framework-owned replacement Items", async () => test("DropPriorityEvent reports the real nested container depth", () => { const harness = createStateHarness(); try { - let priorityEvent: DropPriorityEvent | null = null; + // Asserted (not annotated) so TS does not narrow to `null`: the callback + // assigns it inside a closure that control-flow analysis cannot see. + let priorityEvent = null as DropPriorityEvent | null; const root = mountRoot(harness, "root", { mode: "swap" }); const dragged = mountItem(harness, root, "dragged", { x: 10, diff --git a/tests/ut/transform.spec.ts b/tests/ut/transform.spec.ts index befb41f9..c00e7709 100644 --- a/tests/ut/transform.spec.ts +++ b/tests/ut/transform.spec.ts @@ -109,31 +109,21 @@ function positionOf(transform: { x: number; y: number }) { } test.describe("BaseObject transforms", () => { - test("keeps CoreObject root world and local transforms in sync", () => { - const engine = createEngine(); - const object = new CoreObject(engine); - - object.worldTransform = { x: 12, y: 24, scaleX: 2, scaleY: 3 }; - - expect(positionOf(object.localTransform)).toEqual([12, 24]); - expect(object.localTransform.scaleX).toBe(2); - expect(object.localTransform.scaleY).toBe(3); - expect(object.transform.getWorld()).toBe(object.worldTransform); - }); - test("keeps root world and local transforms in sync", () => { const engine = createEngine(); - const object = new BaseObject(engine); + for (const Kind of [CoreObject, BaseObject]) { + const object = new Kind(engine); - object.worldTransform = { x: 10, y: 20, scaleX: 2, scaleY: 3 }; + object.worldTransform = { x: 10, y: 20, scaleX: 2, scaleY: 3 }; - expect(object.localTransform.x).toBe(10); - expect(object.localTransform.y).toBe(20); - expect(object.localTransform.scaleX).toBe(2); - expect(object.localTransform.scaleY).toBe(3); + expect(positionOf(object.localTransform), Kind.name).toEqual([10, 20]); + expect(object.localTransform.scaleX).toBe(2); + expect(object.localTransform.scaleY).toBe(3); + expect(object.transform.getWorld()).toBe(object.worldTransform); - object.localTransform = { x: 30, y: 40 }; - expect(positionOf(object.worldTransform)).toEqual([30, 40]); + object.localTransform = { x: 30, y: 40 }; + expect(positionOf(object.worldTransform), Kind.name).toEqual([30, 40]); + } }); test("composes child transforms through parent position and scale", () => { @@ -471,9 +461,13 @@ test.describe("ElementObject writeTransformRecursive", () => { const engine = createEngine(); const parent = new WriteSpyObject(engine); const directChild = new WriteSpyObject(engine); + const directGrandchild = new WriteSpyObject(engine); const noneChild = new WriteSpyObject(engine); + const noneGrandchild = new WriteSpyObject(engine); parent.appendChild(directChild); + directChild.appendChild(directGrandchild); parent.appendChild(noneChild); + noneChild.appendChild(noneGrandchild); noneChild.transformMode = "none"; const collider = new RectCollider(engine, parent, 0, 0, 10, 10); parent.addCollider(collider); @@ -487,23 +481,10 @@ test.describe("ElementObject writeTransformRecursive", () => { expect(parent.writeCount).toBe(1); expect(directChild.writeCount).toBe(1); - expect(noneChild.writeCount).toBe(0); // none-mode pruned (with its subtree) - }); - - test("recurses through nested direct-mode children", () => { - const engine = createEngine(); - const parent = new WriteSpyObject(engine); - const child = new WriteSpyObject(engine); - const grandchild = new WriteSpyObject(engine); - parent.appendChild(child); - child.appendChild(grandchild); - - engine.global.currentStage = "WRITE_2"; - parent.writeTransformRecursive(); - - expect(parent.writeCount).toBe(1); - expect(child.writeCount).toBe(1); - expect(grandchild.writeCount).toBe(1); + expect(directGrandchild.writeCount).toBe(1); + // A none-mode child is pruned together with its subtree. + expect(noneChild.writeCount).toBe(0); + expect(noneGrandchild.writeCount).toBe(0); }); test("throws when invoked during a read stage", () => { diff --git a/tsconfig.tests.json b/tsconfig.tests.json new file mode 100644 index 00000000..475a6578 --- /dev/null +++ b/tsconfig.tests.json @@ -0,0 +1,25 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "rootDirs": [ + "src", + "demo", + "tests" + ], + "types": [ + "node" + ], + "lib": [ + "ESNext", + "DOM", + "DOM.Iterable" + ] + }, + "include": [ + "tests/**/*.ts" + ], + "exclude": [ + "tests/types/**" + ] +} diff --git a/website/src/routes/snapdesign/gallery/+page.svelte b/website/src/routes/snapdesign/gallery/+page.svelte index 5b025004..06ef2993 100644 --- a/website/src/routes/snapdesign/gallery/+page.svelte +++ b/website/src/routes/snapdesign/gallery/+page.svelte @@ -1,4 +1,5 @@