@cujuju/solid-reorder-list 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,778 +1,824 @@
1
- /**
2
- * createReorderGrid — 2-D drag-to-reorder primitive for SolidJS.
3
- *
4
- * Sibling to createReorderList; targets responsive grid layouts where
5
- * displacement crosses row-wrap diagonals. v0.3.0 ships activation +
6
- * snapshot + hit-test + per-item flat-order displacement + hysteresis,
7
- * with manual scrollContainer compensation. Auto-scroll (R8/R9) is
8
- * deferred to v0.3.1.
9
- *
10
- * Coordinate frame: container-content coords =
11
- * `clientX + scrollContainer.scrollLeft` (mirror y).
12
- * Snapshot rects, effectiveRects[], and pointer hit-test all live in
13
- * this frame. NOT pageX/pageY — F4's panel is Portal'd `position:fixed`
14
- * so window scroll does not compose into the frame.
15
- */
16
-
17
- import { createSignal, createRoot, onCleanup, getOwner } from 'solid-js';
18
- import { DEFAULT_SKIP_SELECTOR, blockNextClick, createCancelListeners } from './shared';
19
-
20
- // ── Types ──────────────────────────────────────────────────────────────────
21
-
22
- export interface ReorderGridOptions {
23
- /** Reactive list of IDs in current grid order (flat, row-major). */
24
- ids: () => string[];
25
- /** Called on drop with original and target indices. Indices are flat
26
- * positions in the array at drag start (not visual positions). */
27
- onReorder: (fromIndex: number, toIndex: number) => void;
28
- /** Pixels of pointer movement (Euclidean) before drag activates.
29
- * Default 5. */
30
- activateDistance?: number;
31
- /** Duration of displacement transition in ms. Default 200. */
32
- transitionMs?: number;
33
- /** CSS class applied to the active (dragged) item. Default
34
- * 'reorder-active'. */
35
- activeClass?: string;
36
- /** Scale factor for the dragged item's visual lift. Default 0.97. */
37
- dragScale?: number;
38
- /** Whether to call stopPropagation on pointerdown. Default true. */
39
- stopPropagation?: boolean;
40
- /** CSS selector matched via `closest()` from the pointerdown target.
41
- * When matched, drag activation is skipped. Defaults to
42
- * {@link DEFAULT_SKIP_SELECTOR}. Set to an empty string to disable. */
43
- skipSelector?: string;
44
- /** Reactive accessor returning the scroll container, or `null` for
45
- * no compensation. The container's scroll offset is read on each
46
- * pointermove; rect storage uses container-content coords so manual
47
- * scrolls during drag don't desync the hit-test. v0.3.0 supports
48
- * HTMLElement and Window targets. v0.3.1 adds auto-scroll inside
49
- * edge zones of this container. */
50
- scrollContainer?: () => HTMLElement | Window | null | undefined;
51
- }
52
-
53
- interface CachedGridRect {
54
- /** Container-content coords (clientX + container.scrollLeft, mirror y). */
55
- contentLeft: number;
56
- contentTop: number;
57
- contentRight: number;
58
- contentBottom: number;
59
- width: number;
60
- height: number;
61
- }
62
-
63
- interface GridDragState {
64
- id: string;
65
- sourceIndex: number;
66
- /** Pointer position at activate, in VIEWPORT coords (clientX/Y).
67
- * Source-element transform reads this to translate the dragged item
68
- * by the viewport delta as the pointer moves. */
69
- startPointerViewport: { x: number; y: number };
70
- /** Scroll offset at activate. Combined with startPointerViewport
71
- * gives the activate-time content-frame anchor; combined with the
72
- * current scroll gives the current content-frame pointer. */
73
- scrollAtActivate: { x: number; y: number };
74
- /** Original snapshot rects in container-content coords. Immutable
75
- * during drag. */
76
- rects: CachedGridRect[];
77
- /** Mutable mirror of `rects[]` used for hysteresis. Same coordinate
78
- * frame. Mutated on each target change by U4. */
79
- effectiveRects: CachedGridRect[];
80
- /** Inferred grid metrics. */
81
- cellWidth: number;
82
- cellHeight: number;
83
- gutterX: number;
84
- gutterY: number;
85
- cols: number;
86
- /** Bounding rect of the FULL `cols × rowCount` grid, including any
87
- * trailing empty cells where `rects.length` doesn't fill the last
88
- * row. In container-content coords. Used by hit-test to bound the
89
- * nearest-cell fallback — drops far outside this rect (plus
90
- * `OUTSIDE_GRID_MARGIN_FRACTION` slack) return `sourceIndex` so
91
- * `commitDrag` short-circuits via `from === to`. */
92
- gridBoundsContent: {
93
- left: number;
94
- top: number;
95
- right: number;
96
- bottom: number;
97
- };
98
- /** Last-resolved hit-test result. Consumed by commitDrag for the
99
- * onReorder index. */
100
- currentTarget: number;
101
- ids: string[];
102
- /** Placeholder DOM node inserted at source's grid track when the
103
- * source switches to `position: fixed` during drag. Preserves the
104
- * source's grid layout slot so neighbour cells don't reflow into
105
- * it (which would compound with the displacement transforms).
106
- * Removed in clearDragStyles() on commit/cancel. Null when the
107
- * source's parent could not be determined at activate. */
108
- placeholder: HTMLDivElement | null;
109
- }
110
-
111
- // ── Helpers ────────────────────────────────────────────────────────────────
112
-
113
- /** Dev-mode probe — reads `process.env.NODE_ENV` defensively so the
114
- * primitive doesn't require @types/node and works in browser-only
115
- * bundles where `process` is undefined. Production builds have this
116
- * evaluate to `false` (after bundler dead-code elimination), so the
117
- * diagnostic warns add zero runtime cost. */
118
- function isDevMode(): boolean {
119
- const proc = (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process;
120
- return proc?.env?.NODE_ENV !== 'production';
121
- }
122
-
123
- /** Read the scroll container's offset. Window vs Element API quirks
124
- * are isolated here; v0.3.1's auto-scroll loop reuses the same helper. */
125
- function getScroll(c: HTMLElement | Window | null | undefined): { x: number; y: number } {
126
- if (!c) return { x: window.scrollX, y: window.scrollY };
127
- if (c instanceof Window) return { x: c.scrollX, y: c.scrollY };
128
- return { x: c.scrollLeft, y: c.scrollTop };
129
- }
130
-
131
- // ── Primitive ──────────────────────────────────────────────────────────────
132
-
133
- export function createReorderGrid(options: ReorderGridOptions) {
134
- // Pixels of pointer movement (Euclidean) required before drag activates.
135
- // Prevents accidental drag on click (normal mouse jitter is 1-3px).
136
- const getActivateDistance = () => options.activateDistance ?? 5;
137
- const getTransitionMs = () => options.transitionMs ?? 200;
138
- const getActiveClass = () => options.activeClass ?? 'reorder-active';
139
-
140
- // Scale factor applied to the dragged item for visual lift.
141
- // 0.97 = 3% shrink. Set to 1.0 for no scale. Consumers can override.
142
- const DRAG_SCALE = options.dragScale ?? 0.97;
143
- const getStopPropagation = () => options.stopPropagation ?? true;
144
- const getSkipSelector = () => options.skipSelector ?? DEFAULT_SKIP_SELECTOR;
145
- const getScrollContainer = () => options.scrollContainer?.() ?? null;
146
-
147
- // Registered elements keyed by ID.
148
- const nodes = new Map<string, HTMLElement>();
149
-
150
- // Reactive signals in an isolated root — immune to parent scope disposal.
151
- // Without createRoot, SolidJS can dispose these signals (and fire onCleanup)
152
- // when the parent component's reactive graph re-evaluates during a drag,
153
- // killing the active drag mid-flight.
154
- let disposeRoot: (() => void) | undefined;
155
- const { activeId, setActiveId, targetIdx, setTargetIdx } = createRoot((dispose) => {
156
- disposeRoot = dispose;
157
- const [activeId, setActiveId] = createSignal<string | null>(null);
158
- const [targetIdx, setTargetIdx] = createSignal<number>(-1);
159
- return { activeId, setActiveId, targetIdx, setTargetIdx };
160
- });
161
-
162
- // Stored so cancel handlers can clean up pointer listeners.
163
- let pointerCleanup: (() => void) | null = null;
164
-
165
- // Non-reactive drag state — mutated on pointermove for performance.
166
- let drag: GridDragState | null = null;
167
-
168
- // rAF handle for batching dragged-item transform updates.
169
- // (v0.3.1 will add a sibling autoScrollRaf with the same lifecycle.)
170
- let dragRaf: number = 0;
171
-
172
- // ── Drag lifecycle ──────────────────────────────────────────────────────
173
-
174
- /** Measure one element into a CachedGridRect in container-content
175
- * coords (clientLeft/Top + scrollContainer.scrollLeft/Top, mirror y).
176
- * When no scrollContainer is provided, falls back to window.scrollX/Y
177
- * so the no-container path resolves to true page coords. */
178
- function measure(el: HTMLElement, scroll: { x: number; y: number }): CachedGridRect {
179
- const r = el.getBoundingClientRect();
180
- return {
181
- contentLeft: r.left + scroll.x,
182
- contentTop: r.top + scroll.y,
183
- contentRight: r.right + scroll.x,
184
- contentBottom: r.bottom + scroll.y,
185
- width: r.width,
186
- height: r.height,
187
- };
188
- }
189
-
190
- /** Same-row predicate using cell-height-relative tolerance to
191
- * absorb sub-pixel jitter on HiDPI / fractional layouts. */
192
- function sameRow(a: CachedGridRect, b: CachedGridRect, cellHeight: number): boolean {
193
- return Math.abs(a.contentTop - b.contentTop) < cellHeight * 0.1;
194
- }
195
-
196
- /** Hit-test a content-frame pointer against the engine's effective
197
- * rects, with stickiness applied to currentTarget for hysteresis.
198
- *
199
- * Pass 1 — sticky-currentTarget: if currentTarget !== sourceIndex,
200
- * compute its EXTENDED rect (extends the side facing source by
201
- * half-cell magnitudes proportional to source→target unit-vector
202
- * components). If the pointer falls inside that extended rect,
203
- * return currentTarget without a flip. This is the hysteresis: the
204
- * dragged item "sticks" to its current target — pointer must move
205
- * past the natural boundary AND a half-cell extension into the
206
- * source-side gap before the swap drops.
207
- *
208
- * Pass 2 — first-match: pointer is outside the sticky zone; do a
209
- * normal point-in-rect check against effectiveRects[] (which are
210
- * natural inflated rects, never per-target-mutated). First match
211
- * wins (flat-order tie-break for 4-way corners).
212
- *
213
- * Pass 3 — nearest-by-centre fallback: pointer is in a gap or
214
- * clearly outside the grid. Returns the cell whose centre
215
- * minimises Euclidean distance.
216
- *
217
- * Hysteresis is computed ON-THE-FLY at hit-test time, not as a
218
- * per-transition mutation of effectiveRects. This avoids the
219
- * oscillation bug where reset+rebias-on-each-target-change would
220
- * flip the boundary by 2*halfShift between transitions and push
221
- * the pointer into the new target's biased zone, causing rapid
222
- * back-and-forth flipping on small ±X% pointer motion. */
223
- function hitTest(point: { x: number; y: number }): number {
224
- if (!drag) return -1;
225
- const { effectiveRects, rects, currentTarget, sourceIndex, cellWidth, cellHeight, gridBoundsContent } = drag;
226
-
227
- // Pass 1: sticky-currentTarget extension.
228
- // Base is the INFLATED effectiveRect (consistent with Pass 2's
229
- // tessellation), extended further toward source by half-cell
230
- // magnitudes proportional to the source→target unit-vector
231
- // components. Pure horizontal: full half-cellWidth on the
232
- // source-facing side, zero on the perpendicular axis.
233
- if (currentTarget !== sourceIndex && currentTarget >= 0 && currentTarget < effectiveRects.length) {
234
- const cur = effectiveRects[currentTarget];
235
- const src = rects[sourceIndex];
236
- const tgtCx = (cur.contentLeft + cur.contentRight) / 2;
237
- const tgtCy = (cur.contentTop + cur.contentBottom) / 2;
238
- const srcCx = (src.contentLeft + src.contentRight) / 2;
239
- const srcCy = (src.contentTop + src.contentBottom) / 2;
240
- const dx = tgtCx - srcCx;
241
- const dy = tgtCy - srcCy;
242
- const mag = Math.hypot(dx, dy);
243
- if (mag > 0) {
244
- const dxU = dx / mag;
245
- const dyU = dy / mag;
246
- const extendX = Math.abs(dxU) * cellWidth * HYSTERESIS_FRACTION;
247
- const extendY = Math.abs(dyU) * cellHeight * HYSTERESIS_FRACTION;
248
- const left = cur.contentLeft - (dxU > 0 ? extendX : 0);
249
- const right = cur.contentRight + (dxU < 0 ? extendX : 0);
250
- const top = cur.contentTop - (dyU > 0 ? extendY : 0);
251
- const bottom = cur.contentBottom + (dyU < 0 ? extendY : 0);
252
- if (point.x >= left && point.x <= right && point.y >= top && point.y <= bottom) {
253
- return currentTarget;
254
- }
255
- }
256
- }
257
-
258
- // Pass 2: first-match against natural effective (inflated) rects.
259
- for (let i = 0; i < effectiveRects.length; i++) {
260
- const r = effectiveRects[i];
261
- if (
262
- point.x >= r.contentLeft && point.x <= r.contentRight &&
263
- point.y >= r.contentTop && point.y <= r.contentBottom
264
- ) {
265
- return i;
266
- }
267
- }
268
-
269
- // Pass 3: bounded nearest-cell fallback.
270
- // If pointer is more than half-cell beyond the full grid's
271
- // bounding rect, return sourceIndex — commitDrag's
272
- // `from === to` short-circuit fires no-op onReorder, treating
273
- // an off-grid drop as an implicit cancel. Otherwise (pointer in
274
- // a gutter or on a trailing empty cell), nearest-by-centre.
275
- const marginX = cellWidth * OUTSIDE_GRID_MARGIN_FRACTION;
276
- const marginY = cellHeight * OUTSIDE_GRID_MARGIN_FRACTION;
277
- if (
278
- point.x < gridBoundsContent.left - marginX ||
279
- point.x > gridBoundsContent.right + marginX ||
280
- point.y < gridBoundsContent.top - marginY ||
281
- point.y > gridBoundsContent.bottom + marginY
282
- ) {
283
- return sourceIndex;
284
- }
285
-
286
- let bestIdx = 0;
287
- let bestD = Infinity;
288
- for (let i = 0; i < rects.length; i++) {
289
- const r = rects[i];
290
- const cx = (r.contentLeft + r.contentRight) / 2;
291
- const cy = (r.contentTop + r.contentBottom) / 2;
292
- const d = Math.hypot(point.x - cx, point.y - cy);
293
- if (d < bestD) { bestD = d; bestIdx = i; }
294
- }
295
- return bestIdx;
296
- }
297
-
298
- /** Apply lift styling to the dragged element + neighbour transition
299
- * styles. Captures the snapshot, infers grid metrics, builds the
300
- * inflated effectiveRects[]. Displacement and commit logic land in U4. */
301
- function activate(
302
- id: string,
303
- sourceIndex: number,
304
- ids: string[],
305
- startPointerViewport: { x: number; y: number },
306
- scrollAtActivate: { x: number; y: number },
307
- ) {
308
- // Prune stale entries — items removed since last drag.
309
- const idSet = new Set(ids);
310
- for (const key of nodes.keys()) {
311
- if (!idSet.has(key)) nodes.delete(key);
312
- }
313
-
314
- // Snapshot — measure all registered rects in container-content coords.
315
- // Items missing from `nodes` (shouldn't happen in practice but defends
316
- // against partial registration) get zero-rects so indices stay aligned.
317
- const rects: CachedGridRect[] = ids.map((itemId) => {
318
- const el = nodes.get(itemId);
319
- return el
320
- ? measure(el, scrollAtActivate)
321
- : { contentLeft: 0, contentTop: 0, contentRight: 0, contentBottom: 0, width: 0, height: 0 };
322
- });
323
-
324
- // Cell-width / cell-height inference — first item's dimensions.
325
- const cellWidth = rects[0]?.width ?? 0;
326
- const cellHeight = rects[0]?.height ?? 0;
327
-
328
- // Dev-mode-only non-uniform-cell diagnostic. Production builds pay no
329
- // diagnostic cost; external adopters with mismatched cells get a
330
- // console signal instead of silent wrong displacement.
331
- // Skip zero-sized rects (unregistered-sentinel — see measure()'s
332
- // fallback path) so partial registration during incremental mounts
333
- // doesn't trip the warn.
334
- if (isDevMode()) {
335
- for (const r of rects) {
336
- if (r.width === 0 && r.height === 0) continue;
337
- if (
338
- Math.abs(r.width - cellWidth) > cellHeight * 0.05 ||
339
- Math.abs(r.height - cellHeight) > cellHeight * 0.05
340
- ) {
341
- console.warn(
342
- '@cujuju/solid-reorder-list: createReorderGrid expects uniform cell sizes. ' +
343
- 'See README "Scope assumptions". Mismatched cell detected: ' +
344
- `${r.width}x${r.height} vs expected ${cellWidth}x${cellHeight}.`,
345
- );
346
- break;
347
- }
348
- }
349
- }
350
-
351
- // Column count inference — count items in the first row by
352
- // content-top, using a cell-height-relative tolerance.
353
- let cols = 1;
354
- while (cols < rects.length && sameRow(rects[0], rects[cols], cellHeight)) cols++;
355
-
356
- // Defensive guard for degenerate cases — single-row when only one
357
- // row of items exists. Engine continues without crashing rather
358
- // than refuse to drag.
359
- if (cols < 1 || cols > rects.length) cols = rects.length;
360
-
361
- // Cross-validation invariant: row 1's content-top should be
362
- // distinctly below row 0's (offset by ~cellHeight + gutterY). If
363
- // sameRow reports they're on the same row at index `cols`, the
364
- // tolerance was too loose for this layout — emit dev-mode warn so
365
- // tight-row-spacing consumers see the signal instead of silent
366
- // wrong displacement.
367
- if (isDevMode() && rects.length > cols && sameRow(rects[0], rects[cols], cellHeight)) {
368
- console.warn(
369
- '@cujuju/solid-reorder-list: createReorderGrid column-count inference ' +
370
- 'cross-validation failed. Inferred cols=' + cols + ' but row[0] and row[1] ' +
371
- `appear in the same row by cellHeight*0.1 tolerance (cellHeight=${cellHeight}). ` +
372
- 'Likely cause: gutterY < cellHeight*0.1 (compact layout). ' +
373
- 'Engine continues with inferred cols, but displacement may be incorrect.',
374
- );
375
- }
376
-
377
- // Gutter inference — defensive against degenerate layouts.
378
- const gutterX = rects[1] && sameRow(rects[0], rects[1], cellHeight)
379
- ? Math.max(0, rects[1].contentLeft - rects[0].contentRight)
380
- : 0;
381
- const gutterY = rects[cols]
382
- ? Math.max(0, rects[cols].contentTop - rects[0].contentBottom)
383
- : 0;
384
-
385
- // Inflated effectiveRects[] — tessellate cells with no gaps so
386
- // pointer-in-gutter has a deterministic target. Mutable copy lets
387
- // U4 apply per-target hysteresis adjustments in place.
388
- const effectiveRects: CachedGridRect[] = rects.map((r) => ({
389
- contentLeft: r.contentLeft - gutterX / 2,
390
- contentTop: r.contentTop - gutterY / 2,
391
- contentRight: r.contentRight + gutterX / 2,
392
- contentBottom: r.contentBottom + gutterY / 2,
393
- width: r.width + gutterX,
394
- height: r.height + gutterY,
395
- }));
396
-
397
- // Grid-bounding-rect over the FULL `cols × rowCount` layout —
398
- // includes trailing empty cells where rects.length doesn't fill
399
- // the last row. A drop in such an empty cell still snaps to the
400
- // nearest registered cell (intent: "drop at the end"); a drop
401
- // outside this rect plus half-cell margin returns sourceIndex
402
- // (intent: "off the grid → cancel").
403
- const rowCount = Math.ceil(rects.length / cols);
404
- const origin = rects[0] ?? { contentLeft: 0, contentTop: 0 };
405
- const gridBoundsContent = {
406
- left: origin.contentLeft,
407
- top: origin.contentTop,
408
- right: origin.contentLeft + cols * cellWidth + Math.max(0, cols - 1) * gutterX,
409
- bottom: origin.contentTop + rowCount * cellHeight + Math.max(0, rowCount - 1) * gutterY,
410
- };
411
-
412
- // Capture the source element's VIEWPORT rect (clientX/Y, not
413
- // content-frame). Used to position the source via `position: fixed`
414
- // so its translated visual escapes the consumer's scrollContainer
415
- // overflow clip. Captured BEFORE the style application loop below
416
- // so the rect is still natural (no scale(0.97) in effect yet).
417
- const sourceEl = nodes.get(id);
418
- const sourceVpRect = sourceEl
419
- ? sourceEl.getBoundingClientRect()
420
- : { left: 0, top: 0, width: 0, height: 0 } as DOMRect;
421
-
422
- // Insert a placeholder at the source's grid track to preserve the
423
- // layout slot when the source goes out of flow via `position: fixed`.
424
- // Without this, a CSS Grid (or flex) layout reflows the remaining
425
- // items to fill the source's track, compounding with the displacement
426
- // transforms applied to in-flow neighbours and producing double-shift
427
- // visual glitches. Placeholder is invisible, non-interactive, and
428
- // sized to source's snapshot dimensions.
429
- let placeholder: HTMLDivElement | null = null;
430
- if (sourceEl && sourceEl.parentElement) {
431
- placeholder = document.createElement('div');
432
- placeholder.style.width = `${sourceVpRect.width}px`;
433
- placeholder.style.height = `${sourceVpRect.height}px`;
434
- placeholder.style.visibility = 'hidden';
435
- placeholder.style.pointerEvents = 'none';
436
- placeholder.setAttribute('data-reorder-placeholder', '');
437
- sourceEl.parentElement.insertBefore(placeholder, sourceEl);
438
- }
439
-
440
- drag = {
441
- id,
442
- sourceIndex,
443
- startPointerViewport,
444
- scrollAtActivate,
445
- rects,
446
- effectiveRects,
447
- cellWidth,
448
- cellHeight,
449
- gutterX,
450
- gutterY,
451
- cols,
452
- gridBoundsContent,
453
- currentTarget: sourceIndex,
454
- ids,
455
- placeholder,
456
- };
457
-
458
- setActiveId(id);
459
- setTargetIdx(sourceIndex);
460
-
461
- // Style: dragged item gets instant scale lift; all others get a
462
- // smooth transition for displacement animation.
463
- const ms = getTransitionMs();
464
- for (const itemId of ids) {
465
- const el = nodes.get(itemId);
466
- if (!el) continue;
467
- if (itemId === id) {
468
- el.style.willChange = 'transform';
469
- el.style.transition = 'none';
470
- el.style.zIndex = '50';
471
- // `position: fixed` removes the source from its parent's flow
472
- // and binds its containing block to the viewport. This escapes
473
- // ancestor `overflow: auto / hidden / clip` boundaries — without
474
- // this, a transform-translated source on an in-flow element gets
475
- // visually clipped at the nearest scroll container's edges.
476
- // Combined with the placeholder (above), the layout slot stays
477
- // intact while the source visually follows the pointer freely.
478
- // top/left anchor source at its activate-time viewport position;
479
- // updateDrag's `transform: translate(dx, dy)` then offsets from
480
- // that anchor by the pointer's viewport delta.
481
- el.style.position = 'fixed';
482
- el.style.top = `${sourceVpRect.top}px`;
483
- el.style.left = `${sourceVpRect.left}px`;
484
- el.style.width = `${sourceVpRect.width}px`;
485
- el.style.height = `${sourceVpRect.height}px`;
486
- el.style.transform = `scale(${DRAG_SCALE})`;
487
- } else {
488
- el.style.willChange = 'transform';
489
- el.style.transition = `transform ${ms}ms ease`;
490
- el.style.pointerEvents = 'none';
491
- }
492
- }
493
-
494
- document.body.style.cursor = 'grabbing';
495
- cancel.add();
496
- }
497
-
498
- // Hysteresis fraction — half-cell magnitude that currentTarget's
499
- // rect is sticky-extended toward source during hit-test. 0.5 =
500
- // half-cell. See hitTest() Pass 1 for the model. Mirrors 1-D's
501
- // halfShift idiom (createReorderList.ts updateEffectivePositions)
502
- // translated to a hit-test-time stickiness instead of per-transition
503
- // rect mutation, which avoids the oscillation bug an earlier
504
- // implementation hit (reset+rebias-on-each-transition flipped the
505
- // boundary by 2*halfShift between transitions and pushed pointer
506
- // into the new target's biased zone).
507
- const HYSTERESIS_FRACTION = 0.5;
508
-
509
- // Outside-grid drop margin — half-cell magnitude beyond the grid's
510
- // bounding rect that still snaps to a nearest cell. Drops further
511
- // outside return sourceIndex from hitTest, so commitDrag's
512
- // `from === to` short-circuit produces a no-op (the user dropped
513
- // unambiguously off the grid; treat as cancel without firing
514
- // onReorder). Same fraction as HYSTERESIS_FRACTION — both measure
515
- // half-cell dimensional slack, kept named separately so the meaning
516
- // stays clear (one's a stickiness threshold, the other's an
517
- // off-grid threshold).
518
- const OUTSIDE_GRID_MARGIN_FRACTION = 0.5;
519
-
520
- /** Apply per-item flat-order displacement transforms when the target
521
- * changes. Each item between sourceIndex and newTarget (inclusive
522
- * on both ends, in flat-order sequence) translates to its
523
- * predecessor's (forward drag) or successor's (reverse drag)
524
- * snapshot position. Items outside this range get `transform: ''`.
525
- * Source-element transform is owned by `updateDrag` (rAF-batched). */
526
- function applyDisplacement(state: GridDragState) {
527
- const { rects, ids, sourceIndex, currentTarget } = state;
528
- for (let i = 0; i < ids.length; i++) {
529
- if (i === sourceIndex) continue;
530
- const el = nodes.get(ids[i]);
531
- if (!el) continue;
532
-
533
- let destIdx = -1;
534
- if (currentTarget > sourceIndex && i > sourceIndex && i <= currentTarget) {
535
- // Forward drag: items shift backward by one flat-order slot.
536
- destIdx = i - 1;
537
- } else if (currentTarget < sourceIndex && i >= currentTarget && i < sourceIndex) {
538
- // Reverse drag: items shift forward by one flat-order slot.
539
- destIdx = i + 1;
540
- }
541
-
542
- if (destIdx === -1) {
543
- el.style.transform = '';
544
- } else {
545
- const dest = rects[destIdx];
546
- const cur = rects[i];
547
- const tx = dest.contentLeft - cur.contentLeft;
548
- const ty = dest.contentTop - cur.contentTop;
549
- el.style.transform = `translate(${tx}px, ${ty}px)`;
550
- }
551
- }
552
- }
553
-
554
- /** Per-pointermove tick. Two coordinate frames in play:
555
- * - Source-element transform uses VIEWPORT delta (clientX/Y delta
556
- * from `startPointerViewport`), so the dragged item stays glued
557
- * to the user's pointer regardless of mid-drag scroll.
558
- * - Hit-test uses the CONTENT-frame pointer (clientX + current
559
- * scroll), so it tests against the activate-time snapshot rects
560
- * that live in the same frame. */
561
- function updateDrag(ev: PointerEvent) {
562
- if (!drag) return;
563
- const { startPointerViewport } = drag;
564
- const dx = ev.clientX - startPointerViewport.x;
565
- const dy = ev.clientY - startPointerViewport.y;
566
-
567
- // Source-element transform — batched to one DOM write per frame.
568
- const draggedEl = nodes.get(drag.ids[drag.sourceIndex]);
569
- if (draggedEl) {
570
- if (dragRaf) cancelAnimationFrame(dragRaf);
571
- dragRaf = requestAnimationFrame(() => {
572
- draggedEl.style.transform = `translate(${dx}px, ${dy}px) scale(${DRAG_SCALE})`;
573
- dragRaf = 0;
574
- });
575
- }
576
-
577
- // Hit-test in content frame against the activate-time snapshot rects.
578
- // Manual scroll changes since activate are absorbed by re-reading
579
- // the live scroll on every tick (R7).
580
- const currentScroll = getScroll(getScrollContainer());
581
- const pointerContent = {
582
- x: ev.clientX + currentScroll.x,
583
- y: ev.clientY + currentScroll.y,
584
- };
585
- const newTarget = hitTest(pointerContent);
586
-
587
- if (newTarget !== drag.currentTarget) {
588
- drag.currentTarget = newTarget;
589
- setTargetIdx(newTarget);
590
- applyDisplacement(drag);
591
- }
592
- }
593
-
594
- /** Filled by U4. For U2, captures from/to and clears state without
595
- * firing onReorder when the snapshot wasn't taken (avoids spurious
596
- * R5 R7 calls on the partially-implemented engine). */
597
- function commitDrag() {
598
- if (!drag) return;
599
- if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
600
- const { sourceIndex, currentTarget } = drag;
601
-
602
- cancel.remove();
603
- setActiveId(null);
604
- setTargetIdx(-1);
605
- clearDragStyles();
606
- blockNextClick();
607
-
608
- const from = sourceIndex;
609
- const to = currentTarget;
610
- drag = null;
611
- if (from !== to) options.onReorder(from, to);
612
- }
613
-
614
- /** Cancel without firing onReorder. */
615
- function cancelDrag() {
616
- if (!drag) return;
617
- if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
618
- cancel.remove();
619
- setActiveId(null);
620
- setTargetIdx(-1);
621
- clearDragStyles();
622
- drag = null;
623
- }
624
-
625
- // ── Cancellation handlers (Esc / blur / contextmenu via shared.ts) ──────
626
-
627
- const cancel = createCancelListeners({ onCancel: cancelDrag });
628
-
629
- function clearDragStyles() {
630
- if (dragRaf) { cancelAnimationFrame(dragRaf); dragRaf = 0; }
631
-
632
- // Remove the source's grid-track placeholder before resetting source
633
- // styles. Order matters: with the placeholder still in place, the
634
- // source returning to `position: relative` would briefly co-occupy
635
- // the same track, causing a 1-frame layout glitch.
636
- if (drag?.placeholder && drag.placeholder.parentElement) {
637
- drag.placeholder.parentElement.removeChild(drag.placeholder);
638
- }
639
-
640
- const targets = drag?.ids
641
- ? drag.ids.map((id) => nodes.get(id)).filter((el): el is HTMLElement => !!el)
642
- : [...nodes.values()];
643
- for (const el of targets) {
644
- el.style.transform = '';
645
- el.style.transition = '';
646
- el.style.zIndex = '';
647
- el.style.position = '';
648
- el.style.top = '';
649
- el.style.left = '';
650
- el.style.width = '';
651
- el.style.height = '';
652
- el.style.willChange = '';
653
- el.style.pointerEvents = '';
654
- }
655
- document.body.style.cursor = '';
656
- }
657
-
658
- // ── Pointer event wiring ────────────────────────────────────────────────
659
-
660
- function onPointerDown(id: string, e: PointerEvent) {
661
- if (e.button !== 0) return;
662
- if (drag) return;
663
-
664
- // Don't start drag on interactive children (default skipSelector
665
- // blocks button/input/a/[role="button"]). Configurable via
666
- // options.skipSelector; set to '' to disable.
667
- const skip = getSkipSelector();
668
- if (skip && (e.target as HTMLElement).closest(skip)) return;
669
-
670
- if (getStopPropagation()) e.stopPropagation();
671
-
672
- const ids = options.ids();
673
- const sourceIndex = ids.indexOf(id);
674
- if (sourceIndex === -1) return;
675
-
676
- const startX = e.clientX;
677
- const startY = e.clientY;
678
- const threshold = getActivateDistance();
679
- let activated = false;
680
-
681
- const onMove = (ev: PointerEvent) => {
682
- if (!activated) {
683
- const dx = ev.clientX - startX;
684
- const dy = ev.clientY - startY;
685
- // Euclidean activation threshold (R2). 1-D's `Math.abs` becomes
686
- // `Math.hypot` in 2-D so diagonal drags don't need to cross the
687
- // threshold on either axis individually.
688
- if (Math.hypot(dx, dy) >= threshold) {
689
- activated = true;
690
- // Snapshot scroll at activate-time. startPointer is stored as
691
- // viewport coords (for source-element transform deltas);
692
- // scrollAtActivate carries the activate-time scroll separately
693
- // so hit-test can compute content-frame pointer at any later
694
- // time as `clientX + getScroll().x` (R7 live compensation).
695
- const scroll = getScroll(getScrollContainer());
696
- activate(
697
- id,
698
- sourceIndex,
699
- ids,
700
- { x: ev.clientX, y: ev.clientY },
701
- { x: scroll.x, y: scroll.y },
702
- );
703
- }
704
- return;
705
- }
706
- updateDrag(ev);
707
- };
708
-
709
- const onUp = (upEvent: PointerEvent) => {
710
- if (upEvent.button !== 0) return;
711
- if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
712
- if (activated) commitDrag();
713
- };
714
-
715
- document.addEventListener('pointermove', onMove);
716
- document.addEventListener('pointerup', onUp);
717
- pointerCleanup = () => {
718
- document.removeEventListener('pointermove', onMove);
719
- document.removeEventListener('pointerup', onUp);
720
- };
721
- }
722
-
723
- // ── Cleanup ─────────────────────────────────────────────────────────────
724
-
725
- // Guard: only register onCleanup if running inside a SolidJS reactive owner.
726
- // Makes the primitive safe to use in tests or imperative code outside a
727
- // component tree. When used inside a component, cleanup fires on unmount.
728
- if (getOwner()) {
729
- onCleanup(() => {
730
- if (drag) cancelDrag();
731
- nodes.clear();
732
- disposeRoot?.();
733
- });
734
- }
735
-
736
- // ── Public API ──────────────────────────────────────────────────────────
737
-
738
- return {
739
- /** Spread onto each reorderable item element. */
740
- itemProps: (id: string) => ({
741
- ref: (el: HTMLElement) => { nodes.set(id, el); },
742
- onPointerDown: (e: PointerEvent) => onPointerDown(id, e),
743
- classList: { [getActiveClass()]: activeId() === id },
744
- 'data-reorder-id': id,
745
- }),
746
-
747
- /** Whether the given item is currently being dragged. */
748
- isActive: (id: string) => activeId() === id,
749
-
750
- /** Whether any item is currently being dragged. */
751
- isDragging: () => activeId() !== null,
752
-
753
- /** The ID of the item currently being dragged, or null. */
754
- activeId,
755
-
756
- /** The current drop target index, or -1 if not dragging. */
757
- targetIndex: targetIdx,
758
-
759
- /** Abort an in-progress drag without firing onReorder.
760
- * Idempotent no-op when no drag is active. (R13a)
761
- *
762
- * Consumers invalidate the engine's snapshot via this method when
763
- * cross-surface mutations make the captured indices stale (id-list
764
- * shape change, popover dismiss during drag, parent unmount). */
765
- cancel: () => {
766
- if (drag) cancelDrag();
767
- },
768
-
769
- /** Manually dispose the isolated reactive root. Call this if you
770
- * created the primitive outside a SolidJS owner scope and need
771
- * deterministic cleanup. */
772
- dispose: () => {
773
- if (drag) cancelDrag();
774
- nodes.clear();
775
- disposeRoot?.();
776
- },
777
- };
778
- }
1
+ /**
2
+ * createReorderGrid — 2-D drag-to-reorder primitive for SolidJS.
3
+ *
4
+ * Sibling to createReorderList; targets responsive grid layouts where
5
+ * displacement crosses row-wrap diagonals. v0.3.0 ships activation +
6
+ * snapshot + hit-test + per-item flat-order displacement + hysteresis,
7
+ * with manual scrollContainer compensation. Auto-scroll (R8/R9) is
8
+ * deferred to v0.3.1.
9
+ *
10
+ * Coordinate frame: container-content coords =
11
+ * `clientX + scrollContainer.scrollLeft` (mirror y).
12
+ * Snapshot rects, effectiveRects[], and pointer hit-test all live in
13
+ * this frame. NOT pageX/pageY — F4's panel is Portal'd `position:fixed`
14
+ * so window scroll does not compose into the frame.
15
+ */
16
+
17
+ import { createSignal, createRoot, onCleanup, getOwner } from 'solid-js';
18
+ import {
19
+ DEFAULT_ARMED_CLASS, DEFAULT_SKIP_SELECTOR, DEFAULT_TOUCH_HOLD_MS, DEFAULT_TOUCH_HOLD_TOLERANCE, blockNextClick, createCancelListeners, startPressHold,
20
+ } from './shared';
21
+
22
+ // ── Types ──────────────────────────────────────────────────────────────────
23
+
24
+ export interface ReorderGridOptions {
25
+ /** Reactive list of IDs in current grid order (flat, row-major). */
26
+ ids: () => string[];
27
+ /** Called on drop with original and target indices. Indices are flat
28
+ * positions in the array at drag start (not visual positions). */
29
+ onReorder: (fromIndex: number, toIndex: number) => void;
30
+ /** Pixels of pointer movement (Euclidean) before drag activates.
31
+ * Default 5. */
32
+ activateDistance?: number;
33
+ /** Duration of displacement transition in ms. Default 200. */
34
+ transitionMs?: number;
35
+ /** CSS class applied to the active (dragged) item. Default
36
+ * 'reorder-active'. */
37
+ activeClass?: string;
38
+ /** Scale factor for the dragged item's visual lift. Default 0.97. */
39
+ dragScale?: number;
40
+ /** Whether to call stopPropagation on pointerdown. Default true. */
41
+ stopPropagation?: boolean;
42
+ /** CSS selector matched via `closest()` from the pointerdown target.
43
+ * When matched, drag activation is skipped. Defaults to
44
+ * {@link DEFAULT_SKIP_SELECTOR}. Set to an empty string to disable. */
45
+ skipSelector?: string;
46
+ /** Reactive accessor returning the scroll container, or `null` for
47
+ * no compensation. The container's scroll offset is read on each
48
+ * pointermove; rect storage uses container-content coords so manual
49
+ * scrolls during drag don't desync the hit-test. v0.3.0 supports
50
+ * HTMLElement and Window targets. v0.3.1 adds auto-scroll inside
51
+ * edge zones of this container. */
52
+ scrollContainer?: () => HTMLElement | Window | null | undefined;
53
+ /** Milliseconds a touch or pen press must be held before it can drag.
54
+ * Default 200. Stops a finger flick from grabbing an item. Moving more
55
+ * than `touchHoldTolerance` or lifting during the hold gives the press
56
+ * up. A mouse never waits. Set to 0 to turn the hold off. */
57
+ touchHoldMs?: number;
58
+ /** Pixels a press may wander during the hold. Default 10. */
59
+ touchHoldTolerance?: number;
60
+ /** CSS class on an item whose hold has completed, until it is dragged
61
+ * or let go. Default 'reorder-armed'. */
62
+ armedClass?: string;
63
+ }
64
+
65
+ interface CachedGridRect {
66
+ /** Container-content coords (clientX + container.scrollLeft, mirror y). */
67
+ contentLeft: number;
68
+ contentTop: number;
69
+ contentRight: number;
70
+ contentBottom: number;
71
+ width: number;
72
+ height: number;
73
+ }
74
+
75
+ interface GridDragState {
76
+ id: string;
77
+ sourceIndex: number;
78
+ /** Pointer position at activate, in VIEWPORT coords (clientX/Y).
79
+ * Source-element transform reads this to translate the dragged item
80
+ * by the viewport delta as the pointer moves. */
81
+ startPointerViewport: { x: number; y: number };
82
+ /** Scroll offset at activate. Combined with startPointerViewport
83
+ * gives the activate-time content-frame anchor; combined with the
84
+ * current scroll gives the current content-frame pointer. */
85
+ scrollAtActivate: { x: number; y: number };
86
+ /** Original snapshot rects in container-content coords. Immutable
87
+ * during drag. */
88
+ rects: CachedGridRect[];
89
+ /** Mutable mirror of `rects[]` used for hysteresis. Same coordinate
90
+ * frame. Mutated on each target change by U4. */
91
+ effectiveRects: CachedGridRect[];
92
+ /** Inferred grid metrics. */
93
+ cellWidth: number;
94
+ cellHeight: number;
95
+ gutterX: number;
96
+ gutterY: number;
97
+ cols: number;
98
+ /** Bounding rect of the FULL `cols × rowCount` grid, including any
99
+ * trailing empty cells where `rects.length` doesn't fill the last
100
+ * row. In container-content coords. Used by hit-test to bound the
101
+ * nearest-cell fallback — drops far outside this rect (plus
102
+ * `OUTSIDE_GRID_MARGIN_FRACTION` slack) return `sourceIndex` so
103
+ * `commitDrag` short-circuits via `from === to`. */
104
+ gridBoundsContent: {
105
+ left: number;
106
+ top: number;
107
+ right: number;
108
+ bottom: number;
109
+ };
110
+ /** Last-resolved hit-test result. Consumed by commitDrag for the
111
+ * onReorder index. */
112
+ currentTarget: number;
113
+ ids: string[];
114
+ /** Placeholder DOM node inserted at source's grid track when the
115
+ * source switches to `position: fixed` during drag. Preserves the
116
+ * source's grid layout slot so neighbour cells don't reflow into
117
+ * it (which would compound with the displacement transforms).
118
+ * Removed in clearDragStyles() on commit/cancel. Null when the
119
+ * source's parent could not be determined at activate. */
120
+ placeholder: HTMLDivElement | null;
121
+ }
122
+
123
+ // ── Helpers ────────────────────────────────────────────────────────────────
124
+
125
+ /** Dev-mode probe — reads `process.env.NODE_ENV` defensively so the
126
+ * primitive doesn't require @types/node and works in browser-only
127
+ * bundles where `process` is undefined. Production builds have this
128
+ * evaluate to `false` (after bundler dead-code elimination), so the
129
+ * diagnostic warns add zero runtime cost. */
130
+ function isDevMode(): boolean {
131
+ const proc = (globalThis as { process?: { env?: { NODE_ENV?: string } } }).process;
132
+ return proc?.env?.NODE_ENV !== 'production';
133
+ }
134
+
135
+ /** Read the scroll container's offset. Window vs Element API quirks
136
+ * are isolated here; v0.3.1's auto-scroll loop reuses the same helper. */
137
+ function getScroll(c: HTMLElement | Window | null | undefined): { x: number; y: number } {
138
+ if (!c) return { x: window.scrollX, y: window.scrollY };
139
+ if (c instanceof Window) return { x: c.scrollX, y: c.scrollY };
140
+ return { x: c.scrollLeft, y: c.scrollTop };
141
+ }
142
+
143
+ // ── Primitive ──────────────────────────────────────────────────────────────
144
+
145
+ export function createReorderGrid(options: ReorderGridOptions) {
146
+ // Pixels of pointer movement (Euclidean) required before drag activates.
147
+ // Prevents accidental drag on click (normal mouse jitter is 1-3px).
148
+ const getActivateDistance = () => options.activateDistance ?? 5;
149
+ const getTransitionMs = () => options.transitionMs ?? 200;
150
+ const getActiveClass = () => options.activeClass ?? 'reorder-active';
151
+
152
+ // Scale factor applied to the dragged item for visual lift.
153
+ // 0.97 = 3% shrink. Set to 1.0 for no scale. Consumers can override.
154
+ const DRAG_SCALE = options.dragScale ?? 0.97;
155
+ const getStopPropagation = () => options.stopPropagation ?? true;
156
+ const getSkipSelector = () => options.skipSelector ?? DEFAULT_SKIP_SELECTOR;
157
+ const getScrollContainer = () => options.scrollContainer?.() ?? null;
158
+ const getTouchHoldMs = () => options.touchHoldMs ?? DEFAULT_TOUCH_HOLD_MS;
159
+ const getTouchHoldTolerance = () => options.touchHoldTolerance ?? DEFAULT_TOUCH_HOLD_TOLERANCE;
160
+ const getArmedClass = () => options.armedClass ?? DEFAULT_ARMED_CLASS;
161
+
162
+ // Registered elements keyed by ID.
163
+ const nodes = new Map<string, HTMLElement>();
164
+
165
+ // Reactive signals in an isolated root — immune to parent scope disposal.
166
+ // Without createRoot, SolidJS can dispose these signals (and fire onCleanup)
167
+ // when the parent component's reactive graph re-evaluates during a drag,
168
+ // killing the active drag mid-flight.
169
+ let disposeRoot: (() => void) | undefined;
170
+ const { activeId, setActiveId, targetIdx, setTargetIdx, armedId, setArmedId } = createRoot((dispose) => {
171
+ disposeRoot = dispose;
172
+ const [activeId, setActiveId] = createSignal<string | null>(null);
173
+ const [targetIdx, setTargetIdx] = createSignal<number>(-1);
174
+ const [armedId, setArmedId] = createSignal<string | null>(null);
175
+ return { activeId, setActiveId, targetIdx, setTargetIdx, armedId, setArmedId };
176
+ });
177
+
178
+ // Stored so cancel handlers can clean up pointer listeners.
179
+ let pointerCleanup: (() => void) | null = null;
180
+
181
+ // Non-reactive drag state — mutated on pointermove for performance.
182
+ let drag: GridDragState | null = null;
183
+
184
+ // rAF handle for batching dragged-item transform updates.
185
+ // (v0.3.1 will add a sibling autoScrollRaf with the same lifecycle.)
186
+ let dragRaf: number = 0;
187
+
188
+ // ── Drag lifecycle ──────────────────────────────────────────────────────
189
+
190
+ /** Measure one element into a CachedGridRect in container-content
191
+ * coords (clientLeft/Top + scrollContainer.scrollLeft/Top, mirror y).
192
+ * When no scrollContainer is provided, falls back to window.scrollX/Y
193
+ * so the no-container path resolves to true page coords. */
194
+ function measure(el: HTMLElement, scroll: { x: number; y: number }): CachedGridRect {
195
+ const r = el.getBoundingClientRect();
196
+ return {
197
+ contentLeft: r.left + scroll.x,
198
+ contentTop: r.top + scroll.y,
199
+ contentRight: r.right + scroll.x,
200
+ contentBottom: r.bottom + scroll.y,
201
+ width: r.width,
202
+ height: r.height,
203
+ };
204
+ }
205
+
206
+ /** Same-row predicate using cell-height-relative tolerance to
207
+ * absorb sub-pixel jitter on HiDPI / fractional layouts. */
208
+ function sameRow(a: CachedGridRect, b: CachedGridRect, cellHeight: number): boolean {
209
+ return Math.abs(a.contentTop - b.contentTop) < cellHeight * 0.1;
210
+ }
211
+
212
+ /** Hit-test a content-frame pointer against the engine's effective
213
+ * rects, with stickiness applied to currentTarget for hysteresis.
214
+ *
215
+ * Pass 1 — sticky-currentTarget: if currentTarget !== sourceIndex,
216
+ * compute its EXTENDED rect (extends the side facing source by
217
+ * half-cell magnitudes proportional to source→target unit-vector
218
+ * components). If the pointer falls inside that extended rect,
219
+ * return currentTarget without a flip. This is the hysteresis: the
220
+ * dragged item "sticks" to its current target — pointer must move
221
+ * past the natural boundary AND a half-cell extension into the
222
+ * source-side gap before the swap drops.
223
+ *
224
+ * Pass 2 — first-match: pointer is outside the sticky zone; do a
225
+ * normal point-in-rect check against effectiveRects[] (which are
226
+ * natural inflated rects, never per-target-mutated). First match
227
+ * wins (flat-order tie-break for 4-way corners).
228
+ *
229
+ * Pass 3 — nearest-by-centre fallback: pointer is in a gap or
230
+ * clearly outside the grid. Returns the cell whose centre
231
+ * minimises Euclidean distance.
232
+ *
233
+ * Hysteresis is computed ON-THE-FLY at hit-test time, not as a
234
+ * per-transition mutation of effectiveRects. This avoids the
235
+ * oscillation bug where reset+rebias-on-each-target-change would
236
+ * flip the boundary by 2*halfShift between transitions and push
237
+ * the pointer into the new target's biased zone, causing rapid
238
+ * back-and-forth flipping on small ±X% pointer motion. */
239
+ function hitTest(point: { x: number; y: number }): number {
240
+ if (!drag) return -1;
241
+ const { effectiveRects, rects, currentTarget, sourceIndex, cellWidth, cellHeight, gridBoundsContent } = drag;
242
+
243
+ // Pass 1: sticky-currentTarget extension.
244
+ // Base is the INFLATED effectiveRect (consistent with Pass 2's
245
+ // tessellation), extended further toward source by half-cell
246
+ // magnitudes proportional to the source→target unit-vector
247
+ // components. Pure horizontal: full half-cellWidth on the
248
+ // source-facing side, zero on the perpendicular axis.
249
+ if (currentTarget !== sourceIndex && currentTarget >= 0 && currentTarget < effectiveRects.length) {
250
+ const cur = effectiveRects[currentTarget];
251
+ const src = rects[sourceIndex];
252
+ const tgtCx = (cur.contentLeft + cur.contentRight) / 2;
253
+ const tgtCy = (cur.contentTop + cur.contentBottom) / 2;
254
+ const srcCx = (src.contentLeft + src.contentRight) / 2;
255
+ const srcCy = (src.contentTop + src.contentBottom) / 2;
256
+ const dx = tgtCx - srcCx;
257
+ const dy = tgtCy - srcCy;
258
+ const mag = Math.hypot(dx, dy);
259
+ if (mag > 0) {
260
+ const dxU = dx / mag;
261
+ const dyU = dy / mag;
262
+ const extendX = Math.abs(dxU) * cellWidth * HYSTERESIS_FRACTION;
263
+ const extendY = Math.abs(dyU) * cellHeight * HYSTERESIS_FRACTION;
264
+ const left = cur.contentLeft - (dxU > 0 ? extendX : 0);
265
+ const right = cur.contentRight + (dxU < 0 ? extendX : 0);
266
+ const top = cur.contentTop - (dyU > 0 ? extendY : 0);
267
+ const bottom = cur.contentBottom + (dyU < 0 ? extendY : 0);
268
+ if (point.x >= left && point.x <= right && point.y >= top && point.y <= bottom) {
269
+ return currentTarget;
270
+ }
271
+ }
272
+ }
273
+
274
+ // Pass 2: first-match against natural effective (inflated) rects.
275
+ for (let i = 0; i < effectiveRects.length; i++) {
276
+ const r = effectiveRects[i];
277
+ if (
278
+ point.x >= r.contentLeft && point.x <= r.contentRight &&
279
+ point.y >= r.contentTop && point.y <= r.contentBottom
280
+ ) {
281
+ return i;
282
+ }
283
+ }
284
+
285
+ // Pass 3: bounded nearest-cell fallback.
286
+ // If pointer is more than half-cell beyond the full grid's
287
+ // bounding rect, return sourceIndex — commitDrag's
288
+ // `from === to` short-circuit fires no-op onReorder, treating
289
+ // an off-grid drop as an implicit cancel. Otherwise (pointer in
290
+ // a gutter or on a trailing empty cell), nearest-by-centre.
291
+ const marginX = cellWidth * OUTSIDE_GRID_MARGIN_FRACTION;
292
+ const marginY = cellHeight * OUTSIDE_GRID_MARGIN_FRACTION;
293
+ if (
294
+ point.x < gridBoundsContent.left - marginX ||
295
+ point.x > gridBoundsContent.right + marginX ||
296
+ point.y < gridBoundsContent.top - marginY ||
297
+ point.y > gridBoundsContent.bottom + marginY
298
+ ) {
299
+ return sourceIndex;
300
+ }
301
+
302
+ let bestIdx = 0;
303
+ let bestD = Infinity;
304
+ for (let i = 0; i < rects.length; i++) {
305
+ const r = rects[i];
306
+ const cx = (r.contentLeft + r.contentRight) / 2;
307
+ const cy = (r.contentTop + r.contentBottom) / 2;
308
+ const d = Math.hypot(point.x - cx, point.y - cy);
309
+ if (d < bestD) { bestD = d; bestIdx = i; }
310
+ }
311
+ return bestIdx;
312
+ }
313
+
314
+ /** Apply lift styling to the dragged element + neighbour transition
315
+ * styles. Captures the snapshot, infers grid metrics, builds the
316
+ * inflated effectiveRects[]. Displacement and commit logic land in U4. */
317
+ function activate(
318
+ id: string,
319
+ sourceIndex: number,
320
+ ids: string[],
321
+ startPointerViewport: { x: number; y: number },
322
+ scrollAtActivate: { x: number; y: number },
323
+ ) {
324
+ // Prune stale entries — items removed since last drag.
325
+ const idSet = new Set(ids);
326
+ for (const key of nodes.keys()) {
327
+ if (!idSet.has(key)) nodes.delete(key);
328
+ }
329
+
330
+ // Snapshot — measure all registered rects in container-content coords.
331
+ // Items missing from `nodes` (shouldn't happen in practice but defends
332
+ // against partial registration) get zero-rects so indices stay aligned.
333
+ const rects: CachedGridRect[] = ids.map((itemId) => {
334
+ const el = nodes.get(itemId);
335
+ return el
336
+ ? measure(el, scrollAtActivate)
337
+ : { contentLeft: 0, contentTop: 0, contentRight: 0, contentBottom: 0, width: 0, height: 0 };
338
+ });
339
+
340
+ // Cell-width / cell-height inference — first item's dimensions.
341
+ const cellWidth = rects[0]?.width ?? 0;
342
+ const cellHeight = rects[0]?.height ?? 0;
343
+
344
+ // Dev-mode-only non-uniform-cell diagnostic. Production builds pay no
345
+ // diagnostic cost; external adopters with mismatched cells get a
346
+ // console signal instead of silent wrong displacement.
347
+ // Skip zero-sized rects (unregistered-sentinel — see measure()'s
348
+ // fallback path) so partial registration during incremental mounts
349
+ // doesn't trip the warn.
350
+ if (isDevMode()) {
351
+ for (const r of rects) {
352
+ if (r.width === 0 && r.height === 0) continue;
353
+ if (
354
+ Math.abs(r.width - cellWidth) > cellHeight * 0.05 ||
355
+ Math.abs(r.height - cellHeight) > cellHeight * 0.05
356
+ ) {
357
+ console.warn(
358
+ '@cujuju/solid-reorder-list: createReorderGrid expects uniform cell sizes. ' +
359
+ 'See README "Scope assumptions". Mismatched cell detected: ' +
360
+ `${r.width}x${r.height} vs expected ${cellWidth}x${cellHeight}.`,
361
+ );
362
+ break;
363
+ }
364
+ }
365
+ }
366
+
367
+ // Column count inference — count items in the first row by
368
+ // content-top, using a cell-height-relative tolerance.
369
+ let cols = 1;
370
+ while (cols < rects.length && sameRow(rects[0], rects[cols], cellHeight)) cols++;
371
+
372
+ // Defensive guard for degenerate cases — single-row when only one
373
+ // row of items exists. Engine continues without crashing rather
374
+ // than refuse to drag.
375
+ if (cols < 1 || cols > rects.length) cols = rects.length;
376
+
377
+ // Cross-validation invariant: row 1's content-top should be
378
+ // distinctly below row 0's (offset by ~cellHeight + gutterY). If
379
+ // sameRow reports they're on the same row at index `cols`, the
380
+ // tolerance was too loose for this layout — emit dev-mode warn so
381
+ // tight-row-spacing consumers see the signal instead of silent
382
+ // wrong displacement.
383
+ if (isDevMode() && rects.length > cols && sameRow(rects[0], rects[cols], cellHeight)) {
384
+ console.warn(
385
+ '@cujuju/solid-reorder-list: createReorderGrid column-count inference ' +
386
+ 'cross-validation failed. Inferred cols=' + cols + ' but row[0] and row[1] ' +
387
+ `appear in the same row by cellHeight*0.1 tolerance (cellHeight=${cellHeight}). ` +
388
+ 'Likely cause: gutterY < cellHeight*0.1 (compact layout). ' +
389
+ 'Engine continues with inferred cols, but displacement may be incorrect.',
390
+ );
391
+ }
392
+
393
+ // Gutter inference — defensive against degenerate layouts.
394
+ const gutterX = rects[1] && sameRow(rects[0], rects[1], cellHeight)
395
+ ? Math.max(0, rects[1].contentLeft - rects[0].contentRight)
396
+ : 0;
397
+ const gutterY = rects[cols]
398
+ ? Math.max(0, rects[cols].contentTop - rects[0].contentBottom)
399
+ : 0;
400
+
401
+ // Inflated effectiveRects[] — tessellate cells with no gaps so
402
+ // pointer-in-gutter has a deterministic target. Mutable copy lets
403
+ // U4 apply per-target hysteresis adjustments in place.
404
+ const effectiveRects: CachedGridRect[] = rects.map((r) => ({
405
+ contentLeft: r.contentLeft - gutterX / 2,
406
+ contentTop: r.contentTop - gutterY / 2,
407
+ contentRight: r.contentRight + gutterX / 2,
408
+ contentBottom: r.contentBottom + gutterY / 2,
409
+ width: r.width + gutterX,
410
+ height: r.height + gutterY,
411
+ }));
412
+
413
+ // Grid-bounding-rect over the FULL `cols × rowCount` layout —
414
+ // includes trailing empty cells where rects.length doesn't fill
415
+ // the last row. A drop in such an empty cell still snaps to the
416
+ // nearest registered cell (intent: "drop at the end"); a drop
417
+ // outside this rect plus half-cell margin returns sourceIndex
418
+ // (intent: "off the grid → cancel").
419
+ const rowCount = Math.ceil(rects.length / cols);
420
+ const origin = rects[0] ?? { contentLeft: 0, contentTop: 0 };
421
+ const gridBoundsContent = {
422
+ left: origin.contentLeft,
423
+ top: origin.contentTop,
424
+ right: origin.contentLeft + cols * cellWidth + Math.max(0, cols - 1) * gutterX,
425
+ bottom: origin.contentTop + rowCount * cellHeight + Math.max(0, rowCount - 1) * gutterY,
426
+ };
427
+
428
+ // Capture the source element's VIEWPORT rect (clientX/Y, not
429
+ // content-frame). Used to position the source via `position: fixed`
430
+ // so its translated visual escapes the consumer's scrollContainer
431
+ // overflow clip. Captured BEFORE the style application loop below
432
+ // so the rect is still natural (no scale(0.97) in effect yet).
433
+ const sourceEl = nodes.get(id);
434
+ const sourceVpRect = sourceEl
435
+ ? sourceEl.getBoundingClientRect()
436
+ : { left: 0, top: 0, width: 0, height: 0 } as DOMRect;
437
+
438
+ // Insert a placeholder at the source's grid track to preserve the
439
+ // layout slot when the source goes out of flow via `position: fixed`.
440
+ // Without this, a CSS Grid (or flex) layout reflows the remaining
441
+ // items to fill the source's track, compounding with the displacement
442
+ // transforms applied to in-flow neighbours and producing double-shift
443
+ // visual glitches. Placeholder is invisible, non-interactive, and
444
+ // sized to source's snapshot dimensions.
445
+ let placeholder: HTMLDivElement | null = null;
446
+ if (sourceEl && sourceEl.parentElement) {
447
+ placeholder = document.createElement('div');
448
+ placeholder.style.width = `${sourceVpRect.width}px`;
449
+ placeholder.style.height = `${sourceVpRect.height}px`;
450
+ placeholder.style.visibility = 'hidden';
451
+ placeholder.style.pointerEvents = 'none';
452
+ placeholder.setAttribute('data-reorder-placeholder', '');
453
+ sourceEl.parentElement.insertBefore(placeholder, sourceEl);
454
+ }
455
+
456
+ drag = {
457
+ id,
458
+ sourceIndex,
459
+ startPointerViewport,
460
+ scrollAtActivate,
461
+ rects,
462
+ effectiveRects,
463
+ cellWidth,
464
+ cellHeight,
465
+ gutterX,
466
+ gutterY,
467
+ cols,
468
+ gridBoundsContent,
469
+ currentTarget: sourceIndex,
470
+ ids,
471
+ placeholder,
472
+ };
473
+
474
+ setActiveId(id);
475
+ setTargetIdx(sourceIndex);
476
+
477
+ // Style: dragged item gets instant scale lift; all others get a
478
+ // smooth transition for displacement animation.
479
+ const ms = getTransitionMs();
480
+ for (const itemId of ids) {
481
+ const el = nodes.get(itemId);
482
+ if (!el) continue;
483
+ if (itemId === id) {
484
+ el.style.willChange = 'transform';
485
+ el.style.transition = 'none';
486
+ el.style.zIndex = '50';
487
+ // `position: fixed` removes the source from its parent's flow
488
+ // and binds its containing block to the viewport. This escapes
489
+ // ancestor `overflow: auto / hidden / clip` boundaries — without
490
+ // this, a transform-translated source on an in-flow element gets
491
+ // visually clipped at the nearest scroll container's edges.
492
+ // Combined with the placeholder (above), the layout slot stays
493
+ // intact while the source visually follows the pointer freely.
494
+ // top/left anchor source at its activate-time viewport position;
495
+ // updateDrag's `transform: translate(dx, dy)` then offsets from
496
+ // that anchor by the pointer's viewport delta.
497
+ el.style.position = 'fixed';
498
+ el.style.top = `${sourceVpRect.top}px`;
499
+ el.style.left = `${sourceVpRect.left}px`;
500
+ el.style.width = `${sourceVpRect.width}px`;
501
+ el.style.height = `${sourceVpRect.height}px`;
502
+ el.style.transform = `scale(${DRAG_SCALE})`;
503
+ } else {
504
+ el.style.willChange = 'transform';
505
+ el.style.transition = `transform ${ms}ms ease`;
506
+ el.style.pointerEvents = 'none';
507
+ }
508
+ }
509
+
510
+ document.body.style.cursor = 'grabbing';
511
+ cancel.add();
512
+ }
513
+
514
+ // Hysteresis fraction — half-cell magnitude that currentTarget's
515
+ // rect is sticky-extended toward source during hit-test. 0.5 =
516
+ // half-cell. See hitTest() Pass 1 for the model. Mirrors 1-D's
517
+ // halfShift idiom (createReorderList.ts updateEffectivePositions)
518
+ // translated to a hit-test-time stickiness instead of per-transition
519
+ // rect mutation, which avoids the oscillation bug an earlier
520
+ // implementation hit (reset+rebias-on-each-transition flipped the
521
+ // boundary by 2*halfShift between transitions and pushed pointer
522
+ // into the new target's biased zone).
523
+ const HYSTERESIS_FRACTION = 0.5;
524
+
525
+ // Outside-grid drop margin — half-cell magnitude beyond the grid's
526
+ // bounding rect that still snaps to a nearest cell. Drops further
527
+ // outside return sourceIndex from hitTest, so commitDrag's
528
+ // `from === to` short-circuit produces a no-op (the user dropped
529
+ // unambiguously off the grid; treat as cancel without firing
530
+ // onReorder). Same fraction as HYSTERESIS_FRACTION — both measure
531
+ // half-cell dimensional slack, kept named separately so the meaning
532
+ // stays clear (one's a stickiness threshold, the other's an
533
+ // off-grid threshold).
534
+ const OUTSIDE_GRID_MARGIN_FRACTION = 0.5;
535
+
536
+ /** Apply per-item flat-order displacement transforms when the target
537
+ * changes. Each item between sourceIndex and newTarget (inclusive
538
+ * on both ends, in flat-order sequence) translates to its
539
+ * predecessor's (forward drag) or successor's (reverse drag)
540
+ * snapshot position. Items outside this range get `transform: ''`.
541
+ * Source-element transform is owned by `updateDrag` (rAF-batched). */
542
+ function applyDisplacement(state: GridDragState) {
543
+ const { rects, ids, sourceIndex, currentTarget } = state;
544
+ for (let i = 0; i < ids.length; i++) {
545
+ if (i === sourceIndex) continue;
546
+ const el = nodes.get(ids[i]);
547
+ if (!el) continue;
548
+
549
+ let destIdx = -1;
550
+ if (currentTarget > sourceIndex && i > sourceIndex && i <= currentTarget) {
551
+ // Forward drag: items shift backward by one flat-order slot.
552
+ destIdx = i - 1;
553
+ } else if (currentTarget < sourceIndex && i >= currentTarget && i < sourceIndex) {
554
+ // Reverse drag: items shift forward by one flat-order slot.
555
+ destIdx = i + 1;
556
+ }
557
+
558
+ if (destIdx === -1) {
559
+ el.style.transform = '';
560
+ } else {
561
+ const dest = rects[destIdx];
562
+ const cur = rects[i];
563
+ const tx = dest.contentLeft - cur.contentLeft;
564
+ const ty = dest.contentTop - cur.contentTop;
565
+ el.style.transform = `translate(${tx}px, ${ty}px)`;
566
+ }
567
+ }
568
+ }
569
+
570
+ /** Per-pointermove tick. Two coordinate frames in play:
571
+ * - Source-element transform uses VIEWPORT delta (clientX/Y delta
572
+ * from `startPointerViewport`), so the dragged item stays glued
573
+ * to the user's pointer regardless of mid-drag scroll.
574
+ * - Hit-test uses the CONTENT-frame pointer (clientX + current
575
+ * scroll), so it tests against the activate-time snapshot rects
576
+ * that live in the same frame. */
577
+ function updateDrag(ev: PointerEvent) {
578
+ if (!drag) return;
579
+ const { startPointerViewport } = drag;
580
+ const dx = ev.clientX - startPointerViewport.x;
581
+ const dy = ev.clientY - startPointerViewport.y;
582
+
583
+ // Source-element transform — batched to one DOM write per frame.
584
+ const draggedEl = nodes.get(drag.ids[drag.sourceIndex]);
585
+ if (draggedEl) {
586
+ if (dragRaf) cancelAnimationFrame(dragRaf);
587
+ dragRaf = requestAnimationFrame(() => {
588
+ draggedEl.style.transform = `translate(${dx}px, ${dy}px) scale(${DRAG_SCALE})`;
589
+ dragRaf = 0;
590
+ });
591
+ }
592
+
593
+ // Hit-test in content frame against the activate-time snapshot rects.
594
+ // Manual scroll changes since activate are absorbed by re-reading
595
+ // the live scroll on every tick (R7).
596
+ const currentScroll = getScroll(getScrollContainer());
597
+ const pointerContent = {
598
+ x: ev.clientX + currentScroll.x,
599
+ y: ev.clientY + currentScroll.y,
600
+ };
601
+ const newTarget = hitTest(pointerContent);
602
+
603
+ if (newTarget !== drag.currentTarget) {
604
+ drag.currentTarget = newTarget;
605
+ setTargetIdx(newTarget);
606
+ applyDisplacement(drag);
607
+ }
608
+ }
609
+
610
+ /** Filled by U4. For U2, captures from/to and clears state without
611
+ * firing onReorder when the snapshot wasn't taken (avoids spurious
612
+ * R5 R7 calls on the partially-implemented engine). */
613
+ function commitDrag() {
614
+ if (!drag) return;
615
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
616
+ const { sourceIndex, currentTarget } = drag;
617
+
618
+ cancel.remove();
619
+ setActiveId(null);
620
+ setTargetIdx(-1);
621
+ clearDragStyles();
622
+ blockNextClick();
623
+
624
+ const from = sourceIndex;
625
+ const to = currentTarget;
626
+ drag = null;
627
+ if (from !== to) options.onReorder(from, to);
628
+ }
629
+
630
+ /** Cancel without firing onReorder. */
631
+ function cancelDrag() {
632
+ if (!drag) return;
633
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
634
+ cancel.remove();
635
+ setActiveId(null);
636
+ setTargetIdx(-1);
637
+ clearDragStyles();
638
+ drag = null;
639
+ }
640
+
641
+ // ── Cancellation handlers (Esc / blur / contextmenu via shared.ts) ──────
642
+
643
+ const cancel = createCancelListeners({ onCancel: cancelDrag });
644
+
645
+ function clearDragStyles() {
646
+ if (dragRaf) { cancelAnimationFrame(dragRaf); dragRaf = 0; }
647
+
648
+ // Remove the source's grid-track placeholder before resetting source
649
+ // styles. Order matters: with the placeholder still in place, the
650
+ // source returning to `position: relative` would briefly co-occupy
651
+ // the same track, causing a 1-frame layout glitch.
652
+ if (drag?.placeholder && drag.placeholder.parentElement) {
653
+ drag.placeholder.parentElement.removeChild(drag.placeholder);
654
+ }
655
+
656
+ const targets = drag?.ids
657
+ ? drag.ids.map((id) => nodes.get(id)).filter((el): el is HTMLElement => !!el)
658
+ : [...nodes.values()];
659
+ for (const el of targets) {
660
+ el.style.transform = '';
661
+ el.style.transition = '';
662
+ el.style.zIndex = '';
663
+ el.style.position = '';
664
+ el.style.top = '';
665
+ el.style.left = '';
666
+ el.style.width = '';
667
+ el.style.height = '';
668
+ el.style.willChange = '';
669
+ el.style.pointerEvents = '';
670
+ }
671
+ document.body.style.cursor = '';
672
+ }
673
+
674
+ // ── Pointer event wiring ────────────────────────────────────────────────
675
+
676
+ function onPointerDown(id: string, e: PointerEvent) {
677
+ if (e.button !== 0) return;
678
+ if (drag) return;
679
+
680
+ // Don't start drag on interactive children (default skipSelector
681
+ // blocks button/input/a/[role="button"]). Configurable via
682
+ // options.skipSelector; set to '' to disable.
683
+ const skip = getSkipSelector();
684
+ if (skip && (e.target as HTMLElement).closest(skip)) return;
685
+
686
+ if (getStopPropagation()) e.stopPropagation();
687
+
688
+ const ids = options.ids();
689
+ const sourceIndex = ids.indexOf(id);
690
+ if (sourceIndex === -1) return;
691
+
692
+ // A new press replaces one still waiting (e.g. a second finger during a hold).
693
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
694
+
695
+ const startX = e.clientX;
696
+ const startY = e.clientY;
697
+ const threshold = getActivateDistance();
698
+ let activated = false;
699
+ const hold = startPressHold(e, {
700
+ ms: getTouchHoldMs(),
701
+ tolerance: getTouchHoldTolerance(),
702
+ onHeld: () => setArmedId(id),
703
+ });
704
+
705
+ const release = () => { if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; } };
706
+
707
+ const onMove = (ev: PointerEvent) => {
708
+ if (!activated) {
709
+ if (!hold.held) {
710
+ if (!hold.move(ev)) release();
711
+ return;
712
+ }
713
+ const dx = ev.clientX - startX;
714
+ const dy = ev.clientY - startY;
715
+ // Euclidean activation threshold (R2). 1-D's `Math.abs` becomes
716
+ // `Math.hypot` in 2-D so diagonal drags don't need to cross the
717
+ // threshold on either axis individually.
718
+ if (Math.hypot(dx, dy) >= threshold) {
719
+ activated = true;
720
+ setArmedId(null);
721
+ // Snapshot scroll at activate-time. startPointer is stored as
722
+ // viewport coords (for source-element transform deltas);
723
+ // scrollAtActivate carries the activate-time scroll separately
724
+ // so hit-test can compute content-frame pointer at any later
725
+ // time as `clientX + getScroll().x` (R7 live compensation).
726
+ const scroll = getScroll(getScrollContainer());
727
+ activate(
728
+ id,
729
+ sourceIndex,
730
+ ids,
731
+ { x: ev.clientX, y: ev.clientY },
732
+ { x: scroll.x, y: scroll.y },
733
+ );
734
+ }
735
+ return;
736
+ }
737
+ updateDrag(ev);
738
+ };
739
+
740
+ const onUp = (upEvent: PointerEvent) => {
741
+ if (upEvent.button !== 0) return;
742
+ release();
743
+ if (activated) commitDrag();
744
+ };
745
+
746
+ // The browser took the pointer (e.g. to scroll): drop the press and any drag.
747
+ const onPointerCancel = () => {
748
+ release();
749
+ if (activated) cancelDrag();
750
+ };
751
+
752
+ document.addEventListener('pointermove', onMove);
753
+ document.addEventListener('pointerup', onUp);
754
+ document.addEventListener('pointercancel', onPointerCancel);
755
+ pointerCleanup = () => {
756
+ hold.stop();
757
+ setArmedId(null);
758
+ document.removeEventListener('pointermove', onMove);
759
+ document.removeEventListener('pointerup', onUp);
760
+ document.removeEventListener('pointercancel', onPointerCancel);
761
+ };
762
+ }
763
+
764
+ // ── Cleanup ─────────────────────────────────────────────────────────────
765
+
766
+ // Guard: only register onCleanup if running inside a SolidJS reactive owner.
767
+ // Makes the primitive safe to use in tests or imperative code outside a
768
+ // component tree. When used inside a component, cleanup fires on unmount.
769
+ if (getOwner()) {
770
+ onCleanup(() => {
771
+ if (drag) cancelDrag();
772
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
773
+ nodes.clear();
774
+ disposeRoot?.();
775
+ });
776
+ }
777
+
778
+ // ── Public API ──────────────────────────────────────────────────────────
779
+
780
+ return {
781
+ /** Spread onto each reorderable item element. */
782
+ itemProps: (id: string) => ({
783
+ ref: (el: HTMLElement) => { nodes.set(id, el); },
784
+ onPointerDown: (e: PointerEvent) => onPointerDown(id, e),
785
+ classList: { [getActiveClass()]: activeId() === id, [getArmedClass()]: armedId() === id },
786
+ 'data-reorder-id': id,
787
+ }),
788
+
789
+ /** Whether the given item is currently being dragged. */
790
+ isActive: (id: string) => activeId() === id,
791
+
792
+ /** Whether any item is currently being dragged. */
793
+ isDragging: () => activeId() !== null,
794
+
795
+ /** The ID of the item currently being dragged, or null. */
796
+ activeId,
797
+
798
+ /** The current drop target index, or -1 if not dragging. */
799
+ targetIndex: targetIdx,
800
+
801
+ /** The ID of the item whose touch hold has completed, or null. */
802
+ armedId,
803
+
804
+ /** Abort an in-progress drag without firing onReorder.
805
+ * Idempotent no-op when no drag is active. (R13a)
806
+ *
807
+ * Consumers invalidate the engine's snapshot via this method when
808
+ * cross-surface mutations make the captured indices stale (id-list
809
+ * shape change, popover dismiss during drag, parent unmount). */
810
+ cancel: () => {
811
+ if (drag) cancelDrag();
812
+ },
813
+
814
+ /** Manually dispose the isolated reactive root. Call this if you
815
+ * created the primitive outside a SolidJS owner scope and need
816
+ * deterministic cleanup. */
817
+ dispose: () => {
818
+ if (drag) cancelDrag();
819
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
820
+ nodes.clear();
821
+ disposeRoot?.();
822
+ },
823
+ };
824
+ }