@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,442 +1,489 @@
1
- /**
2
- * createReorderList — generic drag-to-reorder primitive for SolidJS.
3
- *
4
- * Handles variable-height items, single-axis movement, and smooth CSS
5
- * transition reflow. Zero external dependencies beyond solid-js.
6
- * Works with any element type — spread `itemProps(id)` onto each
7
- * sortable item.
8
- *
9
- * Collision model (edge-overlap):
10
- * - Dragged card follows the pointer via transform.
11
- * - Swap triggers when the dragged card's leading edge overlaps a
12
- * neighbor past a split threshold (40% forward, 70% reverse).
13
- * - After a swap, effective positions shift by half the dragged size,
14
- * creating a reduced dead zone that allows easy reversal.
15
- * - Displaced cards animate via CSS transition ("pop" reflow).
16
- */
17
-
18
- import { createSignal, createRoot, onCleanup, getOwner } from 'solid-js';
19
- import { DEFAULT_SKIP_SELECTOR, blockNextClick, createCancelListeners } from './shared';
20
-
21
- export { DEFAULT_SKIP_SELECTOR };
22
-
23
- // ── Types ──────────────────────────────────────────────────────────────────
24
-
25
- export interface ReorderListOptions {
26
- /** Reactive list of IDs in current order */
27
- ids: () => string[];
28
- /** Called on drop with original and target indices */
29
- onReorder: (fromIndex: number, toIndex: number) => void;
30
- /** Drag axis — 'y' (default) or 'x' */
31
- axis?: 'x' | 'y';
32
- /** Pixels of movement before drag activates (default: 5) */
33
- activateDistance?: number;
34
- /** Duration of displacement transition in ms (default: 200) */
35
- transitionMs?: number;
36
- /** CSS class applied to the active (dragged) item (default: 'reorder-active') */
37
- activeClass?: string;
38
- /** Scale factor for the dragged item's visual "lift" (default: 0.97).
39
- * Set to 1.0 for no scale effect. */
40
- dragScale?: number;
41
- /** Whether to call stopPropagation on pointerdown. Set to false to allow
42
- * pointer events to reach parent elements. (default: true) */
43
- stopPropagation?: boolean;
44
- /** CSS selector matched via `closest()` from the pointerdown target.
45
- * When the selector matches, drag activation is skipped — useful for
46
- * guarding interactive children (default behaviour) but configurable
47
- * for cases where the draggable item itself has interactive
48
- * semantics (e.g. a `<div role="button">` that IS the draggable).
49
- * Defaults to {@link DEFAULT_SKIP_SELECTOR}. Set to an empty string
50
- * to disable the skip entirely. */
51
- skipSelector?: string;
52
- }
53
-
54
- interface CachedRect {
55
- start: number; // top (y) or left (x)
56
- size: number; // height or width
57
- end: number; // start + size
58
- }
59
-
60
- interface DragState {
61
- id: string;
62
- sourceIndex: number;
63
- startPointer: number;
64
- rects: CachedRect[]; // original positions, immutable during drag
65
- effectiveStarts: number[]; // mutable — updated after each swap for anti-jitter
66
- draggedSize: number;
67
- currentTarget: number;
68
- ids: string[];
69
- }
70
-
71
- // ── Primitive ──────────────────────────────────────────────────────────────
72
-
73
- export function createReorderList(options: ReorderListOptions) {
74
- const getAxis = () => options.axis ?? 'y';
75
- // Pixels of pointer movement required before drag activates.
76
- // Prevents accidental drag on click (normal mouse jitter is 1-3px).
77
- const getActivateDistance = () => options.activateDistance ?? 5;
78
- const getTransitionMs = () => options.transitionMs ?? 200;
79
- const getActiveClass = () => options.activeClass ?? 'reorder-active';
80
-
81
- // Scale factor applied to the dragged item for visual "lift" effect.
82
- // 0.97 = 3% shrink. Set to 1.0 for no scale. Consumers can override.
83
- const DRAG_SCALE = options.dragScale ?? 0.97;
84
- const getStopPropagation = () => options.stopPropagation ?? true;
85
- const getSkipSelector = () => options.skipSelector ?? DEFAULT_SKIP_SELECTOR;
86
-
87
- // Registered elements keyed by ID
88
- const nodes = new Map<string, HTMLElement>();
89
-
90
- // Reactive signals in an isolated root — immune to parent scope disposal.
91
- // Without createRoot, SolidJS can dispose these signals (and fire onCleanup)
92
- // when the parent component's reactive graph re-evaluates during a drag,
93
- // killing the active drag mid-flight.
94
- let disposeRoot: (() => void) | undefined;
95
- const { activeId, setActiveId, targetIdx, setTargetIdx } = createRoot((dispose) => {
96
- disposeRoot = dispose;
97
- const [activeId, setActiveId] = createSignal<string | null>(null);
98
- const [targetIdx, setTargetIdx] = createSignal<number>(-1);
99
- return { activeId, setActiveId, targetIdx, setTargetIdx };
100
- });
101
-
102
- // Stored so cancel handlers can clean up pointer listeners from onPointerDown
103
- let pointerCleanup: (() => void) | null = null;
104
-
105
- // Non-reactive drag state — mutated in pointermove for performance
106
- let drag: DragState | null = null;
107
-
108
- // rAF handle for batching dragged item transform updates
109
- let dragRaf: number = 0;
110
-
111
- // ── Helpers ────────────────────────────────────────────────────────────
112
-
113
- const ptr = (e: PointerEvent) => getAxis() === 'y' ? e.clientY : e.clientX;
114
- const tx = (px: number) =>
115
- getAxis() === 'y' ? `translateY(${px}px)` : `translateX(${px}px)`;
116
-
117
- /** Measure one element into a CachedRect along the active axis */
118
- function measure(el: HTMLElement): CachedRect {
119
- const r = el.getBoundingClientRect();
120
- const start = getAxis() === 'y' ? r.top : r.left;
121
- const size = getAxis() === 'y' ? r.height : r.width;
122
- return { start, size, end: start + size };
123
- }
124
-
125
- /**
126
- * Edge-overlap target calculation.
127
- *
128
- * For each non-source item, compute how much the dragged card's leading
129
- * edge overlaps it. Uses split thresholds: 40% for forward swaps (stable),
130
- * 70% for reversals (easy undo). effectiveStarts shift by half the dragged
131
- * size after swaps, creating a moderate dead zone for anti-jitter.
132
- *
133
- * Returns sourceIndex + belowCount - aboveCount, since each overlapped
134
- * item below pushes the target forward and each above pulls it back.
135
- */
136
- function calcTarget(
137
- draggedStart: number,
138
- draggedEnd: number,
139
- sourceIndex: number,
140
- state: DragState,
141
- ): number {
142
- const { rects, effectiveStarts, draggedSize, currentTarget } = state;
143
- let belowCount = 0;
144
- let aboveCount = 0;
145
-
146
- for (let i = 0; i < rects.length; i++) {
147
- if (i === sourceIndex) continue;
148
-
149
- const targetSize = rects[i].size;
150
- const effectiveStart = effectiveStarts[i];
151
- const effectiveEnd = effectiveStart + targetSize;
152
-
153
- // Split threshold: displaced items use a HIGH threshold (easy to release),
154
- // non-displaced items use a LOW threshold (stable forward movement).
155
- const isDisplaced = (i > sourceIndex && i <= currentTarget)
156
- || (i < sourceIndex && i >= currentTarget);
157
- const pct = isDisplaced ? 0.70 : 0.40;
158
- const overlapThreshold = Math.min(draggedSize, targetSize) * pct;
159
-
160
- if (i > sourceIndex) {
161
- const overlap = draggedEnd - effectiveStart;
162
- if (overlap > overlapThreshold) belowCount++;
163
- } else {
164
- const overlap = effectiveEnd - draggedStart;
165
- if (overlap > overlapThreshold) aboveCount++;
166
- }
167
- }
168
-
169
- return sourceIndex + belowCount - aboveCount;
170
- }
171
-
172
- /**
173
- * After the target changes, update effectiveStarts to create the anti-jitter
174
- * dead zone. Uses half of draggedSize (decoupled from visual displacement)
175
- * so reversals are easy while forward movement stays stable.
176
- */
177
- function updateEffectivePositions(state: DragState) {
178
- const { rects, sourceIndex, currentTarget, draggedSize, effectiveStarts } = state;
179
- const halfShift = draggedSize * 0.5;
180
-
181
- for (let i = 0; i < rects.length; i++) {
182
- if (i === sourceIndex) {
183
- effectiveStarts[i] = rects[i].start;
184
- continue;
185
- }
186
-
187
- if (currentTarget > sourceIndex && i > sourceIndex && i <= currentTarget) {
188
- effectiveStarts[i] = rects[i].start - halfShift;
189
- } else if (currentTarget < sourceIndex && i >= currentTarget && i < sourceIndex) {
190
- effectiveStarts[i] = rects[i].start + halfShift;
191
- } else {
192
- effectiveStarts[i] = rects[i].start;
193
- }
194
- }
195
- }
196
-
197
- // ── Drag lifecycle ─────────────────────────────────────────────────────
198
-
199
- function activate(id: string, sourceIndex: number, ids: string[], startPointer: number) {
200
- // Prune stale entries — items removed from the list since last drag
201
- const idSet = new Set(ids);
202
- for (const key of nodes.keys()) {
203
- if (!idSet.has(key)) nodes.delete(key);
204
- }
205
-
206
- // Snapshot all rects at drag start (measured once, cached for duration)
207
- const rects: CachedRect[] = ids.map(itemId => {
208
- const el = nodes.get(itemId);
209
- return el ? measure(el) : { start: 0, size: 0, end: 0 };
210
- });
211
-
212
- const effectiveStarts = rects.map(r => r.start);
213
-
214
- drag = {
215
- id,
216
- sourceIndex,
217
- startPointer,
218
- rects,
219
- effectiveStarts,
220
- draggedSize: rects[sourceIndex].size,
221
- currentTarget: sourceIndex,
222
- ids,
223
- };
224
-
225
- setActiveId(id);
226
- setTargetIdx(sourceIndex);
227
-
228
- // Style: dragged item gets instant scale lift,
229
- // all others get smooth transition for displacement animation.
230
- const ms = getTransitionMs();
231
- for (const itemId of ids) {
232
- const el = nodes.get(itemId);
233
- if (!el) continue;
234
- if (itemId === id) {
235
- el.style.willChange = 'transform';
236
- el.style.transition = 'none';
237
- el.style.zIndex = '50';
238
- el.style.position = 'relative';
239
- el.style.transform = `scale(${DRAG_SCALE})`;
240
- } else {
241
- el.style.willChange = 'transform';
242
- el.style.transition = `transform ${ms}ms ease`;
243
- el.style.pointerEvents = 'none';
244
- }
245
- }
246
-
247
- document.body.style.cursor = 'grabbing';
248
- cancel.add();
249
- }
250
-
251
- function updateDrag(pointerPos: number) {
252
- if (!drag) return;
253
- const { sourceIndex, startPointer, rects, ids } = drag;
254
- const delta = pointerPos - startPointer;
255
-
256
- // Move dragged item — batched to one DOM write per frame
257
- const draggedEl = nodes.get(ids[sourceIndex]);
258
- if (draggedEl) {
259
- if (dragRaf) cancelAnimationFrame(dragRaf);
260
- dragRaf = requestAnimationFrame(() => {
261
- draggedEl.style.transform = `${tx(delta)} scale(${DRAG_SCALE})`;
262
- dragRaf = 0;
263
- });
264
- }
265
-
266
- // Dragged card's current edges
267
- const draggedStart = rects[sourceIndex].start + delta;
268
- const draggedEnd = draggedStart + rects[sourceIndex].size;
269
-
270
- const prevTarget = drag.currentTarget;
271
- const targetIndex = calcTarget(draggedStart, draggedEnd, sourceIndex, drag);
272
- drag.currentTarget = targetIndex;
273
-
274
- // Only update displacement transforms when the target actually changes
275
- if (targetIndex !== prevTarget) {
276
- updateEffectivePositions(drag);
277
- setTargetIdx(targetIndex);
278
-
279
- const { draggedSize } = drag;
280
- for (let i = 0; i < ids.length; i++) {
281
- if (i === sourceIndex) continue;
282
- const el = nodes.get(ids[i]);
283
- if (!el) continue;
284
-
285
- let shift = 0;
286
- if (targetIndex > sourceIndex && i > sourceIndex && i <= targetIndex) {
287
- shift = -draggedSize;
288
- } else if (targetIndex < sourceIndex && i >= targetIndex && i < sourceIndex) {
289
- shift = draggedSize;
290
- }
291
-
292
- el.style.transform = shift !== 0 ? tx(shift) : '';
293
- }
294
- }
295
- }
296
-
297
- /** Commit the drag — clear styles, block post-drag click, fire onReorder. */
298
- function commitDrag() {
299
- if (!drag) return;
300
- if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
301
- const { sourceIndex, currentTarget } = drag;
302
-
303
- cancel.remove();
304
- setActiveId(null);
305
- setTargetIdx(-1);
306
- clearDragStyles();
307
- blockNextClick();
308
-
309
- const from = sourceIndex;
310
- const to = currentTarget;
311
- drag = null;
312
- if (from !== to) options.onReorder(from, to);
313
- }
314
-
315
- /** Cancel the drag — clear styles, don't commit reorder. */
316
- function cancelDrag() {
317
- if (!drag) return;
318
- if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
319
- cancel.remove();
320
- setActiveId(null);
321
- setTargetIdx(-1);
322
- clearDragStyles();
323
- drag = null;
324
- }
325
-
326
- // ── Cancellation handlers ──────────────────────────────────────────────
327
-
328
- const cancel = createCancelListeners({ onCancel: cancelDrag });
329
-
330
- function clearDragStyles() {
331
- if (dragRaf) { cancelAnimationFrame(dragRaf); dragRaf = 0; }
332
-
333
- const targets = drag?.ids
334
- ? drag.ids.map(id => nodes.get(id)).filter((el): el is HTMLElement => !!el)
335
- : [...nodes.values()];
336
- for (const el of targets) {
337
- el.style.transform = '';
338
- el.style.transition = '';
339
- el.style.zIndex = '';
340
- el.style.position = '';
341
- el.style.willChange = '';
342
- el.style.pointerEvents = '';
343
- }
344
- document.body.style.cursor = '';
345
- }
346
-
347
- // ── Pointer event wiring ───────────────────────────────────────────────
348
-
349
- function onPointerDown(id: string, e: PointerEvent) {
350
- if (e.button !== 0) return;
351
- if (drag) return;
352
-
353
- // Don't start drag on interactive children (buttons, inputs, links).
354
- // Without this, clicking a button and moving 5px activates a drag
355
- // instead of the button's click handler — especially problematic for
356
- // delete buttons and trailing-column controls. Selector is
357
- // configurable via `skipSelector`; pass an empty string to disable.
358
- const skip = getSkipSelector();
359
- if (skip && (e.target as HTMLElement).closest(skip)) return;
360
-
361
- if (getStopPropagation()) e.stopPropagation();
362
-
363
- const ids = options.ids();
364
- const sourceIndex = ids.indexOf(id);
365
- if (sourceIndex === -1) return;
366
-
367
- const start = ptr(e);
368
- const threshold = getActivateDistance();
369
- let activated = false;
370
-
371
- const onMove = (ev: PointerEvent) => {
372
- if (!activated) {
373
- const distance = Math.abs(ptr(ev) - start);
374
- if (distance >= threshold) {
375
- activated = true;
376
- activate(id, sourceIndex, ids, ptr(ev));
377
- }
378
- return;
379
- }
380
- updateDrag(ptr(ev));
381
- };
382
-
383
- const onUp = (upEvent: PointerEvent) => {
384
- if (upEvent.button !== 0) return;
385
- if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
386
- if (activated) commitDrag();
387
- };
388
-
389
- document.addEventListener('pointermove', onMove);
390
- document.addEventListener('pointerup', onUp);
391
- pointerCleanup = () => {
392
- document.removeEventListener('pointermove', onMove);
393
- document.removeEventListener('pointerup', onUp);
394
- };
395
- }
396
-
397
- // ── Cleanup ────────────────────────────────────────────────────────────
398
-
399
- // Guard: only register onCleanup if running inside a SolidJS reactive owner.
400
- // This makes the primitive safe to use in tests or imperative code outside
401
- // a component tree. When used inside a component, cleanup fires automatically
402
- // on unmount.
403
- if (getOwner()) {
404
- onCleanup(() => {
405
- if (drag) cancelDrag();
406
- nodes.clear();
407
- disposeRoot?.();
408
- });
409
- }
410
-
411
- // ── Public API ─────────────────────────────────────────────────────────
412
-
413
- return {
414
- /** Spread onto each reorderable item element */
415
- itemProps: (id: string) => ({
416
- ref: (el: HTMLElement) => { nodes.set(id, el); },
417
- onPointerDown: (e: PointerEvent) => onPointerDown(id, e),
418
- classList: { [getActiveClass()]: activeId() === id },
419
- 'data-reorder-id': id,
420
- }),
421
-
422
- /** Whether the given item is currently being dragged */
423
- isActive: (id: string) => activeId() === id,
424
-
425
- /** Whether any item is currently being dragged */
426
- isDragging: () => activeId() !== null,
427
-
428
- /** The ID of the item currently being dragged, or null */
429
- activeId,
430
-
431
- /** The current drop target index, or -1 if not dragging */
432
- targetIndex: targetIdx,
433
-
434
- /** Manually dispose the isolated reactive root. Call this if you created
435
- * the primitive outside a SolidJS owner scope and need deterministic cleanup. */
436
- dispose: () => {
437
- if (drag) cancelDrag();
438
- nodes.clear();
439
- disposeRoot?.();
440
- },
441
- };
442
- }
1
+ /**
2
+ * createReorderList — generic drag-to-reorder primitive for SolidJS.
3
+ *
4
+ * Handles variable-height items, single-axis movement, and smooth CSS
5
+ * transition reflow. Zero external dependencies beyond solid-js.
6
+ * Works with any element type — spread `itemProps(id)` onto each
7
+ * sortable item.
8
+ *
9
+ * Collision model (edge-overlap):
10
+ * - Dragged card follows the pointer via transform.
11
+ * - Swap triggers when the dragged card's leading edge overlaps a
12
+ * neighbor past a split threshold (40% forward, 70% reverse).
13
+ * - After a swap, effective positions shift by half the dragged size,
14
+ * creating a reduced dead zone that allows easy reversal.
15
+ * - Displaced cards animate via CSS transition ("pop" reflow).
16
+ */
17
+
18
+ import { createSignal, createRoot, onCleanup, getOwner } from 'solid-js';
19
+ import {
20
+ DEFAULT_ARMED_CLASS, DEFAULT_SKIP_SELECTOR, DEFAULT_TOUCH_HOLD_MS, DEFAULT_TOUCH_HOLD_TOLERANCE,
21
+ blockNextClick, createCancelListeners, startPressHold,
22
+ } from './shared';
23
+
24
+ export { DEFAULT_SKIP_SELECTOR };
25
+
26
+ // ── Types ──────────────────────────────────────────────────────────────────
27
+
28
+ export interface ReorderListOptions {
29
+ /** Reactive list of IDs in current order */
30
+ ids: () => string[];
31
+ /** Called on drop with original and target indices */
32
+ onReorder: (fromIndex: number, toIndex: number) => void;
33
+ /** Drag axis — 'y' (default) or 'x' */
34
+ axis?: 'x' | 'y';
35
+ /** Pixels of movement before drag activates (default: 5) */
36
+ activateDistance?: number;
37
+ /** Duration of displacement transition in ms (default: 200) */
38
+ transitionMs?: number;
39
+ /** CSS class applied to the active (dragged) item (default: 'reorder-active') */
40
+ activeClass?: string;
41
+ /** Scale factor for the dragged item's visual "lift" (default: 0.97).
42
+ * Set to 1.0 for no scale effect. */
43
+ dragScale?: number;
44
+ /** Whether to call stopPropagation on pointerdown. Set to false to allow
45
+ * pointer events to reach parent elements. (default: true) */
46
+ stopPropagation?: boolean;
47
+ /** CSS selector matched via `closest()` from the pointerdown target.
48
+ * When the selector matches, drag activation is skipped — useful for
49
+ * guarding interactive children (default behaviour) but configurable
50
+ * for cases where the draggable item itself has interactive
51
+ * semantics (e.g. a `<div role="button">` that IS the draggable).
52
+ * Defaults to {@link DEFAULT_SKIP_SELECTOR}. Set to an empty string
53
+ * to disable the skip entirely. */
54
+ skipSelector?: string;
55
+ /** Milliseconds a touch or pen press must be held before it can drag
56
+ * (default: 200). Stops a finger flick from grabbing an item. Moving more
57
+ * than `touchHoldTolerance` or lifting during the hold gives the press up.
58
+ * A mouse never waits. Set to 0 to turn the hold off. */
59
+ touchHoldMs?: number;
60
+ /** Pixels a press may wander during the hold (default: 10). */
61
+ touchHoldTolerance?: number;
62
+ /** CSS class on an item whose hold has completed, until it is dragged or
63
+ * let go (default: 'reorder-armed'). Use it to show the item is ready. */
64
+ armedClass?: string;
65
+ }
66
+
67
+ interface CachedRect {
68
+ start: number; // top (y) or left (x)
69
+ size: number; // height or width
70
+ end: number; // start + size
71
+ }
72
+
73
+ interface DragState {
74
+ id: string;
75
+ sourceIndex: number;
76
+ startPointer: number;
77
+ rects: CachedRect[]; // original positions, immutable during drag
78
+ effectiveStarts: number[]; // mutable — updated after each swap for anti-jitter
79
+ draggedSize: number;
80
+ currentTarget: number;
81
+ ids: string[];
82
+ }
83
+
84
+ // ── Primitive ──────────────────────────────────────────────────────────────
85
+
86
+ export function createReorderList(options: ReorderListOptions) {
87
+ const getAxis = () => options.axis ?? 'y';
88
+ // Pixels of pointer movement required before drag activates.
89
+ // Prevents accidental drag on click (normal mouse jitter is 1-3px).
90
+ const getActivateDistance = () => options.activateDistance ?? 5;
91
+ const getTransitionMs = () => options.transitionMs ?? 200;
92
+ const getActiveClass = () => options.activeClass ?? 'reorder-active';
93
+
94
+ // Scale factor applied to the dragged item for visual "lift" effect.
95
+ // 0.97 = 3% shrink. Set to 1.0 for no scale. Consumers can override.
96
+ const DRAG_SCALE = options.dragScale ?? 0.97;
97
+ const getStopPropagation = () => options.stopPropagation ?? true;
98
+ const getSkipSelector = () => options.skipSelector ?? DEFAULT_SKIP_SELECTOR;
99
+ const getTouchHoldMs = () => options.touchHoldMs ?? DEFAULT_TOUCH_HOLD_MS;
100
+ const getTouchHoldTolerance = () => options.touchHoldTolerance ?? DEFAULT_TOUCH_HOLD_TOLERANCE;
101
+ const getArmedClass = () => options.armedClass ?? DEFAULT_ARMED_CLASS;
102
+
103
+ // Registered elements keyed by ID
104
+ const nodes = new Map<string, HTMLElement>();
105
+
106
+ // Reactive signals in an isolated root — immune to parent scope disposal.
107
+ // Without createRoot, SolidJS can dispose these signals (and fire onCleanup)
108
+ // when the parent component's reactive graph re-evaluates during a drag,
109
+ // killing the active drag mid-flight.
110
+ let disposeRoot: (() => void) | undefined;
111
+ const { activeId, setActiveId, targetIdx, setTargetIdx, armedId, setArmedId } = createRoot((dispose) => {
112
+ disposeRoot = dispose;
113
+ const [activeId, setActiveId] = createSignal<string | null>(null);
114
+ const [targetIdx, setTargetIdx] = createSignal<number>(-1);
115
+ const [armedId, setArmedId] = createSignal<string | null>(null);
116
+ return { activeId, setActiveId, targetIdx, setTargetIdx, armedId, setArmedId };
117
+ });
118
+
119
+ // Stored so cancel handlers can clean up pointer listeners from onPointerDown
120
+ let pointerCleanup: (() => void) | null = null;
121
+
122
+ // Non-reactive drag state — mutated in pointermove for performance
123
+ let drag: DragState | null = null;
124
+
125
+ // rAF handle for batching dragged item transform updates
126
+ let dragRaf: number = 0;
127
+
128
+ // ── Helpers ────────────────────────────────────────────────────────────
129
+
130
+ const ptr = (e: PointerEvent) => getAxis() === 'y' ? e.clientY : e.clientX;
131
+ const tx = (px: number) =>
132
+ getAxis() === 'y' ? `translateY(${px}px)` : `translateX(${px}px)`;
133
+
134
+ /** Measure one element into a CachedRect along the active axis */
135
+ function measure(el: HTMLElement): CachedRect {
136
+ const r = el.getBoundingClientRect();
137
+ const start = getAxis() === 'y' ? r.top : r.left;
138
+ const size = getAxis() === 'y' ? r.height : r.width;
139
+ return { start, size, end: start + size };
140
+ }
141
+
142
+ /**
143
+ * Edge-overlap target calculation.
144
+ *
145
+ * For each non-source item, compute how much the dragged card's leading
146
+ * edge overlaps it. Uses split thresholds: 40% for forward swaps (stable),
147
+ * 70% for reversals (easy undo). effectiveStarts shift by half the dragged
148
+ * size after swaps, creating a moderate dead zone for anti-jitter.
149
+ *
150
+ * Returns sourceIndex + belowCount - aboveCount, since each overlapped
151
+ * item below pushes the target forward and each above pulls it back.
152
+ */
153
+ function calcTarget(
154
+ draggedStart: number,
155
+ draggedEnd: number,
156
+ sourceIndex: number,
157
+ state: DragState,
158
+ ): number {
159
+ const { rects, effectiveStarts, draggedSize, currentTarget } = state;
160
+ let belowCount = 0;
161
+ let aboveCount = 0;
162
+
163
+ for (let i = 0; i < rects.length; i++) {
164
+ if (i === sourceIndex) continue;
165
+
166
+ const targetSize = rects[i].size;
167
+ const effectiveStart = effectiveStarts[i];
168
+ const effectiveEnd = effectiveStart + targetSize;
169
+
170
+ // Split threshold: displaced items use a HIGH threshold (easy to release),
171
+ // non-displaced items use a LOW threshold (stable forward movement).
172
+ const isDisplaced = (i > sourceIndex && i <= currentTarget)
173
+ || (i < sourceIndex && i >= currentTarget);
174
+ const pct = isDisplaced ? 0.70 : 0.40;
175
+ const overlapThreshold = Math.min(draggedSize, targetSize) * pct;
176
+
177
+ if (i > sourceIndex) {
178
+ const overlap = draggedEnd - effectiveStart;
179
+ if (overlap > overlapThreshold) belowCount++;
180
+ } else {
181
+ const overlap = effectiveEnd - draggedStart;
182
+ if (overlap > overlapThreshold) aboveCount++;
183
+ }
184
+ }
185
+
186
+ return sourceIndex + belowCount - aboveCount;
187
+ }
188
+
189
+ /**
190
+ * After the target changes, update effectiveStarts to create the anti-jitter
191
+ * dead zone. Uses half of draggedSize (decoupled from visual displacement)
192
+ * so reversals are easy while forward movement stays stable.
193
+ */
194
+ function updateEffectivePositions(state: DragState) {
195
+ const { rects, sourceIndex, currentTarget, draggedSize, effectiveStarts } = state;
196
+ const halfShift = draggedSize * 0.5;
197
+
198
+ for (let i = 0; i < rects.length; i++) {
199
+ if (i === sourceIndex) {
200
+ effectiveStarts[i] = rects[i].start;
201
+ continue;
202
+ }
203
+
204
+ if (currentTarget > sourceIndex && i > sourceIndex && i <= currentTarget) {
205
+ effectiveStarts[i] = rects[i].start - halfShift;
206
+ } else if (currentTarget < sourceIndex && i >= currentTarget && i < sourceIndex) {
207
+ effectiveStarts[i] = rects[i].start + halfShift;
208
+ } else {
209
+ effectiveStarts[i] = rects[i].start;
210
+ }
211
+ }
212
+ }
213
+
214
+ // ── Drag lifecycle ─────────────────────────────────────────────────────
215
+
216
+ function activate(id: string, sourceIndex: number, ids: string[], startPointer: number) {
217
+ // Prune stale entries — items removed from the list since last drag
218
+ const idSet = new Set(ids);
219
+ for (const key of nodes.keys()) {
220
+ if (!idSet.has(key)) nodes.delete(key);
221
+ }
222
+
223
+ // Snapshot all rects at drag start (measured once, cached for duration)
224
+ const rects: CachedRect[] = ids.map(itemId => {
225
+ const el = nodes.get(itemId);
226
+ return el ? measure(el) : { start: 0, size: 0, end: 0 };
227
+ });
228
+
229
+ const effectiveStarts = rects.map(r => r.start);
230
+
231
+ drag = {
232
+ id,
233
+ sourceIndex,
234
+ startPointer,
235
+ rects,
236
+ effectiveStarts,
237
+ draggedSize: rects[sourceIndex].size,
238
+ currentTarget: sourceIndex,
239
+ ids,
240
+ };
241
+
242
+ setActiveId(id);
243
+ setTargetIdx(sourceIndex);
244
+
245
+ // Style: dragged item gets instant scale lift,
246
+ // all others get smooth transition for displacement animation.
247
+ const ms = getTransitionMs();
248
+ for (const itemId of ids) {
249
+ const el = nodes.get(itemId);
250
+ if (!el) continue;
251
+ if (itemId === id) {
252
+ el.style.willChange = 'transform';
253
+ el.style.transition = 'none';
254
+ el.style.zIndex = '50';
255
+ el.style.position = 'relative';
256
+ el.style.transform = `scale(${DRAG_SCALE})`;
257
+ } else {
258
+ el.style.willChange = 'transform';
259
+ el.style.transition = `transform ${ms}ms ease`;
260
+ el.style.pointerEvents = 'none';
261
+ }
262
+ }
263
+
264
+ document.body.style.cursor = 'grabbing';
265
+ cancel.add();
266
+ }
267
+
268
+ function updateDrag(pointerPos: number) {
269
+ if (!drag) return;
270
+ const { sourceIndex, startPointer, rects, ids } = drag;
271
+ const delta = pointerPos - startPointer;
272
+
273
+ // Move dragged item — batched to one DOM write per frame
274
+ const draggedEl = nodes.get(ids[sourceIndex]);
275
+ if (draggedEl) {
276
+ if (dragRaf) cancelAnimationFrame(dragRaf);
277
+ dragRaf = requestAnimationFrame(() => {
278
+ draggedEl.style.transform = `${tx(delta)} scale(${DRAG_SCALE})`;
279
+ dragRaf = 0;
280
+ });
281
+ }
282
+
283
+ // Dragged card's current edges
284
+ const draggedStart = rects[sourceIndex].start + delta;
285
+ const draggedEnd = draggedStart + rects[sourceIndex].size;
286
+
287
+ const prevTarget = drag.currentTarget;
288
+ const targetIndex = calcTarget(draggedStart, draggedEnd, sourceIndex, drag);
289
+ drag.currentTarget = targetIndex;
290
+
291
+ // Only update displacement transforms when the target actually changes
292
+ if (targetIndex !== prevTarget) {
293
+ updateEffectivePositions(drag);
294
+ setTargetIdx(targetIndex);
295
+
296
+ const { draggedSize } = drag;
297
+ for (let i = 0; i < ids.length; i++) {
298
+ if (i === sourceIndex) continue;
299
+ const el = nodes.get(ids[i]);
300
+ if (!el) continue;
301
+
302
+ let shift = 0;
303
+ if (targetIndex > sourceIndex && i > sourceIndex && i <= targetIndex) {
304
+ shift = -draggedSize;
305
+ } else if (targetIndex < sourceIndex && i >= targetIndex && i < sourceIndex) {
306
+ shift = draggedSize;
307
+ }
308
+
309
+ el.style.transform = shift !== 0 ? tx(shift) : '';
310
+ }
311
+ }
312
+ }
313
+
314
+ /** Commit the drag — clear styles, block post-drag click, fire onReorder. */
315
+ function commitDrag() {
316
+ if (!drag) return;
317
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
318
+ const { sourceIndex, currentTarget } = drag;
319
+
320
+ cancel.remove();
321
+ setActiveId(null);
322
+ setTargetIdx(-1);
323
+ clearDragStyles();
324
+ blockNextClick();
325
+
326
+ const from = sourceIndex;
327
+ const to = currentTarget;
328
+ drag = null;
329
+ if (from !== to) options.onReorder(from, to);
330
+ }
331
+
332
+ /** Cancel the drag — clear styles, don't commit reorder. */
333
+ function cancelDrag() {
334
+ if (!drag) return;
335
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
336
+ cancel.remove();
337
+ setActiveId(null);
338
+ setTargetIdx(-1);
339
+ clearDragStyles();
340
+ drag = null;
341
+ }
342
+
343
+ // ── Cancellation handlers ──────────────────────────────────────────────
344
+
345
+ const cancel = createCancelListeners({ onCancel: cancelDrag });
346
+
347
+ function clearDragStyles() {
348
+ if (dragRaf) { cancelAnimationFrame(dragRaf); dragRaf = 0; }
349
+
350
+ const targets = drag?.ids
351
+ ? drag.ids.map(id => nodes.get(id)).filter((el): el is HTMLElement => !!el)
352
+ : [...nodes.values()];
353
+ for (const el of targets) {
354
+ el.style.transform = '';
355
+ el.style.transition = '';
356
+ el.style.zIndex = '';
357
+ el.style.position = '';
358
+ el.style.willChange = '';
359
+ el.style.pointerEvents = '';
360
+ }
361
+ document.body.style.cursor = '';
362
+ }
363
+
364
+ // ── Pointer event wiring ───────────────────────────────────────────────
365
+
366
+ function onPointerDown(id: string, e: PointerEvent) {
367
+ if (e.button !== 0) return;
368
+ if (drag) return;
369
+
370
+ // Don't start drag on interactive children (buttons, inputs, links).
371
+ // Without this, clicking a button and moving 5px activates a drag
372
+ // instead of the button's click handler — especially problematic for
373
+ // delete buttons and trailing-column controls. Selector is
374
+ // configurable via `skipSelector`; pass an empty string to disable.
375
+ const skip = getSkipSelector();
376
+ if (skip && (e.target as HTMLElement).closest(skip)) return;
377
+
378
+ if (getStopPropagation()) e.stopPropagation();
379
+
380
+ const ids = options.ids();
381
+ const sourceIndex = ids.indexOf(id);
382
+ if (sourceIndex === -1) return;
383
+
384
+ // A new press replaces one still waiting (e.g. a second finger during a hold).
385
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
386
+
387
+ const start = ptr(e);
388
+ const threshold = getActivateDistance();
389
+ let activated = false;
390
+ const hold = startPressHold(e, {
391
+ ms: getTouchHoldMs(),
392
+ tolerance: getTouchHoldTolerance(),
393
+ onHeld: () => setArmedId(id),
394
+ });
395
+
396
+ const release = () => { if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; } };
397
+
398
+ const onMove = (ev: PointerEvent) => {
399
+ if (!activated) {
400
+ if (!hold.held) {
401
+ if (!hold.move(ev)) release();
402
+ return;
403
+ }
404
+ const distance = Math.abs(ptr(ev) - start);
405
+ if (distance >= threshold) {
406
+ activated = true;
407
+ setArmedId(null);
408
+ activate(id, sourceIndex, ids, ptr(ev));
409
+ }
410
+ return;
411
+ }
412
+ updateDrag(ptr(ev));
413
+ };
414
+
415
+ const onUp = (upEvent: PointerEvent) => {
416
+ if (upEvent.button !== 0) return;
417
+ release();
418
+ if (activated) commitDrag();
419
+ };
420
+
421
+ // The browser took the pointer (e.g. to scroll): drop the press and any drag.
422
+ const onPointerCancel = () => {
423
+ release();
424
+ if (activated) cancelDrag();
425
+ };
426
+
427
+ document.addEventListener('pointermove', onMove);
428
+ document.addEventListener('pointerup', onUp);
429
+ document.addEventListener('pointercancel', onPointerCancel);
430
+ pointerCleanup = () => {
431
+ hold.stop();
432
+ setArmedId(null);
433
+ document.removeEventListener('pointermove', onMove);
434
+ document.removeEventListener('pointerup', onUp);
435
+ document.removeEventListener('pointercancel', onPointerCancel);
436
+ };
437
+ }
438
+
439
+ // ── Cleanup ────────────────────────────────────────────────────────────
440
+
441
+ // Guard: only register onCleanup if running inside a SolidJS reactive owner.
442
+ // This makes the primitive safe to use in tests or imperative code outside
443
+ // a component tree. When used inside a component, cleanup fires automatically
444
+ // on unmount.
445
+ if (getOwner()) {
446
+ onCleanup(() => {
447
+ if (drag) cancelDrag();
448
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
449
+ nodes.clear();
450
+ disposeRoot?.();
451
+ });
452
+ }
453
+
454
+ // ── Public API ─────────────────────────────────────────────────────────
455
+
456
+ return {
457
+ /** Spread onto each reorderable item element */
458
+ itemProps: (id: string) => ({
459
+ ref: (el: HTMLElement) => { nodes.set(id, el); },
460
+ onPointerDown: (e: PointerEvent) => onPointerDown(id, e),
461
+ classList: { [getActiveClass()]: activeId() === id, [getArmedClass()]: armedId() === id },
462
+ 'data-reorder-id': id,
463
+ }),
464
+
465
+ /** Whether the given item is currently being dragged */
466
+ isActive: (id: string) => activeId() === id,
467
+
468
+ /** Whether any item is currently being dragged */
469
+ isDragging: () => activeId() !== null,
470
+
471
+ /** The ID of the item currently being dragged, or null */
472
+ activeId,
473
+
474
+ /** The current drop target index, or -1 if not dragging */
475
+ targetIndex: targetIdx,
476
+
477
+ /** The ID of the item whose touch hold has completed, or null */
478
+ armedId,
479
+
480
+ /** Manually dispose the isolated reactive root. Call this if you created
481
+ * the primitive outside a SolidJS owner scope and need deterministic cleanup. */
482
+ dispose: () => {
483
+ if (drag) cancelDrag();
484
+ if (pointerCleanup) { pointerCleanup(); pointerCleanup = null; }
485
+ nodes.clear();
486
+ disposeRoot?.();
487
+ },
488
+ };
489
+ }