@cujuju/solid-reorder-list 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +561 -3
- package/css/reorder.css +23 -0
- package/dist/index.cjs +807 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +170 -0
- package/dist/index.d.ts +170 -0
- package/dist/index.js +803 -0
- package/dist/index.js.map +1 -0
- package/package.json +60 -6
- package/src/createReorderGrid.ts +824 -0
- package/src/createReorderList.ts +489 -0
- package/src/index.ts +4 -0
- package/src/shared.ts +122 -0
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,561 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @cujuju/solid-reorder-list
|
|
2
|
+
|
|
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
|
+
| `touchHoldMs` | `number` | `200` | Milliseconds a touch or pen press must stay down before it can drag. Stops a finger flick across the list from grabbing an item. Moving more than `touchHoldTolerance` or lifting during the hold gives the press up; the long-press menu is suppressed while the finger is down. A mouse never waits. Set to `0` to turn the hold off and drag on touch at once. |
|
|
89
|
+
| `touchHoldTolerance` | `number` | `10` | Pixels a touch may wander during the hold before it is given up. |
|
|
90
|
+
| `armedClass` | `string` | `'reorder-armed'` | CSS class added to an item once its hold completes, until it is dragged (then `activeClass` takes over) or let go. Style it so the person can see the item is ready to move. |
|
|
91
|
+
|
|
92
|
+
## API
|
|
93
|
+
|
|
94
|
+
`createReorderList(options)` returns an object with the following properties:
|
|
95
|
+
|
|
96
|
+
### `itemProps(id: string)`
|
|
97
|
+
|
|
98
|
+
Returns an object to spread onto each reorderable element:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
{
|
|
102
|
+
ref: (el: HTMLElement) => void, // Registers the DOM element
|
|
103
|
+
onPointerDown: (e: PointerEvent) => void, // Starts the drag sequence
|
|
104
|
+
classList: { [activeClass]: boolean }, // Reactive — true when this item is being dragged
|
|
105
|
+
'data-reorder-id': string, // The item's ID as a data attribute
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Spread it directly onto the element:
|
|
110
|
+
|
|
111
|
+
```tsx
|
|
112
|
+
<div {...reorder.itemProps(item.id)}>...</div>
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
**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:
|
|
116
|
+
|
|
117
|
+
```tsx
|
|
118
|
+
<div
|
|
119
|
+
{...reorder.itemProps(item.id)}
|
|
120
|
+
ref={(el) => {
|
|
121
|
+
reorder.itemProps(item.id).ref(el); // Register with reorder
|
|
122
|
+
myRef = el; // Your own ref
|
|
123
|
+
}}
|
|
124
|
+
>
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### `isActive(id: string): boolean`
|
|
128
|
+
|
|
129
|
+
Returns `true` if the given item is the one currently being dragged. Reactive — re-evaluates when drag starts/ends.
|
|
130
|
+
|
|
131
|
+
```tsx
|
|
132
|
+
<div
|
|
133
|
+
{...reorder.itemProps(item.id)}
|
|
134
|
+
style={{ opacity: reorder.isActive(item.id) ? 0.5 : 1 }}
|
|
135
|
+
>
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### `isDragging(): boolean`
|
|
139
|
+
|
|
140
|
+
Returns `true` if any item is currently being dragged. Useful for hiding tooltips, disabling hover effects, or showing a drop zone overlay.
|
|
141
|
+
|
|
142
|
+
```tsx
|
|
143
|
+
<Show when={reorder.isDragging()}>
|
|
144
|
+
<div class="drop-zone-overlay" />
|
|
145
|
+
</Show>
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### `activeId(): string | null`
|
|
149
|
+
|
|
150
|
+
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.
|
|
151
|
+
|
|
152
|
+
### `armedId(): string | null`
|
|
153
|
+
|
|
154
|
+
The ID of the item whose touch hold has completed but which hasn't started dragging yet, or `null`. Reactive. Always `null` for a mouse, or when `touchHoldMs` is `0`.
|
|
155
|
+
|
|
156
|
+
### `targetIndex(): number`
|
|
157
|
+
|
|
158
|
+
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:
|
|
159
|
+
|
|
160
|
+
```tsx
|
|
161
|
+
<For each={items()}>
|
|
162
|
+
{(item, i) => (
|
|
163
|
+
<>
|
|
164
|
+
<Show when={reorder.targetIndex() === i() && !reorder.isActive(item)}>
|
|
165
|
+
<div class="drop-indicator" />
|
|
166
|
+
</Show>
|
|
167
|
+
<div {...reorder.itemProps(item)}>{item}</div>
|
|
168
|
+
</>
|
|
169
|
+
)}
|
|
170
|
+
</For>
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### `dispose(): void`
|
|
174
|
+
|
|
175
|
+
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`.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
// Outside a component
|
|
179
|
+
const reorder = createReorderList({ ids, onReorder });
|
|
180
|
+
// ... use it ...
|
|
181
|
+
reorder.dispose(); // Clean up when done
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## CSS
|
|
185
|
+
|
|
186
|
+
### Default styles (opt-in)
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
import '@cujuju/solid-reorder-list/css';
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
This imports two rules:
|
|
193
|
+
|
|
194
|
+
```css
|
|
195
|
+
/* Box shadow and grab cursor on the dragged item */
|
|
196
|
+
.reorder-active {
|
|
197
|
+
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
|
|
198
|
+
cursor: grabbing;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/* Disable text selection on all reorderable items */
|
|
202
|
+
[data-reorder-id] {
|
|
203
|
+
user-select: none;
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Custom styles
|
|
208
|
+
|
|
209
|
+
Skip the CSS import and style the `activeClass` yourself:
|
|
210
|
+
|
|
211
|
+
```ts
|
|
212
|
+
const reorder = createReorderList({
|
|
213
|
+
ids,
|
|
214
|
+
onReorder,
|
|
215
|
+
activeClass: 'my-dragging',
|
|
216
|
+
});
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
```css
|
|
220
|
+
.my-dragging {
|
|
221
|
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
|
|
222
|
+
outline: 2px solid blue;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/* REQUIRED when skipping the default CSS — see "Browser defaults"
|
|
226
|
+
section below. Without this, mousedown over text inside an item
|
|
227
|
+
starts a text selection that competes with the drag. */
|
|
228
|
+
[data-reorder-id] {
|
|
229
|
+
user-select: none;
|
|
230
|
+
-webkit-user-select: none;
|
|
231
|
+
}
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### Inline styles managed by the primitive
|
|
235
|
+
|
|
236
|
+
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:
|
|
237
|
+
|
|
238
|
+
| Property | On dragged item | On displaced items | Cleared on drop |
|
|
239
|
+
|---|---|---|---|
|
|
240
|
+
| `transform` | `translateY/X(delta) scale(dragScale)` | `translateY/X(shift)` or `''` | Yes |
|
|
241
|
+
| `transition` | `none` | `transform {transitionMs}ms ease` | Yes |
|
|
242
|
+
| `z-index` | `50` | unchanged | Yes |
|
|
243
|
+
| `position` | `relative` | unchanged | Yes |
|
|
244
|
+
| `will-change` | `transform` | `transform` | Yes |
|
|
245
|
+
| `pointer-events` | unchanged | `none` | Yes |
|
|
246
|
+
|
|
247
|
+
The primitive also sets `document.body.style.cursor = 'grabbing'` during drag and clears it on drop.
|
|
248
|
+
|
|
249
|
+
### The `data-reorder-id` attribute
|
|
250
|
+
|
|
251
|
+
Every item gets `data-reorder-id="{id}"` via `itemProps`. This is useful for:
|
|
252
|
+
|
|
253
|
+
- The `[data-reorder-id] { user-select: none }` CSS rule (included in default CSS)
|
|
254
|
+
- Debugging (inspect which element maps to which ID)
|
|
255
|
+
- Custom CSS selectors targeting all reorderable items
|
|
256
|
+
|
|
257
|
+
## Browser defaults to suppress
|
|
258
|
+
|
|
259
|
+
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.
|
|
260
|
+
|
|
261
|
+
### Text selection during pointerdown
|
|
262
|
+
|
|
263
|
+
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.
|
|
264
|
+
|
|
265
|
+
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).
|
|
266
|
+
|
|
267
|
+
### Natively-draggable inner elements
|
|
268
|
+
|
|
269
|
+
`<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:
|
|
270
|
+
|
|
271
|
+
- "No-drop" cursor (⊘) appears immediately on mousedown
|
|
272
|
+
- The dragged item ends up offset from the cursor once the library's own drag activates at `activateDistance`
|
|
273
|
+
- A ghost image of the inner element follows the cursor independently
|
|
274
|
+
|
|
275
|
+
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).
|
|
276
|
+
|
|
277
|
+
Disable native drag on those elements:
|
|
278
|
+
|
|
279
|
+
```tsx
|
|
280
|
+
<img src={...} alt="" draggable={false} />
|
|
281
|
+
<a href={...} draggable={false}>{label}</a>
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
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.
|
|
285
|
+
|
|
286
|
+
## Patterns and Recipes
|
|
287
|
+
|
|
288
|
+
### Horizontal list
|
|
289
|
+
|
|
290
|
+
```tsx
|
|
291
|
+
const reorder = createReorderList({
|
|
292
|
+
ids: columns,
|
|
293
|
+
onReorder: handleReorder,
|
|
294
|
+
axis: 'x',
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
return (
|
|
298
|
+
<div style={{ display: 'flex' }}>
|
|
299
|
+
<For each={columns()}>
|
|
300
|
+
{(col) => <div {...reorder.itemProps(col)}>{col}</div>}
|
|
301
|
+
</For>
|
|
302
|
+
</div>
|
|
303
|
+
);
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
### Conditional reorder (enable/disable)
|
|
307
|
+
|
|
308
|
+
Guard the spread so items are only draggable when reorder is enabled:
|
|
309
|
+
|
|
310
|
+
```tsx
|
|
311
|
+
const reorder = props.canReorder
|
|
312
|
+
? createReorderList({ ids, onReorder })
|
|
313
|
+
: undefined;
|
|
314
|
+
|
|
315
|
+
// In JSX:
|
|
316
|
+
<div {...(reorder?.itemProps(item.id) ?? { 'data-reorder-id': item.id })}>
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
### Items with buttons, inputs, or links
|
|
320
|
+
|
|
321
|
+
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.
|
|
322
|
+
|
|
323
|
+
### Hiding tooltips during drag
|
|
324
|
+
|
|
325
|
+
Use `isDragging()` to suppress tooltips or hover popups that would interfere with the drag:
|
|
326
|
+
|
|
327
|
+
```tsx
|
|
328
|
+
<Show when={!reorder.isDragging()}>
|
|
329
|
+
<Tooltip target={el}>{tooltipContent}</Tooltip>
|
|
330
|
+
</Show>
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
### Multiple reorder lists on one page
|
|
334
|
+
|
|
335
|
+
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.
|
|
336
|
+
|
|
337
|
+
### Nested reorder lists
|
|
338
|
+
|
|
339
|
+
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:
|
|
340
|
+
|
|
341
|
+
```tsx
|
|
342
|
+
const innerReorder = createReorderList({
|
|
343
|
+
ids: cardIds,
|
|
344
|
+
onReorder: handleCardReorder,
|
|
345
|
+
stopPropagation: false, // Let events bubble to outer list
|
|
346
|
+
});
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
### Draggable items with interactive root semantics
|
|
350
|
+
|
|
351
|
+
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:
|
|
352
|
+
|
|
353
|
+
```tsx
|
|
354
|
+
import { createReorderList, DEFAULT_SKIP_SELECTOR } from '@cujuju/solid-reorder-list';
|
|
355
|
+
|
|
356
|
+
const reorder = createReorderList({
|
|
357
|
+
ids,
|
|
358
|
+
onReorder,
|
|
359
|
+
// Allow drag on the [role="button"] root, but still skip on children
|
|
360
|
+
// marked with data-no-drag (e.g. a close-X span inside the tab).
|
|
361
|
+
skipSelector: 'input, a, [data-no-drag]',
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
<div role="button" {...reorder.itemProps(id)}>
|
|
365
|
+
<span>{label}</span>
|
|
366
|
+
<span data-no-drag onClick={onClose}>×</span>
|
|
367
|
+
</div>
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
Pass an empty string to disable the skip entirely (use with care — accidental drags on form controls become possible).
|
|
371
|
+
|
|
372
|
+
### Persisting order to a server
|
|
373
|
+
|
|
374
|
+
`onReorder` gives you indices. After splicing, persist the new order:
|
|
375
|
+
|
|
376
|
+
```tsx
|
|
377
|
+
onReorder(from, to) {
|
|
378
|
+
const next = [...items()];
|
|
379
|
+
const [moved] = next.splice(from, 1);
|
|
380
|
+
next.splice(to, 0, moved);
|
|
381
|
+
setItems(next);
|
|
382
|
+
|
|
383
|
+
// Persist — fire and forget, or queue a retry
|
|
384
|
+
fetch('/api/reorder', {
|
|
385
|
+
method: 'POST',
|
|
386
|
+
body: JSON.stringify({ from, to }),
|
|
387
|
+
}).catch(console.error);
|
|
388
|
+
},
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
### Using with SolidJS `<For>`
|
|
392
|
+
|
|
393
|
+
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.
|
|
394
|
+
|
|
395
|
+
```tsx
|
|
396
|
+
// Good — keyed by item identity
|
|
397
|
+
<For each={items()}>
|
|
398
|
+
{(item) => <div {...reorder.itemProps(item.id)}>...</div>}
|
|
399
|
+
</For>
|
|
400
|
+
|
|
401
|
+
// Bad — keyed by index, causes unnecessary re-renders
|
|
402
|
+
<Index each={items()}>
|
|
403
|
+
{(item, i) => <div {...reorder.itemProps(item().id)}>...</div>}
|
|
404
|
+
</Index>
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
## How It Works
|
|
408
|
+
|
|
409
|
+
### Drag lifecycle
|
|
410
|
+
|
|
411
|
+
1. **Pointerdown** — Registers `pointermove` and `pointerup` listeners on `document`. Does not activate the drag yet.
|
|
412
|
+
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.
|
|
413
|
+
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.
|
|
414
|
+
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.
|
|
415
|
+
5. **Cancel** — Escape key, right-click, or window blur cancel the drag without firing `onReorder`. All styles revert.
|
|
416
|
+
|
|
417
|
+
### Edge-overlap collision model
|
|
418
|
+
|
|
419
|
+
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**:
|
|
420
|
+
|
|
421
|
+
- **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.
|
|
422
|
+
- **Reverse movement** (dragging back up/left): swap triggers at 70% overlap. This makes it easy to undo an accidental swap without re-triggering it.
|
|
423
|
+
|
|
424
|
+
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.
|
|
425
|
+
|
|
426
|
+
### SolidJS reactivity isolation
|
|
427
|
+
|
|
428
|
+
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).
|
|
429
|
+
|
|
430
|
+
## Grid mode (`createReorderGrid`)
|
|
431
|
+
|
|
432
|
+
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.
|
|
433
|
+
|
|
434
|
+
```tsx
|
|
435
|
+
import { createSignal, For } from 'solid-js';
|
|
436
|
+
import { createReorderGrid } from '@cujuju/solid-reorder-list';
|
|
437
|
+
import '@cujuju/solid-reorder-list/css';
|
|
438
|
+
|
|
439
|
+
function PinnedGrid() {
|
|
440
|
+
const [items, setItems] = createSignal(['a', 'b', 'c', 'd', 'e', 'f']);
|
|
441
|
+
let panelRef: HTMLDivElement | undefined;
|
|
442
|
+
|
|
443
|
+
const grid = createReorderGrid({
|
|
444
|
+
ids: items,
|
|
445
|
+
onReorder(from, to) {
|
|
446
|
+
const next = [...items()];
|
|
447
|
+
const [moved] = next.splice(from, 1);
|
|
448
|
+
next.splice(to, 0, moved);
|
|
449
|
+
setItems(next);
|
|
450
|
+
},
|
|
451
|
+
scrollContainer: () => panelRef ?? null,
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
return (
|
|
455
|
+
<div ref={panelRef} style={{ 'overflow-y': 'auto', 'max-height': '80vh' }}>
|
|
456
|
+
<div style={{ display: 'grid', 'grid-template-columns': 'repeat(auto-fill, minmax(140px, 1fr))', gap: '12px' }}>
|
|
457
|
+
<For each={items()}>
|
|
458
|
+
{(item) => <div {...grid.itemProps(item)}>{item}</div>}
|
|
459
|
+
</For>
|
|
460
|
+
</div>
|
|
461
|
+
</div>
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
### Options (`ReorderGridOptions`)
|
|
467
|
+
|
|
468
|
+
| Option | Type | Default | Description |
|
|
469
|
+
|---|---|---|---|
|
|
470
|
+
| `ids` | `() => string[]` | **required** | Reactive accessor returning the current flat (row-major) order of IDs. |
|
|
471
|
+
| `onReorder` | `(from: number, to: number) => void` | **required** | Called on drop with original and target indices. Not called when `from === to`. |
|
|
472
|
+
| `activateDistance` | `number` | `5` | Pixels of pointer movement (Euclidean `Math.hypot(dx, dy)`) before drag activates. |
|
|
473
|
+
| `transitionMs` | `number` | `200` | CSS transition duration on displaced items. |
|
|
474
|
+
| `activeClass` | `string` | `'reorder-active'` | CSS class added to the dragged item. |
|
|
475
|
+
| `dragScale` | `number` | `0.97` | Scale factor for the dragged item's lift. |
|
|
476
|
+
| `stopPropagation` | `boolean` | `true` | Whether to call `e.stopPropagation()` on pointerdown. |
|
|
477
|
+
| `skipSelector` | `string` | `DEFAULT_SKIP_SELECTOR` | CSS selector matched via `closest()` from the pointerdown target. When matched, drag activation is skipped. |
|
|
478
|
+
| `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`. |
|
|
479
|
+
| `touchHoldMs` | `number` | `200` | Milliseconds a touch or pen press must stay down before it can drag. Stops a finger flick across the list from grabbing an item. Moving more than `touchHoldTolerance` or lifting during the hold gives the press up; the long-press menu is suppressed while the finger is down. A mouse never waits. Set to `0` to turn the hold off and drag on touch at once. |
|
|
480
|
+
| `touchHoldTolerance` | `number` | `10` | Pixels a touch may wander during the hold before it is given up. |
|
|
481
|
+
| `armedClass` | `string` | `'reorder-armed'` | CSS class added to an item once its hold completes, until it is dragged (then `activeClass` takes over) or let go. Style it so the person can see the item is ready to move. |
|
|
482
|
+
|
|
483
|
+
### Public return shape
|
|
484
|
+
|
|
485
|
+
Mirrors `createReorderList` plus `cancel()`:
|
|
486
|
+
|
|
487
|
+
```ts
|
|
488
|
+
{
|
|
489
|
+
itemProps(id: string): { ref, onPointerDown, classList, 'data-reorder-id' };
|
|
490
|
+
isActive(id: string): boolean;
|
|
491
|
+
isDragging(): boolean;
|
|
492
|
+
activeId(): string | null;
|
|
493
|
+
targetIndex(): number; // -1 when not dragging
|
|
494
|
+
cancel(): void; // abort in-progress drag without firing onReorder; idempotent
|
|
495
|
+
dispose(): void;
|
|
496
|
+
}
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
### Coordinate frame
|
|
500
|
+
|
|
501
|
+
`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.
|
|
502
|
+
|
|
503
|
+
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.
|
|
504
|
+
|
|
505
|
+
### Scope assumptions (read before adopting)
|
|
506
|
+
|
|
507
|
+
- **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`.
|
|
508
|
+
- **Non-dense flow.** `grid-auto-flow: dense` is out of scope.
|
|
509
|
+
- **LTR direction.** RTL grids are not handled.
|
|
510
|
+
- **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.
|
|
511
|
+
- **No `cols` option.** Column count is inferred from the snapshot.
|
|
512
|
+
- **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.
|
|
513
|
+
- **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.
|
|
514
|
+
- **No virtualised lists.** All registered items must be present in the DOM at activate.
|
|
515
|
+
- **`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.
|
|
516
|
+
|
|
517
|
+
### Auto-scroll deferred to v0.3.1
|
|
518
|
+
|
|
519
|
+
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.
|
|
520
|
+
|
|
521
|
+
### How it differs from `createReorderList`
|
|
522
|
+
|
|
523
|
+
| Aspect | 1-D | 2-D grid |
|
|
524
|
+
|---|---|---|
|
|
525
|
+
| Collision model | Edge-overlap (40% forward, 70% reverse) | Inflated-rect tessellation, point-in-rect |
|
|
526
|
+
| Activation threshold | `Math.abs(dx)` on the chosen axis | `Math.hypot(dx, dy)` Euclidean |
|
|
527
|
+
| Anti-jitter | Per-displaced-cell halfShift on `effectiveStarts` | Per-target-pair half-cell on `effectiveRects[prev/next]` |
|
|
528
|
+
| Hit-test | Walk forward/backward overlap counts | Tessellation lookup with nearest-cell fallback |
|
|
529
|
+
| Coordinate frame | Viewport (no scroll compensation) | Container-content (R7 manual scroll compensation) |
|
|
530
|
+
| Public surface | Standard | Standard + `cancel()` (R13a) |
|
|
531
|
+
|
|
532
|
+
## Compatibility
|
|
533
|
+
|
|
534
|
+
- **SolidJS** >= 1.8.0
|
|
535
|
+
- **Browser** — any browser with Pointer Events (all modern browsers, IE 11+ with polyfill)
|
|
536
|
+
- **Touch** — works on touch devices (Pointer Events abstract over mouse/touch/pen)
|
|
537
|
+
- **SSR** — safe to import server-side (no DOM access at module level), but the primitive itself requires a DOM to function
|
|
538
|
+
|
|
539
|
+
## TypeScript
|
|
540
|
+
|
|
541
|
+
The package exports full type declarations. Key exports:
|
|
542
|
+
|
|
543
|
+
```ts
|
|
544
|
+
import { createReorderList, createReorderGrid } from '@cujuju/solid-reorder-list';
|
|
545
|
+
import type { ReorderListOptions, ReorderGridOptions } from '@cujuju/solid-reorder-list';
|
|
546
|
+
```
|
|
547
|
+
|
|
548
|
+
For typing a prop that receives the return value:
|
|
549
|
+
|
|
550
|
+
```ts
|
|
551
|
+
import { createReorderList, createReorderGrid } from '@cujuju/solid-reorder-list';
|
|
552
|
+
|
|
553
|
+
interface MyProps {
|
|
554
|
+
reorder: ReturnType<typeof createReorderList>;
|
|
555
|
+
grid: ReturnType<typeof createReorderGrid>;
|
|
556
|
+
}
|
|
557
|
+
```
|
|
558
|
+
|
|
559
|
+
## License
|
|
560
|
+
|
|
561
|
+
MIT
|
package/css/reorder.css
ADDED
|
@@ -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
|
+
}
|