@cujuju/solid-reorder-list 0.0.0-stage → 0.3.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cujuju
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,551 @@
1
- # Temporary Holding Version
1
+ # @cujuju/solid-reorder-list
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Drag-to-reorder primitive for [SolidJS](https://www.solidjs.com/). Handles variable-height items, single-axis movement, and smooth CSS transition reflow. Zero dependencies beyond `solid-js`.
4
+
5
+ ## Features
6
+
7
+ - Vertical or horizontal reordering
8
+ - Variable-height/width items (no fixed-size assumption)
9
+ - Smooth animated displacement of non-dragged items
10
+ - Distance-based activation (won't trigger on accidental clicks)
11
+ - Automatic interactive-element exclusion (buttons, inputs, links)
12
+ - Post-drag click blocking (prevents click events from firing after drop)
13
+ - Cancel via Escape, right-click, or window blur
14
+ - Multiple independent instances on the same page
15
+ - Works inside or outside SolidJS component trees
16
+ - TypeScript with full type exports
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ # From GitHub
22
+ npm install github:Cujuju/solid-reorder-list
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ```tsx
28
+ import { createSignal, For } from 'solid-js';
29
+ import { createReorderList } from '@cujuju/solid-reorder-list';
30
+ import '@cujuju/solid-reorder-list/css';
31
+
32
+ function SortableList() {
33
+ const [items, setItems] = createSignal(['Apple', 'Banana', 'Cherry']);
34
+
35
+ const reorder = createReorderList({
36
+ ids: items,
37
+ onReorder(from, to) {
38
+ const next = [...items()];
39
+ const [moved] = next.splice(from, 1);
40
+ next.splice(to, 0, moved);
41
+ setItems(next);
42
+ },
43
+ });
44
+
45
+ return (
46
+ <div>
47
+ <For each={items()}>
48
+ {(item) => <div {...reorder.itemProps(item)}>{item}</div>}
49
+ </For>
50
+ </div>
51
+ );
52
+ }
53
+ ```
54
+
55
+ ### What's happening here
56
+
57
+ 1. `ids` is a reactive accessor returning the current order of string IDs. The primitive reads it on every pointerdown to get the latest list.
58
+ 2. `onReorder(from, to)` fires on drop with the **original indices** (the positions in the array at drag start, not the visual positions). You splice your own array — the primitive never mutates your data.
59
+ 3. `itemProps(id)` returns an object you spread onto each item element. It wires up the ref, pointer handlers, active class, and data attribute. Every item in the `<For>` must spread this.
60
+
61
+ ## Options
62
+
63
+ ```ts
64
+ interface ReorderListOptions {
65
+ ids: () => string[];
66
+ onReorder: (fromIndex: number, toIndex: number) => void;
67
+ axis?: 'x' | 'y';
68
+ activateDistance?: number;
69
+ transitionMs?: number;
70
+ activeClass?: string;
71
+ dragScale?: number;
72
+ stopPropagation?: boolean;
73
+ skipSelector?: string;
74
+ }
75
+ ```
76
+
77
+ | Option | Type | Default | Description |
78
+ |---|---|---|---|
79
+ | `ids` | `() => string[]` | **required** | Reactive accessor returning the current list of IDs in order. Called on each pointerdown to snapshot the list. Each ID must be unique and must match what you pass to `itemProps(id)`. |
80
+ | `onReorder` | `(from: number, to: number) => void` | **required** | Called on successful drop when the item moved to a different position. `from` is the original index, `to` is the target index. Not called if the item is dropped back in its original position. |
81
+ | `axis` | `'x' \| 'y'` | `'y'` | Drag axis. `'y'` for vertical lists, `'x'` for horizontal lists. Controls which pointer coordinate is tracked and which CSS transform is applied (`translateY` vs `translateX`). |
82
+ | `activateDistance` | `number` | `5` | Pixels the pointer must move before drag activates. Prevents accidental drags from normal click jitter (typically 1-3px). Set higher for touch interfaces, lower for precision use. |
83
+ | `transitionMs` | `number` | `200` | Duration in milliseconds for the CSS transition on displaced (non-dragged) items. Controls how fast neighbors "pop" into their new positions when the dragged item passes them. |
84
+ | `activeClass` | `string` | `'reorder-active'` | CSS class added to the dragged item's element via `classList`. Use this for visual feedback (box-shadow, outline, background, etc.). The default CSS file styles this class. |
85
+ | `dragScale` | `number` | `0.97` | Scale factor applied to the dragged item via CSS `scale()` transform. Creates a subtle "lift" effect. Set to `1.0` to disable the scale effect entirely. |
86
+ | `stopPropagation` | `boolean` | `true` | Whether to call `e.stopPropagation()` on the pointerdown event. Set to `false` when you have nested reorder lists or need pointer events to bubble to a parent handler. |
87
+ | `skipSelector` | `string` | `'button, input, select, textarea, label, a, [role="button"], [contenteditable]'` | CSS selector matched via `closest()` from the pointerdown target. When matched, drag activation is skipped — guards interactive children from accidental drags. Override when the draggable item itself has interactive semantics (e.g. a `<div role="button">` that IS the draggable). Set to an empty string to disable the skip entirely. The default is also exported as `DEFAULT_SKIP_SELECTOR` for composition: `skipSelector: DEFAULT_SKIP_SELECTOR + ', [data-no-drag]'`. |
88
+
89
+ ## API
90
+
91
+ `createReorderList(options)` returns an object with the following properties:
92
+
93
+ ### `itemProps(id: string)`
94
+
95
+ Returns an object to spread onto each reorderable element:
96
+
97
+ ```ts
98
+ {
99
+ ref: (el: HTMLElement) => void, // Registers the DOM element
100
+ onPointerDown: (e: PointerEvent) => void, // Starts the drag sequence
101
+ classList: { [activeClass]: boolean }, // Reactive — true when this item is being dragged
102
+ 'data-reorder-id': string, // The item's ID as a data attribute
103
+ }
104
+ ```
105
+
106
+ Spread it directly onto the element:
107
+
108
+ ```tsx
109
+ <div {...reorder.itemProps(item.id)}>...</div>
110
+ ```
111
+
112
+ **Important:** The `ref` callback registers the element so the primitive can measure its position and apply transforms. If you also need your own ref, chain them:
113
+
114
+ ```tsx
115
+ <div
116
+ {...reorder.itemProps(item.id)}
117
+ ref={(el) => {
118
+ reorder.itemProps(item.id).ref(el); // Register with reorder
119
+ myRef = el; // Your own ref
120
+ }}
121
+ >
122
+ ```
123
+
124
+ ### `isActive(id: string): boolean`
125
+
126
+ Returns `true` if the given item is the one currently being dragged. Reactive — re-evaluates when drag starts/ends.
127
+
128
+ ```tsx
129
+ <div
130
+ {...reorder.itemProps(item.id)}
131
+ style={{ opacity: reorder.isActive(item.id) ? 0.5 : 1 }}
132
+ >
133
+ ```
134
+
135
+ ### `isDragging(): boolean`
136
+
137
+ Returns `true` if any item is currently being dragged. Useful for hiding tooltips, disabling hover effects, or showing a drop zone overlay.
138
+
139
+ ```tsx
140
+ <Show when={reorder.isDragging()}>
141
+ <div class="drop-zone-overlay" />
142
+ </Show>
143
+ ```
144
+
145
+ ### `activeId(): string | null`
146
+
147
+ The ID of the item currently being dragged, or `null`. This is the reactive signal behind `isActive()` — use it when you need the raw value rather than a per-item check.
148
+
149
+ ### `targetIndex(): number`
150
+
151
+ The index where the dragged item would be inserted if dropped right now. Returns `-1` when not dragging. Use this to render a drop indicator line:
152
+
153
+ ```tsx
154
+ <For each={items()}>
155
+ {(item, i) => (
156
+ <>
157
+ <Show when={reorder.targetIndex() === i() && !reorder.isActive(item)}>
158
+ <div class="drop-indicator" />
159
+ </Show>
160
+ <div {...reorder.itemProps(item)}>{item}</div>
161
+ </>
162
+ )}
163
+ </For>
164
+ ```
165
+
166
+ ### `dispose(): void`
167
+
168
+ Manually tears down the primitive's internal reactive root and clears all registered elements. **You only need this if you create the primitive outside a SolidJS reactive owner** (outside a component, in a test, in imperative setup code). Inside a component, cleanup is automatic via SolidJS `onCleanup`.
169
+
170
+ ```ts
171
+ // Outside a component
172
+ const reorder = createReorderList({ ids, onReorder });
173
+ // ... use it ...
174
+ reorder.dispose(); // Clean up when done
175
+ ```
176
+
177
+ ## CSS
178
+
179
+ ### Default styles (opt-in)
180
+
181
+ ```ts
182
+ import '@cujuju/solid-reorder-list/css';
183
+ ```
184
+
185
+ This imports two rules:
186
+
187
+ ```css
188
+ /* Box shadow and grab cursor on the dragged item */
189
+ .reorder-active {
190
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
191
+ cursor: grabbing;
192
+ }
193
+
194
+ /* Disable text selection on all reorderable items */
195
+ [data-reorder-id] {
196
+ user-select: none;
197
+ }
198
+ ```
199
+
200
+ ### Custom styles
201
+
202
+ Skip the CSS import and style the `activeClass` yourself:
203
+
204
+ ```ts
205
+ const reorder = createReorderList({
206
+ ids,
207
+ onReorder,
208
+ activeClass: 'my-dragging',
209
+ });
210
+ ```
211
+
212
+ ```css
213
+ .my-dragging {
214
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
215
+ outline: 2px solid blue;
216
+ }
217
+
218
+ /* REQUIRED when skipping the default CSS — see "Browser defaults"
219
+ section below. Without this, mousedown over text inside an item
220
+ starts a text selection that competes with the drag. */
221
+ [data-reorder-id] {
222
+ user-select: none;
223
+ -webkit-user-select: none;
224
+ }
225
+ ```
226
+
227
+ ### Inline styles managed by the primitive
228
+
229
+ During a drag, the primitive sets these inline styles directly on elements. **Do not override these properties** on reorderable items with `!important` or inline styles, as the primitive needs to control them:
230
+
231
+ | Property | On dragged item | On displaced items | Cleared on drop |
232
+ |---|---|---|---|
233
+ | `transform` | `translateY/X(delta) scale(dragScale)` | `translateY/X(shift)` or `''` | Yes |
234
+ | `transition` | `none` | `transform {transitionMs}ms ease` | Yes |
235
+ | `z-index` | `50` | unchanged | Yes |
236
+ | `position` | `relative` | unchanged | Yes |
237
+ | `will-change` | `transform` | `transform` | Yes |
238
+ | `pointer-events` | unchanged | `none` | Yes |
239
+
240
+ The primitive also sets `document.body.style.cursor = 'grabbing'` during drag and clears it on drop.
241
+
242
+ ### The `data-reorder-id` attribute
243
+
244
+ Every item gets `data-reorder-id="{id}"` via `itemProps`. This is useful for:
245
+
246
+ - The `[data-reorder-id] { user-select: none }` CSS rule (included in default CSS)
247
+ - Debugging (inspect which element maps to which ID)
248
+ - Custom CSS selectors targeting all reorderable items
249
+
250
+ ## Browser defaults to suppress
251
+
252
+ This library uses Pointer Events, which (unlike HTML5 `draggable=true`) leave native browser behaviors intact. Two defaults can interfere with smooth reorder UX. Both are fixable consumer-side, and forgetting either produces visible bugs.
253
+
254
+ ### Text selection during pointerdown
255
+
256
+ Without `user-select: none`, mousedown over text inside a reorderable item starts a text selection that competes with the drag — visible as the drag failing to activate cleanly while the text gets highlighted under the cursor.
257
+
258
+ The default CSS (`import '@cujuju/solid-reorder-list/css'`) handles this with a `[data-reorder-id] { user-select: none }` rule. **If you skip the default CSS** and roll your own visual style, replicate the rule yourself — see the snippet in [Custom styles](#custom-styles).
259
+
260
+ ### Natively-draggable inner elements
261
+
262
+ `<img>` and `<a href>` elements default to `draggable=true` in browsers. When the user mousedowns on one inside a reorderable item, the browser starts its own HTML5 drag-image operation simultaneously with this library's pointer-event drag. Visible symptoms:
263
+
264
+ - "No-drop" cursor (⊘) appears immediately on mousedown
265
+ - The dragged item ends up offset from the cursor once the library's own drag activates at `activateDistance`
266
+ - A ghost image of the inner element follows the cursor independently
267
+
268
+ This bites hardest when the inner element occupies most of the reorderable item's surface (e.g., a tab whose entire visible area is a cover image).
269
+
270
+ Disable native drag on those elements:
271
+
272
+ ```tsx
273
+ <img src={...} alt="" draggable={false} />
274
+ <a href={...} draggable={false}>{label}</a>
275
+ ```
276
+
277
+ This applies whether you use the default CSS or roll your own — the default CSS doesn't help here because there's no CSS-only way to disable the `draggable` attribute on every nested element. The fix has to be on the elements themselves.
278
+
279
+ ## Patterns and Recipes
280
+
281
+ ### Horizontal list
282
+
283
+ ```tsx
284
+ const reorder = createReorderList({
285
+ ids: columns,
286
+ onReorder: handleReorder,
287
+ axis: 'x',
288
+ });
289
+
290
+ return (
291
+ <div style={{ display: 'flex' }}>
292
+ <For each={columns()}>
293
+ {(col) => <div {...reorder.itemProps(col)}>{col}</div>}
294
+ </For>
295
+ </div>
296
+ );
297
+ ```
298
+
299
+ ### Conditional reorder (enable/disable)
300
+
301
+ Guard the spread so items are only draggable when reorder is enabled:
302
+
303
+ ```tsx
304
+ const reorder = props.canReorder
305
+ ? createReorderList({ ids, onReorder })
306
+ : undefined;
307
+
308
+ // In JSX:
309
+ <div {...(reorder?.itemProps(item.id) ?? { 'data-reorder-id': item.id })}>
310
+ ```
311
+
312
+ ### Items with buttons, inputs, or links
313
+
314
+ The primitive automatically skips drag activation when the pointer target is (or is inside) a `button`, `input`, `a`, or `[role="button"]` element. Clicks on these elements work normally without triggering a drag. No configuration needed.
315
+
316
+ ### Hiding tooltips during drag
317
+
318
+ Use `isDragging()` to suppress tooltips or hover popups that would interfere with the drag:
319
+
320
+ ```tsx
321
+ <Show when={!reorder.isDragging()}>
322
+ <Tooltip target={el}>{tooltipContent}</Tooltip>
323
+ </Show>
324
+ ```
325
+
326
+ ### Multiple reorder lists on one page
327
+
328
+ Each `createReorderList` instance is fully independent. You can have several on the same page (e.g., a sidebar list and a column config flyout). They don't interfere with each other as long as each item's ID is unique within its own list.
329
+
330
+ ### Nested reorder lists
331
+
332
+ If you have a reorder list inside another reorder list (e.g., groups containing cards), set `stopPropagation: false` on the inner list so pointer events can reach the outer list when needed:
333
+
334
+ ```tsx
335
+ const innerReorder = createReorderList({
336
+ ids: cardIds,
337
+ onReorder: handleCardReorder,
338
+ stopPropagation: false, // Let events bubble to outer list
339
+ });
340
+ ```
341
+
342
+ ### Draggable items with interactive root semantics
343
+
344
+ The default skip selector matches `[role="button"]` so accidental drags on focusable children are avoided. If your draggable item's *root* element itself uses `role="button"` (or `<button>`, `<a>`, `<input>`, `<label>`), the default selector causes drag to never activate at all. Override `skipSelector` to allow drag on the root while still guarding child controls:
345
+
346
+ ```tsx
347
+ import { createReorderList, DEFAULT_SKIP_SELECTOR } from '@cujuju/solid-reorder-list';
348
+
349
+ const reorder = createReorderList({
350
+ ids,
351
+ onReorder,
352
+ // Allow drag on the [role="button"] root, but still skip on children
353
+ // marked with data-no-drag (e.g. a close-X span inside the tab).
354
+ skipSelector: 'input, a, [data-no-drag]',
355
+ });
356
+
357
+ <div role="button" {...reorder.itemProps(id)}>
358
+ <span>{label}</span>
359
+ <span data-no-drag onClick={onClose}>×</span>
360
+ </div>
361
+ ```
362
+
363
+ Pass an empty string to disable the skip entirely (use with care — accidental drags on form controls become possible).
364
+
365
+ ### Persisting order to a server
366
+
367
+ `onReorder` gives you indices. After splicing, persist the new order:
368
+
369
+ ```tsx
370
+ onReorder(from, to) {
371
+ const next = [...items()];
372
+ const [moved] = next.splice(from, 1);
373
+ next.splice(to, 0, moved);
374
+ setItems(next);
375
+
376
+ // Persist — fire and forget, or queue a retry
377
+ fetch('/api/reorder', {
378
+ method: 'POST',
379
+ body: JSON.stringify({ from, to }),
380
+ }).catch(console.error);
381
+ },
382
+ ```
383
+
384
+ ### Using with SolidJS `<For>`
385
+
386
+ The `<For>` component is the natural fit since it keys on reference identity and won't re-create DOM nodes when the array order changes. **Don't use `<Index>`** — it keys on position, which means every item re-renders on reorder.
387
+
388
+ ```tsx
389
+ // Good — keyed by item identity
390
+ <For each={items()}>
391
+ {(item) => <div {...reorder.itemProps(item.id)}>...</div>}
392
+ </For>
393
+
394
+ // Bad — keyed by index, causes unnecessary re-renders
395
+ <Index each={items()}>
396
+ {(item, i) => <div {...reorder.itemProps(item().id)}>...</div>}
397
+ </Index>
398
+ ```
399
+
400
+ ## How It Works
401
+
402
+ ### Drag lifecycle
403
+
404
+ 1. **Pointerdown** — Registers `pointermove` and `pointerup` listeners on `document`. Does not activate the drag yet.
405
+ 2. **Activation** — When pointer movement exceeds `activateDistance` pixels, the drag activates: all item rects are measured and cached, the dragged item gets a scale transform, non-dragged items get displacement transitions enabled.
406
+ 3. **Dragging** — On each `pointermove`, the dragged item follows the pointer via `requestAnimationFrame`-batched transforms. The edge-overlap algorithm determines the current target position and displaces neighbors.
407
+ 4. **Drop** — On `pointerup`, the final position is committed. If `from !== to`, `onReorder` fires. All inline styles are cleared. A one-shot click blocker prevents the pointerup from triggering a click on the dropped element.
408
+ 5. **Cancel** — Escape key, right-click, or window blur cancel the drag without firing `onReorder`. All styles revert.
409
+
410
+ ### Edge-overlap collision model
411
+
412
+ Unlike center-based collision (where a swap triggers when the dragged item's center passes a neighbor's center), this primitive uses **edge overlap with split thresholds**:
413
+
414
+ - **Forward movement** (dragging down/right): swap triggers when the dragged item's leading edge overlaps 40% of the next item. This feels responsive — you don't have to drag far.
415
+ - **Reverse movement** (dragging back up/left): swap triggers at 70% overlap. This makes it easy to undo an accidental swap without re-triggering it.
416
+
417
+ After each swap, effective positions shift by half the dragged item's size, creating a dead zone that prevents jittery rapid swapping at threshold boundaries.
418
+
419
+ ### SolidJS reactivity isolation
420
+
421
+ The primitive's internal signals (`activeId`, `targetIndex`) live in an isolated `createRoot` scope. This prevents a known issue where SolidJS's reactive graph cleanup can dispose signals owned by a parent scope during drag, killing the drag mid-flight. The isolated root is disposed automatically via `onCleanup` (inside a component) or manually via `dispose()` (outside a component).
422
+
423
+ ## Grid mode (`createReorderGrid`)
424
+
425
+ For 2-D auto-flow grids — responsive `repeat(auto-fill, minmax(N, 1fr))` layouts where displacement crosses row-wrap diagonals — use the sibling primitive `createReorderGrid`. Same spread-`itemProps` shape as `createReorderList`, with snapshot-based hit-test instead of edge-overlap collision.
426
+
427
+ ```tsx
428
+ import { createSignal, For } from 'solid-js';
429
+ import { createReorderGrid } from '@cujuju/solid-reorder-list';
430
+ import '@cujuju/solid-reorder-list/css';
431
+
432
+ function PinnedGrid() {
433
+ const [items, setItems] = createSignal(['a', 'b', 'c', 'd', 'e', 'f']);
434
+ let panelRef: HTMLDivElement | undefined;
435
+
436
+ const grid = createReorderGrid({
437
+ ids: items,
438
+ onReorder(from, to) {
439
+ const next = [...items()];
440
+ const [moved] = next.splice(from, 1);
441
+ next.splice(to, 0, moved);
442
+ setItems(next);
443
+ },
444
+ scrollContainer: () => panelRef ?? null,
445
+ });
446
+
447
+ return (
448
+ <div ref={panelRef} style={{ 'overflow-y': 'auto', 'max-height': '80vh' }}>
449
+ <div style={{ display: 'grid', 'grid-template-columns': 'repeat(auto-fill, minmax(140px, 1fr))', gap: '12px' }}>
450
+ <For each={items()}>
451
+ {(item) => <div {...grid.itemProps(item)}>{item}</div>}
452
+ </For>
453
+ </div>
454
+ </div>
455
+ );
456
+ }
457
+ ```
458
+
459
+ ### Options (`ReorderGridOptions`)
460
+
461
+ | Option | Type | Default | Description |
462
+ |---|---|---|---|
463
+ | `ids` | `() => string[]` | **required** | Reactive accessor returning the current flat (row-major) order of IDs. |
464
+ | `onReorder` | `(from: number, to: number) => void` | **required** | Called on drop with original and target indices. Not called when `from === to`. |
465
+ | `activateDistance` | `number` | `5` | Pixels of pointer movement (Euclidean `Math.hypot(dx, dy)`) before drag activates. |
466
+ | `transitionMs` | `number` | `200` | CSS transition duration on displaced items. |
467
+ | `activeClass` | `string` | `'reorder-active'` | CSS class added to the dragged item. |
468
+ | `dragScale` | `number` | `0.97` | Scale factor for the dragged item's lift. |
469
+ | `stopPropagation` | `boolean` | `true` | Whether to call `e.stopPropagation()` on pointerdown. |
470
+ | `skipSelector` | `string` | `DEFAULT_SKIP_SELECTOR` | CSS selector matched via `closest()` from the pointerdown target. When matched, drag activation is skipped. |
471
+ | `scrollContainer` | `() => HTMLElement \| Window \| null` | — | Reactive accessor returning the scroll container. Snapshot rects are stored in container-content coords (`clientX + container.scrollLeft`); manual scrolls during drag are compensated on each `pointermove`. |
472
+
473
+ ### Public return shape
474
+
475
+ Mirrors `createReorderList` plus `cancel()`:
476
+
477
+ ```ts
478
+ {
479
+ itemProps(id: string): { ref, onPointerDown, classList, 'data-reorder-id' };
480
+ isActive(id: string): boolean;
481
+ isDragging(): boolean;
482
+ activeId(): string | null;
483
+ targetIndex(): number; // -1 when not dragging
484
+ cancel(): void; // abort in-progress drag without firing onReorder; idempotent
485
+ dispose(): void;
486
+ }
487
+ ```
488
+
489
+ ### Coordinate frame
490
+
491
+ `createReorderGrid` operates in **container-content coords** = `clientX + scrollContainer.scrollLeft` (mirror y). When `scrollContainer` is omitted (or returns `null`), it falls back to `window.scrollX/Y` and the frame becomes true page coords.
492
+
493
+ This is **not** `pageX/pageY` directly. For Portal'd panels with `position: fixed`, window scroll does not compose into the frame — the container's scroll offset is the only meaningful frame.
494
+
495
+ ### Scope assumptions (read before adopting)
496
+
497
+ - **Uniform cell width and height.** Auto-fill grids with `minmax(140px, 1fr)` qualify; masonry, mixed-size cards, or stretchy items don't. Dev-mode emits `console.warn` when cells differ in size beyond `cellHeight × 0.05`.
498
+ - **Non-dense flow.** `grid-auto-flow: dense` is out of scope.
499
+ - **LTR direction.** RTL grids are not handled.
500
+ - **Cell-height-relative tolerance.** Same-row tolerance is `cellHeight × 0.1`. If your `gutterY < cellHeight × 0.1` (very compact layouts), column-count inference may misfire — dev-mode cross-validation invariant emits `console.warn` when violated.
501
+ - **No `cols` option.** Column count is inferred from the snapshot.
502
+ - **No mid-drag layout-change tracking.** If the window resizes, the panel resizes, the theme switches, or the scroll container's `clientWidth` otherwise changes during a drag, the snapshot becomes stale. Consumers can wire a `ResizeObserver` on the container that calls `gridReorder.cancel()` to invalidate the snapshot when this matters.
503
+ - **No cross-instance concurrent drag protection.** Each `createReorderList` / `createReorderGrid` instance guards its own drag state; nothing prevents two instances activating simultaneously on multi-touch devices. Pre-existing in 1-D, inherited.
504
+ - **No virtualised lists.** All registered items must be present in the DOM at activate.
505
+ - **`touch-action` is the consumer's responsibility.** Apply `touch-action: none` to registered grid cells (matched via `[data-reorder-id]`) so Pointer Events drive the drag instead of the browser scrolling.
506
+
507
+ ### Auto-scroll deferred to v0.3.1
508
+
509
+ v0.3.0 ships scroll-aware hit-test (R7 — manual scrolls during drag compensate correctly) but **no auto-scroll** when the pointer enters the container's edge zone. Auto-scroll is tracked as `R8`/`R9` and lands in v0.3.1 once a consumer demonstrates the panel routinely overflows AND users routinely drag to off-screen targets.
510
+
511
+ ### How it differs from `createReorderList`
512
+
513
+ | Aspect | 1-D | 2-D grid |
514
+ |---|---|---|
515
+ | Collision model | Edge-overlap (40% forward, 70% reverse) | Inflated-rect tessellation, point-in-rect |
516
+ | Activation threshold | `Math.abs(dx)` on the chosen axis | `Math.hypot(dx, dy)` Euclidean |
517
+ | Anti-jitter | Per-displaced-cell halfShift on `effectiveStarts` | Per-target-pair half-cell on `effectiveRects[prev/next]` |
518
+ | Hit-test | Walk forward/backward overlap counts | Tessellation lookup with nearest-cell fallback |
519
+ | Coordinate frame | Viewport (no scroll compensation) | Container-content (R7 manual scroll compensation) |
520
+ | Public surface | Standard | Standard + `cancel()` (R13a) |
521
+
522
+ ## Compatibility
523
+
524
+ - **SolidJS** >= 1.8.0
525
+ - **Browser** — any browser with Pointer Events (all modern browsers, IE 11+ with polyfill)
526
+ - **Touch** — works on touch devices (Pointer Events abstract over mouse/touch/pen)
527
+ - **SSR** — safe to import server-side (no DOM access at module level), but the primitive itself requires a DOM to function
528
+
529
+ ## TypeScript
530
+
531
+ The package exports full type declarations. Key exports:
532
+
533
+ ```ts
534
+ import { createReorderList, createReorderGrid } from '@cujuju/solid-reorder-list';
535
+ import type { ReorderListOptions, ReorderGridOptions } from '@cujuju/solid-reorder-list';
536
+ ```
537
+
538
+ For typing a prop that receives the return value:
539
+
540
+ ```ts
541
+ import { createReorderList, createReorderGrid } from '@cujuju/solid-reorder-list';
542
+
543
+ interface MyProps {
544
+ reorder: ReturnType<typeof createReorderList>;
545
+ grid: ReturnType<typeof createReorderGrid>;
546
+ }
547
+ ```
548
+
549
+ ## License
550
+
551
+ MIT
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Default styles for @cujuju/solid-reorder-list.
3
+ *
4
+ * Import via: import '@cujuju/solid-reorder-list/css'
5
+ *
6
+ * These are optional — you can skip this import and style the activeClass
7
+ * yourself. The primitive sets inline transforms, z-index, and position
8
+ * during drag; this file only adds the visual "lift" shadow and cursor.
9
+ */
10
+
11
+ /* Active (dragged) item — only static visual properties here.
12
+ Transform, transition, z-index, and position are owned by JS
13
+ to avoid conflicts with inline translateY/translateX. */
14
+ .reorder-active {
15
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
16
+ cursor: grabbing;
17
+ }
18
+
19
+ /* Reorder items — disable text selection so pointer-down initiates drag,
20
+ not text selection. Targets the data attribute set by itemProps(). */
21
+ [data-reorder-id] {
22
+ user-select: none;
23
+ }