@vielzeug/codex 26.11.21 → 26.11.22
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/data/catalog.json +48 -48
- package/data/llms-full.txt +23 -16
- package/data/llms.txt +1 -1
- package/data/manifest.json +1 -1
- package/data/packages/dnd.json +2 -2
- package/data/packages/gesture.json +2 -2
- package/data/refine.json +78 -2
- package/package.json +2 -2
- package/skills/vielzeug/SKILL.md +18 -16
package/data/catalog.json
CHANGED
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"rune"
|
|
39
39
|
],
|
|
40
40
|
"slug": "archive",
|
|
41
|
-
"version": "26.11.
|
|
41
|
+
"version": "26.11.21"
|
|
42
42
|
},
|
|
43
43
|
{
|
|
44
44
|
"availableDocPages": [
|
|
@@ -111,7 +111,7 @@
|
|
|
111
111
|
"coins"
|
|
112
112
|
],
|
|
113
113
|
"slug": "arsenal",
|
|
114
|
-
"version": "26.11.
|
|
114
|
+
"version": "26.11.21"
|
|
115
115
|
},
|
|
116
116
|
{
|
|
117
117
|
"availableDocPages": [
|
|
@@ -166,7 +166,7 @@
|
|
|
166
166
|
"refine"
|
|
167
167
|
],
|
|
168
168
|
"slug": "assay",
|
|
169
|
-
"version": "26.11.
|
|
169
|
+
"version": "26.11.21"
|
|
170
170
|
},
|
|
171
171
|
{
|
|
172
172
|
"availableDocPages": [
|
|
@@ -198,7 +198,7 @@
|
|
|
198
198
|
"necromancer"
|
|
199
199
|
],
|
|
200
200
|
"slug": "bard",
|
|
201
|
-
"version": "26.11.
|
|
201
|
+
"version": "26.11.21"
|
|
202
202
|
},
|
|
203
203
|
{
|
|
204
204
|
"availableDocPages": [
|
|
@@ -237,7 +237,7 @@
|
|
|
237
237
|
"vault"
|
|
238
238
|
],
|
|
239
239
|
"slug": "beacon",
|
|
240
|
-
"version": "26.11.
|
|
240
|
+
"version": "26.11.21"
|
|
241
241
|
},
|
|
242
242
|
{
|
|
243
243
|
"availableDocPages": [
|
|
@@ -279,7 +279,7 @@
|
|
|
279
279
|
"ward"
|
|
280
280
|
],
|
|
281
281
|
"slug": "clockwork",
|
|
282
|
-
"version": "26.11.
|
|
282
|
+
"version": "26.11.21"
|
|
283
283
|
},
|
|
284
284
|
{
|
|
285
285
|
"availableDocPages": [
|
|
@@ -311,7 +311,7 @@
|
|
|
311
311
|
"refine"
|
|
312
312
|
],
|
|
313
313
|
"slug": "codex",
|
|
314
|
-
"version": "26.11.
|
|
314
|
+
"version": "26.11.21"
|
|
315
315
|
},
|
|
316
316
|
{
|
|
317
317
|
"availableDocPages": [
|
|
@@ -381,7 +381,7 @@
|
|
|
381
381
|
"spell"
|
|
382
382
|
],
|
|
383
383
|
"slug": "coins",
|
|
384
|
-
"version": "26.11.
|
|
384
|
+
"version": "26.11.21"
|
|
385
385
|
},
|
|
386
386
|
{
|
|
387
387
|
"availableDocPages": [
|
|
@@ -422,7 +422,7 @@
|
|
|
422
422
|
"rune"
|
|
423
423
|
],
|
|
424
424
|
"slug": "conduit",
|
|
425
|
-
"version": "26.11.
|
|
425
|
+
"version": "26.11.21"
|
|
426
426
|
},
|
|
427
427
|
{
|
|
428
428
|
"availableDocPages": [
|
|
@@ -464,7 +464,7 @@
|
|
|
464
464
|
"postmaster"
|
|
465
465
|
],
|
|
466
466
|
"slug": "courier",
|
|
467
|
-
"version": "26.11.
|
|
467
|
+
"version": "26.11.21"
|
|
468
468
|
},
|
|
469
469
|
{
|
|
470
470
|
"availableDocPages": [
|
|
@@ -510,7 +510,7 @@
|
|
|
510
510
|
"refine"
|
|
511
511
|
],
|
|
512
512
|
"slug": "dnd",
|
|
513
|
-
"version": "26.11.
|
|
513
|
+
"version": "26.11.21"
|
|
514
514
|
},
|
|
515
515
|
{
|
|
516
516
|
"availableDocPages": [
|
|
@@ -552,7 +552,7 @@
|
|
|
552
552
|
"herald"
|
|
553
553
|
],
|
|
554
554
|
"slug": "familiar",
|
|
555
|
-
"version": "26.11.
|
|
555
|
+
"version": "26.11.21"
|
|
556
556
|
},
|
|
557
557
|
{
|
|
558
558
|
"availableDocPages": [
|
|
@@ -619,7 +619,7 @@
|
|
|
619
619
|
"courier"
|
|
620
620
|
],
|
|
621
621
|
"slug": "flux",
|
|
622
|
-
"version": "26.11.
|
|
622
|
+
"version": "26.11.21"
|
|
623
623
|
},
|
|
624
624
|
{
|
|
625
625
|
"availableDocPages": [
|
|
@@ -659,7 +659,7 @@
|
|
|
659
659
|
"ore"
|
|
660
660
|
],
|
|
661
661
|
"slug": "focus",
|
|
662
|
-
"version": "26.11.
|
|
662
|
+
"version": "26.11.21"
|
|
663
663
|
},
|
|
664
664
|
{
|
|
665
665
|
"availableDocPages": [
|
|
@@ -701,7 +701,7 @@
|
|
|
701
701
|
"assay"
|
|
702
702
|
],
|
|
703
703
|
"slug": "forge",
|
|
704
|
-
"version": "26.11.
|
|
704
|
+
"version": "26.11.21"
|
|
705
705
|
},
|
|
706
706
|
{
|
|
707
707
|
"availableDocPages": [
|
|
@@ -739,7 +739,7 @@
|
|
|
739
739
|
"keymap"
|
|
740
740
|
],
|
|
741
741
|
"slug": "gesture",
|
|
742
|
-
"version": "26.11.
|
|
742
|
+
"version": "26.11.21"
|
|
743
743
|
},
|
|
744
744
|
{
|
|
745
745
|
"availableDocPages": [
|
|
@@ -783,7 +783,7 @@
|
|
|
783
783
|
"familiar"
|
|
784
784
|
],
|
|
785
785
|
"slug": "herald",
|
|
786
|
-
"version": "26.11.
|
|
786
|
+
"version": "26.11.21"
|
|
787
787
|
},
|
|
788
788
|
{
|
|
789
789
|
"availableDocPages": [
|
|
@@ -826,7 +826,7 @@
|
|
|
826
826
|
"tempo"
|
|
827
827
|
],
|
|
828
828
|
"slug": "illusionist",
|
|
829
|
-
"version": "26.11.
|
|
829
|
+
"version": "26.11.21"
|
|
830
830
|
},
|
|
831
831
|
{
|
|
832
832
|
"availableDocPages": [
|
|
@@ -871,7 +871,7 @@
|
|
|
871
871
|
"ore"
|
|
872
872
|
],
|
|
873
873
|
"slug": "keymap",
|
|
874
|
-
"version": "26.11.
|
|
874
|
+
"version": "26.11.21"
|
|
875
875
|
},
|
|
876
876
|
{
|
|
877
877
|
"availableDocPages": [
|
|
@@ -918,7 +918,7 @@
|
|
|
918
918
|
"vault"
|
|
919
919
|
],
|
|
920
920
|
"slug": "ledger",
|
|
921
|
-
"version": "26.11.
|
|
921
|
+
"version": "26.11.21"
|
|
922
922
|
},
|
|
923
923
|
{
|
|
924
924
|
"availableDocPages": [
|
|
@@ -963,7 +963,7 @@
|
|
|
963
963
|
"courier"
|
|
964
964
|
],
|
|
965
965
|
"slug": "lingua",
|
|
966
|
-
"version": "26.11.
|
|
966
|
+
"version": "26.11.21"
|
|
967
967
|
},
|
|
968
968
|
{
|
|
969
969
|
"availableDocPages": [
|
|
@@ -1001,7 +1001,7 @@
|
|
|
1001
1001
|
"herald"
|
|
1002
1002
|
],
|
|
1003
1003
|
"slug": "mesh",
|
|
1004
|
-
"version": "26.11.
|
|
1004
|
+
"version": "26.11.21"
|
|
1005
1005
|
},
|
|
1006
1006
|
{
|
|
1007
1007
|
"availableDocPages": [
|
|
@@ -1038,7 +1038,7 @@
|
|
|
1038
1038
|
"ore"
|
|
1039
1039
|
],
|
|
1040
1040
|
"slug": "necromancer",
|
|
1041
|
-
"version": "26.11.
|
|
1041
|
+
"version": "26.11.21"
|
|
1042
1042
|
},
|
|
1043
1043
|
{
|
|
1044
1044
|
"availableDocPages": [
|
|
@@ -1078,7 +1078,7 @@
|
|
|
1078
1078
|
"prism"
|
|
1079
1079
|
],
|
|
1080
1080
|
"slug": "orbit",
|
|
1081
|
-
"version": "26.11.
|
|
1081
|
+
"version": "26.11.21"
|
|
1082
1082
|
},
|
|
1083
1083
|
{
|
|
1084
1084
|
"availableDocPages": [
|
|
@@ -1146,7 +1146,7 @@
|
|
|
1146
1146
|
"orbit"
|
|
1147
1147
|
],
|
|
1148
1148
|
"slug": "ore",
|
|
1149
|
-
"version": "26.11.
|
|
1149
|
+
"version": "26.11.21"
|
|
1150
1150
|
},
|
|
1151
1151
|
{
|
|
1152
1152
|
"availableDocPages": [
|
|
@@ -1190,7 +1190,7 @@
|
|
|
1190
1190
|
"vault"
|
|
1191
1191
|
],
|
|
1192
1192
|
"slug": "patchwork",
|
|
1193
|
-
"version": "26.11.
|
|
1193
|
+
"version": "26.11.21"
|
|
1194
1194
|
},
|
|
1195
1195
|
{
|
|
1196
1196
|
"availableDocPages": [
|
|
@@ -1234,7 +1234,7 @@
|
|
|
1234
1234
|
"ripple"
|
|
1235
1235
|
],
|
|
1236
1236
|
"slug": "postmaster",
|
|
1237
|
-
"version": "26.11.
|
|
1237
|
+
"version": "26.11.21"
|
|
1238
1238
|
},
|
|
1239
1239
|
{
|
|
1240
1240
|
"availableDocPages": [
|
|
@@ -1278,7 +1278,7 @@
|
|
|
1278
1278
|
"orbit"
|
|
1279
1279
|
],
|
|
1280
1280
|
"slug": "prism",
|
|
1281
|
-
"version": "26.11.
|
|
1281
|
+
"version": "26.11.21"
|
|
1282
1282
|
},
|
|
1283
1283
|
{
|
|
1284
1284
|
"availableDocPages": [
|
|
@@ -1342,7 +1342,7 @@
|
|
|
1342
1342
|
"clockwork"
|
|
1343
1343
|
],
|
|
1344
1344
|
"slug": "pulse",
|
|
1345
|
-
"version": "26.11.
|
|
1345
|
+
"version": "26.11.21"
|
|
1346
1346
|
},
|
|
1347
1347
|
{
|
|
1348
1348
|
"availableDocPages": [
|
|
@@ -1475,7 +1475,7 @@
|
|
|
1475
1475
|
"keymap"
|
|
1476
1476
|
],
|
|
1477
1477
|
"slug": "refine",
|
|
1478
|
-
"version": "26.11.
|
|
1478
|
+
"version": "26.11.21"
|
|
1479
1479
|
},
|
|
1480
1480
|
{
|
|
1481
1481
|
"availableDocPages": [
|
|
@@ -1520,7 +1520,7 @@
|
|
|
1520
1520
|
"ledger"
|
|
1521
1521
|
],
|
|
1522
1522
|
"slug": "ripple",
|
|
1523
|
-
"version": "26.11.
|
|
1523
|
+
"version": "26.11.21"
|
|
1524
1524
|
},
|
|
1525
1525
|
{
|
|
1526
1526
|
"availableDocPages": [
|
|
@@ -1574,7 +1574,7 @@
|
|
|
1574
1574
|
"familiar"
|
|
1575
1575
|
],
|
|
1576
1576
|
"slug": "rune",
|
|
1577
|
-
"version": "26.11.
|
|
1577
|
+
"version": "26.11.21"
|
|
1578
1578
|
},
|
|
1579
1579
|
{
|
|
1580
1580
|
"availableDocPages": [
|
|
@@ -1615,7 +1615,7 @@
|
|
|
1615
1615
|
"refine"
|
|
1616
1616
|
],
|
|
1617
1617
|
"slug": "sandbox",
|
|
1618
|
-
"version": "26.11.
|
|
1618
|
+
"version": "26.11.21"
|
|
1619
1619
|
},
|
|
1620
1620
|
{
|
|
1621
1621
|
"availableDocPages": [
|
|
@@ -1665,7 +1665,7 @@
|
|
|
1665
1665
|
"ripple"
|
|
1666
1666
|
],
|
|
1667
1667
|
"slug": "scout",
|
|
1668
|
-
"version": "26.11.
|
|
1668
|
+
"version": "26.11.21"
|
|
1669
1669
|
},
|
|
1670
1670
|
{
|
|
1671
1671
|
"availableDocPages": [
|
|
@@ -1707,7 +1707,7 @@
|
|
|
1707
1707
|
"archive"
|
|
1708
1708
|
],
|
|
1709
1709
|
"slug": "scribe",
|
|
1710
|
-
"version": "26.11.
|
|
1710
|
+
"version": "26.11.21"
|
|
1711
1711
|
},
|
|
1712
1712
|
{
|
|
1713
1713
|
"availableDocPages": [
|
|
@@ -1760,7 +1760,7 @@
|
|
|
1760
1760
|
"refine"
|
|
1761
1761
|
],
|
|
1762
1762
|
"slug": "scroll",
|
|
1763
|
-
"version": "26.11.
|
|
1763
|
+
"version": "26.11.21"
|
|
1764
1764
|
},
|
|
1765
1765
|
{
|
|
1766
1766
|
"availableDocPages": [
|
|
@@ -1807,7 +1807,7 @@
|
|
|
1807
1807
|
"gesture"
|
|
1808
1808
|
],
|
|
1809
1809
|
"slug": "sentinel",
|
|
1810
|
-
"version": "26.11.
|
|
1810
|
+
"version": "26.11.21"
|
|
1811
1811
|
},
|
|
1812
1812
|
{
|
|
1813
1813
|
"availableDocPages": [
|
|
@@ -1847,7 +1847,7 @@
|
|
|
1847
1847
|
"refine"
|
|
1848
1848
|
],
|
|
1849
1849
|
"slug": "sigil",
|
|
1850
|
-
"version": "26.11.
|
|
1850
|
+
"version": "26.11.21"
|
|
1851
1851
|
},
|
|
1852
1852
|
{
|
|
1853
1853
|
"availableDocPages": [
|
|
@@ -1892,7 +1892,7 @@
|
|
|
1892
1892
|
"wayfinder"
|
|
1893
1893
|
],
|
|
1894
1894
|
"slug": "sourcerer",
|
|
1895
|
-
"version": "26.11.
|
|
1895
|
+
"version": "26.11.21"
|
|
1896
1896
|
},
|
|
1897
1897
|
{
|
|
1898
1898
|
"availableDocPages": [
|
|
@@ -1952,7 +1952,7 @@
|
|
|
1952
1952
|
"vault"
|
|
1953
1953
|
],
|
|
1954
1954
|
"slug": "spell",
|
|
1955
|
-
"version": "26.11.
|
|
1955
|
+
"version": "26.11.21"
|
|
1956
1956
|
},
|
|
1957
1957
|
{
|
|
1958
1958
|
"availableDocPages": [
|
|
@@ -1995,7 +1995,7 @@
|
|
|
1995
1995
|
"archive"
|
|
1996
1996
|
],
|
|
1997
1997
|
"slug": "tabula",
|
|
1998
|
-
"version": "26.11.
|
|
1998
|
+
"version": "26.11.21"
|
|
1999
1999
|
},
|
|
2000
2000
|
{
|
|
2001
2001
|
"availableDocPages": [
|
|
@@ -2036,7 +2036,7 @@
|
|
|
2036
2036
|
"ripple"
|
|
2037
2037
|
],
|
|
2038
2038
|
"slug": "tandem",
|
|
2039
|
-
"version": "26.11.
|
|
2039
|
+
"version": "26.11.21"
|
|
2040
2040
|
},
|
|
2041
2041
|
{
|
|
2042
2042
|
"availableDocPages": [
|
|
@@ -2086,7 +2086,7 @@
|
|
|
2086
2086
|
"herald"
|
|
2087
2087
|
],
|
|
2088
2088
|
"slug": "tavern",
|
|
2089
|
-
"version": "26.11.
|
|
2089
|
+
"version": "26.11.21"
|
|
2090
2090
|
},
|
|
2091
2091
|
{
|
|
2092
2092
|
"availableDocPages": [
|
|
@@ -2147,7 +2147,7 @@
|
|
|
2147
2147
|
"vault"
|
|
2148
2148
|
],
|
|
2149
2149
|
"slug": "tempo",
|
|
2150
|
-
"version": "26.11.
|
|
2150
|
+
"version": "26.11.21"
|
|
2151
2151
|
},
|
|
2152
2152
|
{
|
|
2153
2153
|
"availableDocPages": [
|
|
@@ -2197,7 +2197,7 @@
|
|
|
2197
2197
|
"ripple"
|
|
2198
2198
|
],
|
|
2199
2199
|
"slug": "vault",
|
|
2200
|
-
"version": "26.11.
|
|
2200
|
+
"version": "26.11.21"
|
|
2201
2201
|
},
|
|
2202
2202
|
{
|
|
2203
2203
|
"availableDocPages": [
|
|
@@ -2243,7 +2243,7 @@
|
|
|
2243
2243
|
"refine"
|
|
2244
2244
|
],
|
|
2245
2245
|
"slug": "ward",
|
|
2246
|
-
"version": "26.11.
|
|
2246
|
+
"version": "26.11.21"
|
|
2247
2247
|
},
|
|
2248
2248
|
{
|
|
2249
2249
|
"availableDocPages": [
|
|
@@ -2300,8 +2300,8 @@
|
|
|
2300
2300
|
"herald"
|
|
2301
2301
|
],
|
|
2302
2302
|
"slug": "wayfinder",
|
|
2303
|
-
"version": "26.11.
|
|
2303
|
+
"version": "26.11.21"
|
|
2304
2304
|
}
|
|
2305
2305
|
],
|
|
2306
|
-
"version": "26.11.
|
|
2306
|
+
"version": "26.11.21"
|
|
2307
2307
|
}
|
package/data/llms-full.txt
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Vielzeug: Full Documentation
|
|
2
2
|
|
|
3
|
-
> Complete documentation for 47 packages. Version: 26.11.
|
|
3
|
+
> Complete documentation for 47 packages. Version: 26.11.21
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -7220,7 +7220,7 @@ type SortableTouchOptions = Readonly HTMLElement | null);
|
|
|
7220
7220
|
|
|
7221
7221
|
`preview` returns a template that Dnd clones before mounting it as a transient touch preview, so returning an element from the sortable item does not reparent or remove caller-owned DOM. Return `false` to disable the preview.
|
|
7222
7222
|
|
|
7223
|
-
Touch sorting delegates
|
|
7223
|
+
Touch sorting delegates activation, movement, identity, and cancellation to Gesture's `createDragGesture()` with pointer capture disabled for document hit-testing. Dnd retains preview rendering, hit-testing, synthetic drag events, and sortable transactions. A second touch cancels sorting and restores the pre-drag order without firing `onReorder` or `onMove`. Without a configured handle, touch starts on editing controls, buttons, links, ARIA controls, and `[data-no-drag]` subtrees are excluded. Explicit handles remain eligible, including button handles.
|
|
7224
7224
|
|
|
7225
7225
|
## `createDropZone()`
|
|
7226
7226
|
|
|
@@ -7702,6 +7702,8 @@ createSortable({
|
|
|
7702
7702
|
});
|
|
7703
7703
|
```
|
|
7704
7704
|
|
|
7705
|
+
Touch sorting ignores controls inside an item unless they belong to the configured handle. Put `data-no-drag` on a custom interaction subtree to exclude it when sorting whole items. A second finger cancels the drag and restores the original order; it never commits a reorder.
|
|
7706
|
+
|
|
7705
7707
|
### Keyboard reordering
|
|
7706
7708
|
|
|
7707
7709
|
Focus an item and use arrow keys to move it. `Home` and `End` move to the boundary positions.
|
|
@@ -10962,7 +10964,7 @@ const hold = createLongPress(list, {
|
|
|
10962
10964
|
});
|
|
10963
10965
|
```
|
|
10964
10966
|
|
|
10965
|
-
Movement beyond `slopPx
|
|
10967
|
+
Movement beyond `slopPx`, a second touch, window blur, or a hidden document cancels a pending hold. The dynamic `disabled` predicate is checked again before the timer fires. The pointer-generated click following a fired hold is swallowed through a capture-phase listener on `target`; keyboard clicks (`detail: 0`) remain available. Bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers.
|
|
10966
10968
|
|
|
10967
10969
|
## Types
|
|
10968
10970
|
|
|
@@ -10983,6 +10985,7 @@ type DragGestureOptions = Readonly boolean | undefined);
|
|
|
10983
10985
|
onMove?: (detail: DragGestureDetail) => void;
|
|
10984
10986
|
onStart?: (detail: DragGestureDetail) => void;
|
|
10985
10987
|
pointerCapture?: boolean;
|
|
10988
|
+
shouldActivate?: (detail: DragGestureDetail) => boolean;
|
|
10986
10989
|
shouldStart?: (event: PointerEvent) => boolean;
|
|
10987
10990
|
signal?: AbortSignal;
|
|
10988
10991
|
}>;
|
|
@@ -11007,6 +11010,7 @@ type PanGestureOptions = Readonly PanAxis);
|
|
|
11007
11010
|
onMove?: (detail: PanGestureDetail) => void;
|
|
11008
11011
|
onStart?: (detail: PanGestureDetail) => void;
|
|
11009
11012
|
pointerCapture?: boolean;
|
|
11013
|
+
shouldActivate?: (detail: PanGestureDetail) => boolean;
|
|
11010
11014
|
shouldStart?: (event: PointerEvent) => boolean;
|
|
11011
11015
|
signal?: AbortSignal;
|
|
11012
11016
|
}>;
|
|
@@ -11014,6 +11018,8 @@ type PanGestureOptions = Readonly PanAxis);
|
|
|
11014
11018
|
|
|
11015
11019
|
Pan details project `start`, `current`, and `distance` onto `axis`. The default axis is `'x'`.
|
|
11016
11020
|
|
|
11021
|
+
Velocity is signed CSS pixels per second over the trailing 90 ms. Samples include pointerdown, movement (including activation), and release. A window with fewer than two distinct sample times reports zero velocity; a pause longer than the window removes earlier movement.
|
|
11022
|
+
|
|
11017
11023
|
### Long-press types
|
|
11018
11024
|
|
|
11019
11025
|
```ts
|
|
@@ -11046,21 +11052,22 @@ type PanGesture = DragGesture;
|
|
|
11046
11052
|
|
|
11047
11053
|
### Shared option behavior
|
|
11048
11054
|
|
|
11049
|
-
| Option | Default | Contract
|
|
11050
|
-
| -------------------- | ------- |
|
|
11051
|
-
| `activationDistance` | `6` | Non-negative finite CSS pixels; drag uses Euclidean distance, pan waits for dominant-axis intent
|
|
11052
|
-
| `axis` | `'x'` | Pan only; fixed value or getter sampled when each interaction starts
|
|
11053
|
-
| `disabled` | `false` | Fixed value or getter; blocks starts and cancels active recognition on the next matching pointer event
|
|
11054
|
-
| `pointerCapture` | `true` | Best-effort capture after activation; document tracking continues when capture is disabled or fails
|
|
11055
|
-
| `shouldStart` | N/A | Admission predicate evaluated for the primary pointer before tracking starts
|
|
11056
|
-
| `
|
|
11057
|
-
| `
|
|
11058
|
-
| `
|
|
11059
|
-
| `
|
|
11055
|
+
| Option | Default | Contract |
|
|
11056
|
+
| -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
|
11057
|
+
| `activationDistance` | `6` | Non-negative finite CSS pixels; drag uses Euclidean distance, pan waits for dominant-axis intent |
|
|
11058
|
+
| `axis` | `'x'` | Pan only; fixed value or getter sampled when each interaction starts |
|
|
11059
|
+
| `disabled` | `false` | Fixed value or getter; blocks starts and cancels active recognition on the next matching pointer event |
|
|
11060
|
+
| `pointerCapture` | `true` | Best-effort capture after activation; document tracking continues when capture is disabled or fails |
|
|
11061
|
+
| `shouldStart` | N/A | Admission predicate evaluated for the primary pointer before tracking starts |
|
|
11062
|
+
| `shouldActivate` | N/A | Drag/pan predicate evaluated once after distance/axis recognition and before capture or callbacks; false rejects the session |
|
|
11063
|
+
| `signal` | N/A | Disposes the handle when the external owner aborts |
|
|
11064
|
+
| `onStart` | N/A | Runs once on the activating movement |
|
|
11065
|
+
| `onMove` | N/A | Runs on the activating movement and each later matching movement |
|
|
11066
|
+
| `onEnd` | N/A | Runs once for active release or cancellation; pending interactions end without callbacks |
|
|
11060
11067
|
|
|
11061
11068
|
Options and callback details are readonly. Fixed callbacks and capture policy are snapshotted at construction. Function-valued `axis` and `disabled` options remain dynamic.
|
|
11062
11069
|
|
|
11063
|
-
Gesture tracks accepted movement with capture-phase listeners on the target's current owner document. Window blur, hidden-document transition, `pointercancel`,
|
|
11070
|
+
Gesture tracks accepted movement with capture-phase listeners on the target's current owner document. Window blur, hidden-document transition, `pointercancel`, pointer capture loss on the gesture target, and a second touch anywhere in that document cancel recognition. A `lostpointercapture` event bubbling from a descendant does not cancel the target's gesture. Exact diagonal ties remain pending until one axis dominates; cross-axis dominance rejects the pending pan. Gesture does not arbitrate ownership between recognizers on the same axis.
|
|
11064
11071
|
|
|
11065
11072
|
## Errors
|
|
11066
11073
|
|
|
@@ -11155,7 +11162,7 @@ Gesture reports movement and terminal state but does not decide what constitutes
|
|
|
11155
11162
|
const pan = createPanGesture(panel, {
|
|
11156
11163
|
axis: 'x',
|
|
11157
11164
|
onEnd: ({ distance, reason }) => {
|
|
11158
|
-
if (reason === 'release' && distance
|
|
11165
|
+
if (reason === 'release' && distance distance > 0 && scroller.scrollTop
|
|
11159
11166
|
!event.composedPath().some((node) => node instanceof Element && node.matches('button, a, input, select, textarea')),
|
|
11160
11167
|
onMove,
|
|
11161
11168
|
onEnd,
|
package/data/llms.txt
CHANGED
package/data/manifest.json
CHANGED
package/data/packages/dnd.json
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"apiSource": "// Full API aggregate and IIFE bundle entry. For tree-shaken imports prefer the\n// `@vielzeug/dnd/drop` and `@vielzeug/dnd/sortable` subpaths.\nexport * from './drop-zone.js';\nexport { DndError, DndScopeError } from './errors.js';\nexport * from './sortable.js';\nexport * from './types.js';\n",
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: 'Dnd: Drag-and-drop primitives for the DOM'\ndescription: 'Framework-agnostic drag-and-drop. Drop zones with MIME filtering, sortable lists with drag handles, and explicit connected scopes: zero third-party dependencies.'\npackage: dnd\ncategory: ui-interaction\nkeywords: [drag-drop, sortable, file-upload, drop-zone, dnd, reorder]\nrelated: [gesture, ore, scroll, refine]\nexports: [createDropZone, createSortable, createSortableScope, applyReorder, matchesAccept]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"dnd\" />\n\n## Why Dnd?\n\nThe HTML5 Drag & Drop API requires careful counter tracking to avoid hover state flicker, has no MIME type pre-filtering, and provides no sortable list abstraction.\n\n```ts\n// Before: raw HTML5 Drag & Drop\nlet enterCount = 0;\ndropzone.addEventListener('dragenter', () => {\n enterCount++;\n dropzone.classList.add('over');\n});\ndropzone.addEventListener('dragleave', () => {\n if (--enterCount === 0) dropzone.classList.remove('over');\n});\ndropzone.addEventListener('dragover', (e) => e.preventDefault());\ndropzone.addEventListener('drop', (e) => {\n e.preventDefault();\n enterCount = 0;\n const files = [...e.dataTransfer!.files];\n if (!files.every((f) => f.type.startsWith('image/'))) return showError('Images only');\n uploadFiles(files);\n});\n\n// After: Dnd\nimport { createDropZone } from '@vielzeug/dnd/drop';\nconst zone = createDropZone({\n element: dropzone,\n accept: ['image/*'],\n onDrop: (files) => uploadFiles(files),\n onDropRejected: (files) => showError(`${files.length} file(s) not accepted`),\n onHoverChange: (hovered) => dropzone.classList.toggle('over', hovered),\n});\n```\n\n| Feature | DND | SortableJS | dnd-kit |\n| ----------------------------- | ---------------------------------------------------------- | -------------------------------------------- | -------------------------------------------- |\n| Bundle size | <PackageInfo package=\"dnd\" type=\"size\" /> | ~15 kB | ~30 kB |\n| Framework agnostic | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| MIME type filtering | <ore-icon name=\"check\" size=\"16\"></ore-icon> Pre-validated | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Counter-based hover | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | N/A |\n| Sortable lists | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Drag handles | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| `using` support | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n| Touch support | <ore-icon name=\"check\" size=\"16\"></ore-icon> Scoped opt-in | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> |\n| Zero third-party dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"check\" size=\"16\"></ore-icon> | <ore-icon name=\"x\" size=\"16\"></ore-icon> |\n\n<div class=\"decision-callout\">\n\n**Use Dnd when** an item is picked up and dropped: file drop zones, sortable collections, keyboard reordering, or connected lists.\n\n**Use Gesture instead** when a surface follows free or axis-locked pointer movement and application code owns rendering and completion, such as direct manipulation, swipe reveal, carousel navigation, or drawer dismissal.\n\n**Consider dnd-kit** if you are building a React app and need complex multi-container drag interactions or accessibility-first sortable trees.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/dnd\n```\n\n```sh [npm]\nnpm install @vielzeug/dnd\n```\n\n```sh [yarn]\nyarn add @vielzeug/dnd\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createDropZone } from '@vielzeug/dnd/drop';\nimport { createSortable } from '@vielzeug/dnd/sortable';\n\n// File drop zone: with async validation and paste support\nconst dropzone = document.getElementById('dropzone')!;\n\nusing zone = createDropZone({\n element: dropzone,\n accept: ['image/*', '.pdf'],\n paste: true,\n onValidate: (files) => files.every((file) => file.size <= 5_000_000),\n onDrop: (files) => console.log('Upload', files),\n onDropRejected: (files) => {\n console.warn(`${files.length} file(s) rejected`);\n },\n onHoverChange: (hovered) => {\n dropzone.classList.toggle('drag-over', hovered);\n },\n});\n\n// Sortable list: with application-owned rollback for optimistic updates\nlet currentOrder = ['a', 'b', 'c'];\nconst history: Array<{ before: readonly string[] }> = [];\n\nusing sortable = createSortable({\n element: document.getElementById('list')!,\n keyboard: true,\n onBeforeReorder: (from, to) => {\n // record positions here before the DOM commits (for FLIP animations)\n },\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ before, after }) => {\n history.push({ before });\n currentOrder = after;\n },\n});\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- **Counter-based hover state**: `onHoverChange` stays accurate when dragging over child elements; hover only activates when the drag payload passes the `accept` filter, with symmetric enter/leave pairing to prevent flicker\n- **MIME type pre-validation**: queries `dataTransfer.items` during drag to set `dropEffect='none'` before the drop; confirmed against `File.type` on drop\n- **Flexible accept patterns**: MIME types (`image/png`), wildcards (`image/*`), and file extensions (`.pdf`)\n- **`maxFiles` limit**: cap the number of accepted files per drop; excess files are forwarded to `onDropRejected`\n- **`onValidate` async gating**: optional cancellable async step after type filtering; `zone.validating` remains `true` until every pending validation settles\n- **Clipboard paste support**: `paste: true` routes pasted files through the same `accept`, `maxFiles`, and `onValidate` pipeline; `onPaste` provides a separate callback; paste rejections are forwarded to `onDropRejected` with the same `(files: File[]) => void` signature as drop rejections\n- **`onDropRejected`**: separate callback for files that didn't match `accept`, exceeded `maxFiles`, or were rejected by `onValidate`\n- **Sortable lists**: reorders DOM children with a placeholder indicator; fires `onReorder` only when the order actually changes\n- **Drag handles**: scope dragging to a child selector via `handle`; whole item is draggable when omitted\n- **Custom drag preview**: pass an element or a `(id, item, event) => element | null` factory; control hotspot with `dragImageOffset`\n- **`onBeforeReorder` FLIP hook**: fires before commit for both drag and keyboard moves; pair it with [`captureLayout()`](/necromancer/api.md#capturelayout) for lifecycle-owned FLIP animation\n- **Application-owned rollback**: `onReorder` emits `{ before, after, item }` so application history can own undo/rollback instead of the drag controller\n- **Boundary-safe keyboard reordering**: arrow keys at the first/last item no longer suppress `preventDefault`, so the browser can scroll the page normally\n- **Transactional connected scopes**: one `onMove` callback receives each cross-list transfer with both final orders\n- **Scoped touch support**: `createSortableScope({ touch: true })` handles only items registered to that scope and uses an inert outline preview\n- **Explicit DOM refresh**: call `sortable.refresh()` after DOM mutations, or provide an `items()` provider for explicit item ownership\n- **`[Symbol.dispose]`**: both primitives support the `using` keyword for automatic cleanup\n- **Reactive-friendly options**: `disabled` is re-read on each event (reassign `options.disabled = true` to toggle); `accept` is normalized and snapshotted at construction; recreate the zone to change accepted types\n- **Shared pointer recognition**: touch sorting uses `@vielzeug/gesture`; Dnd retains previews, hit-testing, drag events, and sortable transactions\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Orbit](/orbit/): floating element positioning; use alongside Dnd to anchor drag previews and drop-zone indicators to precise positions\n- [Gesture](/gesture/): pointer recognition used by Dnd touch sorting and directly by swipe, reveal, carousel, and drawer interactions\n- [Ore](/ore/): web-component authoring framework for application-owned draggable and sortable surfaces\n- [Refine](/refine/): accessible web components; Dnd powers Refine's file-drop input behavior\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Dnd: API Reference'\ndescription: Complete API reference for Dnd.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------------------- | -------------------------------------------- | -------------- | ----------------------------------------------------------------- |\n| `createDropZone()` | Create a typed drop-zone controller | Sync | Dispose the controller during teardown |\n| `createSortable()` | Add sortable drag-and-drop behavior to lists | Sync | Provide stable item identity for reorder operations |\n| `createSortableScope()` | Create a shared scope for connected lists | Sync | Each set of connected containers needs its own scope instance |\n| `applyReorder()` | Apply ordered IDs to data arrays | Sync | Unknown IDs are skipped; non-mentioned items are appended |\n| `DropZoneOptions.accept` | Filter file types before processing | Sync | Mismatch between MIME and extension can reject files unexpectedly |\n| `DropZoneOptions.maxFiles` | Cap accepted files per drop | Sync | Excess accepted files become rejected; `onDropRejected` is called |\n| `matchesAccept()` | Test a single `File` against an accept list | Sync | Extension patterns are case-insensitive; empty list accepts all |\n| `DndError` | Base class for Dnd errors | Sync | Use `instanceof DndError` to narrow unknown errors |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | ---------------------------------------------------------------- |\n| `@vielzeug/dnd` | Backward-compat root barrel |\n| `@vielzeug/dnd/drop` | Drop-zone APIs plus `DndError` and `Disposable` |\n| `@vielzeug/dnd/sortable` | Sortable APIs plus `DndError`, `DndScopeError`, and `Disposable` |\n\nDnd has no third-party runtime dependencies. Its sortable touch adapter uses `@vielzeug/gesture` for shared pointer recognition.\n\n## Types\n\n### `Disposable`\n\n```ts\ninterface Disposable {\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n```\n\n### `DropZoneOptions`\n\n```ts\ninterface DropZoneOptions {\n element: HTMLElement;\n accept?: readonly string[];\n maxFiles?: number;\n onValidate?: (files: File[], context: DropValidationContext) => boolean | Promise<boolean>;\n disabled?: boolean;\n dropEffect?: DataTransfer['dropEffect'];\n onDrop?: (files: File[]) => void;\n onDropRejected?: (files: File[]) => void;\n onHoverChange?: (hovered: boolean) => void;\n onValidatingChange?: (validating: boolean) => void;\n paste?: boolean;\n onPaste?: (files: File[]) => void;\n}\n```\n\n### `DropZone`\n\n```ts\ninterface DropZone extends Disposable {\n readonly hovered: boolean;\n readonly validating: boolean;\n}\n```\n\n### `DropValidationContext`\n\n```ts\ninterface DropValidationContext {\n readonly signal: AbortSignal;\n}\n```\n\n### `SortableOptions`\n\n```ts\ninterface SortableOptions {\n element: HTMLElement;\n getKey: (element: HTMLElement) => string;\n scope?: SortableScope;\n handle?: string;\n keyboard?: boolean;\n axis?: 'vertical' | 'horizontal';\n autoScroll?: boolean | AutoScrollOptions;\n dragImage?: HTMLElement | ((id: string, item: HTMLElement, event: DragEvent) => HTMLElement | null | undefined);\n dragImageOffset?: [number, number];\n placeholderClass?: string;\n disabled?: boolean;\n onDragStart?: (id: string, event: DragEvent) => void;\n onDragEnd?: (id: string, event: DragEvent) => void;\n onInteraction?: (event: SortableInteractionEvent) => void;\n onBeforeReorder?: (from: readonly string[], to: readonly string[]) => void;\n onReorder?: (event: ReorderEvent) => void;\n items?: () => readonly HTMLElement[];\n}\n```\n\n### `AutoScrollOptions`\n\n```ts\ninterface AutoScrollOptions {\n edgeThreshold?: number;\n speed?: number;\n container?: boolean;\n viewport?: boolean;\n}\n```\n\n### `ReorderEvent`\n\n```ts\ninterface ReorderEvent {\n before: readonly string[];\n after: readonly string[];\n item: string;\n}\n```\n\n### `Sortable`\n\n```ts\ninterface Sortable extends Disposable {\n readonly isDragging: boolean;\n refresh(): void;\n}\n```\n\n### `SortableScope`\n\n```ts\ninterface SortableScope extends Disposable {\n readonly isDragging: boolean;\n}\n```\n\n### `SortableScopeOptions`\n\n```ts\ninterface SortableScopeOptions {\n onMove?: (event: SortableMoveEvent) => void;\n touch?: boolean | SortableTouchOptions;\n}\n```\n\n### `SortableMoveEvent`\n\n```ts\ninterface SortableMoveEvent {\n readonly itemId: string;\n readonly source: HTMLElement;\n readonly sourceBeforeIds: readonly string[];\n readonly sourceIds: readonly string[];\n readonly target: HTMLElement;\n readonly targetBeforeIds: readonly string[];\n readonly targetIds: readonly string[];\n}\n```\n\n### `SortableInteractionEvent`\n\nStructured accessibility/observability event for sortable interactions. Drag emits `pickup` on dragstart, `drop` on commit, `cancel` on cancel. Keyboard emits `move` on each successful arrow/Home/End reorder (direct-commit model).\n\n```ts\ntype SortableInteractionEvent =\n | { readonly type: 'pickup'; readonly itemId: string; readonly index: number; readonly total: number }\n | {\n readonly type: 'move';\n readonly itemId: string;\n readonly previousIndex: number;\n readonly index: number;\n readonly total: number;\n }\n | { readonly type: 'drop'; readonly itemId: string; readonly index: number; readonly total: number }\n | { readonly type: 'cancel'; readonly itemId: string; readonly index: number; readonly total: number };\n```\n\nWire a consumer-side announcer to provide screen-reader feedback:\n\n```ts\nimport { createSortable } from '@vielzeug/dnd/sortable';\n\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.id!,\n onInteraction(event) {\n switch (event.type) {\n case 'pickup':\n announce(`Picked up ${event.itemId}, position ${event.index + 1} of ${event.total}`);\n break;\n case 'move':\n announce(`Moved ${event.itemId} to position ${event.index + 1} of ${event.total}`);\n break;\n case 'drop':\n announce(`Dropped ${event.itemId} at position ${event.index + 1} of ${event.total}`);\n break;\n case 'cancel':\n announce(`Cancelled, ${event.itemId} returned to position ${event.index + 1} of ${event.total}`);\n break;\n }\n },\n});\n```\n\n### `SortableTouchOptions`\n\n```ts\ntype SortableTouchOptions = Readonly<{\n activationDistance?: number;\n preview?: false | ((item: HTMLElement) => HTMLElement | null);\n}>;\n```\n\n`activationDistance` is the non-negative finite movement threshold in pixels before touch sorting starts (default `6`). Invalid values throw `DndError`.\n\n`preview` returns a template that Dnd clones before mounting it as a transient touch preview, so returning an element from the sortable item does not reparent or remove caller-owned DOM. Return `false` to disable the preview.\n\nTouch sorting delegates one-pointer activation, movement, identity, and cancellation to Gesture's `createDragGesture()` with pointer capture disabled for document hit-testing. Dnd retains preview rendering, hit-testing, synthetic drag events, and sortable transactions. Non-primary pointers are ignored, and cancellation restores the pre-drag order without firing `onReorder`.\n\n## `createDropZone()`\n\n```ts\ndeclare function createDropZone(options: DropZoneOptions): DropZone;\n```\n\nAttaches drag-and-drop file handling to a DOM element. Returns a `DropZone` handle.\n\n| Option | Type | Default | Description |\n| -------------------- | ---------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `element` | `HTMLElement` | N/A | **Required.** The element to attach drag listeners to. |\n| `accept` | `string[]` | `[]` | Accepted file types, normalized and snapshotted at construction. Empty array accepts everything; invalid MIME, wildcard, or extension patterns throw `DndError`. |\n| `maxFiles` | `number` | N/A | Non-negative safe-integer file limit. Excess files are passed to `onDropRejected`; invalid values throw `DndError` during construction. |\n| `onValidate` | `(files, { signal }) => boolean \\| Promise<boolean>` | N/A | Optional async gating step. Return or resolve `false` to reject all accepted files. `validating` remains true until every operation settles; `signal` aborts on disposal. |\n| `disabled` | `boolean` | N/A | When `true`, all drag and paste events are ignored. A disabled zone does not call `preventDefault` on `dragenter`, `dragover`, `drop`, or `paste`, so underlying elements (text editors, etc.) receive them normally. |\n| `dropEffect` | `'copy' \\| 'move' \\| 'link' \\| 'none'` | `'copy'` | The `dropEffect` set on `dataTransfer` during `dragover`. Controls the cursor indicator. |\n| `onDrop` | `(files: File[]) => void` | N/A | Called with accepted files only. Not called if all dropped files are rejected. Also receives paste events when `paste: true` and `onPaste` is omitted. |\n| `onDropRejected` | `(files: File[]) => void` | N/A | Called with files that did not match `accept`, exceeded `maxFiles`, or were rejected by `onValidate`. |\n| `onHoverChange` | `(hovered: boolean) => void` | N/A | Called when hover state toggles. Use this callback for drag-over styling. |\n| `onValidatingChange` | `(validating: boolean) => void` | N/A | Called whenever the aggregate async validation state changes. |\n| `paste` | `boolean` | `false` | When `true`, attaches a `paste` listener to `element`. Pasted files run through the same `accept`, `maxFiles`, and `onValidate` pipeline as dropped files. |\n| `onPaste` | `(files: File[]) => void` | N/A | Called when files are pasted from the clipboard. Falls back to `onDrop` when omitted. Only active when `paste: true`. |\n\n**Returns:** `DropZone`\n\nNotes:\n\n- Extension accept patterns are approximate during pre-check (`DataTransferItem` has no filename); exact filtering is applied at drop time.\n- Hover state (`hovered`) only becomes `true` when the dragged payload passes the `accept` filter. Drags carrying rejected file types enter and leave the zone without triggering `onHoverChange`.\n- Hover state is reset on element drop and also global `window` `drop`/`dragend` to avoid stuck hover state when drags leave the viewport.\n- Disposal aborts validation and transitions `validating` to `false` before teardown completes.\n- Consumer callback failures are reported through Dnd's development warning channel and never reclassify accepted files as rejected.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*', '.pdf'],\n onDrop: (files) => {\n upload(files);\n },\n onDropRejected: (files) => {\n showError(`${files.length} rejected`);\n },\n onHoverChange: (hovered) => {\n dropEl.classList.toggle('drag-over', hovered);\n },\n});\n```\n\n## `DropZone` Interface\n\n### `zone.hovered`\n\n`readonly hovered: boolean`\n\n`true` when a drag is currently over the zone. Updated synchronously by the internal counter: safe to read at any time.\n\n### `zone.validating`\n\n`readonly validating: boolean`\n\n`true` while an `onValidate` promise is pending. Use this to render a loading indicator between file selection and the acceptance/rejection callbacks firing.\n\n```ts\nconsole.log(zone.validating); // true between drop and onValidate resolution\n```\n\n### `zone.disposed`\n\n`readonly disposed: boolean`\n\n`true` once `dispose()` has been called. Safe to read at any time.\n\n### `zone.disposalSignal`\n\n`readonly disposalSignal: AbortSignal`\n\nAn `AbortSignal` that fires when `dispose()` is called. Use it to cancel in-flight requests tied to the zone's lifetime.\n\n### `zone.dispose()`\n\n`dispose(): void`\n\nRemoves all event listeners, aborts pending validation, and resets `hovered` and `validating`. Idempotent: safe to call multiple times.\n\n```ts\nzone.dispose();\n```\n\n### `zone[Symbol.dispose]()`\n\n`[Symbol.dispose](): void`\n\nAlias for `dispose()`. Called automatically when used with the `using` keyword.\n\n```ts\n{\n using zone = createDropZone({ element: dropEl, onDrop: handleFiles });\n} // zone.dispose() runs here\n```\n\n## `createSortable()`\n\n```ts\ndeclare function createSortable(options: SortableOptions): Sortable;\n```\n\nMakes the direct children of a container element reorderable via drag. Returns a `Sortable` handle.\n\n`createSortable` adds drag and keyboard defaults only when callers have not already supplied semantics. Every changed attribute and inline style is restored to its prior value on disposal.\n\n- `element`: `HTMLElement`, required. The container whose children become sortable.\n- `getKey`: `(element: HTMLElement) => string`, required. Maps each item element to its stable string identity. Children for which `getKey` returns a falsy value are skipped.\n- `scope`: `SortableScope`, default private scope. Connects sortable lists explicitly; containers only exchange items when they share the same scope instance.\n- `handle`: `string`. Valid CSS selector for a drag handle inside each item. Invalid selectors throw `DndError`; an empty selector warns and disables dragging.\n- `keyboard`: `boolean`, default `true`. Enables keyboard reordering with arrow keys plus `Home` and `End`, matched through `matchKey` from `@vielzeug/keymap`: modifier chords (e.g. Ctrl+ArrowDown, browser back/forward) are ignored. Events from interactive descendants are ignored unless they match the configured handle.\n- `axis`: `'vertical' | 'horizontal'`, default `'vertical'`. Controls midpoint calculation for placeholder insertion.\n- `autoScroll`: `boolean | AutoScrollOptions`, default `true`. Scrolls near edges; threshold must be finite and non-negative and speed finite and positive.\n- `dragImage`: `HTMLElement | ((id, item, event) => HTMLElement | null | undefined)`. Custom native drag preview passed to `dataTransfer.setDragImage()`. A `null` or `undefined` return skips `setDragImage` entirely.\n- `dragImageOffset`: `[number, number]`, default `[0, 0]`. The `[x, y]` hotspot offset passed to `setDragImage`. Controls which point of the preview image follows the cursor.\n- `placeholderClass`: `string`, default `'dnd-placeholder'`. CSS class applied to the generated placeholder element.\n- `disabled`: `boolean`. Blocks drag interactions. If a list becomes disabled mid-drag, Dnd cancels the drag and restores the original order.\n- `onDragStart`: `(id: string, event: DragEvent) => void`. Called when a drag starts.\n- `onDragEnd`: `(id: string, event: DragEvent) => void`. Called when a drag ends, whether completed or cancelled.\n- `onInteraction`: `(event: SortableInteractionEvent) => void`. Structured accessibility event for pickup/move/drop/cancel: wire to a consumer-side announcer for screen-reader feedback. See [`SortableInteractionEvent`](#sortableinteractionevent).\n- `onBeforeReorder`: `(from: readonly string[], to: readonly string[]) => void`. Called with the before/after order snapshots just before a successful reorder commits: for both drag and keyboard. Items are still in their pre-commit positions at the time of the call, making it ideal for [`captureLayout()`](/necromancer/api.md#capturelayout) setup.\n- `items`: `() => readonly HTMLElement[]`. Returns direct children owned by this sortable. `refresh()` restores elements no longer returned before marking the current set.\n- `onReorder`: `(event: ReorderEvent) => void`. Called after a successful reorder (drag or keyboard), only when the order changed. The event carries `before`, `after`, and `item` so application history can own rollback.\n\nOrder arrays and interaction events are frozen snapshots. Callback failures are reported through Dnd's development warning channel and cannot interrupt session completion or corrupt later events. Native touch scrolling is preserved unless the shared scope enables touch input.\n\n**Returns:** `Sortable`\n\n```ts\nconst boardScope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => saveMove(itemId, sourceIds, targetIds),\n touch: true,\n});\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.id!,\n handle: '.drag-handle',\n onDragStart: (id) => {\n listEl.classList.add('sorting');\n },\n onDragEnd: (id) => {\n listEl.classList.remove('sorting');\n },\n onReorder: ({ before, after }) => {\n history.push({ revert: () => saveOrder(before) });\n saveOrder(after);\n },\n scope: boardScope,\n});\n```\n\n### `createSortableScope()`\n\n```ts\ndeclare function createSortableScope(options?: SortableScopeOptions): SortableScope;\n```\n\nUse one scope per connected set of containers. `onMove` fires once for cross-list moves with both final orders; local reorders continue to call the sortable's `onReorder`.\n\n| Parameter | Type | Description |\n| --------- | ---------------------- | --------------------------------------------------------------------- |\n| `options` | `SortableScopeOptions` | Optional cross-list move callback and scope-owned touch configuration |\n\n**Returns:** `SortableScope`.\n\n```ts\nimport { createSortableScope } from '@vielzeug/dnd/sortable';\n\nconst scope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => {\n persistMove(itemId, sourceIds, targetIds);\n },\n touch: true,\n});\n```\n\n## `Sortable` Interface\n\n### `sortable.isDragging`\n\n`readonly isDragging: boolean`\n\n`true` while an item drag is in progress.\n\n### `sortable.refresh()`\n\n`refresh(): void`\n\nRe-reads items from the `items` provider (or the container's direct children) and reapplies `draggable`, `role`, and handle attributes. Call it after adding, removing, or replacing sortable children.\n\n### `sortable.disposed`\n\n`readonly disposed: boolean`\n\n`true` once `dispose()` has been called.\n\n### `sortable.disposalSignal`\n\n`readonly disposalSignal: AbortSignal`\n\nAn `AbortSignal` that fires when `dispose()` is called.\n\n### `sortable.dispose()`\n\n`dispose(): void`\n\nRemoves all event listeners from the container, strips sortable attributes from items and handles, and cancels any in-progress drag by restoring the original order. Idempotent: safe to call multiple times.\n\n### `sortable[Symbol.dispose]()`\n\n`[Symbol.dispose](): void`\n\nAlias for `dispose()`.\n\n## `SortableScope` Interface\n\n### `scope.isDragging`\n\n`readonly isDragging: boolean`\n\n`true` while any sortable registered to the scope is dragging.\n\n### `scope.dispose()`\n\n`dispose(): void`\n\nDisposes scope-owned touch input and all registered sortables. Registering a new sortable with a disposed scope throws `DndScopeError`.\n\n## DOM Attributes\n\nDnd reads and writes the following DOM attributes:\n\n- `data-dnd-item`: internal marker applied by `createSortable` to children that return a truthy key from `getKey`. Restored on `dispose()`.\n- `draggable`, roles, tabindex, and `touchAction`: managed only as needed and restored to their exact prior values on `dispose()`.\n- `data-dragging`: set during drag, removed on `dragend` or `dispose()`. Use it as your styling hook for drag state.\n- `data-dnd-handle`: internal marker set by `createSortable` and `sortable.refresh()`, removed by `dispose()`. Lets Dnd clean up only the handle attributes it applied.\n- `aria-hidden=\"true\"`: set on placeholder creation and removed with the placeholder. Applied to the `.dnd-placeholder` element.\n- `style.touchAction = 'none'` (inline style): set by `createSortable` and `sortable.refresh()` on the item (or the handle, when `handle` is set), then restored on `dispose()`.\n\n## CSS Classes\n\n| Class | Applied to | When |\n| ----------------- | ---------------------------- | ------------------------------------------------------------- |\n| `dnd-placeholder` | `<div>` inserted by sortable | While an item is being dragged, in the placeholder's position |\n\n## `matchesAccept()`\n\n```ts\ndeclare function matchesAccept(file: File, accept: readonly string[]): boolean;\n```\n\nTests whether a `File` matches an accept pattern list. Each pattern can be:\n\n- A MIME type: `'image/png'`\n- A MIME wildcard: `'image/*'`\n- A file extension: `'.pdf'`\n\nAn empty list accepts everything. Extension matching is case-insensitive.\n\n**Returns:** `true` when the file matches at least one pattern, or when `accept` is empty.\n\n```ts\nimport { matchesAccept } from '@vielzeug/dnd/drop';\n\nmatchesAccept(file, ['image/*', '.pdf']); // true or false\n```\n\n## `applyReorder()`\n\n```ts\ndeclare function applyReorder<T>(items: readonly T[], ids: readonly string[], getKey: (item: T) => string): T[];\n```\n\nApplies a DOM reorder result (`orderedIds`) to your backing array.\n\n- IDs missing from `items` are ignored.\n- Items not listed in `ids` are appended in original order.\n- Duplicate IDs in `ids`: first occurrence wins, later occurrences are ignored.\n- Duplicate keys in `items` throw `DndError`; data is never silently discarded.\n\n**Returns:** A new array ordered by `ids`, with omitted items appended in their original order.\n\n```ts\nconst next = applyReorder(items, orderedIds, (item) => item.id);\n```\n\n## Errors\n\n| Error | Trigger | Notable property |\n| --------------- | ------------------------------------------------------------------------------------------- | ----------------------------- |\n| `DndError` | Invalid configuration, duplicate item data, or duplicate sortable registration in one scope | Base class for package errors |\n| `DndScopeError` | A sortable receives an invalid or disposed scope | Extends `DndError` |\n",
|
|
6
|
-
"usage": "---\ntitle: 'Dnd: Usage Guide'\ndescription: Drop zones, sortable lists, explicit connected scopes, keyboard sorting, and cleanup patterns with Dnd.\n---\n\n[[toc]]\n\n## Basic Usage\n\n`createDropZone` attaches drag-and-drop behavior to any DOM element and keeps hover state stable with a counter.\n\n```ts\nimport { createDropZone } from '@vielzeug/dnd/drop';\n\nconst dropzone = document.getElementById('dropzone')!;\n\nconst zone = createDropZone({\n element: dropzone,\n onDrop: (files) => {\n console.log('Accepted files:', files);\n },\n});\n```\n\n### Accept filtering\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*', '.pdf', 'application/json'],\n onDrop: (files) => {\n // accepted files only\n },\n onDropRejected: (files) => {\n showToast(`${files.length} file(s) not accepted`);\n },\n});\n```\n\nThe `accept` list is normalized and snapshotted at construction. MIME matching is case-insensitive; invalid patterns throw `DndError`. Recreate the zone to change accepted types.\n\n### Hover state\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n onHoverChange: (hovered) => {\n dropEl.classList.toggle('drag-over', hovered);\n },\n});\n```\n\nRead zone state imperatively:\n\n```ts\nconsole.log(zone.hovered);\nconsole.log(zone.validating);\n```\n\n### Drop effect\n\n```ts\ncreateDropZone({\n element: dropEl,\n dropEffect: 'move',\n onDrop: (files) => {\n // ...\n },\n});\n```\n\n### Disabled state\n\n```ts\nconst options = { disabled: false, element: dropEl, onDrop: handleFiles };\nconst zone = createDropZone(options);\n\n// options.disabled is read live on each event: mutate to toggle:\noptions.disabled = isReadOnly;\n```\n\n### File limit\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*'],\n maxFiles: 5,\n onDrop: (files) => {\n // 1-5 accepted files\n },\n onDropRejected: (files) => {\n showToast(`Only 5 files at a time. ${files.length} were ignored.`);\n },\n});\n```\n\n### Cleanup\n\n```ts\nzone.dispose();\n// or:\nusing zone = createDropZone({ element: dropEl, onDrop: handleFiles });\n```\n\n`maxFiles` must be a non-negative safe integer.\n\n### Async validation\n\nGate drops behind an async check with `onValidate`. The zone remains `validating: true` until every pending validation settles, and disposal aborts each validation signal.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*'],\n onValidate: async (files, { signal }) => {\n const ok = await checkServerQuota(files, { signal });\n return ok; // false → all files forwarded to onDropRejected\n },\n onDrop: (files) => uploadFiles(files),\n onDropRejected: (files) => showError('Quota exceeded'),\n});\n\n// show a spinner while checking\nconsole.log(zone.validating); // true during pending check\n```\n\nA synchronous boolean return skips the microtask queue entirely:\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n onValidate: (files) => files.every((f) => f.size < 5_000_000), // sync\n onDrop: handleFiles,\n});\n```\n\n### Clipboard paste\n\nSet `paste: true` to accept files pasted through the drop-zone element. The focused paste target must be the element or its descendant; the same `accept`, `maxFiles`, and `onValidate` pipeline applies.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n paste: true,\n accept: ['image/*'],\n onPaste: (files) => {\n uploadFiles(files);\n },\n onDropRejected: (files) => {\n showError(`${files.length} file(s) not accepted`);\n },\n});\n```\n\nWhen `onPaste` is omitted, accepted pasted files fall through to `onDrop`.\n\n## Sortable\n\n`createSortable` makes direct children of a container reorderable via drag.\n\n### Setup\n\n```html\n<ul id=\"task-list\">\n <li data-sort-id=\"task-1\">Design</li>\n <li data-sort-id=\"task-2\">Develop</li>\n <li data-sort-id=\"task-3\">Review</li>\n</ul>\n```\n\n```ts\nconst sortable = createSortable({\n element: document.getElementById('task-list')!,\n getKey: (el) => el.dataset.sortId!,\n axis: 'vertical',\n onReorder: ({ after }) => {\n saveTaskOrder(after);\n },\n});\n```\n\nDnd automatically sets:\n\n- `draggable=\"true\"` on sortable nodes (or handles)\n- `role=\"listitem\"` on each item\n- `role=\"list\"` on the container\n- `tabindex=\"0\"` on each item for keyboard reordering\n\n### Drag handles\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n handle: '.drag-handle',\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Keyboard reordering\n\nFocus an item and use arrow keys to move it. `Home` and `End` move to the boundary positions.\n\nWhen an item is already at the first or last position, the boundary key press is not consumed: the browser handles it normally (for example, scrolling the page). Only keys that actually move an item call `preventDefault`. Arrow keys from buttons, links, form fields, and editable descendants remain native unless that descendant matches the configured drag handle. Wire `onInteraction` to an application live region for screen-reader announcements.\n\n### Connected lists\n\nCreate a shared scope when items should move between containers:\n\n```ts\nconst boardScope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => {\n persistMove(itemId, sourceIds, targetIds);\n },\n touch: true,\n});\n\ncreateSortable({\n element: todoEl,\n getKey: (el) => el.dataset.sortId!,\n scope: boardScope,\n});\ncreateSortable({\n element: doneEl,\n getKey: (el) => el.dataset.sortId!,\n scope: boardScope,\n});\n```\n\n### Auto-scroll and drag preview\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n autoScroll: { edgeThreshold: 40, speed: 24, viewport: true },\n dragImage: (id, item) => item,\n dragImageOffset: [8, 8],\n});\n```\n\nViewport scrolling is opt-in. Container scrolling stays enabled by default.\n\n### Lifecycle hooks\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onDragStart: (id) => {\n listEl.classList.add('sorting');\n },\n onDragEnd: (id) => {\n listEl.classList.remove('sorting');\n },\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Custom identity function\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.getAttribute('data-id')!,\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Dynamic lists\n\nCall `sortable.refresh()` after adding, removing, or replacing sortable items. It restores Dnd-managed semantics on elements no longer returned by `items()` before marking the current direct children.\n\n```ts\nconst item = document.createElement('li');\nitem.dataset.sortId = 'task-4';\nitem.textContent = 'Deploy';\nlistEl.appendChild(item);\nsortable.refresh();\n```\n\n### Disabled state\n\n```ts\nimport { createSortable, type SortableOptions } from '@vielzeug/dnd/sortable';\n\nconst options: SortableOptions = {\n disabled: false,\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => saveOrder(after),\n};\nconst sortable = createSortable(options);\n\n// options.disabled is read live on each event: mutate to toggle:\noptions.disabled = isLocked;\n```\n\n### Placeholder styling\n\n```css\n.dnd-placeholder {\n background: var(--color-primary-50);\n border: 2px dashed var(--color-primary-300);\n border-radius: 4px;\n box-sizing: border-box;\n}\n\n[data-dragging] {\n opacity: 0.35;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n}\n```\n\n### Mapping DOM order back to data\n\n```ts\nimport { applyReorder, createSortable } from '@vielzeug/dnd/sortable';\n\nlet items = [\n { id: 'task-1', title: 'Design' },\n { id: 'task-2', title: 'Develop' },\n { id: 'task-3', title: 'Review' },\n];\n\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n items = applyReorder(items, after, (item) => item.id);\n },\n});\n```\n\n### Cleanup\n\n```ts\nsortable.dispose();\n// or:\nusing sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### FLIP animation hook\n\n`onBeforeReorder` fires just before the DOM reorder commits, for both drag and keyboard moves. Pair it with [`captureLayout()`](/necromancer/api.md#capturelayout) to animate the resulting layout without managing rectangles, transforms, or animation frames yourself.\n\n```ts\nimport { captureLayout, type LayoutTransition } from '@vielzeug/necromancer';\n\nlet layout: LayoutTransition<HTMLElement> | undefined;\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onBeforeReorder: () => {\n layout = captureLayout(listEl.querySelectorAll<HTMLElement>('[data-sort-id]'), {\n getKey: (el) => el.dataset.sortId!,\n });\n },\n onReorder: ({ after }) => {\n saveOrder(after); // Commit a framework render here when needed.\n layout?.animate({\n duration: 200,\n easing: 'ease-out',\n elements: listEl.querySelectorAll('[data-sort-id]'),\n });\n layout = undefined;\n },\n});\n```\n\nIf `saveOrder()` triggers a render that replaces list items, call `layout?.animate({ elements: committedItems })` after that render commits. When DnD's own reordered elements remain in the DOM, call `layout?.animate()` directly. Dnd does not depend on Necromancer: the application installs it only when FLIP animation is required. Dnd's sole runtime dependency is Gesture for touch pointer recognition.\n\n### Optimistic updates and rollback\n\nThe `onReorder` event carries `before`, `after`, and `item`. Application history owns rollback: use `before` to record an undo entry.\n\n```ts\nconst history: Array<{ before: readonly string[] }> = [];\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ before, after }) => {\n history.push({ before });\n setOrder(after); // optimistic update\n },\n});\n\n// On server error:\ntry {\n await api.saveOrder(currentOrder);\n} catch {\n const entry = history.pop();\n if (entry) setOrder(entry.before);\n}\n```\n\n## Touch Support\n\nThe HTML Drag and Drop API has no reliable native touch path. Enable touch on a sortable scope; it only recognizes items registered to that scope, never unrelated `draggable` elements.\n\n```ts\nimport { createSortable, createSortableScope } from '@vielzeug/dnd/sortable';\n\nusing scope = createSortableScope({ touch: true });\nusing sortable = createSortable({ element: listEl, getKey: (el) => el.dataset.id!, scope });\n```\n\nGesture tracks the primary touch pointer for the active drag. Additional contacts cannot move, finish, or replace it. Pointer cancellation restores the original item order and removes the transient preview.\n\n### Touch preview\n\nTouch uses an inert outline by default, avoiding cloned application DOM. Provide a preview factory or opt out when your item styling supplies its own feedback.\n\n```ts\nconst scope = createSortableScope({\n touch: {\n activationDistance: 8,\n // The returned element is cloned before Dnd mounts it as a transient preview.\n preview: (item) => item.querySelector<HTMLElement>('.drag-preview'),\n },\n});\n```\n\n### Why touch-enabled items get `touch-action: none`\n\nWhen a sortable scope enables touch input, `createSortable` sets `touch-action: none` on the managed item or handle. This prevents a mobile browser from claiming the gesture as page scrolling before the scope controller starts the drag. Sortables without touch input preserve native touch scrolling.\n\n## Testing\n\nTest observable callbacks and controller state with your DOM test runner. Construct the zone in each test, dispatch a real `drop` event, then dispose it during teardown.\n\n```ts\nimport { afterEach, expect, it, vi } from 'vitest';\nimport { createDropZone } from '@vielzeug/dnd/drop';\n\nconst zones: Array<{ dispose(): void }> = [];\n\nafterEach(() => zones.splice(0).forEach((zone) => zone.dispose()));\n\nit('forwards accepted files', async () => {\n const element = document.createElement('div');\n const onDrop = vi.fn();\n const zone = createDropZone({ element, onDrop });\n zones.push(zone);\n const file = new File(['content'], 'readme.txt', { type: 'text/plain' });\n const event = new Event('drop') as DragEvent;\n\n Object.defineProperty(event, 'dataTransfer', { value: { files: [file] } });\n element.dispatchEvent(event);\n\n await Promise.resolve();\n\n expect(onDrop).toHaveBeenCalledWith([file]);\n expect(zone.disposed).toBe(false);\n});\n```\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\nimport { createSortable, applyReorder } from '@vielzeug/dnd/sortable';\n\nfunction SortableList({ initialItems }: { initialItems: { id: string; text: string }[] }) {\n const listRef = useRef<HTMLUListElement>(null);\n const items = useRef(initialItems);\n\n useEffect(() => {\n const sortable = createSortable({\n element: listRef.current!,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n items.current = applyReorder(items.current, after, (i) => i.id);\n },\n });\n return () => sortable.dispose();\n }, []);\n\n return (\n <ul ref={listRef}>\n {initialItems.map((item) => (\n <li key={item.id} data-sort-id={item.id}>\n {item.text}\n </li>\n ))}\n </ul>\n );\n}\n```\n\n```ts [Vue 3]\nimport { ref, onMounted, onUnmounted } from 'vue';\nimport { createSortable, applyReorder, type Sortable } from '@vielzeug/dnd/sortable';\n\nfunction useSortable(items: { id: string; text: string }[]) {\n const listRef = ref<HTMLElement | null>(null);\n const orderedItems = ref(items);\n let sortable: Sortable | null = null;\n\n onMounted(() => {\n sortable = createSortable({\n element: listRef.value!,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n orderedItems.value = applyReorder(orderedItems.value, after, (i) => i.id);\n },\n });\n });\n\n onUnmounted(() => sortable?.dispose());\n return { listRef, orderedItems };\n}\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createSortable, applyReorder } from '@vielzeug/dnd/sortable';\n\n export let initialItems: { id: string; text: string }[] = [];\n let items = initialItems;\n let listEl: HTMLUListElement;\n\n onMount(() => {\n const sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => { items = applyReorder(items, after, (i) => i.id); },\n });\n return () => sortable.dispose();\n });\n</script>\n\n<ul bind:this={listEl}>\n {#each items as item (item.id)}\n <li data-sort-id={item.id}>{item.text}</li>\n {/each}\n</ul>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Ore\n\nUse Dnd in custom web components by attaching behavior in component lifecycle hooks.\n\n```ts\nimport { createSortable } from '@vielzeug/dnd/sortable';\nimport { define, getHost, html, onMounted } from '@vielzeug/ore';\n\ndefine('task-list', {\n setup(_props) {\n const el = getHost();\n\n onMounted(() => {\n const sortable = createSortable({\n element: el,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => save(after),\n });\n return () => sortable.dispose();\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\n### With Gesture\n\nKeep direct manipulation separate from drag-and-drop semantics. Use Gesture for one-axis surfaces that follow the pointer and let application code decide the outcome; use Dnd when an item enters a drag lifecycle and is dropped into a zone or reordered collection. Dnd touch sorting uses Gesture's two-dimensional pointer recognizer, then adds previews, hit-testing, synthetic drag events, and sortable transactions. Direct-manipulation consumers use Gesture without Dnd.\n\n## Best Practices\n\n- Attach `createDropZone` and `createSortable` after the container element is in the DOM: use `onMounted` in component frameworks.\n- Call `.dispose()` in the cleanup phase of your framework (useEffect return, onUnmounted, onDestroy) to prevent memory leaks.\n- Use `data-sort-id` attributes that match your data's identity field: do not use DOM index as an identifier.\n- Prefer `applyReorder()` over manual array splicing, and guarantee unique backing keys; duplicates throw `DndError` rather than dropping data.\n- Use `createSortableScope()` only when items should genuinely move between containers.\n- Use drag handles (`.handle` selector) when the full item surface area conflicts with other interactions such as text selection.\n- Test keyboard reordering explicitly: Dnd sets `tabindex` on items and supports arrow keys by default.\n- Enable `touch: true` only on scopes that own touch-sortable lists.\n",
|
|
5
|
+
"api": "---\ntitle: 'Dnd: API Reference'\ndescription: Complete API reference for Dnd.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| -------------------------- | -------------------------------------------- | -------------- | ----------------------------------------------------------------- |\n| `createDropZone()` | Create a typed drop-zone controller | Sync | Dispose the controller during teardown |\n| `createSortable()` | Add sortable drag-and-drop behavior to lists | Sync | Provide stable item identity for reorder operations |\n| `createSortableScope()` | Create a shared scope for connected lists | Sync | Each set of connected containers needs its own scope instance |\n| `applyReorder()` | Apply ordered IDs to data arrays | Sync | Unknown IDs are skipped; non-mentioned items are appended |\n| `DropZoneOptions.accept` | Filter file types before processing | Sync | Mismatch between MIME and extension can reject files unexpectedly |\n| `DropZoneOptions.maxFiles` | Cap accepted files per drop | Sync | Excess accepted files become rejected; `onDropRejected` is called |\n| `matchesAccept()` | Test a single `File` against an accept list | Sync | Extension patterns are case-insensitive; empty list accepts all |\n| `DndError` | Base class for Dnd errors | Sync | Use `instanceof DndError` to narrow unknown errors |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------------ | ---------------------------------------------------------------- |\n| `@vielzeug/dnd` | Backward-compat root barrel |\n| `@vielzeug/dnd/drop` | Drop-zone APIs plus `DndError` and `Disposable` |\n| `@vielzeug/dnd/sortable` | Sortable APIs plus `DndError`, `DndScopeError`, and `Disposable` |\n\nDnd has no third-party runtime dependencies. Its sortable touch adapter uses `@vielzeug/gesture` for shared pointer recognition.\n\n## Types\n\n### `Disposable`\n\n```ts\ninterface Disposable {\n readonly disposed: boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n [Symbol.dispose](): void;\n}\n```\n\n### `DropZoneOptions`\n\n```ts\ninterface DropZoneOptions {\n element: HTMLElement;\n accept?: readonly string[];\n maxFiles?: number;\n onValidate?: (files: File[], context: DropValidationContext) => boolean | Promise<boolean>;\n disabled?: boolean;\n dropEffect?: DataTransfer['dropEffect'];\n onDrop?: (files: File[]) => void;\n onDropRejected?: (files: File[]) => void;\n onHoverChange?: (hovered: boolean) => void;\n onValidatingChange?: (validating: boolean) => void;\n paste?: boolean;\n onPaste?: (files: File[]) => void;\n}\n```\n\n### `DropZone`\n\n```ts\ninterface DropZone extends Disposable {\n readonly hovered: boolean;\n readonly validating: boolean;\n}\n```\n\n### `DropValidationContext`\n\n```ts\ninterface DropValidationContext {\n readonly signal: AbortSignal;\n}\n```\n\n### `SortableOptions`\n\n```ts\ninterface SortableOptions {\n element: HTMLElement;\n getKey: (element: HTMLElement) => string;\n scope?: SortableScope;\n handle?: string;\n keyboard?: boolean;\n axis?: 'vertical' | 'horizontal';\n autoScroll?: boolean | AutoScrollOptions;\n dragImage?: HTMLElement | ((id: string, item: HTMLElement, event: DragEvent) => HTMLElement | null | undefined);\n dragImageOffset?: [number, number];\n placeholderClass?: string;\n disabled?: boolean;\n onDragStart?: (id: string, event: DragEvent) => void;\n onDragEnd?: (id: string, event: DragEvent) => void;\n onInteraction?: (event: SortableInteractionEvent) => void;\n onBeforeReorder?: (from: readonly string[], to: readonly string[]) => void;\n onReorder?: (event: ReorderEvent) => void;\n items?: () => readonly HTMLElement[];\n}\n```\n\n### `AutoScrollOptions`\n\n```ts\ninterface AutoScrollOptions {\n edgeThreshold?: number;\n speed?: number;\n container?: boolean;\n viewport?: boolean;\n}\n```\n\n### `ReorderEvent`\n\n```ts\ninterface ReorderEvent {\n before: readonly string[];\n after: readonly string[];\n item: string;\n}\n```\n\n### `Sortable`\n\n```ts\ninterface Sortable extends Disposable {\n readonly isDragging: boolean;\n refresh(): void;\n}\n```\n\n### `SortableScope`\n\n```ts\ninterface SortableScope extends Disposable {\n readonly isDragging: boolean;\n}\n```\n\n### `SortableScopeOptions`\n\n```ts\ninterface SortableScopeOptions {\n onMove?: (event: SortableMoveEvent) => void;\n touch?: boolean | SortableTouchOptions;\n}\n```\n\n### `SortableMoveEvent`\n\n```ts\ninterface SortableMoveEvent {\n readonly itemId: string;\n readonly source: HTMLElement;\n readonly sourceBeforeIds: readonly string[];\n readonly sourceIds: readonly string[];\n readonly target: HTMLElement;\n readonly targetBeforeIds: readonly string[];\n readonly targetIds: readonly string[];\n}\n```\n\n### `SortableInteractionEvent`\n\nStructured accessibility/observability event for sortable interactions. Drag emits `pickup` on dragstart, `drop` on commit, `cancel` on cancel. Keyboard emits `move` on each successful arrow/Home/End reorder (direct-commit model).\n\n```ts\ntype SortableInteractionEvent =\n | { readonly type: 'pickup'; readonly itemId: string; readonly index: number; readonly total: number }\n | {\n readonly type: 'move';\n readonly itemId: string;\n readonly previousIndex: number;\n readonly index: number;\n readonly total: number;\n }\n | { readonly type: 'drop'; readonly itemId: string; readonly index: number; readonly total: number }\n | { readonly type: 'cancel'; readonly itemId: string; readonly index: number; readonly total: number };\n```\n\nWire a consumer-side announcer to provide screen-reader feedback:\n\n```ts\nimport { createSortable } from '@vielzeug/dnd/sortable';\n\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.id!,\n onInteraction(event) {\n switch (event.type) {\n case 'pickup':\n announce(`Picked up ${event.itemId}, position ${event.index + 1} of ${event.total}`);\n break;\n case 'move':\n announce(`Moved ${event.itemId} to position ${event.index + 1} of ${event.total}`);\n break;\n case 'drop':\n announce(`Dropped ${event.itemId} at position ${event.index + 1} of ${event.total}`);\n break;\n case 'cancel':\n announce(`Cancelled, ${event.itemId} returned to position ${event.index + 1} of ${event.total}`);\n break;\n }\n },\n});\n```\n\n### `SortableTouchOptions`\n\n```ts\ntype SortableTouchOptions = Readonly<{\n activationDistance?: number;\n preview?: false | ((item: HTMLElement) => HTMLElement | null);\n}>;\n```\n\n`activationDistance` is the non-negative finite movement threshold in pixels before touch sorting starts (default `6`). Invalid values throw `DndError`.\n\n`preview` returns a template that Dnd clones before mounting it as a transient touch preview, so returning an element from the sortable item does not reparent or remove caller-owned DOM. Return `false` to disable the preview.\n\nTouch sorting delegates activation, movement, identity, and cancellation to Gesture's `createDragGesture()` with pointer capture disabled for document hit-testing. Dnd retains preview rendering, hit-testing, synthetic drag events, and sortable transactions. A second touch cancels sorting and restores the pre-drag order without firing `onReorder` or `onMove`. Without a configured handle, touch starts on editing controls, buttons, links, ARIA controls, and `[data-no-drag]` subtrees are excluded. Explicit handles remain eligible, including button handles.\n\n## `createDropZone()`\n\n```ts\ndeclare function createDropZone(options: DropZoneOptions): DropZone;\n```\n\nAttaches drag-and-drop file handling to a DOM element. Returns a `DropZone` handle.\n\n| Option | Type | Default | Description |\n| -------------------- | ---------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `element` | `HTMLElement` | N/A | **Required.** The element to attach drag listeners to. |\n| `accept` | `string[]` | `[]` | Accepted file types, normalized and snapshotted at construction. Empty array accepts everything; invalid MIME, wildcard, or extension patterns throw `DndError`. |\n| `maxFiles` | `number` | N/A | Non-negative safe-integer file limit. Excess files are passed to `onDropRejected`; invalid values throw `DndError` during construction. |\n| `onValidate` | `(files, { signal }) => boolean \\| Promise<boolean>` | N/A | Optional async gating step. Return or resolve `false` to reject all accepted files. `validating` remains true until every operation settles; `signal` aborts on disposal. |\n| `disabled` | `boolean` | N/A | When `true`, all drag and paste events are ignored. A disabled zone does not call `preventDefault` on `dragenter`, `dragover`, `drop`, or `paste`, so underlying elements (text editors, etc.) receive them normally. |\n| `dropEffect` | `'copy' \\| 'move' \\| 'link' \\| 'none'` | `'copy'` | The `dropEffect` set on `dataTransfer` during `dragover`. Controls the cursor indicator. |\n| `onDrop` | `(files: File[]) => void` | N/A | Called with accepted files only. Not called if all dropped files are rejected. Also receives paste events when `paste: true` and `onPaste` is omitted. |\n| `onDropRejected` | `(files: File[]) => void` | N/A | Called with files that did not match `accept`, exceeded `maxFiles`, or were rejected by `onValidate`. |\n| `onHoverChange` | `(hovered: boolean) => void` | N/A | Called when hover state toggles. Use this callback for drag-over styling. |\n| `onValidatingChange` | `(validating: boolean) => void` | N/A | Called whenever the aggregate async validation state changes. |\n| `paste` | `boolean` | `false` | When `true`, attaches a `paste` listener to `element`. Pasted files run through the same `accept`, `maxFiles`, and `onValidate` pipeline as dropped files. |\n| `onPaste` | `(files: File[]) => void` | N/A | Called when files are pasted from the clipboard. Falls back to `onDrop` when omitted. Only active when `paste: true`. |\n\n**Returns:** `DropZone`\n\nNotes:\n\n- Extension accept patterns are approximate during pre-check (`DataTransferItem` has no filename); exact filtering is applied at drop time.\n- Hover state (`hovered`) only becomes `true` when the dragged payload passes the `accept` filter. Drags carrying rejected file types enter and leave the zone without triggering `onHoverChange`.\n- Hover state is reset on element drop and also global `window` `drop`/`dragend` to avoid stuck hover state when drags leave the viewport.\n- Disposal aborts validation and transitions `validating` to `false` before teardown completes.\n- Consumer callback failures are reported through Dnd's development warning channel and never reclassify accepted files as rejected.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*', '.pdf'],\n onDrop: (files) => {\n upload(files);\n },\n onDropRejected: (files) => {\n showError(`${files.length} rejected`);\n },\n onHoverChange: (hovered) => {\n dropEl.classList.toggle('drag-over', hovered);\n },\n});\n```\n\n## `DropZone` Interface\n\n### `zone.hovered`\n\n`readonly hovered: boolean`\n\n`true` when a drag is currently over the zone. Updated synchronously by the internal counter: safe to read at any time.\n\n### `zone.validating`\n\n`readonly validating: boolean`\n\n`true` while an `onValidate` promise is pending. Use this to render a loading indicator between file selection and the acceptance/rejection callbacks firing.\n\n```ts\nconsole.log(zone.validating); // true between drop and onValidate resolution\n```\n\n### `zone.disposed`\n\n`readonly disposed: boolean`\n\n`true` once `dispose()` has been called. Safe to read at any time.\n\n### `zone.disposalSignal`\n\n`readonly disposalSignal: AbortSignal`\n\nAn `AbortSignal` that fires when `dispose()` is called. Use it to cancel in-flight requests tied to the zone's lifetime.\n\n### `zone.dispose()`\n\n`dispose(): void`\n\nRemoves all event listeners, aborts pending validation, and resets `hovered` and `validating`. Idempotent: safe to call multiple times.\n\n```ts\nzone.dispose();\n```\n\n### `zone[Symbol.dispose]()`\n\n`[Symbol.dispose](): void`\n\nAlias for `dispose()`. Called automatically when used with the `using` keyword.\n\n```ts\n{\n using zone = createDropZone({ element: dropEl, onDrop: handleFiles });\n} // zone.dispose() runs here\n```\n\n## `createSortable()`\n\n```ts\ndeclare function createSortable(options: SortableOptions): Sortable;\n```\n\nMakes the direct children of a container element reorderable via drag. Returns a `Sortable` handle.\n\n`createSortable` adds drag and keyboard defaults only when callers have not already supplied semantics. Every changed attribute and inline style is restored to its prior value on disposal.\n\n- `element`: `HTMLElement`, required. The container whose children become sortable.\n- `getKey`: `(element: HTMLElement) => string`, required. Maps each item element to its stable string identity. Children for which `getKey` returns a falsy value are skipped.\n- `scope`: `SortableScope`, default private scope. Connects sortable lists explicitly; containers only exchange items when they share the same scope instance.\n- `handle`: `string`. Valid CSS selector for a drag handle inside each item. Invalid selectors throw `DndError`; an empty selector warns and disables dragging.\n- `keyboard`: `boolean`, default `true`. Enables keyboard reordering with arrow keys plus `Home` and `End`, matched through `matchKey` from `@vielzeug/keymap`: modifier chords (e.g. Ctrl+ArrowDown, browser back/forward) are ignored. Events from interactive descendants are ignored unless they match the configured handle.\n- `axis`: `'vertical' | 'horizontal'`, default `'vertical'`. Controls midpoint calculation for placeholder insertion.\n- `autoScroll`: `boolean | AutoScrollOptions`, default `true`. Scrolls near edges; threshold must be finite and non-negative and speed finite and positive.\n- `dragImage`: `HTMLElement | ((id, item, event) => HTMLElement | null | undefined)`. Custom native drag preview passed to `dataTransfer.setDragImage()`. A `null` or `undefined` return skips `setDragImage` entirely.\n- `dragImageOffset`: `[number, number]`, default `[0, 0]`. The `[x, y]` hotspot offset passed to `setDragImage`. Controls which point of the preview image follows the cursor.\n- `placeholderClass`: `string`, default `'dnd-placeholder'`. CSS class applied to the generated placeholder element.\n- `disabled`: `boolean`. Blocks drag interactions. If a list becomes disabled mid-drag, Dnd cancels the drag and restores the original order.\n- `onDragStart`: `(id: string, event: DragEvent) => void`. Called when a drag starts.\n- `onDragEnd`: `(id: string, event: DragEvent) => void`. Called when a drag ends, whether completed or cancelled.\n- `onInteraction`: `(event: SortableInteractionEvent) => void`. Structured accessibility event for pickup/move/drop/cancel: wire to a consumer-side announcer for screen-reader feedback. See [`SortableInteractionEvent`](#sortableinteractionevent).\n- `onBeforeReorder`: `(from: readonly string[], to: readonly string[]) => void`. Called with the before/after order snapshots just before a successful reorder commits: for both drag and keyboard. Items are still in their pre-commit positions at the time of the call, making it ideal for [`captureLayout()`](/necromancer/api.md#capturelayout) setup.\n- `items`: `() => readonly HTMLElement[]`. Returns direct children owned by this sortable. `refresh()` restores elements no longer returned before marking the current set.\n- `onReorder`: `(event: ReorderEvent) => void`. Called after a successful reorder (drag or keyboard), only when the order changed. The event carries `before`, `after`, and `item` so application history can own rollback.\n\nOrder arrays and interaction events are frozen snapshots. Callback failures are reported through Dnd's development warning channel and cannot interrupt session completion or corrupt later events. Native touch scrolling is preserved unless the shared scope enables touch input.\n\n**Returns:** `Sortable`\n\n```ts\nconst boardScope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => saveMove(itemId, sourceIds, targetIds),\n touch: true,\n});\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.id!,\n handle: '.drag-handle',\n onDragStart: (id) => {\n listEl.classList.add('sorting');\n },\n onDragEnd: (id) => {\n listEl.classList.remove('sorting');\n },\n onReorder: ({ before, after }) => {\n history.push({ revert: () => saveOrder(before) });\n saveOrder(after);\n },\n scope: boardScope,\n});\n```\n\n### `createSortableScope()`\n\n```ts\ndeclare function createSortableScope(options?: SortableScopeOptions): SortableScope;\n```\n\nUse one scope per connected set of containers. `onMove` fires once for cross-list moves with both final orders; local reorders continue to call the sortable's `onReorder`.\n\n| Parameter | Type | Description |\n| --------- | ---------------------- | --------------------------------------------------------------------- |\n| `options` | `SortableScopeOptions` | Optional cross-list move callback and scope-owned touch configuration |\n\n**Returns:** `SortableScope`.\n\n```ts\nimport { createSortableScope } from '@vielzeug/dnd/sortable';\n\nconst scope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => {\n persistMove(itemId, sourceIds, targetIds);\n },\n touch: true,\n});\n```\n\n## `Sortable` Interface\n\n### `sortable.isDragging`\n\n`readonly isDragging: boolean`\n\n`true` while an item drag is in progress.\n\n### `sortable.refresh()`\n\n`refresh(): void`\n\nRe-reads items from the `items` provider (or the container's direct children) and reapplies `draggable`, `role`, and handle attributes. Call it after adding, removing, or replacing sortable children.\n\n### `sortable.disposed`\n\n`readonly disposed: boolean`\n\n`true` once `dispose()` has been called.\n\n### `sortable.disposalSignal`\n\n`readonly disposalSignal: AbortSignal`\n\nAn `AbortSignal` that fires when `dispose()` is called.\n\n### `sortable.dispose()`\n\n`dispose(): void`\n\nRemoves all event listeners from the container, strips sortable attributes from items and handles, and cancels any in-progress drag by restoring the original order. Idempotent: safe to call multiple times.\n\n### `sortable[Symbol.dispose]()`\n\n`[Symbol.dispose](): void`\n\nAlias for `dispose()`.\n\n## `SortableScope` Interface\n\n### `scope.isDragging`\n\n`readonly isDragging: boolean`\n\n`true` while any sortable registered to the scope is dragging.\n\n### `scope.dispose()`\n\n`dispose(): void`\n\nDisposes scope-owned touch input and all registered sortables. Registering a new sortable with a disposed scope throws `DndScopeError`.\n\n## DOM Attributes\n\nDnd reads and writes the following DOM attributes:\n\n- `data-dnd-item`: internal marker applied by `createSortable` to children that return a truthy key from `getKey`. Restored on `dispose()`.\n- `draggable`, roles, tabindex, and `touchAction`: managed only as needed and restored to their exact prior values on `dispose()`.\n- `data-dragging`: set during drag, removed on `dragend` or `dispose()`. Use it as your styling hook for drag state.\n- `data-dnd-handle`: internal marker set by `createSortable` and `sortable.refresh()`, removed by `dispose()`. Lets Dnd clean up only the handle attributes it applied.\n- `aria-hidden=\"true\"`: set on placeholder creation and removed with the placeholder. Applied to the `.dnd-placeholder` element.\n- `style.touchAction = 'none'` (inline style): set by `createSortable` and `sortable.refresh()` on the item (or the handle, when `handle` is set), then restored on `dispose()`.\n\n## CSS Classes\n\n| Class | Applied to | When |\n| ----------------- | ---------------------------- | ------------------------------------------------------------- |\n| `dnd-placeholder` | `<div>` inserted by sortable | While an item is being dragged, in the placeholder's position |\n\n## `matchesAccept()`\n\n```ts\ndeclare function matchesAccept(file: File, accept: readonly string[]): boolean;\n```\n\nTests whether a `File` matches an accept pattern list. Each pattern can be:\n\n- A MIME type: `'image/png'`\n- A MIME wildcard: `'image/*'`\n- A file extension: `'.pdf'`\n\nAn empty list accepts everything. Extension matching is case-insensitive.\n\n**Returns:** `true` when the file matches at least one pattern, or when `accept` is empty.\n\n```ts\nimport { matchesAccept } from '@vielzeug/dnd/drop';\n\nmatchesAccept(file, ['image/*', '.pdf']); // true or false\n```\n\n## `applyReorder()`\n\n```ts\ndeclare function applyReorder<T>(items: readonly T[], ids: readonly string[], getKey: (item: T) => string): T[];\n```\n\nApplies a DOM reorder result (`orderedIds`) to your backing array.\n\n- IDs missing from `items` are ignored.\n- Items not listed in `ids` are appended in original order.\n- Duplicate IDs in `ids`: first occurrence wins, later occurrences are ignored.\n- Duplicate keys in `items` throw `DndError`; data is never silently discarded.\n\n**Returns:** A new array ordered by `ids`, with omitted items appended in their original order.\n\n```ts\nconst next = applyReorder(items, orderedIds, (item) => item.id);\n```\n\n## Errors\n\n| Error | Trigger | Notable property |\n| --------------- | ------------------------------------------------------------------------------------------- | ----------------------------- |\n| `DndError` | Invalid configuration, duplicate item data, or duplicate sortable registration in one scope | Base class for package errors |\n| `DndScopeError` | A sortable receives an invalid or disposed scope | Extends `DndError` |\n",
|
|
6
|
+
"usage": "---\ntitle: 'Dnd: Usage Guide'\ndescription: Drop zones, sortable lists, explicit connected scopes, keyboard sorting, and cleanup patterns with Dnd.\n---\n\n[[toc]]\n\n## Basic Usage\n\n`createDropZone` attaches drag-and-drop behavior to any DOM element and keeps hover state stable with a counter.\n\n```ts\nimport { createDropZone } from '@vielzeug/dnd/drop';\n\nconst dropzone = document.getElementById('dropzone')!;\n\nconst zone = createDropZone({\n element: dropzone,\n onDrop: (files) => {\n console.log('Accepted files:', files);\n },\n});\n```\n\n### Accept filtering\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*', '.pdf', 'application/json'],\n onDrop: (files) => {\n // accepted files only\n },\n onDropRejected: (files) => {\n showToast(`${files.length} file(s) not accepted`);\n },\n});\n```\n\nThe `accept` list is normalized and snapshotted at construction. MIME matching is case-insensitive; invalid patterns throw `DndError`. Recreate the zone to change accepted types.\n\n### Hover state\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n onHoverChange: (hovered) => {\n dropEl.classList.toggle('drag-over', hovered);\n },\n});\n```\n\nRead zone state imperatively:\n\n```ts\nconsole.log(zone.hovered);\nconsole.log(zone.validating);\n```\n\n### Drop effect\n\n```ts\ncreateDropZone({\n element: dropEl,\n dropEffect: 'move',\n onDrop: (files) => {\n // ...\n },\n});\n```\n\n### Disabled state\n\n```ts\nconst options = { disabled: false, element: dropEl, onDrop: handleFiles };\nconst zone = createDropZone(options);\n\n// options.disabled is read live on each event: mutate to toggle:\noptions.disabled = isReadOnly;\n```\n\n### File limit\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*'],\n maxFiles: 5,\n onDrop: (files) => {\n // 1-5 accepted files\n },\n onDropRejected: (files) => {\n showToast(`Only 5 files at a time. ${files.length} were ignored.`);\n },\n});\n```\n\n### Cleanup\n\n```ts\nzone.dispose();\n// or:\nusing zone = createDropZone({ element: dropEl, onDrop: handleFiles });\n```\n\n`maxFiles` must be a non-negative safe integer.\n\n### Async validation\n\nGate drops behind an async check with `onValidate`. The zone remains `validating: true` until every pending validation settles, and disposal aborts each validation signal.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n accept: ['image/*'],\n onValidate: async (files, { signal }) => {\n const ok = await checkServerQuota(files, { signal });\n return ok; // false → all files forwarded to onDropRejected\n },\n onDrop: (files) => uploadFiles(files),\n onDropRejected: (files) => showError('Quota exceeded'),\n});\n\n// show a spinner while checking\nconsole.log(zone.validating); // true during pending check\n```\n\nA synchronous boolean return skips the microtask queue entirely:\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n onValidate: (files) => files.every((f) => f.size < 5_000_000), // sync\n onDrop: handleFiles,\n});\n```\n\n### Clipboard paste\n\nSet `paste: true` to accept files pasted through the drop-zone element. The focused paste target must be the element or its descendant; the same `accept`, `maxFiles`, and `onValidate` pipeline applies.\n\n```ts\nconst zone = createDropZone({\n element: dropEl,\n paste: true,\n accept: ['image/*'],\n onPaste: (files) => {\n uploadFiles(files);\n },\n onDropRejected: (files) => {\n showError(`${files.length} file(s) not accepted`);\n },\n});\n```\n\nWhen `onPaste` is omitted, accepted pasted files fall through to `onDrop`.\n\n## Sortable\n\n`createSortable` makes direct children of a container reorderable via drag.\n\n### Setup\n\n```html\n<ul id=\"task-list\">\n <li data-sort-id=\"task-1\">Design</li>\n <li data-sort-id=\"task-2\">Develop</li>\n <li data-sort-id=\"task-3\">Review</li>\n</ul>\n```\n\n```ts\nconst sortable = createSortable({\n element: document.getElementById('task-list')!,\n getKey: (el) => el.dataset.sortId!,\n axis: 'vertical',\n onReorder: ({ after }) => {\n saveTaskOrder(after);\n },\n});\n```\n\nDnd automatically sets:\n\n- `draggable=\"true\"` on sortable nodes (or handles)\n- `role=\"listitem\"` on each item\n- `role=\"list\"` on the container\n- `tabindex=\"0\"` on each item for keyboard reordering\n\n### Drag handles\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n handle: '.drag-handle',\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\nTouch sorting ignores controls inside an item unless they belong to the configured handle. Put `data-no-drag` on a custom interaction subtree to exclude it when sorting whole items. A second finger cancels the drag and restores the original order; it never commits a reorder.\n\n### Keyboard reordering\n\nFocus an item and use arrow keys to move it. `Home` and `End` move to the boundary positions.\n\nWhen an item is already at the first or last position, the boundary key press is not consumed: the browser handles it normally (for example, scrolling the page). Only keys that actually move an item call `preventDefault`. Arrow keys from buttons, links, form fields, and editable descendants remain native unless that descendant matches the configured drag handle. Wire `onInteraction` to an application live region for screen-reader announcements.\n\n### Connected lists\n\nCreate a shared scope when items should move between containers:\n\n```ts\nconst boardScope = createSortableScope({\n onMove: ({ itemId, sourceIds, targetIds }) => {\n persistMove(itemId, sourceIds, targetIds);\n },\n touch: true,\n});\n\ncreateSortable({\n element: todoEl,\n getKey: (el) => el.dataset.sortId!,\n scope: boardScope,\n});\ncreateSortable({\n element: doneEl,\n getKey: (el) => el.dataset.sortId!,\n scope: boardScope,\n});\n```\n\n### Auto-scroll and drag preview\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n autoScroll: { edgeThreshold: 40, speed: 24, viewport: true },\n dragImage: (id, item) => item,\n dragImageOffset: [8, 8],\n});\n```\n\nViewport scrolling is opt-in. Container scrolling stays enabled by default.\n\n### Lifecycle hooks\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onDragStart: (id) => {\n listEl.classList.add('sorting');\n },\n onDragEnd: (id) => {\n listEl.classList.remove('sorting');\n },\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Custom identity function\n\n```ts\ncreateSortable({\n element: listEl,\n getKey: (el) => el.getAttribute('data-id')!,\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### Dynamic lists\n\nCall `sortable.refresh()` after adding, removing, or replacing sortable items. It restores Dnd-managed semantics on elements no longer returned by `items()` before marking the current direct children.\n\n```ts\nconst item = document.createElement('li');\nitem.dataset.sortId = 'task-4';\nitem.textContent = 'Deploy';\nlistEl.appendChild(item);\nsortable.refresh();\n```\n\n### Disabled state\n\n```ts\nimport { createSortable, type SortableOptions } from '@vielzeug/dnd/sortable';\n\nconst options: SortableOptions = {\n disabled: false,\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => saveOrder(after),\n};\nconst sortable = createSortable(options);\n\n// options.disabled is read live on each event: mutate to toggle:\noptions.disabled = isLocked;\n```\n\n### Placeholder styling\n\n```css\n.dnd-placeholder {\n background: var(--color-primary-50);\n border: 2px dashed var(--color-primary-300);\n border-radius: 4px;\n box-sizing: border-box;\n}\n\n[data-dragging] {\n opacity: 0.35;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n}\n```\n\n### Mapping DOM order back to data\n\n```ts\nimport { applyReorder, createSortable } from '@vielzeug/dnd/sortable';\n\nlet items = [\n { id: 'task-1', title: 'Design' },\n { id: 'task-2', title: 'Develop' },\n { id: 'task-3', title: 'Review' },\n];\n\ncreateSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n items = applyReorder(items, after, (item) => item.id);\n },\n});\n```\n\n### Cleanup\n\n```ts\nsortable.dispose();\n// or:\nusing sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => saveOrder(after),\n});\n```\n\n### FLIP animation hook\n\n`onBeforeReorder` fires just before the DOM reorder commits, for both drag and keyboard moves. Pair it with [`captureLayout()`](/necromancer/api.md#capturelayout) to animate the resulting layout without managing rectangles, transforms, or animation frames yourself.\n\n```ts\nimport { captureLayout, type LayoutTransition } from '@vielzeug/necromancer';\n\nlet layout: LayoutTransition<HTMLElement> | undefined;\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onBeforeReorder: () => {\n layout = captureLayout(listEl.querySelectorAll<HTMLElement>('[data-sort-id]'), {\n getKey: (el) => el.dataset.sortId!,\n });\n },\n onReorder: ({ after }) => {\n saveOrder(after); // Commit a framework render here when needed.\n layout?.animate({\n duration: 200,\n easing: 'ease-out',\n elements: listEl.querySelectorAll('[data-sort-id]'),\n });\n layout = undefined;\n },\n});\n```\n\nIf `saveOrder()` triggers a render that replaces list items, call `layout?.animate({ elements: committedItems })` after that render commits. When DnD's own reordered elements remain in the DOM, call `layout?.animate()` directly. Dnd does not depend on Necromancer: the application installs it only when FLIP animation is required. Dnd's sole runtime dependency is Gesture for touch pointer recognition.\n\n### Optimistic updates and rollback\n\nThe `onReorder` event carries `before`, `after`, and `item`. Application history owns rollback: use `before` to record an undo entry.\n\n```ts\nconst history: Array<{ before: readonly string[] }> = [];\n\nconst sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ before, after }) => {\n history.push({ before });\n setOrder(after); // optimistic update\n },\n});\n\n// On server error:\ntry {\n await api.saveOrder(currentOrder);\n} catch {\n const entry = history.pop();\n if (entry) setOrder(entry.before);\n}\n```\n\n## Touch Support\n\nThe HTML Drag and Drop API has no reliable native touch path. Enable touch on a sortable scope; it only recognizes items registered to that scope, never unrelated `draggable` elements.\n\n```ts\nimport { createSortable, createSortableScope } from '@vielzeug/dnd/sortable';\n\nusing scope = createSortableScope({ touch: true });\nusing sortable = createSortable({ element: listEl, getKey: (el) => el.dataset.id!, scope });\n```\n\nGesture tracks the primary touch pointer for the active drag. Additional contacts cannot move, finish, or replace it. Pointer cancellation restores the original item order and removes the transient preview.\n\n### Touch preview\n\nTouch uses an inert outline by default, avoiding cloned application DOM. Provide a preview factory or opt out when your item styling supplies its own feedback.\n\n```ts\nconst scope = createSortableScope({\n touch: {\n activationDistance: 8,\n // The returned element is cloned before Dnd mounts it as a transient preview.\n preview: (item) => item.querySelector<HTMLElement>('.drag-preview'),\n },\n});\n```\n\n### Why touch-enabled items get `touch-action: none`\n\nWhen a sortable scope enables touch input, `createSortable` sets `touch-action: none` on the managed item or handle. This prevents a mobile browser from claiming the gesture as page scrolling before the scope controller starts the drag. Sortables without touch input preserve native touch scrolling.\n\n## Testing\n\nTest observable callbacks and controller state with your DOM test runner. Construct the zone in each test, dispatch a real `drop` event, then dispose it during teardown.\n\n```ts\nimport { afterEach, expect, it, vi } from 'vitest';\nimport { createDropZone } from '@vielzeug/dnd/drop';\n\nconst zones: Array<{ dispose(): void }> = [];\n\nafterEach(() => zones.splice(0).forEach((zone) => zone.dispose()));\n\nit('forwards accepted files', async () => {\n const element = document.createElement('div');\n const onDrop = vi.fn();\n const zone = createDropZone({ element, onDrop });\n zones.push(zone);\n const file = new File(['content'], 'readme.txt', { type: 'text/plain' });\n const event = new Event('drop') as DragEvent;\n\n Object.defineProperty(event, 'dataTransfer', { value: { files: [file] } });\n element.dispatchEvent(event);\n\n await Promise.resolve();\n\n expect(onDrop).toHaveBeenCalledWith([file]);\n expect(zone.disposed).toBe(false);\n});\n```\n\n## Framework Integration\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\nimport { createSortable, applyReorder } from '@vielzeug/dnd/sortable';\n\nfunction SortableList({ initialItems }: { initialItems: { id: string; text: string }[] }) {\n const listRef = useRef<HTMLUListElement>(null);\n const items = useRef(initialItems);\n\n useEffect(() => {\n const sortable = createSortable({\n element: listRef.current!,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n items.current = applyReorder(items.current, after, (i) => i.id);\n },\n });\n return () => sortable.dispose();\n }, []);\n\n return (\n <ul ref={listRef}>\n {initialItems.map((item) => (\n <li key={item.id} data-sort-id={item.id}>\n {item.text}\n </li>\n ))}\n </ul>\n );\n}\n```\n\n```ts [Vue 3]\nimport { ref, onMounted, onUnmounted } from 'vue';\nimport { createSortable, applyReorder, type Sortable } from '@vielzeug/dnd/sortable';\n\nfunction useSortable(items: { id: string; text: string }[]) {\n const listRef = ref<HTMLElement | null>(null);\n const orderedItems = ref(items);\n let sortable: Sortable | null = null;\n\n onMounted(() => {\n sortable = createSortable({\n element: listRef.value!,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => {\n orderedItems.value = applyReorder(orderedItems.value, after, (i) => i.id);\n },\n });\n });\n\n onUnmounted(() => sortable?.dispose());\n return { listRef, orderedItems };\n}\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createSortable, applyReorder } from '@vielzeug/dnd/sortable';\n\n export let initialItems: { id: string; text: string }[] = [];\n let items = initialItems;\n let listEl: HTMLUListElement;\n\n onMount(() => {\n const sortable = createSortable({\n element: listEl,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => { items = applyReorder(items, after, (i) => i.id); },\n });\n return () => sortable.dispose();\n });\n</script>\n\n<ul bind:this={listEl}>\n {#each items as item (item.id)}\n <li data-sort-id={item.id}>{item.text}</li>\n {/each}\n</ul>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### With Ore\n\nUse Dnd in custom web components by attaching behavior in component lifecycle hooks.\n\n```ts\nimport { createSortable } from '@vielzeug/dnd/sortable';\nimport { define, getHost, html, onMounted } from '@vielzeug/ore';\n\ndefine('task-list', {\n setup(_props) {\n const el = getHost();\n\n onMounted(() => {\n const sortable = createSortable({\n element: el,\n getKey: (el) => el.dataset.sortId!,\n onReorder: ({ after }) => save(after),\n });\n return () => sortable.dispose();\n });\n\n return html`<slot></slot>`;\n },\n});\n```\n\n### With Gesture\n\nKeep direct manipulation separate from drag-and-drop semantics. Use Gesture for one-axis surfaces that follow the pointer and let application code decide the outcome; use Dnd when an item enters a drag lifecycle and is dropped into a zone or reordered collection. Dnd touch sorting uses Gesture's two-dimensional pointer recognizer, then adds previews, hit-testing, synthetic drag events, and sortable transactions. Direct-manipulation consumers use Gesture without Dnd.\n\n## Best Practices\n\n- Attach `createDropZone` and `createSortable` after the container element is in the DOM: use `onMounted` in component frameworks.\n- Call `.dispose()` in the cleanup phase of your framework (useEffect return, onUnmounted, onDestroy) to prevent memory leaks.\n- Use `data-sort-id` attributes that match your data's identity field: do not use DOM index as an identifier.\n- Prefer `applyReorder()` over manual array splicing, and guarantee unique backing keys; duplicates throw `DndError` rather than dropping data.\n- Use `createSortableScope()` only when items should genuinely move between containers.\n- Use drag handles (`.handle` selector) when the full item surface area conflicts with other interactions such as text selection.\n- Test keyboard reordering explicitly: Dnd sets `tabindex` on items and supports arrow keys by default.\n- Enable `touch: true` only on scopes that own touch-sortable lists.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Dnd: Examples'\ndescription: Practical examples and recipes for dnd.\n---\n\n## Examples\n\n- [Sortable List](./examples/sortable-list.md)\n- [Touch-Enabled Sortable List](./examples/touch-enabled-sortable-list.md)\n- [File Upload Drop Zone](./examples/file-upload-drop-zone.md)\n- [Optimistic Reorder with Revert and FLIP Animation](./examples/optimistic-reorder-with-revert.md)\n- [Combined Sortable With Inline Editing](./examples/combined-sortable-with-inline-editing.md)\n- [Connected Kanban Keyboard Sorting](./examples/connected-kanban-keyboard-sorting.md)\n- [Web Component With Ore](./examples/web-component-with-craft.md)\n- [Using `using` for scoped cleanup](./examples/using-using-for-scoped-cleanup.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"apiSource": "export {\n createDragGesture,\n type DragEndReason,\n type DragGesture,\n type DragGestureDetail,\n type DragGestureEndDetail,\n type DragGestureOptions,\n type DragPoint,\n} from './drag-gesture.js';\nexport { GestureConfigError, GestureError } from './errors.js';\nexport {\n createLongPress,\n type LongPress,\n type LongPressDetail,\n type LongPressOptions,\n} from './long-press.js';\nexport {\n createPanGesture,\n type PanAxis,\n type PanEndReason,\n type PanGesture,\n type PanGestureDetail,\n type PanGestureEndDetail,\n type PanGestureOptions,\n} from './pan-gesture.js';\n",
|
|
3
3
|
"docs": {
|
|
4
4
|
"index": "---\ntitle: 'Gesture: Pointer movement primitives'\ndescription: Framework-neutral two-dimensional pointer drag and one-axis pan recognition with lifecycle-owned handles.\npackage: gesture\ncategory: input\nkeywords: [pointer, pan, swipe, gesture, touch, drag, long press]\nexports: [createDragGesture, createPanGesture, createLongPress, GestureConfigError]\nrelated: [refine, dnd, keymap]\nenvironments: [browser]\n---\n\n<!-- markdownlint-disable MD025 MD033 MD060 -->\n\n<PackageHero package=\"gesture\" />\n\n## Why Gesture?\n\nPointer-driven interfaces need reliable one-pointer movement tracking without coupling recognition to rendering, drag-and-drop semantics, or product-specific completion policy.\n\n```ts\n// Before\nelement.addEventListener('pointermove', (event) => {\n // Coordinate tracking, pointer identity, direction locking, and cleanup\n});\n\n// After\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onMove: ({ distance }) => console.log('distance', distance),\n onEnd: ({ reason }) => console.log('ended', reason),\n});\n```\n\n| Feature | Gesture | Ad-hoc pointer handling |\n| ----------------------------- | --------------------------------------------- | ----------------------- |\n| Bundle size | <PackageInfo package=\"gesture\" type=\"size\" /> | n/a |\n| Zero dependencies | <ore-icon name=\"check\" size=\"16\"></ore-icon> | n/a |\n| Two-dimensional drag tracking | Built in | Manual |\n| Axis intent recognition | Built in | Manual |\n| Pointer ownership | Tracked across the document | Manual |\n| Lifecycle cleanup | `dispose()` + `disposalSignal` | Manual |\n\n<div class=\"decision-callout\">\n\n**Use Gesture when** UI surfaces need consistent free drag or axis-locked pan tracking while retaining their own rendering and completion rules.\n\n**Consider direct pointer handling when** the interaction is isolated and does not need reusable lifecycle or direction-lock behavior.\n\n</div>\n\n## Installation\n\n::: code-group\n\n```sh [pnpm]\npnpm add @vielzeug/gesture\n```\n\n```sh [npm]\nnpm install @vielzeug/gesture\n```\n\n```sh [yarn]\nyarn add @vielzeug/gesture\n```\n\n:::\n\n## Quick Start\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst element = document.querySelector<HTMLElement>('[data-swipe]');\nif (!element) throw new Error('Missing [data-swipe] element');\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onMove: ({ distance }) => {\n element.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n element.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 48) {\n pan.dispose();\n element.remove();\n }\n },\n});\n\nwindow.addEventListener('pagehide', () => pan.dispose(), { once: true });\n```\n\n## Features\n\n<div class=\"features-grid\">\n\n- `createDragGesture()`: unrestricted two-dimensional pointer movement tracking\n- `createPanGesture()`: one-axis pointer movement with direction intent recognition\n- `createLongPress()`: hold recognition with slop cancellation and click swallowing\n- Direction locking: activates only when movement favors the configured axis\n- Configurable pointer capture: own the pointer by default or preserve native targeting\n- Configurable `activationDistance`: tune slop for touch density and component needs\n- Consumer-owned policy: completion thresholds, snapping, and outcomes stay in application code\n- Stable completion: one `onEnd` callback for release and cancellation\n- Lifecycle ownership: `dispose()`, `disposed`, `disposalSignal`, optional owner `signal`, and `[Symbol.dispose]()`\n\n</div>\n\n## Documentation\n\n<div class=\"doc-links\">\n\n- [Usage Guide](./usage.md)\n- [API Reference](./api.md)\n- [Examples](./examples.md)\n- [Migration Guide](./migration.md)\n\n</div>\n\n## See Also\n\n<div class=\"see-also\">\n\n- [Refine](/refine/): components that use pan recognition for carousel, drawer, toast, and list interactions.\n- [Dnd](/dnd/): builds touch sorting on `createDragGesture()` and adds files, previews, drop targets, keyboard reordering, and connected-list transactions.\n- [Keymap](/keymap/): keyboard interaction primitives for complementary input paths.\n\n</div>\n\n<!-- markdownlint-enable MD025 MD033 MD060 -->\n",
|
|
5
|
-
"api": "---\ntitle: 'Gesture: API Reference'\ndescription: API reference for two-dimensional drag and one-axis pan recognition.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------ | --------------------------------------------------- | -------------- | ------------------------------------------------------- |\n| `createDragGesture()` | Track unrestricted two-dimensional pointer movement | Sync | Does not provide DOM movement or drop semantics |\n| `createPanGesture()` | Track pointer movement projected onto one axis | Sync | Cross-axis intent ends a pending interaction |\n| `createLongPress()` | Recognize a primary pointer held in place | Sync | The click that follows a fired hold is swallowed |\n| `DragGesture` / `PanGesture` / `LongPress` | Control recognition lifecycle | Sync | `dispose()` does not invoke `onEnd` |\n| `DragGestureOptions` | Configure free-drag recognition | Sync | `activationDistance` uses Euclidean distance |\n| `PanGestureOptions` | Configure axis-locked recognition | Sync | Completion thresholds belong in `onEnd` |\n| `LongPressOptions` | Configure hold recognition | Sync | `durationMs` and `slopPx` are validated at construction |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------- | ----------------------------------------------------------------------------------------- |\n| `@vielzeug/gesture` | Drag and pan factories, handles, callback details, options, axes, points, and end reasons |\n\n## Core Functions\n\n### `createDragGesture()`\n\n```ts\nfunction createDragGesture(target: Element, options?: DragGestureOptions): DragGesture;\n```\n\nTracks one primary pointer without restricting movement to an axis.\n\n| Parameter | Type | Description |\n| --------- | -------------------- | --------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `DragGestureOptions` | Activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `DragGesture` handle.\n\n**Example**\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst drag = createDragGesture(element, {\n onMove: ({ delta }) => {\n element.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n element.style.translate = '';\n },\n});\n```\n\n---\n\n### `createPanGesture()`\n\n```ts\nfunction createPanGesture(target: Element, options?: PanGestureOptions): PanGesture;\n```\n\nTracks one primary pointer after movement establishes intent on the configured axis.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | --------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `PanGestureOptions` | Axis, activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `PanGesture` handle.\n\n**Example**\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 48) dismiss();\n },\n});\n```\n\nBoth handles expose the same members:\n\n| Member | Type | Contract |\n| -------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------- |\n| `active` | `boolean` | `true` after activation and before release or cancellation |\n| `cancel()` | `() => boolean` | Clears pending recognition or ends active recognition with `reason: 'cancel'`; returns whether a session existed |\n| `disposalSignal` | `AbortSignal` | Aborts when the handle is disposed |\n| `dispose()` | `() => void` | Aborts `disposalSignal`, clears recognition, releases capture, and detaches listeners; idempotent |\n| `disposed` | `boolean` | `true` after disposal |\n| `[Symbol.dispose]()` | `() => void` | Calls `dispose()` |\n\n---\n\n### `createLongPress()`\n\n```ts\nfunction createLongPress(target: Element, options?: LongPressOptions): LongPress;\n```\n\nRecognizes a primary pointer held in place: `onLongPress` fires with the originating pointerdown once the hold outlasts `durationMs`.\n\n| Parameter | Type | Description |\n| --------- | ------------------ | ---------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission, document tracking, and click swallowing |\n| `options` | `LongPressOptions` | Hold time, slop distance, admission, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `LongPress` handle with the same members as the other gestures; `active` is `true` while a hold is pending.\n\n**Example**\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(list, {\n shouldStart: (event) => event.pointerType !== 'mouse',\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest('.tile');\n openDetail(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx` cancels back to a normal press, and window blur or a hidden document cancels a pending hold. The click that follows a fired hold is swallowed through a capture-phase listener on `target`, so releasing never commits what the hold opened; bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers.\n\n## Types\n\n### Drag types\n\n```ts\ntype DragEndReason = 'cancel' | 'release';\n\ntype DragPoint = Readonly<{\n x: number;\n y: number;\n}>;\n\ntype DragGestureDetail = Readonly<{\n current: DragPoint;\n delta: DragPoint;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: DragPoint;\n target: Element;\n}>;\n\ntype DragGestureEndDetail = DragGestureDetail &\n Readonly<{\n reason: DragEndReason;\n }>;\n\ntype DragGestureOptions = Readonly<{\n activationDistance?: number;\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: DragGestureEndDetail) => void;\n onMove?: (detail: DragGestureDetail) => void;\n onStart?: (detail: DragGestureDetail) => void;\n pointerCapture?: boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\n`start`, `current`, and `delta` use viewport `clientX` and `clientY` coordinates. Activation uses `Math.hypot(delta.x, delta.y)`.\n\n### Pan types\n\n```ts\ntype PanAxis = 'x' | 'y';\ntype PanEndReason = 'cancel' | 'release';\n\ntype PanGestureDetail = Readonly<{\n axis: PanAxis;\n current: number;\n distance: number;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: number;\n target: Element;\n}>;\n\ntype PanGestureEndDetail = PanGestureDetail &\n Readonly<{\n reason: PanEndReason;\n }>;\n\ntype PanGestureOptions = Readonly<{\n activationDistance?: number;\n axis?: PanAxis | (() => PanAxis);\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: PanGestureEndDetail) => void;\n onMove?: (detail: PanGestureDetail) => void;\n onStart?: (detail: PanGestureDetail) => void;\n pointerCapture?: boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\nPan details project `start`, `current`, and `distance` onto `axis`. The default axis is `'x'`.\n\n### Long-press types\n\n```ts\ntype LongPressDetail = Readonly<{\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n target: Element;\n}>;\n\ntype LongPressOptions = Readonly<{\n durationMs?: number;\n disabled?: boolean | (() => boolean | undefined);\n onLongPress?: (detail: LongPressDetail) => void;\n shouldStart?: (event: PointerEvent) => boolean;\n slopPx?: number;\n signal?: AbortSignal;\n}>;\n```\n\n`durationMs` defaults to `500` and `slopPx` to `8`. `event` is the pointerdown that started the hold, so `event.target` is the pressed element.\n\n### Handle types\n\n```ts\ntype DragGesture = {\n readonly active: boolean;\n [Symbol.dispose](): void;\n cancel(): boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n};\n\ntype PanGesture = DragGesture;\n```\n\n### Shared option behavior\n\n| Option | Default | Contract |\n| -------------------- | ------- | ------------------------------------------------------------------------------------------------------ |\n| `activationDistance` | `6` | Non-negative finite CSS pixels; drag uses Euclidean distance, pan waits for dominant-axis intent |\n| `axis` | `'x'` | Pan only; fixed value or getter sampled when each interaction starts |\n| `disabled` | `false` | Fixed value or getter; blocks starts and cancels active recognition on the next matching pointer event |\n| `pointerCapture` | `true` | Best-effort capture after activation; document tracking continues when capture is disabled or fails |\n| `shouldStart` | N/A | Admission predicate evaluated for the primary pointer before tracking starts |\n| `signal` | N/A | Disposes the handle when the external owner aborts |\n| `onStart` | N/A | Runs once on the activating movement |\n| `onMove` | N/A | Runs on the activating movement and each later matching movement |\n| `onEnd` | N/A | Runs once for active release or cancellation; pending interactions end without callbacks |\n\nOptions and callback details are readonly. Fixed callbacks and capture policy are snapshotted at construction. Function-valued `axis` and `disabled` options remain dynamic.\n\nGesture tracks accepted movement with capture-phase listeners on the target's current owner document. Window blur, hidden-document transition, `pointercancel`, and pointer capture loss on the gesture target cancel active recognition. A `lostpointercapture` event bubbling from a descendant does not cancel the target's gesture.\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| -------------------- | --------------------------------------------- | --------------------------------------------------- |\n| `GestureError` | Base class for every gesture-originated error | `instanceof GestureError` catches any gesture error |\n| `GestureConfigError` | Invalid option value | Extends `GestureError` |\n\n- Invalid `activationDistance` values throw `GestureConfigError` during construction.\n- Invalid fixed `axis` values throw `GestureConfigError` during construction.\n- Invalid values returned by a dynamic `axis` getter throw `GestureConfigError` when a pointer interaction starts.\n",
|
|
6
|
-
"usage": "---\ntitle: 'Gesture: Usage Guide'\ndescription: Track unrestricted pointer dragging and axis-locked pans with application-owned rendering and completion.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate one handle for the element that owns the interaction. This example creates its surface, applies the required touch policy, and disposes the handle when the page unloads.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst row = document.body.appendChild(document.createElement('div'));\nrow.textContent = 'Swipe to archive';\nrow.style.touchAction = 'pan-y';\n\nconst pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) {\n pan.dispose();\n row.remove();\n }\n },\n});\n\nwindow.addEventListener('pagehide', () => pan.dispose(), { once: true });\n```\n\n## Track Two-Dimensional Dragging\n\nUse `createDragGesture()` when movement must remain unrestricted in both dimensions:\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst card = document.querySelector<HTMLElement>('[data-draggable]');\nif (!card) throw new Error('Missing [data-draggable] element');\n\nconst drag = createDragGesture(card, {\n activationDistance: 6,\n onMove: ({ delta }) => {\n card.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n card.style.translate = '';\n },\n});\n\nwindow.addEventListener('pagehide', () => drag.dispose(), { once: true });\n```\n\n`start`, `current`, and `delta` are readonly `{ x, y }` points. Set `touch-action: none` when the surface owns movement in both dimensions. Drag recognition does not provide previews, drop targets, DOM movement, or `DataTransfer`; use Dnd for those semantics.\n\n## Recognize Long Presses\n\nUse `createLongPress()` for hold interactions: the touch counterpart of a keyboard preview key. `onLongPress` receives the originating pointerdown once the hold outlasts `durationMs`:\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(grid, {\n durationMs: 500,\n shouldStart: (event) => event.pointerType !== 'mouse' && (event.target as HTMLElement).closest('.tile') !== null,\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest<HTMLElement>('.tile');\n openPreview(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx` cancels back to a normal press, so scrolling never triggers the hold. The click that follows a fired hold is swallowed through a capture-phase listener on `target`: bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers, and gate `shouldStart` to the elements the hold belongs to.\n\n## Completion Rules\n\nGesture reports movement and terminal state but does not decide what constitutes a swipe. Apply thresholds and allowed directions in `onEnd`.\n\n```ts\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && distance <= -80) {\n openNext();\n } else {\n resetPanel();\n }\n },\n});\n```\n\n## Direction Recognition\n\nThe gesture remains pending during small movement. It activates only after movement favors the configured axis. Cross-axis movement ends the pending interaction without invoking callbacks.\n\nThe default `activationDistance` is 6 pixels. Tune direction-recognition slop for touch density or component-specific needs:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n activationDistance: 12,\n onMove,\n onEnd,\n});\n```\n\nSet `activationDistance: 0` when the first pointer move with non-zero displacement should activate immediately. Zero-motion events remain pending.\n\nUse the corresponding `touch-action` value so the browser retains native scrolling on the other axis.\n\n```css\n.swipe-row {\n touch-action: pan-y;\n}\n```\n\n```ts\nconst pan = createPanGesture(row, { axis: 'x', onMove });\n```\n\n## Pointer Capture\n\nPointer capture is enabled by default. After axis intent is accepted, Gesture attempts to capture the pointer while continuing to track movement through document-level listeners. Capture failure (for example after target detachment or pointer termination) falls back to document tracking without stranding the session.\n\nDisable capture when nested or newly revealed controls must retain native pointer-up and click targeting:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n pointerCapture: false,\n onMove: renderReveal,\n onEnd: settleReveal,\n});\n```\n\nDocument-level tracking still keeps the pan active outside the target. Disabling capture changes event targeting, not gesture tracking.\n\n## Interactive Descendants\n\nUse `shouldStart` when buttons, links, or form controls inside the surface must not start a pan.\n\n```ts\nconst pan = createPanGesture(notification, {\n axis: 'x',\n pointerCapture: false,\n shouldStart: (event) =>\n !event.composedPath().some((node) => node instanceof Element && node.matches('button, a, input, select, textarea')),\n onMove,\n onEnd,\n});\n```\n\n`shouldStart` protects controls under the initial pointer. `pointerCapture: false` additionally protects controls that appear beneath the pointer during a reveal interaction.\n\n## Disabled State\n\nA boolean disables the recognizer permanently. A getter supports state that changes while the handle is alive.\n\n```ts\nconst pan = createPanGesture(row, {\n disabled: () => isLocked,\n onEnd: ({ reason }) => {\n if (reason === 'cancel') resetRow();\n },\n});\n```\n\nWhen the getter becomes `true`, the next pointer event cancels an active pan. Window blur or a hidden owner document also cancels active tracking so a lost release cannot block later gestures.\n\nGesture snapshots fixed callbacks and capture policy at construction. Use the `axis` and `disabled` functions for behavior that must remain dynamic instead of mutating the options object.\n\n## Lifecycle\n\nDispose the target-bound handle when its owning UI scope unmounts.\n\n```ts\nconst element = document.querySelector<HTMLElement>('[data-pan]');\nif (!element) throw new Error('Missing [data-pan] element');\n\nconst owner = new AbortController();\nconst request = new AbortController();\nconst pan = createPanGesture(element, {\n axis: 'x',\n signal: owner.signal,\n});\n\nconst childSignal = AbortSignal.any([pan.disposalSignal, request.signal]);\nwindow.addEventListener('pagehide', () => owner.abort(), { once: true });\n```\n\nPass `{ signal }` to dispose with an existing owner signal. `disposalSignal` always aborts when Gesture finishes teardown, so child work can compose with the handle regardless of how disposal starts.\n\nUse `cancel()` to stop a pending or active interaction without disposing the handle. An active interaction emits `onEnd` with `reason: 'cancel'`. Call `cancel()` before `dispose()` when a connected surface needs its `onEnd` reset path; disposal itself does not invoke callbacks.\n\n## Framework Integration\n\nCreate the handle after the target element exists and dispose it on unmount.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\nimport { createPanGesture } from '@vielzeug/gesture';\n\nfunction SwipeRow({ onDismiss }: { onDismiss: () => void }) {\n const rowRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const row = rowRef.current;\n if (!row) return;\n\n const pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) onDismiss();\n },\n });\n\n return () => pan.dispose();\n }, [onDismiss]);\n\n return <div ref={rowRef}>Swipe me</div>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, ref } from 'vue';\nimport { createPanGesture, type PanGesture } from '@vielzeug/gesture';\n\nconst emit = defineEmits<{ dismiss: [] }>();\nconst rowEl = ref<HTMLDivElement | null>(null);\nlet pan: PanGesture | undefined;\n\nonMounted(() => {\n const row = rowEl.value;\n if (!row) return;\n\n pan = createPanGesture(row, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) emit('dismiss');\n },\n });\n});\n\nonUnmounted(() => pan?.dispose());\n</script>\n\n<template>\n <div ref=\"rowEl\">Swipe me</div>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createPanGesture } from '@vielzeug/gesture';\n\n let { ondismiss = () => {} }: { ondismiss: () => void } = $props();\n let rowEl: HTMLDivElement;\n\n onMount(() => {\n const pan = createPanGesture(rowEl, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) ondismiss();\n },\n });\n\n return () => pan.dispose();\n });\n</script>\n\n<div bind:this={rowEl}>Swipe me</div>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### Gesture + Refine\n\nRefine uses Gesture internally for carousel, drawer, toast, and list-item pointer interactions. Custom surfaces can use the same pan lifecycle while keeping visual state local.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onMove: ({ distance }) => {\n panel.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n panel.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 80) revealActions();\n },\n});\n```\n\n### Gesture + Dnd\n\nGesture owns pointer recognition: unrestricted two-dimensional drag and one-axis pan. Dnd builds touch sorting on `createDragGesture()`, then owns `DataTransfer`, previews, hit-testing, file drop zones, keyboard sorting, DOM reordering, and connected-list transactions. Use Dnd when an item is picked up and dropped; use Gesture directly when application code owns rendering and completion.\n\n## Best Practices\n\n- **Set** `touch-action` for the axis the browser should continue scrolling.\n- **Use** `shouldStart` to exclude nested interactive controls.\n- **Disable** pointer capture when nested or newly revealed controls must keep native release targeting.\n- **Apply** completion thresholds and direction rules in `onEnd`; use `activationDistance` only for recognition slop.\n- **Treat** `reason: 'cancel'` as a reset path, never a commit path. Pointer capture loss on the gesture target cancels; capture loss bubbling from a descendant does not.\n- **Keep** `onMove` rendering lightweight.\n- **Dispose** the handle when its target leaves the UI.\n",
|
|
5
|
+
"api": "---\ntitle: 'Gesture: API Reference'\ndescription: API reference for two-dimensional drag and one-axis pan recognition.\n---\n\n[[toc]]\n\n## API Overview\n\n| Symbol | Purpose | Execution mode | Common gotcha |\n| ------------------------------------------ | --------------------------------------------------- | -------------- | ------------------------------------------------------- |\n| `createDragGesture()` | Track unrestricted two-dimensional pointer movement | Sync | Does not provide DOM movement or drop semantics |\n| `createPanGesture()` | Track pointer movement projected onto one axis | Sync | Cross-axis intent ends a pending interaction |\n| `createLongPress()` | Recognize a primary pointer held in place | Sync | The click that follows a fired hold is swallowed |\n| `DragGesture` / `PanGesture` / `LongPress` | Control recognition lifecycle | Sync | `dispose()` does not invoke `onEnd` |\n| `DragGestureOptions` | Configure free-drag recognition | Sync | `activationDistance` uses Euclidean distance |\n| `PanGestureOptions` | Configure axis-locked recognition | Sync | Completion thresholds belong in `onEnd` |\n| `LongPressOptions` | Configure hold recognition | Sync | `durationMs` and `slopPx` are validated at construction |\n\n## Package Entry Point\n\n| Import | Purpose |\n| ------------------- | ----------------------------------------------------------------------------------------- |\n| `@vielzeug/gesture` | Drag and pan factories, handles, callback details, options, axes, points, and end reasons |\n\n## Core Functions\n\n### `createDragGesture()`\n\n```ts\nfunction createDragGesture(target: Element, options?: DragGestureOptions): DragGesture;\n```\n\nTracks one primary pointer without restricting movement to an axis.\n\n| Parameter | Type | Description |\n| --------- | -------------------- | --------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `DragGestureOptions` | Activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `DragGesture` handle.\n\n**Example**\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst drag = createDragGesture(element, {\n onMove: ({ delta }) => {\n element.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n element.style.translate = '';\n },\n});\n```\n\n---\n\n### `createPanGesture()`\n\n```ts\nfunction createPanGesture(target: Element, options?: PanGestureOptions): PanGesture;\n```\n\nTracks one primary pointer after movement establishes intent on the configured axis.\n\n| Parameter | Type | Description |\n| --------- | ------------------- | --------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission and optional capture |\n| `options` | `PanGestureOptions` | Axis, activation, admission, capture, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `PanGesture` handle.\n\n**Example**\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(element, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 48) dismiss();\n },\n});\n```\n\nBoth handles expose the same members:\n\n| Member | Type | Contract |\n| -------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------- |\n| `active` | `boolean` | `true` after activation and before release or cancellation |\n| `cancel()` | `() => boolean` | Clears pending recognition or ends active recognition with `reason: 'cancel'`; returns whether a session existed |\n| `disposalSignal` | `AbortSignal` | Aborts when the handle is disposed |\n| `dispose()` | `() => void` | Aborts `disposalSignal`, clears recognition, releases capture, and detaches listeners; idempotent |\n| `disposed` | `boolean` | `true` after disposal |\n| `[Symbol.dispose]()` | `() => void` | Calls `dispose()` |\n\n---\n\n### `createLongPress()`\n\n```ts\nfunction createLongPress(target: Element, options?: LongPressOptions): LongPress;\n```\n\nRecognizes a primary pointer held in place: `onLongPress` fires with the originating pointerdown once the hold outlasts `durationMs`.\n\n| Parameter | Type | Description |\n| --------- | ------------------ | ---------------------------------------------------------------------------- |\n| `target` | `Element` | Element that owns pointer admission, document tracking, and click swallowing |\n| `options` | `LongPressOptions` | Hold time, slop distance, admission, callback, and lifecycle configuration |\n\n**Returns:** A lifecycle-owned `LongPress` handle with the same members as the other gestures; `active` is `true` while a hold is pending.\n\n**Example**\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(list, {\n shouldStart: (event) => event.pointerType !== 'mouse',\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest('.tile');\n openDetail(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx`, a second touch, window blur, or a hidden document cancels a pending hold. The dynamic `disabled` predicate is checked again before the timer fires. The pointer-generated click following a fired hold is swallowed through a capture-phase listener on `target`; keyboard clicks (`detail: 0`) remain available. Bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers.\n\n## Types\n\n### Drag types\n\n```ts\ntype DragEndReason = 'cancel' | 'release';\n\ntype DragPoint = Readonly<{\n x: number;\n y: number;\n}>;\n\ntype DragGestureDetail = Readonly<{\n current: DragPoint;\n delta: DragPoint;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: DragPoint;\n target: Element;\n velocity: DragPoint;\n}>;\n\ntype DragGestureEndDetail = DragGestureDetail &\n Readonly<{\n reason: DragEndReason;\n }>;\n\ntype DragGestureOptions = Readonly<{\n activationDistance?: number;\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: DragGestureEndDetail) => void;\n onMove?: (detail: DragGestureDetail) => void;\n onStart?: (detail: DragGestureDetail) => void;\n pointerCapture?: boolean;\n shouldActivate?: (detail: DragGestureDetail) => boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\n`start`, `current`, and `delta` use viewport `clientX` and `clientY` coordinates. Activation uses `Math.hypot(delta.x, delta.y)`.\n\n### Pan types\n\n```ts\ntype PanAxis = 'x' | 'y';\ntype PanEndReason = 'cancel' | 'release';\n\ntype PanGestureDetail = Readonly<{\n axis: PanAxis;\n current: number;\n distance: number;\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n start: number;\n target: Element;\n velocity: number;\n}>;\n\ntype PanGestureEndDetail = PanGestureDetail &\n Readonly<{\n reason: PanEndReason;\n }>;\n\ntype PanGestureOptions = Readonly<{\n activationDistance?: number;\n axis?: PanAxis | (() => PanAxis);\n disabled?: boolean | (() => boolean | undefined);\n onEnd?: (detail: PanGestureEndDetail) => void;\n onMove?: (detail: PanGestureDetail) => void;\n onStart?: (detail: PanGestureDetail) => void;\n pointerCapture?: boolean;\n shouldActivate?: (detail: PanGestureDetail) => boolean;\n shouldStart?: (event: PointerEvent) => boolean;\n signal?: AbortSignal;\n}>;\n```\n\nPan details project `start`, `current`, and `distance` onto `axis`. The default axis is `'x'`.\n\nVelocity is signed CSS pixels per second over the trailing 90 ms. Samples include pointerdown, movement (including activation), and release. A window with fewer than two distinct sample times reports zero velocity; a pause longer than the window removes earlier movement.\n\n### Long-press types\n\n```ts\ntype LongPressDetail = Readonly<{\n event: PointerEvent;\n pointerId: number;\n pointerType: string;\n target: Element;\n}>;\n\ntype LongPressOptions = Readonly<{\n durationMs?: number;\n disabled?: boolean | (() => boolean | undefined);\n onLongPress?: (detail: LongPressDetail) => void;\n shouldStart?: (event: PointerEvent) => boolean;\n slopPx?: number;\n signal?: AbortSignal;\n}>;\n```\n\n`durationMs` defaults to `500` and `slopPx` to `8`. `event` is the pointerdown that started the hold, so `event.target` is the pressed element.\n\n### Handle types\n\n```ts\ntype DragGesture = {\n readonly active: boolean;\n [Symbol.dispose](): void;\n cancel(): boolean;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n};\n\ntype PanGesture = DragGesture;\n```\n\n### Shared option behavior\n\n| Option | Default | Contract |\n| -------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |\n| `activationDistance` | `6` | Non-negative finite CSS pixels; drag uses Euclidean distance, pan waits for dominant-axis intent |\n| `axis` | `'x'` | Pan only; fixed value or getter sampled when each interaction starts |\n| `disabled` | `false` | Fixed value or getter; blocks starts and cancels active recognition on the next matching pointer event |\n| `pointerCapture` | `true` | Best-effort capture after activation; document tracking continues when capture is disabled or fails |\n| `shouldStart` | N/A | Admission predicate evaluated for the primary pointer before tracking starts |\n| `shouldActivate` | N/A | Drag/pan predicate evaluated once after distance/axis recognition and before capture or callbacks; false rejects the session |\n| `signal` | N/A | Disposes the handle when the external owner aborts |\n| `onStart` | N/A | Runs once on the activating movement |\n| `onMove` | N/A | Runs on the activating movement and each later matching movement |\n| `onEnd` | N/A | Runs once for active release or cancellation; pending interactions end without callbacks |\n\nOptions and callback details are readonly. Fixed callbacks and capture policy are snapshotted at construction. Function-valued `axis` and `disabled` options remain dynamic.\n\nGesture tracks accepted movement with capture-phase listeners on the target's current owner document. Window blur, hidden-document transition, `pointercancel`, pointer capture loss on the gesture target, and a second touch anywhere in that document cancel recognition. A `lostpointercapture` event bubbling from a descendant does not cancel the target's gesture. Exact diagonal ties remain pending until one axis dominates; cross-axis dominance rejects the pending pan. Gesture does not arbitrate ownership between recognizers on the same axis.\n\n## Errors\n\n| Error | Trigger | Notable properties |\n| -------------------- | --------------------------------------------- | --------------------------------------------------- |\n| `GestureError` | Base class for every gesture-originated error | `instanceof GestureError` catches any gesture error |\n| `GestureConfigError` | Invalid option value | Extends `GestureError` |\n\n- Invalid `activationDistance` values throw `GestureConfigError` during construction.\n- Invalid fixed `axis` values throw `GestureConfigError` during construction.\n- Invalid values returned by a dynamic `axis` getter throw `GestureConfigError` when a pointer interaction starts.\n",
|
|
6
|
+
"usage": "---\ntitle: 'Gesture: Usage Guide'\ndescription: Track unrestricted pointer dragging and axis-locked pans with application-owned rendering and completion.\n---\n\n[[toc]]\n\n## Basic Usage\n\nCreate one handle for the element that owns the interaction. This example creates its surface, applies the required touch policy, and disposes the handle when the page unloads.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst row = document.body.appendChild(document.createElement('div'));\nrow.textContent = 'Swipe to archive';\nrow.style.touchAction = 'pan-y';\n\nconst pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) {\n pan.dispose();\n row.remove();\n }\n },\n});\n\nwindow.addEventListener('pagehide', () => pan.dispose(), { once: true });\n```\n\n## Track Two-Dimensional Dragging\n\nUse `createDragGesture()` when movement must remain unrestricted in both dimensions:\n\n```ts\nimport { createDragGesture } from '@vielzeug/gesture';\n\nconst card = document.querySelector<HTMLElement>('[data-draggable]');\nif (!card) throw new Error('Missing [data-draggable] element');\n\nconst drag = createDragGesture(card, {\n activationDistance: 6,\n onMove: ({ delta }) => {\n card.style.translate = `${delta.x}px ${delta.y}px`;\n },\n onEnd: () => {\n card.style.translate = '';\n },\n});\n\nwindow.addEventListener('pagehide', () => drag.dispose(), { once: true });\n```\n\n`start`, `current`, and `delta` are readonly `{ x, y }` points. Set `touch-action: none` when the surface owns movement in both dimensions. Drag recognition does not provide previews, drop targets, DOM movement, or `DataTransfer`; use Dnd for those semantics.\n\n## Recognize Long Presses\n\nUse `createLongPress()` for hold interactions: the touch counterpart of a keyboard preview key. `onLongPress` receives the originating pointerdown once the hold outlasts `durationMs`:\n\n```ts\nimport { createLongPress } from '@vielzeug/gesture';\n\nconst hold = createLongPress(grid, {\n durationMs: 500,\n shouldStart: (event) => event.pointerType !== 'mouse' && (event.target as HTMLElement).closest('.tile') !== null,\n onLongPress: (detail) => {\n const tile = (detail.event.target as HTMLElement).closest<HTMLElement>('.tile');\n openPreview(tile?.dataset.id);\n },\n});\n```\n\nMovement beyond `slopPx` cancels back to a normal press, so scrolling never triggers the hold. The click that follows a fired hold is swallowed through a capture-phase listener on `target`: bind `target` to a stable ancestor of the pressed controls so the swallow precedes their click handlers, and gate `shouldStart` to the elements the hold belongs to.\n\n## Completion Rules\n\nGesture reports movement and terminal state but does not decide what constitutes a swipe. Apply thresholds and allowed directions in `onEnd`.\n\n```ts\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && distance <= -80) {\n openNext();\n } else {\n resetPanel();\n }\n },\n});\n```\n\n## Direction Recognition\n\nThe gesture remains pending during small movement and exact diagonal ties. It activates only after movement strictly favors the configured axis. Cross-axis movement ends the pending interaction without invoking callbacks.\n\nThe default `activationDistance` is 6 pixels. Tune direction-recognition slop for touch density or component-specific needs:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n activationDistance: 12,\n onMove,\n onEnd,\n});\n```\n\nSet `activationDistance: 0` when the first pointer move with non-zero displacement should activate immediately. Zero-motion events remain pending.\n\nUse the corresponding `touch-action` value so the browser retains native scrolling on the other axis.\n\n```css\n.swipe-row {\n touch-action: pan-y pinch-zoom;\n}\n```\n\n```ts\nconst pan = createPanGesture(row, { axis: 'x', onMove });\n```\n\nUse `shouldStart` to exclude controls at pointerdown. Use `shouldActivate` for direction or boundary checks that require movement; rejection happens before capture or callbacks.\n\n```ts\nconst pan = createPanGesture(panel, {\n axis: 'y',\n shouldActivate: ({ distance }) => distance > 0 && scroller.scrollTop <= 0,\n onMove: renderPull,\n onEnd: settlePull,\n});\n```\n\nGesture cancels pending and active touch recognition when a second finger touches the owner document. Reset presentation on `reason: 'cancel'`; never commit an action from cancellation. Native scroll and pinch behavior still depends on the surface's CSS and event handling. Once native scrolling owns a touch sequence, start a fresh swipe at the boundary rather than attempting a mid-scroll handoff.\n\n## Pointer Capture\n\nPointer capture is enabled by default. After axis intent is accepted, Gesture attempts to capture the pointer while continuing to track movement through document-level listeners. Capture failure (for example after target detachment or pointer termination) falls back to document tracking without stranding the session.\n\nDisable capture when nested or newly revealed controls must retain native pointer-up and click targeting:\n\n```ts\nconst pan = createPanGesture(row, {\n axis: 'x',\n pointerCapture: false,\n onMove: renderReveal,\n onEnd: settleReveal,\n});\n```\n\nDocument-level tracking still keeps the pan active outside the target. Disabling capture changes event targeting, not gesture tracking.\n\n## Interactive Descendants\n\nUse `shouldStart` when buttons, links, or form controls inside the surface must not start a pan.\n\n```ts\nconst pan = createPanGesture(notification, {\n axis: 'x',\n pointerCapture: false,\n shouldStart: (event) =>\n !event.composedPath().some((node) => node instanceof Element && node.matches('button, a, input, select, textarea')),\n onMove,\n onEnd,\n});\n```\n\n`shouldStart` protects controls under the initial pointer. `pointerCapture: false` additionally protects controls that appear beneath the pointer during a reveal interaction.\n\n## Disabled State\n\nA boolean disables the recognizer permanently. A getter supports state that changes while the handle is alive.\n\n```ts\nconst pan = createPanGesture(row, {\n disabled: () => isLocked,\n onEnd: ({ reason }) => {\n if (reason === 'cancel') resetRow();\n },\n});\n```\n\nWhen the getter becomes `true`, the next pointer event cancels an active pan. Window blur or a hidden owner document also cancels active tracking so a lost release cannot block later gestures.\n\nGesture snapshots fixed callbacks and capture policy at construction. Use the `axis` and `disabled` functions for behavior that must remain dynamic instead of mutating the options object.\n\n## Lifecycle\n\nDispose the target-bound handle when its owning UI scope unmounts.\n\n```ts\nconst element = document.querySelector<HTMLElement>('[data-pan]');\nif (!element) throw new Error('Missing [data-pan] element');\n\nconst owner = new AbortController();\nconst request = new AbortController();\nconst pan = createPanGesture(element, {\n axis: 'x',\n signal: owner.signal,\n});\n\nconst childSignal = AbortSignal.any([pan.disposalSignal, request.signal]);\nwindow.addEventListener('pagehide', () => owner.abort(), { once: true });\n```\n\nPass `{ signal }` to dispose with an existing owner signal. `disposalSignal` always aborts when Gesture finishes teardown, so child work can compose with the handle regardless of how disposal starts.\n\nUse `cancel()` to stop a pending or active interaction without disposing the handle. An active interaction emits `onEnd` with `reason: 'cancel'`. Call `cancel()` before `dispose()` when a connected surface needs its `onEnd` reset path; disposal itself does not invoke callbacks.\n\n## Framework Integration\n\nCreate the handle after the target element exists and dispose it on unmount.\n\n::: code-group\n\n```tsx [React]\nimport { useEffect, useRef } from 'react';\nimport { createPanGesture } from '@vielzeug/gesture';\n\nfunction SwipeRow({ onDismiss }: { onDismiss: () => void }) {\n const rowRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const row = rowRef.current;\n if (!row) return;\n\n const pan = createPanGesture(row, {\n axis: 'x',\n onMove: ({ distance }) => {\n row.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n row.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 64) onDismiss();\n },\n });\n\n return () => pan.dispose();\n }, [onDismiss]);\n\n return <div ref={rowRef}>Swipe me</div>;\n}\n```\n\n```vue [Vue 3]\n<script setup lang=\"ts\">\nimport { onMounted, onUnmounted, ref } from 'vue';\nimport { createPanGesture, type PanGesture } from '@vielzeug/gesture';\n\nconst emit = defineEmits<{ dismiss: [] }>();\nconst rowEl = ref<HTMLDivElement | null>(null);\nlet pan: PanGesture | undefined;\n\nonMounted(() => {\n const row = rowEl.value;\n if (!row) return;\n\n pan = createPanGesture(row, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) emit('dismiss');\n },\n });\n});\n\nonUnmounted(() => pan?.dispose());\n</script>\n\n<template>\n <div ref=\"rowEl\">Swipe me</div>\n</template>\n```\n\n```svelte [Svelte]\n<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { createPanGesture } from '@vielzeug/gesture';\n\n let { ondismiss = () => {} }: { ondismiss: () => void } = $props();\n let rowEl: HTMLDivElement;\n\n onMount(() => {\n const pan = createPanGesture(rowEl, {\n axis: 'x',\n onEnd: ({ distance, reason }) => {\n if (reason === 'release' && Math.abs(distance) >= 64) ondismiss();\n },\n });\n\n return () => pan.dispose();\n });\n</script>\n\n<div bind:this={rowEl}>Swipe me</div>\n```\n\n:::\n\n## Working with Other Vielzeug Libraries\n\n### Gesture + Refine\n\nRefine uses Gesture internally for carousel, drawer, toast, and list-item pointer interactions. Custom surfaces can use the same pan lifecycle while keeping visual state local.\n\n```ts\nimport { createPanGesture } from '@vielzeug/gesture';\n\nconst pan = createPanGesture(panel, {\n axis: 'x',\n onMove: ({ distance }) => {\n panel.style.transform = `translateX(${distance}px)`;\n },\n onEnd: ({ distance, reason }) => {\n panel.style.transform = '';\n if (reason === 'release' && Math.abs(distance) >= 80) revealActions();\n },\n});\n```\n\n### Gesture + Dnd\n\nGesture owns pointer recognition: unrestricted two-dimensional drag and one-axis pan. Dnd builds touch sorting on `createDragGesture()`, then owns `DataTransfer`, previews, hit-testing, file drop zones, keyboard sorting, DOM reordering, and connected-list transactions. Use Dnd when an item is picked up and dropped; use Gesture directly when application code owns rendering and completion.\n\n## Best Practices\n\n- **Set** `touch-action` for the axis the browser should continue scrolling.\n- **Use** `shouldStart` to exclude nested interactive controls.\n- **Disable** pointer capture when nested or newly revealed controls must keep native release targeting.\n- **Apply** completion thresholds and direction rules in `onEnd`; use `activationDistance` only for recognition slop.\n- **Treat** `reason: 'cancel'` as a reset path, never a commit path. Pointer capture loss on the gesture target cancels; capture loss bubbling from a descendant does not.\n- **Keep** `onMove` rendering lightweight.\n- **Dispose** the handle when its target leaves the UI.\n",
|
|
7
7
|
"examples": "---\ntitle: 'Gesture: Examples'\ndescription: Worked examples for @vielzeug/gesture.\n---\n\n## Examples\n\n- [Carousel Pan Navigation](./examples/carousel-swipe-navigation.md)\n- [Swipe-to-Dismiss Notifications](./examples/swipe-dismiss-notifications.md)\n"
|
|
8
8
|
},
|
|
9
9
|
"examples": [
|
package/data/refine.json
CHANGED
|
@@ -1805,6 +1805,74 @@
|
|
|
1805
1805
|
"default": "{ lg: { '--_min-height': 'var(--size-40)', fontSize: 'var(--text-base)', }, md: { '--_min-height': 'var(--size-32)', fontSize: 'var(--text-sm)', }, sm: { '--_min-height': 'var(--size-28)', fontSize: 'var(--text-xs)', }, } satisfies FullSizePreset",
|
|
1806
1806
|
"description": "Shared size preset for the file-input dropzone."
|
|
1807
1807
|
},
|
|
1808
|
+
{
|
|
1809
|
+
"kind": "variable",
|
|
1810
|
+
"name": "SWIPE_EDITABLE_SELECTOR"
|
|
1811
|
+
},
|
|
1812
|
+
{
|
|
1813
|
+
"kind": "variable",
|
|
1814
|
+
"name": "SWIPE_INTERACTIVE_SELECTOR",
|
|
1815
|
+
"default": "`a[href], button, summary, label, ore-button, ore-checkbox, [role=\"button\"], [role=\"link\"], ${SWIPE_EDITABLE_SELECTOR}`"
|
|
1816
|
+
},
|
|
1817
|
+
{
|
|
1818
|
+
"kind": "variable",
|
|
1819
|
+
"name": "SWIPE_SURFACES",
|
|
1820
|
+
"type": {
|
|
1821
|
+
"text": "string"
|
|
1822
|
+
},
|
|
1823
|
+
"default": "'[data-no-swipe], ore-carousel, ore-list-item, ore-pull-to-refresh, ore-sidebar, ore-toast, ore-drawer'"
|
|
1824
|
+
},
|
|
1825
|
+
{
|
|
1826
|
+
"kind": "variable",
|
|
1827
|
+
"name": "SWIPE_EXCLUSIONS",
|
|
1828
|
+
"default": "`${SWIPE_INTERACTIVE_SELECTOR}, ${SWIPE_SURFACES}`"
|
|
1829
|
+
},
|
|
1830
|
+
{
|
|
1831
|
+
"kind": "function",
|
|
1832
|
+
"name": "swipePath",
|
|
1833
|
+
"return": {
|
|
1834
|
+
"type": {
|
|
1835
|
+
"text": "HTMLElement[]"
|
|
1836
|
+
}
|
|
1837
|
+
},
|
|
1838
|
+
"parameters": [
|
|
1839
|
+
{
|
|
1840
|
+
"name": "event",
|
|
1841
|
+
"type": {
|
|
1842
|
+
"text": "Event"
|
|
1843
|
+
}
|
|
1844
|
+
},
|
|
1845
|
+
{
|
|
1846
|
+
"name": "boundary",
|
|
1847
|
+
"type": {
|
|
1848
|
+
"text": "Element"
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
]
|
|
1852
|
+
},
|
|
1853
|
+
{
|
|
1854
|
+
"kind": "function",
|
|
1855
|
+
"name": "canScrollInDirection",
|
|
1856
|
+
"return": {
|
|
1857
|
+
"type": {
|
|
1858
|
+
"text": "boolean"
|
|
1859
|
+
}
|
|
1860
|
+
},
|
|
1861
|
+
"parameters": [
|
|
1862
|
+
{
|
|
1863
|
+
"name": "elements",
|
|
1864
|
+
"type": {
|
|
1865
|
+
"text": "readonly HTMLElement[]"
|
|
1866
|
+
}
|
|
1867
|
+
},
|
|
1868
|
+
{
|
|
1869
|
+
"name": "{ axis, direction }",
|
|
1870
|
+
"type": {
|
|
1871
|
+
"text": "{ axis: 'x' | 'y'; direction: number }"
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
]
|
|
1875
|
+
},
|
|
1808
1876
|
{
|
|
1809
1877
|
"kind": "variable",
|
|
1810
1878
|
"name": "COMPONENT_SIZES",
|
|
@@ -10921,14 +10989,14 @@
|
|
|
10921
10989
|
"text": "'ore-rating'"
|
|
10922
10990
|
},
|
|
10923
10991
|
"default": "'ore-rating'",
|
|
10924
|
-
"description": "A star rating control.\n\nImplements the WAI-ARIA slider rating pattern: the star row is a single\nfocusable `role=\"slider\"`, arrows adjust by `precision`, Home/End jump to\n0/max, click or drag sets the star (the
|
|
10992
|
+
"description": "A star rating control.\n\nImplements the WAI-ARIA slider rating pattern: the star row is a single\nfocusable `role=\"slider\"`, arrows adjust by `precision`, Home/End jump to\n0/max, click or drag sets the star (the leading half of a star with\n`precision=\"0.5\"` selects the half step). Selected stars are always filled,\nso filled-vs-outline carries the value without relying on color."
|
|
10925
10993
|
},
|
|
10926
10994
|
{
|
|
10927
10995
|
"kind": "class",
|
|
10928
10996
|
"name": "OreRatingElement",
|
|
10929
10997
|
"tagName": "ore-rating",
|
|
10930
10998
|
"customElement": true,
|
|
10931
|
-
"description": "A star rating control.\nImplements the WAI-ARIA slider rating pattern: the star row is a single\nfocusable `role=\"slider\"`, arrows adjust by `precision`, Home/End jump to\n0/max, click or drag sets the star (the
|
|
10999
|
+
"description": "A star rating control.\nImplements the WAI-ARIA slider rating pattern: the star row is a single\nfocusable `role=\"slider\"`, arrows adjust by `precision`, Home/End jump to\n0/max, click or drag sets the star (the leading half of a star with\n`precision=\"0.5\"` selects the half step). Selected stars are always filled,\nso filled-vs-outline carries the value without relying on color.",
|
|
10932
11000
|
"summary": "",
|
|
10933
11001
|
"attributes": [
|
|
10934
11002
|
{
|
|
@@ -16028,6 +16096,14 @@
|
|
|
16028
16096
|
},
|
|
16029
16097
|
"description": "Prevent backdrop-click from closing (default: false)",
|
|
16030
16098
|
"default": "false"
|
|
16099
|
+
},
|
|
16100
|
+
{
|
|
16101
|
+
"name": "swipe-from-content",
|
|
16102
|
+
"type": {
|
|
16103
|
+
"text": "boolean"
|
|
16104
|
+
},
|
|
16105
|
+
"description": "Allow touch dragging from the body at its scroll boundary (default: true)",
|
|
16106
|
+
"default": "true"
|
|
16031
16107
|
}
|
|
16032
16108
|
],
|
|
16033
16109
|
"events": [
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vielzeug/codex",
|
|
3
|
-
"version": "26.11.
|
|
3
|
+
"version": "26.11.22",
|
|
4
4
|
"description": "MCP server exposing all Vielzeug docs to AI clients",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
54
|
"@types/node": "^26.6.6",
|
|
55
|
-
"@vielzeug/refine": "26.11.
|
|
55
|
+
"@vielzeug/refine": "26.11.22",
|
|
56
56
|
"typescript": "^6.0.3",
|
|
57
57
|
"vitest": "^5.1.0"
|
|
58
58
|
}
|
package/skills/vielzeug/SKILL.md
CHANGED
|
@@ -9,7 +9,7 @@ Vielzeug is a monorepo of independently published TypeScript packages. "Zero dep
|
|
|
9
9
|
|
|
10
10
|
## Detect
|
|
11
11
|
|
|
12
|
-
1.
|
|
12
|
+
1. If codex's MCP server is connected, call `check-install` once per project: it compares every declared `@vielzeug/*` dependency with the snapshot. Offline, read `package.json` (`dependencies`, `devDependencies`, `peerDependencies`) and list every `@vielzeug/*` entry, resolving each installed version from `node_modules/@vielzeug/<pkg>/package.json` when present, otherwise from the package-manager lockfile.
|
|
13
13
|
2. Note whether `@vielzeug/refine` is installed. If it is, the **Refine** and **Theme** sections below are mandatory for any UI work.
|
|
14
14
|
3. Read the project's own agent contract (`AGENTS.md`, `.github/copilot-instructions.md`) first: project rules win over this skill.
|
|
15
15
|
|
|
@@ -17,24 +17,25 @@ Vielzeug is a monorepo of independently published TypeScript packages. "Zero dep
|
|
|
17
17
|
|
|
18
18
|
Never guess exports, attributes, events, slots, or token names. Look them up:
|
|
19
19
|
|
|
20
|
-
| Question
|
|
21
|
-
|
|
|
22
|
-
| Which package solves X?
|
|
23
|
-
| How do I use package X?
|
|
24
|
-
| Exact signature of an export
|
|
25
|
-
|
|
|
26
|
-
|
|
|
27
|
-
|
|
|
28
|
-
|
|
|
29
|
-
|
|
|
30
|
-
|
|
|
31
|
-
|
|
|
20
|
+
| Question | MCP tool (`@vielzeug/codex`) | Offline fallback |
|
|
21
|
+
| ----------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
|
|
22
|
+
| Which package solves X? | `search-packages`, `list-packages` | the package list below |
|
|
23
|
+
| How do I use package X? | `get-docs` (`index`, `usage`, `api`, `examples`) | `node_modules/@vielzeug/<pkg>/README.md` |
|
|
24
|
+
| Exact signature of an export | `get-type-signature` (`slug`, `symbol`) | the declaration file named by the installed manifest's matching export |
|
|
25
|
+
| Bundled source of one package (only on a `check-install` `match`) | `get-source` (`packageSlug`) | the installed package's declaration files; checkout `packages/<pkg>/src/` when the repository is checked out |
|
|
26
|
+
| Runnable example | `list-examples`, `get-example` | package README; `docs/<pkg>/examples/` when the Vielzeug repository is checked out |
|
|
27
|
+
| Which Refine components exist? | `refine-list-components` (tags + descriptions) | `rg '"tagName"' node_modules/@vielzeug/refine/dist/custom-elements.json` |
|
|
28
|
+
| Attributes, properties, events, slots, CSS parts of `ore-*` | `refine-get-component` | extract the matching `tagName` declaration from the manifest with a JSON parser |
|
|
29
|
+
| Component CSS custom properties | `refine-get-tokens` (pass a prefix) | extract the component's `cssProperties` from the manifest |
|
|
30
|
+
| Global design tokens | targeted search in installed theme CSS | `node_modules/@vielzeug/refine/dist/styles/theme.css` or checkout `packages/refine/src/styles/theme.css` |
|
|
31
|
+
| Are component attribute names recognized? | `refine-validate-usage` | compare against the manifest |
|
|
32
|
+
| Blank component scaffold | `refine-generate-template` | N/A |
|
|
32
33
|
|
|
33
34
|
Look each thing up once, from the smallest source that answers it: reuse a lookup already in this task while its version and relevant inputs remain unchanged; read one component with `refine-get-component` instead of listing the whole catalog; pass the narrowest known prefix (prefer an exact token name when known) to `refine-get-tokens`; fetch the one `get-docs` page that answers the question, not `index` + `usage` + `api` + `examples`. Verified installed declarations or checkout source are sufficient evidence without an additional docs fetch. Offline, use targeted searches to locate source or CSS; extract a component declaration from the JSON manifest with a structured parser rather than dumping the manifest.
|
|
34
35
|
|
|
35
36
|
`refine-get-tokens` reads CEM component CSS properties, not the complete global theme. For global tokens such as `--size-*`, search the relevant prefix or exact name in theme CSS; an empty MCP result does not prove a global token is unavailable. `tokens.css` only imports the underlying stylesheets.
|
|
36
37
|
|
|
37
|
-
Codex serves a versioned snapshot, which may not match the versions installed in the project or include the newest packages.
|
|
38
|
+
Codex serves a versioned snapshot, which may not match the versions installed in the project or include the newest packages. Call codex's `check-install` once per project to compare the snapshot against every `@vielzeug/*` dependency the project declares; it reports `match`, `drift`, `linked`, `not-in-snapshot`, or `unresolved`. Use snapshot docs, signatures, and `get-source` only for a `match`. Otherwise, treat the installed package's declarations, docs, and runtime as authoritative; do not use newer snapshot APIs unless the dependency is deliberately updated. Treat the generated package list as a discovery aid, not proof that no other package exists.
|
|
38
39
|
|
|
39
40
|
`get-docs` reaches only the four standard pages (`index`, `api`, `usage`, `examples`). A package's extra guides (Refine's `frameworks`, `theming`, `accessibility`, per-component references) are not in that set: read them from `https://vielzeug.dev/<pkg>/<page>` or from the checkout's `docs/<pkg>/`, not from `get-docs`.
|
|
40
41
|
|
|
@@ -101,6 +102,7 @@ Common compositions (verify unfamiliar APIs from the smallest applicable source
|
|
|
101
102
|
- **Data**: `courier` for HTTP with caching and structured errors; `sourcerer` for paged/cursor/infinite collections; `vault` for storage; `postmaster` for durable jobs; `scout` for fuzzy search; `mesh` for backendless peer sessions on a LAN; `sigil` for QR generation/scanning: prefer `ore-qr-code` / `ore-qr-scanner` when Refine is installed.
|
|
102
103
|
- **Forms**: `forge` for form state, validation, and submission; `spell` for schemas; render fields with Refine inputs when Refine is installed.
|
|
103
104
|
- **App shell**: `wayfinder` routing; `conduit` DI; `herald` events; `lingua` i18n; `rune` logging; `ward` authorization; `keymap` shortcuts.
|
|
105
|
+
- **Dates**: `tempo` for date utilities; do not hand-roll date math.
|
|
104
106
|
- **Own cleanup** for every stateful handle or subscription whose API documents disposal or unsubscription, and tie it to the owner's lifecycle. Pure functions and value-returning APIs need no cleanup; verify the specific API contract rather than assuming it returns a disposable.
|
|
105
107
|
|
|
106
108
|
## Refine (when `@vielzeug/refine` is installed)
|
|
@@ -128,7 +130,7 @@ Refine is the UI layer. Build interfaces from `ore-*` elements before anything e
|
|
|
128
130
|
|
|
129
131
|
7. **Check attribute names** with `refine-validate-usage` when available. It only checks for unknown attributes on the specified component's opening tag; it does not validate HTML generally, attribute values, JavaScript properties, events, slots, accessibility, or runtime behavior. Check those against the component docs and relevant tests instead.
|
|
130
132
|
|
|
131
|
-
8. **Missing capability?** Compose existing `ore-*` elements when they fit. If none meets the documented feature and project requirements, use the simplest appropriate native element or other package and report the gap
|
|
133
|
+
8. **Missing capability?** Compose existing `ore-*` elements when they fit. If none meets the documented feature and project requirements, use the simplest appropriate native element or other package and report the gap.
|
|
132
134
|
|
|
133
135
|
## Theme (when `@vielzeug/refine` is installed)
|
|
134
136
|
|
|
@@ -165,6 +167,6 @@ Refine covers the widget layer; these provide specialized behavior it may not co
|
|
|
165
167
|
|
|
166
168
|
- Every new capability maps to an installed `@vielzeug/*` package or is justified as out of scope.
|
|
167
169
|
- No parallel implementation of something an installed package provides.
|
|
168
|
-
- With Refine installed:
|
|
170
|
+
- With Refine installed: component choice follows Refine step 3; load `tokens.css` + `fouc.css` once, use the attribute checker within its stated limits, and use Refine tokens for app styling where suitable tokens exist.
|
|
169
171
|
- Every API that documents an owned resource or cleanup operation is integrated with the owning lifecycle; pure and value-returning APIs are not given invented cleanup.
|
|
170
172
|
- Claims about package APIs were verified from an applicable lookup, installed declarations, or checkout source, not recalled; completion does not require repeating unchanged evidence.
|