@zonsh/ui 0.2.0 → 0.4.1

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.
Files changed (180) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +19 -13
  3. package/dist/components/alert-dialog.js +1 -1
  4. package/dist/components/ascii-field.d.ts +1 -1
  5. package/dist/components/bottom-nav.d.ts +86 -0
  6. package/dist/components/bottom-nav.js +175 -0
  7. package/dist/components/breadcrumb.d.ts +9 -0
  8. package/dist/components/breadcrumb.js +6 -1
  9. package/dist/components/button-group.d.ts +1 -1
  10. package/dist/components/button-group.js +2 -2
  11. package/dist/components/calendar.d.ts +1 -1
  12. package/dist/components/calendar.js +18 -3
  13. package/dist/components/carousel.d.ts +22 -3
  14. package/dist/components/carousel.js +25 -7
  15. package/dist/components/chart.d.ts +9 -0
  16. package/dist/components/chart.js +40 -3
  17. package/dist/components/code-block.d.ts +20 -10
  18. package/dist/components/code-block.js +54 -12
  19. package/dist/components/collapsible.js +2 -2
  20. package/dist/components/color-picker.d.ts +30 -8
  21. package/dist/components/color-picker.js +48 -27
  22. package/dist/components/combobox.d.ts +21 -3
  23. package/dist/components/combobox.js +79 -7
  24. package/dist/components/command.d.ts +23 -3
  25. package/dist/components/command.js +61 -16
  26. package/dist/components/conversation.d.ts +10 -1
  27. package/dist/components/conversation.js +14 -4
  28. package/dist/components/copy-button.d.ts +15 -6
  29. package/dist/components/copy-button.js +20 -5
  30. package/dist/components/data-table.d.ts +66 -6
  31. package/dist/components/data-table.js +376 -23
  32. package/dist/components/date-picker.d.ts +73 -4
  33. package/dist/components/date-picker.js +138 -7
  34. package/dist/components/dialog.d.ts +10 -1
  35. package/dist/components/dialog.js +6 -3
  36. package/dist/components/drawer.d.ts +10 -1
  37. package/dist/components/drawer.js +6 -3
  38. package/dist/components/feature-list.js +2 -2
  39. package/dist/components/field.d.ts +27 -8
  40. package/dist/components/field.js +49 -4
  41. package/dist/components/file-drop.d.ts +26 -4
  42. package/dist/components/file-drop.js +125 -64
  43. package/dist/components/filter-bar.d.ts +50 -3
  44. package/dist/components/filter-bar.js +71 -33
  45. package/dist/components/form.d.ts +4 -2
  46. package/dist/components/form.js +24 -2
  47. package/dist/components/graph.d.ts +41 -0
  48. package/dist/components/graph.js +84 -45
  49. package/dist/components/illustration.js +1 -1
  50. package/dist/components/input-group.d.ts +16 -5
  51. package/dist/components/input-group.js +35 -15
  52. package/dist/components/input.d.ts +2 -2
  53. package/dist/components/input.js +3 -3
  54. package/dist/components/kbd.d.ts +17 -0
  55. package/dist/components/kbd.js +8 -1
  56. package/dist/components/lightbox.d.ts +100 -0
  57. package/dist/components/lightbox.js +439 -0
  58. package/dist/components/locale.d.ts +44 -0
  59. package/dist/components/locale.js +37 -0
  60. package/dist/components/logo.js +1 -1
  61. package/dist/components/menu.js +3 -1
  62. package/dist/components/message.d.ts +3 -3
  63. package/dist/components/message.js +10 -7
  64. package/dist/components/meter.js +3 -1
  65. package/dist/components/money-input.d.ts +80 -0
  66. package/dist/components/money-input.js +253 -0
  67. package/dist/components/number-field.d.ts +21 -2
  68. package/dist/components/number-field.js +27 -16
  69. package/dist/components/otp-field.d.ts +14 -1
  70. package/dist/components/otp-field.js +10 -2
  71. package/dist/components/pagination.d.ts +13 -7
  72. package/dist/components/pagination.js +18 -7
  73. package/dist/components/pdf-viewer.d.ts +67 -2
  74. package/dist/components/pdf-viewer.js +88 -21
  75. package/dist/components/phone-input.d.ts +79 -0
  76. package/dist/components/phone-input.js +282 -0
  77. package/dist/components/popover.js +1 -1
  78. package/dist/components/progress.js +3 -1
  79. package/dist/components/prompt-input.d.ts +34 -9
  80. package/dist/components/prompt-input.js +28 -16
  81. package/dist/components/rating.d.ts +73 -0
  82. package/dist/components/rating.js +124 -0
  83. package/dist/components/reasoning.d.ts +16 -1
  84. package/dist/components/reasoning.js +10 -7
  85. package/dist/components/resizable.d.ts +10 -1
  86. package/dist/components/resizable.js +4 -1
  87. package/dist/components/response.d.ts +14 -3
  88. package/dist/components/response.js +36 -8
  89. package/dist/components/scroll-area.d.ts +1 -1
  90. package/dist/components/select.js +14 -3
  91. package/dist/components/separator.js +1 -1
  92. package/dist/components/sidebar.d.ts +20 -4
  93. package/dist/components/sidebar.js +34 -18
  94. package/dist/components/site-header.d.ts +46 -12
  95. package/dist/components/site-header.js +73 -19
  96. package/dist/components/slider.js +3 -1
  97. package/dist/components/sortable.d.ts +178 -0
  98. package/dist/components/sortable.js +1258 -0
  99. package/dist/components/sources.d.ts +17 -2
  100. package/dist/components/sources.js +11 -4
  101. package/dist/components/spinner.d.ts +13 -1
  102. package/dist/components/spinner.js +5 -2
  103. package/dist/components/stat.d.ts +91 -0
  104. package/dist/components/stat.js +141 -0
  105. package/dist/components/stepper.d.ts +71 -0
  106. package/dist/components/stepper.js +101 -0
  107. package/dist/components/switch.d.ts +2 -2
  108. package/dist/components/switch.js +2 -2
  109. package/dist/components/table.d.ts +12 -2
  110. package/dist/components/table.js +176 -39
  111. package/dist/components/tags-input.d.ts +18 -2
  112. package/dist/components/tags-input.js +65 -33
  113. package/dist/components/theme.d.ts +16 -2
  114. package/dist/components/theme.js +15 -7
  115. package/dist/components/time-field.d.ts +22 -3
  116. package/dist/components/time-field.js +19 -6
  117. package/dist/components/timeline.d.ts +18 -2
  118. package/dist/components/timeline.js +13 -4
  119. package/dist/components/tippy.d.ts +48 -0
  120. package/dist/components/tippy.js +648 -0
  121. package/dist/components/toast.d.ts +18 -2
  122. package/dist/components/toast.js +12 -3
  123. package/dist/components/tool-call.d.ts +19 -8
  124. package/dist/components/tool-call.js +18 -7
  125. package/dist/components/toolbar.js +6 -1
  126. package/dist/components/tour.d.ts +127 -0
  127. package/dist/components/tour.js +648 -0
  128. package/dist/components/tree.js +17 -4
  129. package/dist/components/video-player.d.ts +10 -2
  130. package/dist/components/video-player.js +73 -33
  131. package/dist/illustration.d.ts +2 -0
  132. package/dist/illustration.js +7 -0
  133. package/dist/index.d.ts +11 -3
  134. package/dist/index.js +11 -3
  135. package/dist/lib/code-highlight.d.ts +3 -16
  136. package/dist/lib/code-highlight.js +160 -10
  137. package/dist/lib/code-theme.js +3 -3
  138. package/dist/lib/digit-roll.js +8 -8
  139. package/dist/lib/field-errors.d.ts +28 -0
  140. package/dist/lib/field-errors.js +24 -0
  141. package/dist/lib/field-value.d.ts +13 -0
  142. package/dist/lib/field-value.js +44 -0
  143. package/dist/lib/graph-layout.js +11 -2
  144. package/dist/lib/money.d.ts +73 -0
  145. package/dist/lib/money.js +343 -0
  146. package/dist/lib/phone-countries.d.ts +1 -0
  147. package/dist/lib/phone-countries.js +281 -0
  148. package/dist/lib/phone.d.ts +90 -0
  149. package/dist/lib/phone.js +286 -0
  150. package/dist/lib/platform.d.ts +8 -3
  151. package/dist/lib/platform.js +13 -6
  152. package/dist/lib/row-index.d.ts +15 -0
  153. package/dist/lib/row-index.js +136 -0
  154. package/dist/lib/table-fit.js +23 -4
  155. package/dist/lib/theme-script.d.ts +15 -2
  156. package/dist/lib/theme-script.js +23 -3
  157. package/dist/lib/tippy/pixels.d.ts +47 -0
  158. package/dist/lib/tippy/pixels.js +187 -0
  159. package/dist/lib/tippy/sprite.d.ts +86 -0
  160. package/dist/lib/tippy/sprite.js +753 -0
  161. package/dist/messages/de.d.ts +12 -0
  162. package/dist/messages/de.js +326 -0
  163. package/dist/styles/expressive.css +20 -5
  164. package/dist/styles/index.css +3 -2
  165. package/dist/styles/material.css +7 -3
  166. package/dist/styles/parts/ai.css +2 -1
  167. package/dist/styles/parts/controls.css +62 -13
  168. package/dist/styles/parts/feedback.css +68 -1
  169. package/dist/styles/parts/foundations.css +1 -1
  170. package/dist/styles/parts/navigation.css +194 -2
  171. package/dist/styles/parts/overlays.css +7 -7
  172. package/dist/styles/tokens.css +12 -3
  173. package/dist/vite.d.ts +0 -50
  174. package/dist/vite.js +0 -100
  175. package/package.json +28 -33
  176. package/dist/components/code-highlight.d.ts +0 -13
  177. package/dist/components/code-highlight.js +0 -107
  178. package/dist/components/whiteboard.d.ts +0 -80
  179. package/dist/components/whiteboard.js +0 -389
  180. package/dist/styles/parts/whiteboard.css +0 -855
@@ -0,0 +1,1258 @@
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useRender } from "@base-ui/react/use-render";
4
+ import { GripHorizontalIcon, GripIcon, GripVerticalIcon } from "lucide-react";
5
+ import * as React from "react";
6
+ import { createPortal } from "react-dom";
7
+ import { cn, sx } from "../lib/cn.js";
8
+ import { mergeRefs } from "../lib/merge-refs.js";
9
+ import { Button } from "./button.js";
10
+ import { useMessages } from "./locale.js";
11
+ /** "Lead, position 2 of 4" or "position 2 of 4". */
12
+ const at = (p) => `${p.list ? `${p.list}, position` : "position"} ${p.position} of ${p.count}`;
13
+ /** The same, starting a sentence. */
14
+ const At = (p) => {
15
+ const text = at(p);
16
+ return text.charAt(0).toUpperCase() + text.slice(1);
17
+ };
18
+ const defaultMessages = {
19
+ handle: (item) => `Move ${item}`,
20
+ instructions: "Press Space to pick the item up. Use the arrow keys to move it, Space to drop it, Escape to cancel.",
21
+ pickedUp: (item, p) => `Picked up ${item}. ${At(p)}.`,
22
+ pickedUpKeyboard: (item, p) => `Picked up ${item}. ${At(p)}. Use the arrow keys to move it, Space to drop it, Escape to cancel.`,
23
+ movedWithin: (_item, p) => `${At(p)}.`,
24
+ movedTo: (_item, p) => `Moved to ${at(p)}.`,
25
+ moved: (item, p) => `Moved ${item} to ${at(p)}.`,
26
+ dropped: (item, p) => `Dropped ${item}. ${At(p)}.`,
27
+ cancelled: (item, p) => `Move cancelled. ${item} is back in ${at(p)}.`,
28
+ cannotMove: (item, p) => `${item} cannot move further. ${At(p)}.`,
29
+ };
30
+ /** The lists of a value, with `""` for a single list. */
31
+ const toLists = (value) => (Array.isArray(value) ? { "": value } : value);
32
+ function placeIn(lists, item) {
33
+ for (const [list, ids] of Object.entries(lists)) {
34
+ const index = ids.indexOf(item);
35
+ if (index !== -1)
36
+ return { list, index };
37
+ }
38
+ return null;
39
+ }
40
+ function moveIn(lists, item, to) {
41
+ const next = {};
42
+ for (const [list, ids] of Object.entries(lists))
43
+ next[list] = ids.filter((id) => id !== item);
44
+ const target = next[to.list];
45
+ if (!target)
46
+ return lists;
47
+ target.splice(Math.max(0, Math.min(to.index, target.length)), 0, item);
48
+ return next;
49
+ }
50
+ /**
51
+ * Takes `item` out of wherever it is and puts it at `to` — the index in the target list without
52
+ * the item. Works on one list (`to.list` is ignored) and on several. The value is not changed; a
53
+ * new one is returned. Every way of moving an item should go through it.
54
+ */
55
+ export function moveSortableItem(value, item, to) {
56
+ const lists = toLists(value);
57
+ const from = placeIn(lists, item);
58
+ const list = Array.isArray(value) ? "" : (to.list ?? from?.list ?? "");
59
+ const next = moveIn(lists, item, { list, index: to.index ?? Number.MAX_SAFE_INTEGER });
60
+ return (Array.isArray(value) ? next[""] : next);
61
+ }
62
+ /* ── Timing and distances ──────────────────────────────────────────────────── */
63
+ /** Mouse and pen drags start after this many pixels, so a click stays a click. */
64
+ const DRAG_THRESHOLD = 4;
65
+ /** Touch drags start on a long press, so a swipe still scrolls. */
66
+ const LONG_PRESS = 400;
67
+ /** A touch that moves this far before the long press is a scroll. */
68
+ const TOUCH_SLOP = 8;
69
+ /** Within this many pixels of a scrolling edge, a drag scrolls it. */
70
+ const EDGE = 56;
71
+ /** The fastest autoscroll, in pixels a frame, right at the edge. */
72
+ const SPEED = 14;
73
+ /** A release this far past the root's edge still lands in the nearest list; further out it cancels. */
74
+ const DROP_MARGIN = 32;
75
+ /** Controls on an item that keep their own clicks: a press on them never starts a drag. */
76
+ const CONTROLS = "button, a[href], input, textarea, select, label, summary, [contenteditable=''], [contenteditable=true], [role=button], [role=menuitem], [role=slider], [role=checkbox], [role=switch], [role=tab]";
77
+ const SortableContext = React.createContext(null);
78
+ function useSortableContext(part) {
79
+ const context = React.useContext(SortableContext);
80
+ if (!context)
81
+ throw new Error(`${part} must be used within a <Sortable />`);
82
+ return context;
83
+ }
84
+ const SortableItemContext = React.createContext(null);
85
+ /** The item a part is in: its value, and whether it is being dragged, lifted, or is the copy under the pointer. */
86
+ export function useSortableItem() {
87
+ const context = React.useContext(SortableItemContext);
88
+ if (!context)
89
+ throw new Error("useSortableItem must be used within a <SortableItem /> or a Sortable overlay");
90
+ return context;
91
+ }
92
+ /** The Sortable around a part: `move` an item from your own controls, and what is moving now. */
93
+ export function useSortable() {
94
+ const context = useSortableContext("useSortable");
95
+ return {
96
+ move: context.move,
97
+ dragging: context.drag?.item ?? null,
98
+ lifted: context.lifted?.item ?? null,
99
+ };
100
+ }
101
+ /* ── Measuring ─────────────────────────────────────────────────────────────── */
102
+ const isRtl = (el) => !!el && getComputedStyle(el).direction === "rtl";
103
+ /** The items of a list in DOM order — not those of a list nested in one of them. */
104
+ function itemsOf(list) {
105
+ return [...list.querySelectorAll("[data-sortable-item]")].filter((el) => el.closest("[data-sortable-list]") === list);
106
+ }
107
+ /** The distance from a point to a rectangle, 0 inside it. */
108
+ function distanceTo(rect, x, y) {
109
+ const dx = x < rect.left ? rect.left - x : x > rect.right ? x - rect.right : 0;
110
+ const dy = y < rect.top ? rect.top - y : y > rect.bottom ? y - rect.bottom : 0;
111
+ return Math.hypot(dx, dy);
112
+ }
113
+ /** The space along a list between item `a` and the item after it, `b`. */
114
+ function spaceBetween(a, b, vertical, rtl) {
115
+ if (vertical)
116
+ return b.y - (a.y + a.h);
117
+ return rtl ? a.x - (b.x + b.w) : b.x - (a.x + a.w);
118
+ }
119
+ /** Whether two items sit on the same row: their tops are less than half the smaller apart. */
120
+ const sameRow = (a, b) => Math.abs(a.y - b.y) < Math.min(a.h, b.h) / 2;
121
+ /** Whether items in reading order wrap: some neighbours share a row, and some start a new one. */
122
+ function wraps(items) {
123
+ let along = false;
124
+ let across = false;
125
+ for (let i = 1; i < items.length && !(along && across); i++) {
126
+ if (sameRow(items[i - 1], items[i]))
127
+ along = true;
128
+ else
129
+ across = true;
130
+ }
131
+ return along && across;
132
+ }
133
+ /**
134
+ * The slots of a grid: where each item is, then where one more would go — after the last on its
135
+ * row if it fits there, else at the start of the next row.
136
+ */
137
+ function slotsOf(items, rtl, start, end, gaps) {
138
+ const slots = items.map((it) => ({ x: it.x, y: it.y }));
139
+ const first = items[0];
140
+ const last = items[items.length - 1];
141
+ if (!first || !last)
142
+ return slots;
143
+ const second = items[1];
144
+ const step = second && sameRow(first, second) ? Math.abs(second.x - first.x) : last.w + gaps.x;
145
+ const below = items.find((it) => !sameRow(it, first));
146
+ const x = rtl ? last.x - step : last.x + step;
147
+ const fits = rtl ? x >= start - 0.5 : x + last.w <= end + 0.5;
148
+ slots.push(fits ? { x, y: last.y } : { x: first.x, y: last.y + (below ? below.y - first.y : last.h + gaps.y) });
149
+ return slots;
150
+ }
151
+ /** Slide an item to `by` — `"x y"`, or `""` for its own place — with the item's own transition. */
152
+ function slide(el, by) {
153
+ el.style.translate = by;
154
+ }
155
+ /** Change the elements' inline styles at once: no transition, as if they had always been so. */
156
+ function snap(els, change) {
157
+ if (!els.length)
158
+ return;
159
+ const transitions = els.map((el) => el.style.transition);
160
+ for (const el of els) {
161
+ el.style.transition = "none";
162
+ change(el);
163
+ }
164
+ void els[0].offsetWidth;
165
+ els.forEach((el, i) => (el.style.transition = transitions[i]));
166
+ }
167
+ /**
168
+ * FLIP: every item that moved since `before` is put back where it was drawn, then slides from
169
+ * there into its new place with its own transition — at once under reduced motion.
170
+ */
171
+ function flip(els, before) {
172
+ if (!els.length)
173
+ return;
174
+ const transitions = els.map((el) => el.style.transition);
175
+ for (const el of els) {
176
+ el.style.transition = "none";
177
+ el.style.translate = "";
178
+ }
179
+ els.forEach((el) => {
180
+ const was = before.get(el.dataset.sortableItem ?? "");
181
+ if (!was)
182
+ return;
183
+ const now = el.getBoundingClientRect();
184
+ const dx = was.left - now.left;
185
+ const dy = was.top - now.top;
186
+ if (Math.abs(dx) >= 0.5 || Math.abs(dy) >= 0.5)
187
+ el.style.translate = `${dx}px ${dy}px`;
188
+ });
189
+ void els[0].offsetWidth;
190
+ els.forEach((el, i) => {
191
+ el.style.transition = transitions[i];
192
+ el.style.translate = "";
193
+ });
194
+ }
195
+ /**
196
+ * Scroll whatever scrolls under the pointer while it is held near an edge: the innermost
197
+ * container, from the list outwards to the page, that can still move that way.
198
+ */
199
+ function autoScroll(from, x, y) {
200
+ let doneX = false;
201
+ let doneY = false;
202
+ const page = document.scrollingElement ?? document.documentElement;
203
+ for (let el = from; el && !(doneX && doneY); el = el.parentElement) {
204
+ const isPage = el === page || el === document.body;
205
+ const style = getComputedStyle(el);
206
+ const rect = isPage
207
+ ? new DOMRect(0, 0, window.innerWidth, window.innerHeight)
208
+ : el.getBoundingClientRect();
209
+ const target = isPage ? page : el;
210
+ const step = (low, high, size) => {
211
+ const edge = Math.min(EDGE, size / 4);
212
+ if (low < edge)
213
+ return -Math.ceil(SPEED * (1 - Math.max(low, 0) / edge));
214
+ if (high < edge)
215
+ return Math.ceil(SPEED * (1 - Math.max(high, 0) / edge));
216
+ return 0;
217
+ };
218
+ if (!doneX &&
219
+ (isPage || /auto|scroll/.test(style.overflowX)) &&
220
+ target.scrollWidth > target.clientWidth) {
221
+ const dx = step(x - rect.left, rect.right - x, rect.width);
222
+ if (dx) {
223
+ const before = target.scrollLeft;
224
+ target.scrollLeft += dx;
225
+ if (target.scrollLeft !== before)
226
+ doneX = true;
227
+ }
228
+ }
229
+ if (!doneY &&
230
+ (isPage || /auto|scroll/.test(style.overflowY)) &&
231
+ target.scrollHeight > target.clientHeight) {
232
+ const dy = step(y - rect.top, rect.bottom - y, rect.height);
233
+ if (dy) {
234
+ const before = target.scrollTop;
235
+ target.scrollTop += dy;
236
+ if (target.scrollTop !== before)
237
+ doneY = true;
238
+ }
239
+ }
240
+ if (isPage)
241
+ break;
242
+ }
243
+ }
244
+ /**
245
+ * Sortable — reorderable lists: one list, a row, a wrapping grid, or several lists that items
246
+ * move between, as the columns of a board.
247
+ *
248
+ * Drag an item with the mouse, a pen or — after a long press, so a swipe still scrolls — a finger:
249
+ * a copy follows the pointer, the other items slide aside to open a gap where it will land (in a
250
+ * grid, slot to slot across the row breaks), and on release the copy glides into the gap (or
251
+ * home, on a cancel), taking the size of its place. Over a list of narrower or wider items the
252
+ * copy takes their width. Edges scroll as it nears them.
253
+ * Every item has a `SortableHandle`: Space or Enter picks the item up, the arrows move it — the
254
+ * items slide into their new order — Space drops it and Escape puts it back. Every move is read
255
+ * out in a polite live region. No drag-and-drop library: measured once, moved by transforms.
256
+ *
257
+ * Compose `Sortable` → `SortableList` → `SortableItem` → `SortableHandle`. The rule people break:
258
+ * leaving out the handle. Without it there is no keyboard way to move an item.
259
+ */
260
+ export function Sortable({ value: valueProp, defaultValue, onValueChange, onMoveEnd, overlay, handleOnly = false, labels, render, className, children, ref, ...props }) {
261
+ const text = useMessages("sortable", defaultMessages, labels);
262
+ const [uncontrolled, setUncontrolled] = React.useState(defaultValue ?? []);
263
+ const value = valueProp ?? uncontrolled;
264
+ const single = Array.isArray(value);
265
+ const lists = React.useMemo(() => toLists(value), [value]);
266
+ /** The lists as of now, for handlers that run before the next render. */
267
+ const listsRef = React.useRef(lists);
268
+ listsRef.current = lists;
269
+ const [drag, setDrag] = React.useState(null);
270
+ const [lifted, setLiftedState] = React.useState(null);
271
+ const liftedRef = React.useRef(lifted);
272
+ const setLifted = (next) => {
273
+ liftedRef.current = next;
274
+ setLiftedState(next);
275
+ };
276
+ const [message, setMessage] = React.useState("");
277
+ const instructionsId = React.useId();
278
+ const rootRef = React.useRef(null);
279
+ const overlayRef = React.useRef(null);
280
+ const pointerRef = React.useRef({ x: 0, y: 0 });
281
+ const listMap = React.useRef(new Map());
282
+ const itemLabels = React.useRef(new Map());
283
+ /** After a move that remounts an item in another list, focus goes back to this. */
284
+ const refocus = React.useRef(null);
285
+ const callbacks = React.useRef({ onValueChange, onMoveEnd });
286
+ callbacks.current = { onValueChange, onMoveEnd };
287
+ /** Say it again even when the words repeat: a trailing no-break space makes it a new message. */
288
+ const announce = React.useCallback((words) => setMessage((prev) => (prev === words ? `${words} ` : words)), []);
289
+ const labelOf = (item) => itemLabels.current.get(item) ?? item;
290
+ const describe = (current, place) => ({
291
+ list: listMap.current.get(place.list)?.label,
292
+ position: place.index + 1,
293
+ count: current[place.list]?.length ?? 0,
294
+ });
295
+ const commit = (next, details) => {
296
+ listsRef.current = next;
297
+ const out = (single ? next[""] : next);
298
+ if (valueProp === undefined)
299
+ setUncontrolled(out);
300
+ callbacks.current.onValueChange?.(out, details);
301
+ };
302
+ /** Where every item is drawn before a keyboard or `move` step, so they all slide from there. */
303
+ const before = React.useRef(null);
304
+ const allItems = () => [...listMap.current.values()].flatMap((entry) => itemsOf(entry.el));
305
+ const snapshot = () => {
306
+ before.current = new Map(allItems().map((el) => [el.dataset.sortableItem ?? "", el.getBoundingClientRect()]));
307
+ };
308
+ React.useLayoutEffect(() => {
309
+ const rects = before.current;
310
+ if (!rects)
311
+ return;
312
+ before.current = null;
313
+ flip(allItems(), rects);
314
+ }, [lists]);
315
+ React.useLayoutEffect(() => {
316
+ const target = refocus.current;
317
+ if (!target)
318
+ return;
319
+ refocus.current = null;
320
+ // After the frame, so a closing menu's own focus return does not win.
321
+ const frame = requestAnimationFrame(() => {
322
+ const item = rootRef.current?.querySelector(`[data-sortable-item="${CSS.escape(target.item)}"]`);
323
+ item?.querySelector(target.selector)?.focus();
324
+ });
325
+ return () => cancelAnimationFrame(frame);
326
+ }, [lists]);
327
+ const registerList = React.useCallback((id, entry) => {
328
+ listMap.current.set(id, entry);
329
+ return () => {
330
+ if (listMap.current.get(id) === entry)
331
+ listMap.current.delete(id);
332
+ };
333
+ }, []);
334
+ const setItemLabel = React.useCallback((item, label) => {
335
+ itemLabels.current.set(item, label);
336
+ }, []);
337
+ /** Whether a point is on `rect`, or close enough past its edge to count as a drop on it. */
338
+ const within = (rect, x, y) => !!rect &&
339
+ x >= rect.left - DROP_MARGIN &&
340
+ x <= rect.right + DROP_MARGIN &&
341
+ y >= rect.top - DROP_MARGIN &&
342
+ y <= rect.bottom + DROP_MARGIN;
343
+ /** Whether a point is on the root, or close enough past its edge to count as a drop on it. */
344
+ const onRoot = (x, y) => within(rootRef.current?.getBoundingClientRect(), x, y);
345
+ /** The pointer drag in progress, measured when it started. */
346
+ const sessionRef = React.useRef(null);
347
+ /** Ends the glide after a release at once: a new drag or key does not wait for it. */
348
+ const settleRef = React.useRef(null);
349
+ /** What each press in progress has hooked into the page, to unhook if Sortable goes. */
350
+ const detachers = React.useRef(new Set());
351
+ // Unmounted mid-drag — a route change, a parent that removes it: the drag lets go of the page
352
+ // and says nothing, as there is no one left to tell. (The copy is in a portal of ours: it goes
353
+ // with us, and the settle glide's own cleanup stops its timer.)
354
+ React.useEffect(() => {
355
+ const pending = detachers.current;
356
+ return () => {
357
+ for (const detach of [...pending])
358
+ detach();
359
+ sessionRef.current = null;
360
+ settleRef.current = null;
361
+ };
362
+ }, []);
363
+ /** Every list, and every item in it, where they are now — read once, as a drag starts. */
364
+ const measure = () => {
365
+ const lists = new Map();
366
+ const entries = [...listMap.current].filter(([id]) => id in listsRef.current);
367
+ // An item still sliding from the last keyboard move is measured where it will be.
368
+ const sliding = entries.flatMap(([, entry]) => itemsOf(entry.el)).filter((el) => el.style.translate);
369
+ snap(sliding, (el) => (el.style.translate = ""));
370
+ for (const [id, entry] of entries) {
371
+ const el = entry.el;
372
+ const style = getComputedStyle(el);
373
+ const vertical = entry.orientation === "vertical";
374
+ const rtl = style.direction === "rtl";
375
+ const rect = el.getBoundingClientRect();
376
+ const originX = rect.left + el.clientLeft - el.scrollLeft;
377
+ const originY = rect.top + el.clientTop - el.scrollTop;
378
+ const items = itemsOf(el).map((itemEl) => {
379
+ const r = itemEl.getBoundingClientRect();
380
+ return {
381
+ id: itemEl.dataset.sortableItem ?? "",
382
+ el: itemEl,
383
+ x: r.left - originX,
384
+ y: r.top - originY,
385
+ w: r.width,
386
+ h: r.height,
387
+ };
388
+ });
389
+ const [a, b] = items;
390
+ const gap = parseFloat(vertical ? style.rowGap : style.columnGap) || 0;
391
+ const grid = entry.orientation === "grid" || wraps(items);
392
+ const start = parseFloat(style.paddingLeft) || 0;
393
+ const end = el.clientWidth - (parseFloat(style.paddingRight) || 0);
394
+ const gaps = { x: parseFloat(style.columnGap) || 0, y: parseFloat(style.rowGap) || 0 };
395
+ lists.set(id, {
396
+ id,
397
+ el,
398
+ vertical,
399
+ rtl,
400
+ grid,
401
+ items,
402
+ slots: grid ? slotsOf(items, rtl, start, end, gaps) : [],
403
+ spacing: Math.max(0, a && b ? spaceBetween(a, b, vertical, rtl) : gap),
404
+ contentWidth: end - start,
405
+ rect,
406
+ originX,
407
+ originY,
408
+ });
409
+ }
410
+ return lists;
411
+ };
412
+ /** After a scroll or a resize: where the lists are now. Their items stay where they are in them. */
413
+ const refresh = (session) => {
414
+ session.dirty = false;
415
+ session.root = rootRef.current?.getBoundingClientRect() ?? null;
416
+ for (const list of session.lists.values()) {
417
+ const el = list.el;
418
+ list.rect = el.getBoundingClientRect();
419
+ list.originX = list.rect.left + el.clientLeft - el.scrollLeft;
420
+ list.originY = list.rect.top + el.clientTop - el.scrollTop;
421
+ }
422
+ };
423
+ /**
424
+ * The list nearest the pointer, and the place in it before the first item past the pointer —
425
+ * by where the items were when the drag started, not where they have slid since, so the place
426
+ * never chases its own slides.
427
+ */
428
+ const placeAt = (session, x, y) => {
429
+ let best = null;
430
+ for (const list of session.lists.values()) {
431
+ if (!list.rect.width && !list.rect.height)
432
+ continue;
433
+ const distance = distanceTo(list.rect, x, y);
434
+ if (!best || distance < best.distance)
435
+ best = { list, distance };
436
+ }
437
+ if (!best)
438
+ return null;
439
+ const { list } = best;
440
+ if (list.grid && list.items.length) {
441
+ // In a grid, the slot nearest the pointer: its own list has a slot for each item, another
442
+ // one also the slot after its last.
443
+ const count = list.id === session.from.list ? list.items.length : list.items.length + 1;
444
+ let index = 0;
445
+ let nearest = Infinity;
446
+ for (let k = 0; k < count; k++) {
447
+ const slot = list.slots[k];
448
+ const it = list.items[Math.min(k, list.items.length - 1)];
449
+ const left = list.originX + slot.x;
450
+ const top = list.originY + slot.y;
451
+ const edge = distanceTo(new DOMRect(left, top, it.w, it.h), x, y);
452
+ const centre = Math.hypot(left + it.w / 2 - x, top + it.h / 2 - y);
453
+ const score = edge * 1e4 + centre;
454
+ if (score < nearest) {
455
+ nearest = score;
456
+ index = k;
457
+ }
458
+ }
459
+ return { place: { list: list.id, index }, list };
460
+ }
461
+ const others = list.items.filter((it) => it.id !== session.item);
462
+ const index = others.findIndex((it) => {
463
+ if (list.vertical)
464
+ return y < list.originY + it.y + it.h / 2;
465
+ const middle = list.originX + it.x + it.w / 2;
466
+ return list.rtl ? x > middle : x < middle;
467
+ });
468
+ return { place: { list: list.id, index: index === -1 ? others.length : index }, list };
469
+ };
470
+ /** The dragged item's size in a list: where it came from, as it was; elsewhere, as it lands there. */
471
+ const sizeIn = (session, list) => list === session.from.list ? session.size : (session.sizes.get(list) ?? session.size);
472
+ /**
473
+ * The width the dragged item takes in another list, so the copy fits where it will land: the
474
+ * width all that list's items share, or — in an empty column, when it filled its own — the
475
+ * column's. Lists of items of their own widths leave it as it was.
476
+ */
477
+ const widthIn = (session, list) => {
478
+ const { w } = session.size;
479
+ if (list.id === session.from.list)
480
+ return w;
481
+ const others = list.items.filter((it) => it.id !== session.item);
482
+ if (others.length) {
483
+ const first = others[0].w;
484
+ return others.every((it) => Math.abs(it.w - first) < 1) ? first : w;
485
+ }
486
+ const home = session.lists.get(session.from.list);
487
+ const fills = !!home && home.vertical && !home.grid && Math.abs(w - home.contentWidth) < 1;
488
+ return fills && list.vertical && !list.grid ? list.contentWidth : w;
489
+ };
490
+ /**
491
+ * The copy's height at a width: drawn there for a moment, without its transition, then put back
492
+ * at the width it is drawn at — halfway through fitting a list, it goes on from there.
493
+ */
494
+ const copyHeightAt = (width) => {
495
+ const el = overlayRef.current;
496
+ if (!el)
497
+ return null;
498
+ const drawn = el.getBoundingClientRect().width;
499
+ const { transition } = el.style;
500
+ el.style.transition = "none";
501
+ el.style.width = `${width}px`;
502
+ const height = el.offsetHeight;
503
+ el.style.width = `${drawn}px`;
504
+ void el.offsetWidth;
505
+ el.style.transition = transition;
506
+ return height;
507
+ };
508
+ /** The copy takes the width of the list it would land in, quickly, so it fits there. */
509
+ const fitCopy = (session, target) => {
510
+ const list = target ? session.lists.get(target.list) : undefined;
511
+ let size = session.size;
512
+ if (list && list.id !== session.from.list) {
513
+ size = session.sizes.get(list.id) ?? size;
514
+ if (!session.sizes.has(list.id)) {
515
+ const w = widthIn(session, list);
516
+ const h = Math.abs(w - session.size.w) < 1 ? session.size.h : (copyHeightAt(w) ?? session.size.h);
517
+ size = { w, h };
518
+ session.sizes.set(list.id, size);
519
+ }
520
+ }
521
+ const el = overlayRef.current;
522
+ if (!el || Math.abs(parseFloat(el.style.width) - size.w) < 0.5)
523
+ return;
524
+ session.resized = true;
525
+ el.style.transition = "width var(--duration, 150ms) var(--ease)";
526
+ el.style.width = `${size.w}px`;
527
+ };
528
+ /**
529
+ * Open the gap at `target`: the items after it in its list slide on by the dragged item's size,
530
+ * and the items after its old place slide back over it — in a grid, each into its neighbour's
531
+ * slot, from the end of one row to the start of the next. `null` (past the root's edge) shows
532
+ * it back where it was. Nothing is laid out again: a list an item comes into overflows its end
533
+ * by one item until the drop, rather than growing and moving the page around it.
534
+ */
535
+ const showAt = (session, target) => {
536
+ const { from } = session;
537
+ for (const list of session.lists.values()) {
538
+ const size = sizeIn(session, list.id);
539
+ const along = list.vertical ? size.h : size.w;
540
+ const by = (along + list.spacing) * (list.vertical || !list.rtl ? 1 : -1);
541
+ let j = 0; // the index among the other items
542
+ list.items.forEach((it, i) => {
543
+ if (it.id === session.item)
544
+ return;
545
+ // The index it takes while the gap is at `target`.
546
+ let k = i;
547
+ if (list.id === from.list)
548
+ k = !target ? i : target.list === list.id ? (j < target.index ? j : j + 1) : j;
549
+ else if (target?.list === list.id && j >= target.index)
550
+ k = j + 1;
551
+ j++;
552
+ let shift = "";
553
+ if (list.grid) {
554
+ const to = list.slots[k];
555
+ const was = list.slots[i];
556
+ const dx = to && was ? to.x - was.x : 0;
557
+ const dy = to && was ? to.y - was.y : 0;
558
+ if (Math.abs(dx) >= 0.5 || Math.abs(dy) >= 0.5)
559
+ shift = `${dx}px ${dy}px`;
560
+ }
561
+ else if (k !== i)
562
+ shift = list.vertical ? `0 ${(k - i) * by}px` : `${(k - i) * by}px 0`;
563
+ if ((session.shifts.get(it.el) ?? "") === shift)
564
+ return;
565
+ session.shifts.set(it.el, shift);
566
+ slide(it.el, shift);
567
+ });
568
+ }
569
+ };
570
+ /** The slides end: at once when the order now has the item where the gap was, else gliding home. */
571
+ const release = (session, now) => {
572
+ const shifted = [...session.shifts.keys()];
573
+ session.shifts.clear();
574
+ if (now)
575
+ snap(shifted, (el) => (el.style.translate = ""));
576
+ else
577
+ for (const el of shifted)
578
+ el.style.translate = "";
579
+ };
580
+ /**
581
+ * Keep the copy of the item under the pointer, where it was grabbed — at the same share of its
582
+ * width as it narrows or widens to fit another list.
583
+ */
584
+ const placeOverlay = () => {
585
+ const el = overlayRef.current;
586
+ if (!el)
587
+ return;
588
+ const { x, y } = pointerRef.current;
589
+ const offsetX = Number(el.dataset.offsetX);
590
+ const offsetY = Number(el.dataset.offsetY);
591
+ // Read only once it has been resized: the copy's box is not asked for on every move.
592
+ const session = sessionRef.current;
593
+ const resized = !!session?.resized;
594
+ const left = resized ? offsetX * (el.offsetWidth / session.size.w || 1) : offsetX;
595
+ const top = resized ? Math.min(offsetY, Math.max(0, el.offsetHeight - 1)) : offsetY;
596
+ el.style.translate = `${x - left}px ${y - top}px`;
597
+ };
598
+ const startPointer = (event, item) => {
599
+ if (liftedRef.current || (event.pointerType === "mouse" && event.button !== 0) || !event.isPrimary)
600
+ return;
601
+ const el = event.target;
602
+ const itemEl = event.currentTarget;
603
+ const handle = el.closest("[data-sortable-handle]");
604
+ const onHandle = !!handle && handle.closest("[data-sortable-item]") === itemEl;
605
+ // Other controls on the item keep their own clicks.
606
+ if (!onHandle && (handleOnly || el.closest(CONTROLS)))
607
+ return;
608
+ // A press in an item nested inside this one is that item's.
609
+ if (el.closest("[data-sortable-item]") !== itemEl && !onHandle)
610
+ return;
611
+ // The last drop is still gliding into place: it lands now.
612
+ settleRef.current?.();
613
+ const startX = event.clientX;
614
+ const startY = event.clientY;
615
+ // The handle drags at once, even on touch: it never scrolls.
616
+ const touch = event.pointerType === "touch" && !onHandle;
617
+ let pointer = { x: startX, y: startY };
618
+ pointerRef.current = pointer;
619
+ let active = false;
620
+ let frame = 0;
621
+ let timer = 0;
622
+ const bodyStyle = { userSelect: document.body.style.userSelect, cursor: document.body.style.cursor };
623
+ /** Where a release now would put the item: nowhere past the root's edge. */
624
+ const dropTarget = (session) => within(session.root, pointer.x, pointer.y)
625
+ ? (placeAt(session, pointer.x, pointer.y)?.place ?? null)
626
+ : null;
627
+ const retarget = (session) => {
628
+ const target = dropTarget(session);
629
+ const current = session.target;
630
+ if (current?.list === target?.list && current?.index === target?.index)
631
+ return;
632
+ session.target = target;
633
+ // The copy first: its height in the list it comes over is the size of the gap there.
634
+ fitCopy(session, target);
635
+ showAt(session, target);
636
+ setDrag((d) => (d ? { ...d, target } : d));
637
+ };
638
+ // Once a frame: read the rects again if something scrolled, scroll near the edges — not once
639
+ // the pointer is past the root's edge: it is on its way out, and a release there cancels —
640
+ // and open the gap where the item would land.
641
+ const tick = () => {
642
+ const session = sessionRef.current;
643
+ if (!session)
644
+ return;
645
+ if (session.dirty)
646
+ refresh(session);
647
+ if (within(session.root, pointer.x, pointer.y)) {
648
+ const under = placeAt(session, pointer.x, pointer.y);
649
+ if (under)
650
+ autoScroll(under.list.el, pointer.x, pointer.y);
651
+ }
652
+ retarget(session);
653
+ // A copy fitting another list's width keeps the pointer at the same share of it.
654
+ if (session.resized)
655
+ placeOverlay();
656
+ frame = requestAnimationFrame(tick);
657
+ };
658
+ const onScroll = () => {
659
+ if (sessionRef.current)
660
+ sessionRef.current.dirty = true;
661
+ };
662
+ const begin = () => {
663
+ active = true;
664
+ const from = placeIn(listsRef.current, item);
665
+ if (!from)
666
+ return end(false);
667
+ before.current = null;
668
+ const lists = measure();
669
+ const rect = itemEl.getBoundingClientRect();
670
+ sessionRef.current = {
671
+ item,
672
+ from,
673
+ size: { w: rect.width, h: rect.height },
674
+ sizes: new Map(),
675
+ resized: false,
676
+ lists,
677
+ root: rootRef.current?.getBoundingClientRect() ?? null,
678
+ dirty: false,
679
+ target: from,
680
+ shifts: new Map(),
681
+ };
682
+ setDrag({
683
+ item,
684
+ target: from,
685
+ width: rect.width,
686
+ offsetX: startX - rect.left,
687
+ offsetY: startY - rect.top,
688
+ dir: rootRef.current ? getComputedStyle(rootRef.current).direction : "ltr",
689
+ phase: "drag",
690
+ landed: null,
691
+ });
692
+ document.body.style.userSelect = "none";
693
+ document.body.style.cursor = "grabbing";
694
+ window.addEventListener("scroll", onScroll, true);
695
+ window.addEventListener("resize", onScroll);
696
+ announce(text.pickedUp(labelOf(item), describe(listsRef.current, from)));
697
+ if (touch)
698
+ navigator.vibrate?.(10);
699
+ frame = requestAnimationFrame(tick);
700
+ };
701
+ const onMove = (e) => {
702
+ if (e.pointerId !== event.pointerId)
703
+ return;
704
+ // The button came up where the page never heard of it, outside the window: a cancel.
705
+ if (e.pointerType === "mouse" && e.buttons === 0)
706
+ return end(false);
707
+ pointer = { x: e.clientX, y: e.clientY };
708
+ pointerRef.current = pointer;
709
+ const moved = Math.hypot(pointer.x - startX, pointer.y - startY);
710
+ if (!active) {
711
+ if (touch) {
712
+ if (moved > TOUCH_SLOP)
713
+ end(false); // a scroll, not a drag
714
+ return;
715
+ }
716
+ if (moved < DRAG_THRESHOLD)
717
+ return;
718
+ begin();
719
+ }
720
+ placeOverlay();
721
+ };
722
+ // Once a touch drag has started, the finger moves the item and not the page.
723
+ const onTouchMove = (e) => {
724
+ if (active && e.cancelable)
725
+ e.preventDefault();
726
+ };
727
+ const onKey = (e) => {
728
+ if (e.key !== "Escape" || !active)
729
+ return;
730
+ e.preventDefault();
731
+ e.stopPropagation();
732
+ end(false);
733
+ };
734
+ /** Lets go of the page: the listeners, the frame, the long-press timer and the page's styles. */
735
+ const detach = () => {
736
+ detachers.current.delete(detach);
737
+ clearTimeout(timer);
738
+ cancelAnimationFrame(frame);
739
+ window.removeEventListener("pointermove", onMove);
740
+ window.removeEventListener("pointerup", onUp);
741
+ window.removeEventListener("pointercancel", onCancel);
742
+ window.removeEventListener("touchmove", onTouchMove);
743
+ window.removeEventListener("keydown", onKey, true);
744
+ window.removeEventListener("scroll", onScroll, true);
745
+ window.removeEventListener("resize", onScroll);
746
+ document.body.style.userSelect = bodyStyle.userSelect;
747
+ document.body.style.cursor = bodyStyle.cursor;
748
+ };
749
+ const end = (drop) => {
750
+ detach();
751
+ if (!active)
752
+ return;
753
+ active = false;
754
+ const session = sessionRef.current;
755
+ const current = listsRef.current;
756
+ const from = placeIn(current, item);
757
+ if (!session || !from) {
758
+ if (session)
759
+ release(session, true);
760
+ sessionRef.current = null;
761
+ setDrag(null);
762
+ return;
763
+ }
764
+ if (session.dirty)
765
+ refresh(session);
766
+ // Escape, an interrupted touch, or a release past the root's edge: the item goes back.
767
+ const target = drop ? dropTarget(session) : null;
768
+ if (!target) {
769
+ announce(text.cancelled(labelOf(item), describe(current, from)));
770
+ callbacks.current.onMoveEnd?.({ item, from, to: from, cancelled: true });
771
+ setDrag((d) => (d ? { ...d, target: null, phase: "settle", landed: null } : d));
772
+ return;
773
+ }
774
+ const next = moveIn(current, item, target);
775
+ const to = placeIn(next, item) ?? target;
776
+ if (to.list !== from.list || to.index !== from.index)
777
+ commit(next, { item, from, to, source: "pointer" });
778
+ announce(text.dropped(labelOf(item), describe(next, to)));
779
+ callbacks.current.onMoveEnd?.({ item, from, to, cancelled: false });
780
+ setDrag((d) => (d ? { ...d, target: null, phase: "settle", landed: to } : d));
781
+ };
782
+ const onUp = (e) => {
783
+ if (e.pointerId !== event.pointerId)
784
+ return;
785
+ pointer = { x: e.clientX, y: e.clientY };
786
+ end(true);
787
+ };
788
+ const onCancel = (e) => {
789
+ if (e.pointerId === event.pointerId)
790
+ end(false);
791
+ };
792
+ detachers.current.add(detach);
793
+ window.addEventListener("pointermove", onMove);
794
+ window.addEventListener("pointerup", onUp);
795
+ window.addEventListener("pointercancel", onCancel);
796
+ window.addEventListener("touchmove", onTouchMove, { passive: false });
797
+ window.addEventListener("keydown", onKey, true);
798
+ if (touch)
799
+ timer = window.setTimeout(begin, LONG_PRESS);
800
+ // The handle is for dragging: no text selection, no focus jump on the first move.
801
+ else if (onHandle)
802
+ event.preventDefault();
803
+ };
804
+ // After a release the copy glides into the item's place — the gap it was dropped in, or where it
805
+ // was picked up — while the other items end their slides; then the item shows again.
806
+ React.useLayoutEffect(() => {
807
+ if (drag?.phase !== "settle")
808
+ return;
809
+ const session = sessionRef.current;
810
+ const item = drag.item;
811
+ let done = false;
812
+ const finish = () => {
813
+ if (done)
814
+ return;
815
+ done = true;
816
+ settleRef.current = null;
817
+ if (sessionRef.current === session) {
818
+ if (session)
819
+ release(session, true);
820
+ sessionRef.current = null;
821
+ }
822
+ setDrag(null);
823
+ };
824
+ const landed = drag.landed;
825
+ const listEl = landed ? listMap.current.get(landed.list)?.el : undefined;
826
+ const placed = !!listEl && itemsOf(listEl)[landed.index]?.dataset.sortableItem === item;
827
+ // Where the value now has it, everything already stands where it is drawn: the slides end at
828
+ // once. Put back — or not taken by a controlled value — everything glides home.
829
+ if (session)
830
+ release(session, placed);
831
+ const copy = overlayRef.current;
832
+ let home;
833
+ for (const entry of listMap.current.values())
834
+ home ??= itemsOf(entry.el).find((el) => el.dataset.sortableItem === item);
835
+ if (!copy || !home)
836
+ return finish();
837
+ const rect = home.getBoundingClientRect();
838
+ // It lands at the size of its place, too — a narrower column, a wider cell — gliding from the
839
+ // size it is drawn at now, even halfway through fitting a list.
840
+ const drawn = copy.getBoundingClientRect();
841
+ copy.style.transition = "none";
842
+ copy.style.width = `${drawn.width}px`;
843
+ copy.style.height = `${drawn.height}px`;
844
+ void copy.offsetWidth;
845
+ const glide = "calc(var(--duration, 150ms) * 4 / 3) var(--ease)";
846
+ copy.style.transition = `translate ${glide}, width ${glide}, height ${glide}`;
847
+ copy.style.translate = `${rect.left}px ${rect.top}px`;
848
+ copy.style.width = `${rect.width}px`;
849
+ copy.style.height = `${rect.height}px`;
850
+ const seconds = parseFloat(getComputedStyle(copy).transitionDuration);
851
+ if (!seconds)
852
+ return finish();
853
+ settleRef.current = finish;
854
+ const onEnd = (event) => {
855
+ if (event.target === copy)
856
+ finish();
857
+ };
858
+ copy.addEventListener("transitionend", onEnd);
859
+ const timeout = window.setTimeout(finish, seconds * 1000 + 100);
860
+ return () => {
861
+ copy.removeEventListener("transitionend", onEnd);
862
+ clearTimeout(timeout);
863
+ };
864
+ // eslint-disable-next-line react-hooks/exhaustive-deps
865
+ }, [drag?.phase]);
866
+ // The value changed under a drag — from outside, as nothing of ours commits before the drop:
867
+ // the items are measured again where they now are, and the next frame opens the gap afresh.
868
+ React.useLayoutEffect(() => {
869
+ const session = sessionRef.current;
870
+ if (!session || drag?.phase !== "drag")
871
+ return;
872
+ const from = placeIn(lists, session.item);
873
+ if (!from)
874
+ return;
875
+ release(session, true);
876
+ session.from = from;
877
+ session.target = from;
878
+ session.lists = measure();
879
+ session.dirty = false;
880
+ setDrag((d) => (d ? { ...d, target: from } : d));
881
+ // eslint-disable-next-line react-hooks/exhaustive-deps
882
+ }, [lists]);
883
+ // Place the copy as soon as it mounts, before it is painted in the corner; and without an
884
+ // `overlay` of your own, fill it with a copy of the item.
885
+ React.useLayoutEffect(() => {
886
+ const container = overlayRef.current;
887
+ if (!drag || !container)
888
+ return;
889
+ placeOverlay();
890
+ if (overlay)
891
+ return;
892
+ const source = rootRef.current?.querySelector(`[data-sortable-item="${CSS.escape(drag.item)}"]`);
893
+ if (!source)
894
+ return;
895
+ const copy = source.cloneNode(true);
896
+ for (const el of [copy, ...copy.querySelectorAll("[id]")])
897
+ el.removeAttribute("id");
898
+ copy.removeAttribute("data-dragging");
899
+ copy.removeAttribute("data-sortable-item");
900
+ copy.setAttribute("data-sortable-overlay", "");
901
+ copy.querySelectorAll("[data-sortable-item]").forEach((el) => el.removeAttribute("data-sortable-item"));
902
+ copy
903
+ .querySelectorAll("[data-sortable-handle]")
904
+ .forEach((el) => el.removeAttribute("data-sortable-handle"));
905
+ container.replaceChildren(copy);
906
+ return () => container.replaceChildren();
907
+ // Only when a drag starts: the copy stays as it was picked up.
908
+ // eslint-disable-next-line react-hooks/exhaustive-deps
909
+ }, [drag?.item]);
910
+ /** Puts down the item lifted with the keyboard: where it is now, or (`cancel`) where it was picked up. */
911
+ const putDown = (cancel) => {
912
+ const current = liftedRef.current;
913
+ if (!current)
914
+ return;
915
+ setLifted(null);
916
+ const label = labelOf(current.item);
917
+ const now = listsRef.current;
918
+ if (!cancel) {
919
+ const to = placeIn(now, current.item) ?? current.from;
920
+ announce(text.dropped(label, describe(now, to)));
921
+ callbacks.current.onMoveEnd?.({ item: current.item, from: current.from, to, cancelled: false });
922
+ return;
923
+ }
924
+ if (now !== current.before) {
925
+ const from = placeIn(now, current.item) ?? current.from;
926
+ snapshot();
927
+ commit(current.before, { item: current.item, from, to: current.from, source: "cancel" });
928
+ }
929
+ announce(text.cancelled(label, describe(current.before, current.from)));
930
+ callbacks.current.onMoveEnd?.({
931
+ item: current.item,
932
+ from: current.from,
933
+ to: current.from,
934
+ cancelled: true,
935
+ });
936
+ };
937
+ // A press anywhere but the lifted item's handle puts it down, as a release there would: on the
938
+ // root where it is now, past the root's edge back where it was.
939
+ React.useEffect(() => {
940
+ if (!lifted)
941
+ return;
942
+ const onPointerDown = (event) => {
943
+ const handle = event.target.closest?.("[data-sortable-handle]");
944
+ if (handle &&
945
+ rootRef.current?.contains(handle) &&
946
+ handle.getAttribute("data-sortable-handle") === lifted.item)
947
+ return;
948
+ putDown(!onRoot(event.clientX, event.clientY));
949
+ };
950
+ document.addEventListener("pointerdown", onPointerDown, true);
951
+ return () => document.removeEventListener("pointerdown", onPointerDown, true);
952
+ // eslint-disable-next-line react-hooks/exhaustive-deps
953
+ }, [lifted]);
954
+ /* Keyboard: Space picks the item up, the arrows move it, Space drops it and Escape puts it back. */
955
+ const onHandleKeyDown = (event, item) => {
956
+ settleRef.current?.();
957
+ const current = listsRef.current;
958
+ const label = labelOf(item);
959
+ const held = liftedRef.current;
960
+ if (!held || held.item !== item) {
961
+ if (event.key === " " || event.key === "Enter") {
962
+ event.preventDefault();
963
+ if (held)
964
+ putDown(false);
965
+ const from = placeIn(current, item);
966
+ if (!from)
967
+ return;
968
+ setLifted({ item, before: current, from });
969
+ announce(text.pickedUpKeyboard(label, describe(current, from)));
970
+ }
971
+ return;
972
+ }
973
+ const from = placeIn(current, item);
974
+ if (!from)
975
+ return;
976
+ const entry = listMap.current.get(from.list);
977
+ const listIds = Object.keys(current);
978
+ const length = current[from.list].length;
979
+ // Laid out where they stand, not where a slide has them now: offsets leave out the translate.
980
+ const boxes = entry
981
+ ? itemsOf(entry.el).map((el) => ({
982
+ x: el.offsetLeft,
983
+ y: el.offsetTop,
984
+ w: el.offsetWidth,
985
+ h: el.offsetHeight,
986
+ }))
987
+ : [];
988
+ const grid = entry?.orientation === "grid" || wraps(boxes);
989
+ const vertical = !grid && (entry?.orientation ?? "vertical") === "vertical";
990
+ /**
991
+ * In a grid, Up and Down take it to the item above or below — on the row before or after, the
992
+ * one nearest across — or, past the first or last row, into the list before or after.
993
+ */
994
+ const rowStep = (dir) => {
995
+ const here = boxes[from.index];
996
+ if (!here)
997
+ return null;
998
+ let best = -1;
999
+ let nearest = Infinity;
1000
+ let row = null;
1001
+ for (let k = from.index + dir; k >= 0 && k < boxes.length; k += dir) {
1002
+ const box = boxes[k];
1003
+ if (!row) {
1004
+ if (sameRow(box, here))
1005
+ continue;
1006
+ row = box;
1007
+ }
1008
+ else if (!sameRow(box, row))
1009
+ break;
1010
+ const distance = Math.abs(box.x + box.w / 2 - (here.x + here.w / 2));
1011
+ if (distance < nearest) {
1012
+ nearest = distance;
1013
+ best = k;
1014
+ }
1015
+ }
1016
+ if (best !== -1)
1017
+ return { list: from.list, index: best };
1018
+ if (listIds.length < 2)
1019
+ return from;
1020
+ const list = listIds[listIds.indexOf(from.list) + dir];
1021
+ if (list === undefined)
1022
+ return from;
1023
+ return { list, index: dir > 0 ? 0 : current[list].length };
1024
+ };
1025
+ // Along the list, and across the lists the way they are laid out: right to left, the next
1026
+ // list is on the left.
1027
+ const alongRtl = !vertical && isRtl(entry?.el ?? null);
1028
+ const acrossRtl = vertical && isRtl(rootRef.current);
1029
+ const back = vertical ? "ArrowUp" : alongRtl ? "ArrowRight" : "ArrowLeft";
1030
+ const forward = vertical ? "ArrowDown" : alongRtl ? "ArrowLeft" : "ArrowRight";
1031
+ const prevList = vertical ? (acrossRtl ? "ArrowRight" : "ArrowLeft") : "ArrowUp";
1032
+ const nextList = vertical ? (acrossRtl ? "ArrowLeft" : "ArrowRight") : "ArrowDown";
1033
+ let target = null;
1034
+ switch (grid && (event.key === "ArrowUp" || event.key === "ArrowDown") ? "row" : event.key) {
1035
+ case "row":
1036
+ target = rowStep(event.key === "ArrowUp" ? -1 : 1);
1037
+ if (!target)
1038
+ return;
1039
+ break;
1040
+ case back:
1041
+ target = { list: from.list, index: Math.max(0, from.index - 1) };
1042
+ break;
1043
+ case forward:
1044
+ target = { list: from.list, index: Math.min(length - 1, from.index + 1) };
1045
+ break;
1046
+ case "Home":
1047
+ target = { list: from.list, index: 0 };
1048
+ break;
1049
+ case "End":
1050
+ target = { list: from.list, index: length - 1 };
1051
+ break;
1052
+ case prevList:
1053
+ case nextList: {
1054
+ if (listIds.length < 2)
1055
+ return;
1056
+ const list = listIds[listIds.indexOf(from.list) + (event.key === nextList ? 1 : -1)];
1057
+ target = list === undefined ? from : { list, index: Math.min(from.index, current[list].length) };
1058
+ break;
1059
+ }
1060
+ case " ":
1061
+ case "Enter":
1062
+ event.preventDefault();
1063
+ putDown(false);
1064
+ return;
1065
+ case "Escape":
1066
+ event.preventDefault();
1067
+ event.stopPropagation();
1068
+ // Moved since the pickup: the item goes back, and focus with it to its remounted handle.
1069
+ if (held.before !== current)
1070
+ refocus.current = { item, selector: "[data-sortable-handle]" };
1071
+ putDown(true);
1072
+ return;
1073
+ case "Tab":
1074
+ putDown(false);
1075
+ return;
1076
+ default:
1077
+ return;
1078
+ }
1079
+ event.preventDefault();
1080
+ if (target.list === from.list && target.index === from.index) {
1081
+ announce(text.cannotMove(label, describe(current, from)));
1082
+ return;
1083
+ }
1084
+ const next = moveIn(current, item, target);
1085
+ refocus.current = { item, selector: "[data-sortable-handle]" };
1086
+ snapshot();
1087
+ commit(next, { item, from, to: target, source: "keyboard" });
1088
+ announce(target.list === from.list
1089
+ ? text.movedWithin(label, describe(next, target))
1090
+ : text.movedTo(label, describe(next, target)));
1091
+ };
1092
+ // Focus leaving for another control drops the item where it is. (An item moving to another list
1093
+ // loses focus with no related target; that blur is ours and does not drop it.)
1094
+ const onHandleBlur = (event, item) => {
1095
+ if (liftedRef.current?.item !== item || !event.relatedTarget)
1096
+ return;
1097
+ putDown(false);
1098
+ };
1099
+ const move = (item, to, options) => {
1100
+ const current = listsRef.current;
1101
+ const from = placeIn(current, item);
1102
+ if (!from)
1103
+ return;
1104
+ const list = to.list ?? from.list;
1105
+ if (!(list in current))
1106
+ return;
1107
+ const next = moveIn(current, item, { list, index: to.index ?? Number.MAX_SAFE_INTEGER });
1108
+ const place = placeIn(next, item);
1109
+ if (place.list === from.list && place.index === from.index)
1110
+ return;
1111
+ if (options?.focus)
1112
+ refocus.current = { item, selector: options.focus };
1113
+ snapshot();
1114
+ commit(next, { item, from, to: place, source: "api" });
1115
+ announce(text.moved(labelOf(item), describe(next, place)));
1116
+ callbacks.current.onMoveEnd?.({ item, from, to: place, cancelled: false });
1117
+ };
1118
+ const context = {
1119
+ drag,
1120
+ lifted,
1121
+ handleOnly,
1122
+ instructionsId,
1123
+ text,
1124
+ registerList,
1125
+ setItemLabel,
1126
+ startPointer,
1127
+ onHandleKeyDown,
1128
+ onHandleBlur,
1129
+ move,
1130
+ };
1131
+ const rootRefs = React.useMemo(() => mergeRefs(ref, rootRef), [ref]);
1132
+ const element = useRender({
1133
+ defaultTagName: "div",
1134
+ render,
1135
+ ref: rootRefs,
1136
+ props: {
1137
+ "data-slot": "sortable",
1138
+ "data-dragging": drag ? "" : undefined,
1139
+ ...props,
1140
+ // Relative, so the screen-reader text below stays inside it — and inside its scroll.
1141
+ className: cn("relative", className),
1142
+ children: (_jsxs(_Fragment, { children: [children, _jsx("span", { id: instructionsId, "data-slot": "sortable-instructions", className: "sr-only", children: text.instructions }), _jsx("span", { "data-slot": "sortable-announcer", "aria-live": "polite", "aria-atomic": "true", className: "sr-only", children: message })] })),
1143
+ },
1144
+ });
1145
+ return (_jsxs(SortableContext.Provider, { value: context, children: [element, drag &&
1146
+ createPortal(_jsx("div", { ref: overlayRef, "aria-hidden": true, inert: true, dir: drag.dir, "data-slot": "sortable-overlay", "data-offset-x": drag.offsetX, "data-offset-y": drag.offsetY, className: "pointer-events-none fixed top-0 left-0 z-50 list-none", style: { width: drag.width }, children: overlay && (_jsx(SortableItemContext.Provider, { value: {
1147
+ value: drag.item,
1148
+ label: labelOf(drag.item),
1149
+ disabled: false,
1150
+ dragging: false,
1151
+ lifted: false,
1152
+ overlay: true,
1153
+ }, children: overlay(drag.item) })) }), document.body)] }));
1154
+ }
1155
+ /**
1156
+ * One list of items, an `<ol>` by default. Items keep the order of `value`; render them in it.
1157
+ * Lay it out yourself (`flex flex-col gap-2`, a row with `flex-row`, a `grid grid-cols-3`). While
1158
+ * an item is dragged the others slide aside to open a gap of its size where it will land — in a
1159
+ * grid each moves into the slot of its neighbour, across the row breaks.
1160
+ */
1161
+ export function SortableList({ id = "", orientation = "vertical", label, render, className, children, ref, ...props }) {
1162
+ const context = useSortableContext("SortableList");
1163
+ const own = React.useRef(null);
1164
+ const { registerList, drag } = context;
1165
+ React.useLayoutEffect(() => {
1166
+ if (!own.current)
1167
+ return;
1168
+ return registerList(id, { el: own.current, orientation, label });
1169
+ }, [registerList, id, orientation, label]);
1170
+ const over = !!drag?.target && drag.target.list === id;
1171
+ const hasName = props["aria-label"] !== undefined || props["aria-labelledby"] !== undefined;
1172
+ const refs = React.useMemo(() => mergeRefs(ref, own), [ref]);
1173
+ return useRender({
1174
+ defaultTagName: "ol",
1175
+ render,
1176
+ ref: refs,
1177
+ props: {
1178
+ "data-slot": "sortable-list",
1179
+ "data-sortable-list": id,
1180
+ "data-orientation": orientation,
1181
+ "data-over": over ? "" : undefined,
1182
+ "aria-label": hasName ? undefined : label,
1183
+ ...props,
1184
+ className: cn("relative", className),
1185
+ children,
1186
+ },
1187
+ });
1188
+ }
1189
+ /**
1190
+ * One item, an `<li>` by default. Dragged, it leaves its place (`data-dragging`, hidden) while a
1191
+ * copy follows the pointer and the other items slide around the gap; picked up with the keyboard
1192
+ * it has `data-lifted`, and it slides with the others as the arrows move it. Presses on buttons,
1193
+ * links and fields inside it keep their own clicks.
1194
+ */
1195
+ export function SortableItem({ value, label, disabled = false, render, className, children, onPointerDown, onContextMenu, ref, ...props }) {
1196
+ const context = useSortableContext("SortableItem");
1197
+ const name = label ?? value;
1198
+ const { setItemLabel } = context;
1199
+ React.useLayoutEffect(() => setItemLabel(value, name), [setItemLabel, value, name]);
1200
+ const dragging = context.drag?.item === value;
1201
+ const lifted = context.lifted?.item === value;
1202
+ const item = React.useMemo(() => ({ value, label: name, disabled, dragging, lifted, overlay: false }), [value, name, disabled, dragging, lifted]);
1203
+ const element = useRender({
1204
+ defaultTagName: "li",
1205
+ render,
1206
+ ref,
1207
+ props: {
1208
+ "data-slot": "sortable-item",
1209
+ "data-sortable-item": value,
1210
+ "data-dragging": dragging ? "" : undefined,
1211
+ "data-lifted": lifted ? "" : undefined,
1212
+ "data-disabled": disabled ? "" : undefined,
1213
+ ...props,
1214
+ onPointerDown: (event) => {
1215
+ onPointerDown?.(event);
1216
+ if (!event.defaultPrevented && !disabled)
1217
+ context.startPointer(event, value);
1218
+ },
1219
+ // A long press would open the browser's own menu and select the text.
1220
+ onContextMenu: (event) => {
1221
+ onContextMenu?.(event);
1222
+ if (!context.handleOnly && event.nativeEvent.pointerType === "touch")
1223
+ event.preventDefault();
1224
+ },
1225
+ className: cn(
1226
+ // The slides are the item's own translate: 150ms, at once under reduced motion.
1227
+ "relative transition-[translate] duration-(--duration) ease-(--ease) data-dragging:opacity-0", !context.handleOnly && !disabled && "select-none [-webkit-touch-callout:none]", className),
1228
+ children,
1229
+ },
1230
+ });
1231
+ return _jsx(SortableItemContext.Provider, { value: item, children: element });
1232
+ }
1233
+ /**
1234
+ * The grip that moves an item: drag it — at once, even on touch — or focus it and press Space.
1235
+ * A ghost 30px icon button named "Move {label}", described by the keyboard instructions, with
1236
+ * `aria-pressed` while the item is lifted. Without children it draws a grip in the list's direction.
1237
+ */
1238
+ export function SortableHandle({ variant = "ghost", size = "icon-sm", className, children, onKeyDown, onBlur, ref, ...props }) {
1239
+ const context = useSortableContext("SortableHandle");
1240
+ const item = useSortableItem();
1241
+ const own = React.useRef(null);
1242
+ // Your ref and the one that finds the list, so a ref of your own keeps the grip's orientation.
1243
+ const refs = React.useMemo(() => mergeRefs(ref, own), [ref]);
1244
+ const [orientation, setOrientation] = React.useState(null);
1245
+ React.useLayoutEffect(() => {
1246
+ const list = own.current?.closest("[data-sortable-list]");
1247
+ setOrientation(list?.getAttribute("data-orientation") ?? null);
1248
+ }, []);
1249
+ return (_jsx(Button, { ref: refs, variant: variant, size: size, "data-slot": "sortable-handle", "data-sortable-handle": item.value, "aria-label": context.text.handle(item.label), "aria-describedby": context.instructionsId, "aria-pressed": item.lifted, disabled: item.disabled, onKeyDown: (event) => {
1250
+ onKeyDown?.(event);
1251
+ if (!event.defaultPrevented)
1252
+ context.onHandleKeyDown(event, item.value);
1253
+ }, onBlur: (event) => {
1254
+ onBlur?.(event);
1255
+ context.onHandleBlur(event, item.value);
1256
+ }, className: sx("cursor-grab touch-none text-muted-foreground active:cursor-grabbing", className), ...props, children: children ??
1257
+ (orientation === "grid" ? (_jsx(GripIcon, {})) : orientation === "horizontal" ? (_jsx(GripHorizontalIcon, {})) : (_jsx(GripVerticalIcon, {}))) }));
1258
+ }