@pyreon/dnd 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -71,7 +71,7 @@ Full sortable list with edge detection, auto-scroll, and keyboard reordering. `b
71
71
  ```tsx
72
72
  const cols = signal<Column[]>([])
73
73
 
74
- const { containerRef, itemRef, activeId, overId, overEdge } = useSortable({
74
+ const { containerRef, itemRef, isActive, isOverKey, overEdge } = useSortable({
75
75
  items: () => cols(),
76
76
  by: (c) => c.id,
77
77
  onReorder: (next) => cols.set(next),
@@ -83,9 +83,9 @@ const { containerRef, itemRef, activeId, overId, overEdge } = useSortable({
83
83
  {(col) => (
84
84
  <li
85
85
  ref={itemRef(col.id)}
86
- class={activeId() === col.id ? 'dragging' : ''}
86
+ class={isActive(col.id) ? 'dragging' : ''}
87
87
  style={() =>
88
- overId() === col.id && overEdge() === 'top'
88
+ isOverKey(col.id) && overEdge() === 'top'
89
89
  ? 'border-top: 2px solid blue'
90
90
  : ''
91
91
  }
@@ -173,6 +173,16 @@ useDraggable({
173
173
  })
174
174
  ```
175
175
 
176
+ ## Accessibility (built in)
177
+
178
+ `useSortable` announces drags through `@pyreon/a11y`'s live region — "Picked up Alice", "Moved Alice to position 2 of 3", "Dropped …" — and auto-creates a visually-hidden instructions node ("Press Alt plus arrow keys to reorder") linked to every item via `aria-describedby`. Pass `label: (item) => string` so announcements use human names instead of raw keys. Alt+Arrow keyboard reordering ships by default.
179
+
180
+ ## Custom drag previews, edges, handles
181
+
182
+ - `useDraggable({ preview: { render(container) { /* draw */ }, offset: 'center' } })` — replace the browser's default drag snapshot (pdnd's `setCustomNativeDragPreview`; offsets: `'pointer-outside' | 'center' | 'preserve-offset'`).
183
+ - `useDroppable({ edges: ['top', 'bottom'], sticky: true })` — closest-edge detection on plain drop zones via the returned `overEdge()` accessor; `sticky` keeps the target held across gaps.
184
+ - `useSortable().itemHandleRef(key)` — scope drag initiation to a grip element inside the row; rows without a handle stay fully draggable.
185
+
176
186
  ## Gotchas
177
187
 
178
188
  - **Hooks are SSR-safe** — they return zero-state accessors when `document` is undefined. Real registration happens at first browser tick.
@@ -185,7 +195,7 @@ useDraggable({
185
195
 
186
196
  ## Performance
187
197
 
188
- The signal-driven layer adds **near-zero overhead** over calling pdnd directly. A package-level benchmark (`bun run bench`) measures the _wrapper tax_ — the JS the ergonomic hook adds over a hand-rolled Pyreon+pdnd integration wiring the same reactive state — against the **real** pdnd build under happy-dom, with per-`(op × impl)` process isolation and a bootstrap CI95. `useDraggable` / `useDroppable` / `useSortable`-item mount→unmount lifecycles all tie the hand-rolled baseline (CI overlap); `useDragMonitor` adds ~one closure allocation per mount; per drag-event dispatch adds one optional-callback hop. Reactive DnD at ~raw-pdnd cost. (Real pointer-gesture timing is browser-dependent and out of scope for the micro-bench; author-judge disclosed.)
198
+ The signal-driven layer adds **near-zero overhead** over calling pdnd directly. A package-level benchmark (`bun run bench`) measures the _wrapper tax_ — the JS the ergonomic hook adds over a hand-rolled Pyreon+pdnd integration wiring the same reactive state — against the **real** pdnd build under happy-dom, with per-`(op × impl)` process isolation and a bootstrap CI95. `useDraggable` / `useDroppable` / `useSortable`-item mount→unmount lifecycles all tie the hand-rolled baseline (CI overlap); `useDragMonitor` adds ~one closure allocation per mount; per drag-event dispatch adds one optional-callback hop. Reactive DnD at ~raw-pdnd cost. The bench also measures the ROW-BINDING idiom at scale: at N=1000 sortable rows, one row-enter costs ~26µs with the naive `overId() === key` equality idiom (every row subscribes — O(N) notifies) vs ~1.5µs with the `isOverKey(key)` selector idiom (**~18× / 94% faster**, `createSelector`-backed O(2) notifies — use the selectors, they exist for exactly this). (Real pointer-gesture timing is browser-dependent and out of scope for the micro-bench; author-judge disclosed.)
189
199
 
190
200
  ## Documentation
191
201
 
@@ -5386,7 +5386,7 @@ var drawChart = (function (exports) {
5386
5386
  </script>
5387
5387
  <script>
5388
5388
  /*<!--*/
5389
- const data = {"version":2,"tree":{"name":"root","children":[{"name":"index.js","children":[{"uid":"ba65a4f8-1","name":"package.json"},{"name":"src","children":[{"uid":"ba65a4f8-3","name":"use-drag-monitor.ts"},{"uid":"ba65a4f8-5","name":"use-draggable.ts"},{"uid":"ba65a4f8-7","name":"use-droppable.ts"},{"uid":"ba65a4f8-9","name":"use-file-drop.ts"},{"uid":"ba65a4f8-11","name":"use-sortable.ts"},{"uid":"ba65a4f8-13","name":"index.ts"}]}]}],"isRoot":true},"nodeParts":{"ba65a4f8-1":{"renderedLength":86,"gzipLength":97,"brotliLength":0,"metaUid":"ba65a4f8-0"},"ba65a4f8-3":{"renderedLength":1445,"gzipLength":702,"brotliLength":0,"metaUid":"ba65a4f8-2"},"ba65a4f8-5":{"renderedLength":1553,"gzipLength":713,"brotliLength":0,"metaUid":"ba65a4f8-4"},"ba65a4f8-7":{"renderedLength":1569,"gzipLength":689,"brotliLength":0,"metaUid":"ba65a4f8-6"},"ba65a4f8-9":{"renderedLength":2436,"gzipLength":1007,"brotliLength":0,"metaUid":"ba65a4f8-8"},"ba65a4f8-11":{"renderedLength":9322,"gzipLength":2933,"brotliLength":0,"metaUid":"ba65a4f8-10"},"ba65a4f8-13":{"renderedLength":87,"gzipLength":99,"brotliLength":0,"metaUid":"ba65a4f8-12"}},"nodeMetas":{"ba65a4f8-0":{"id":"/package.json","moduleParts":{"index.js":"ba65a4f8-1"},"imported":[],"importedBy":[{"uid":"ba65a4f8-12"}]},"ba65a4f8-2":{"id":"/src/use-drag-monitor.ts","moduleParts":{"index.js":"ba65a4f8-3"},"imported":[{"uid":"ba65a4f8-15"},{"uid":"ba65a4f8-14"}],"importedBy":[{"uid":"ba65a4f8-12"}]},"ba65a4f8-4":{"id":"/src/use-draggable.ts","moduleParts":{"index.js":"ba65a4f8-5"},"imported":[{"uid":"ba65a4f8-15"},{"uid":"ba65a4f8-14"}],"importedBy":[{"uid":"ba65a4f8-12"}]},"ba65a4f8-6":{"id":"/src/use-droppable.ts","moduleParts":{"index.js":"ba65a4f8-7"},"imported":[{"uid":"ba65a4f8-15"},{"uid":"ba65a4f8-14"}],"importedBy":[{"uid":"ba65a4f8-12"}]},"ba65a4f8-8":{"id":"/src/use-file-drop.ts","moduleParts":{"index.js":"ba65a4f8-9"},"imported":[{"uid":"ba65a4f8-16"},{"uid":"ba65a4f8-17"},{"uid":"ba65a4f8-14"}],"importedBy":[{"uid":"ba65a4f8-12"}]},"ba65a4f8-10":{"id":"/src/use-sortable.ts","moduleParts":{"index.js":"ba65a4f8-11"},"imported":[{"uid":"ba65a4f8-18"},{"uid":"ba65a4f8-15"},{"uid":"ba65a4f8-19"},{"uid":"ba65a4f8-20"},{"uid":"ba65a4f8-14"}],"importedBy":[{"uid":"ba65a4f8-12"}]},"ba65a4f8-12":{"id":"/src/index.ts","moduleParts":{"index.js":"ba65a4f8-13"},"imported":[{"uid":"ba65a4f8-0"},{"uid":"ba65a4f8-14"},{"uid":"ba65a4f8-2"},{"uid":"ba65a4f8-4"},{"uid":"ba65a4f8-6"},{"uid":"ba65a4f8-8"},{"uid":"ba65a4f8-10"}],"importedBy":[],"isEntry":true},"ba65a4f8-14":{"id":"@pyreon/reactivity","moduleParts":{},"imported":[],"importedBy":[{"uid":"ba65a4f8-12"},{"uid":"ba65a4f8-2"},{"uid":"ba65a4f8-4"},{"uid":"ba65a4f8-6"},{"uid":"ba65a4f8-8"},{"uid":"ba65a4f8-10"}]},"ba65a4f8-15":{"id":"@atlaskit/pragmatic-drag-and-drop/element/adapter","moduleParts":{},"imported":[],"importedBy":[{"uid":"ba65a4f8-2"},{"uid":"ba65a4f8-4"},{"uid":"ba65a4f8-6"},{"uid":"ba65a4f8-10"}]},"ba65a4f8-16":{"id":"@atlaskit/pragmatic-drag-and-drop/external/adapter","moduleParts":{},"imported":[],"importedBy":[{"uid":"ba65a4f8-8"}]},"ba65a4f8-17":{"id":"@atlaskit/pragmatic-drag-and-drop/external/file","moduleParts":{},"imported":[],"importedBy":[{"uid":"ba65a4f8-8"}]},"ba65a4f8-18":{"id":"@atlaskit/pragmatic-drag-and-drop/combine","moduleParts":{},"imported":[],"importedBy":[{"uid":"ba65a4f8-10"}]},"ba65a4f8-19":{"id":"@atlaskit/pragmatic-drag-and-drop-auto-scroll/element","moduleParts":{},"imported":[],"importedBy":[{"uid":"ba65a4f8-10"}]},"ba65a4f8-20":{"id":"@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge","moduleParts":{},"imported":[],"importedBy":[{"uid":"ba65a4f8-10"}]}},"env":{"rollup":"4.23.0"},"options":{"gzip":true,"brotli":false,"sourcemap":false}};
5389
+ const data = {"version":2,"tree":{"name":"root","children":[{"name":"index.js","children":[{"uid":"4cc3aa4e-1","name":"package.json"},{"name":"src","children":[{"uid":"4cc3aa4e-3","name":"use-drag-monitor.ts"},{"uid":"4cc3aa4e-5","name":"use-draggable.ts"},{"uid":"4cc3aa4e-7","name":"use-droppable.ts"},{"uid":"4cc3aa4e-9","name":"use-file-drop.ts"},{"uid":"4cc3aa4e-11","name":"use-sortable.ts"},{"uid":"4cc3aa4e-13","name":"index.ts"}]}]}],"isRoot":true},"nodeParts":{"4cc3aa4e-1":{"renderedLength":86,"gzipLength":97,"brotliLength":0,"metaUid":"4cc3aa4e-0"},"4cc3aa4e-3":{"renderedLength":1445,"gzipLength":702,"brotliLength":0,"metaUid":"4cc3aa4e-2"},"4cc3aa4e-5":{"renderedLength":2473,"gzipLength":1086,"brotliLength":0,"metaUid":"4cc3aa4e-4"},"4cc3aa4e-7":{"renderedLength":2351,"gzipLength":950,"brotliLength":0,"metaUid":"4cc3aa4e-6"},"4cc3aa4e-9":{"renderedLength":2436,"gzipLength":1007,"brotliLength":0,"metaUid":"4cc3aa4e-8"},"4cc3aa4e-11":{"renderedLength":12668,"gzipLength":4007,"brotliLength":0,"metaUid":"4cc3aa4e-10"},"4cc3aa4e-13":{"renderedLength":87,"gzipLength":99,"brotliLength":0,"metaUid":"4cc3aa4e-12"}},"nodeMetas":{"4cc3aa4e-0":{"id":"/package.json","moduleParts":{"index.js":"4cc3aa4e-1"},"imported":[],"importedBy":[{"uid":"4cc3aa4e-12"}]},"4cc3aa4e-2":{"id":"/src/use-drag-monitor.ts","moduleParts":{"index.js":"4cc3aa4e-3"},"imported":[{"uid":"4cc3aa4e-15"},{"uid":"4cc3aa4e-14"}],"importedBy":[{"uid":"4cc3aa4e-12"}]},"4cc3aa4e-4":{"id":"/src/use-draggable.ts","moduleParts":{"index.js":"4cc3aa4e-5"},"imported":[{"uid":"4cc3aa4e-15"},{"uid":"4cc3aa4e-16"},{"uid":"4cc3aa4e-17"},{"uid":"4cc3aa4e-18"},{"uid":"4cc3aa4e-19"},{"uid":"4cc3aa4e-14"}],"importedBy":[{"uid":"4cc3aa4e-12"}]},"4cc3aa4e-6":{"id":"/src/use-droppable.ts","moduleParts":{"index.js":"4cc3aa4e-7"},"imported":[{"uid":"4cc3aa4e-15"},{"uid":"4cc3aa4e-20"},{"uid":"4cc3aa4e-14"}],"importedBy":[{"uid":"4cc3aa4e-12"}]},"4cc3aa4e-8":{"id":"/src/use-file-drop.ts","moduleParts":{"index.js":"4cc3aa4e-9"},"imported":[{"uid":"4cc3aa4e-21"},{"uid":"4cc3aa4e-22"},{"uid":"4cc3aa4e-14"}],"importedBy":[{"uid":"4cc3aa4e-12"}]},"4cc3aa4e-10":{"id":"/src/use-sortable.ts","moduleParts":{"index.js":"4cc3aa4e-11"},"imported":[{"uid":"4cc3aa4e-23"},{"uid":"4cc3aa4e-15"},{"uid":"4cc3aa4e-24"},{"uid":"4cc3aa4e-20"},{"uid":"4cc3aa4e-25"},{"uid":"4cc3aa4e-14"}],"importedBy":[{"uid":"4cc3aa4e-12"}]},"4cc3aa4e-12":{"id":"/src/index.ts","moduleParts":{"index.js":"4cc3aa4e-13"},"imported":[{"uid":"4cc3aa4e-0"},{"uid":"4cc3aa4e-14"},{"uid":"4cc3aa4e-2"},{"uid":"4cc3aa4e-4"},{"uid":"4cc3aa4e-6"},{"uid":"4cc3aa4e-8"},{"uid":"4cc3aa4e-10"}],"importedBy":[],"isEntry":true},"4cc3aa4e-14":{"id":"@pyreon/reactivity","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-12"},{"uid":"4cc3aa4e-2"},{"uid":"4cc3aa4e-4"},{"uid":"4cc3aa4e-6"},{"uid":"4cc3aa4e-8"},{"uid":"4cc3aa4e-10"}]},"4cc3aa4e-15":{"id":"@atlaskit/pragmatic-drag-and-drop/element/adapter","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-2"},{"uid":"4cc3aa4e-4"},{"uid":"4cc3aa4e-6"},{"uid":"4cc3aa4e-10"}]},"4cc3aa4e-16":{"id":"@atlaskit/pragmatic-drag-and-drop/element/center-under-pointer","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-4"}]},"4cc3aa4e-17":{"id":"@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-4"}]},"4cc3aa4e-18":{"id":"@atlaskit/pragmatic-drag-and-drop/element/preserve-offset-on-source","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-4"}]},"4cc3aa4e-19":{"id":"@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-4"}]},"4cc3aa4e-20":{"id":"@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-6"},{"uid":"4cc3aa4e-10"}]},"4cc3aa4e-21":{"id":"@atlaskit/pragmatic-drag-and-drop/external/adapter","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-8"}]},"4cc3aa4e-22":{"id":"@atlaskit/pragmatic-drag-and-drop/external/file","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-8"}]},"4cc3aa4e-23":{"id":"@atlaskit/pragmatic-drag-and-drop/combine","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-10"}]},"4cc3aa4e-24":{"id":"@atlaskit/pragmatic-drag-and-drop-auto-scroll/element","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-10"}]},"4cc3aa4e-25":{"id":"@pyreon/a11y","moduleParts":{},"imported":[],"importedBy":[{"uid":"4cc3aa4e-10"}]}},"env":{"rollup":"4.23.0"},"options":{"gzip":true,"brotli":false,"sourcemap":false}};
5390
5390
 
5391
5391
  const run = () => {
5392
5392
  const width = window.innerWidth;
package/lib/index.js CHANGED
@@ -1,14 +1,19 @@
1
- import { batch, isServer, onCleanup, registerSingleton, signal } from "@pyreon/reactivity";
1
+ import { batch, createSelector, isServer, onCleanup, registerSingleton, signal } from "@pyreon/reactivity";
2
2
  import { draggable, dropTargetForElements, monitorForElements } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
3
+ import { centerUnderPointer } from "@atlaskit/pragmatic-drag-and-drop/element/center-under-pointer";
4
+ import { pointerOutsideOfPreview } from "@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview";
5
+ import { preserveOffsetOnSource } from "@atlaskit/pragmatic-drag-and-drop/element/preserve-offset-on-source";
6
+ import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview";
7
+ import { attachClosestEdge, extractClosestEdge } from "@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge";
3
8
  import { dropTargetForExternal, monitorForExternal } from "@atlaskit/pragmatic-drag-and-drop/external/adapter";
4
9
  import { containsFiles, getFiles } from "@atlaskit/pragmatic-drag-and-drop/external/file";
5
10
  import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";
6
11
  import { autoScrollForElements } from "@atlaskit/pragmatic-drag-and-drop-auto-scroll/element";
7
- import { attachClosestEdge, extractClosestEdge } from "@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge";
12
+ import { announce } from "@pyreon/a11y";
8
13
 
9
14
  //#region package.json
10
15
  var name = "@pyreon/dnd";
11
- var version = "0.49.0";
16
+ var version = "0.50.0";
12
17
 
13
18
  //#endregion
14
19
  //#region src/use-drag-monitor.ts
@@ -67,6 +72,22 @@ function useDragMonitor(options) {
67
72
  //#endregion
68
73
  //#region src/use-draggable.ts
69
74
  /**
75
+ * Resolve a preview `offset` preset to pdnd's `GetOffsetFn`. Split out so
76
+ * the ternary chain is directly unit-testable; `undefined` keeps the
77
+ * browser default (top-left of the preview under the pointer).
78
+ */
79
+ function resolvePreviewOffset(offset, source, input) {
80
+ if (offset === "pointer-outside") return pointerOutsideOfPreview({
81
+ x: "16px",
82
+ y: "8px"
83
+ });
84
+ if (offset === "center") return centerUnderPointer;
85
+ if (offset === "preserve-offset") return preserveOffsetOnSource({
86
+ element: source.element,
87
+ input
88
+ });
89
+ }
90
+ /**
70
91
  * Make an element draggable with signal-driven state.
71
92
  *
72
93
  * @example
@@ -97,9 +118,18 @@ function useDraggable(options) {
97
118
  if (!el) return;
98
119
  const resolveData = () => typeof options.data === "function" ? options.data() : options.data;
99
120
  const handle = options.handle?.();
121
+ const preview = options.preview;
100
122
  cleanup = draggable({
101
123
  element: el,
102
124
  ...handle ? { dragHandle: handle } : {},
125
+ ...preview ? { onGenerateDragPreview: ({ nativeSetDragImage, source, location }) => {
126
+ const getOffset = resolvePreviewOffset(preview.offset, source, location.initial.input);
127
+ setCustomNativeDragPreview({
128
+ render: ({ container }) => preview.render(container),
129
+ nativeSetDragImage,
130
+ ...getOffset ? { getOffset } : {}
131
+ });
132
+ } } : {},
103
133
  getInitialData: resolveData,
104
134
  canDrag: () => {
105
135
  const disabled = options.disabled;
@@ -133,10 +163,11 @@ function useDraggable(options) {
133
163
  * ```tsx
134
164
  * let zoneEl: HTMLElement | null = null
135
165
  *
136
- * const { isOver } = useDroppable({
166
+ * const { isOver, overEdge } = useDroppable({
137
167
  * element: () => zoneEl,
138
168
  * onDrop: (data) => handleDrop(data),
139
169
  * canDrop: (data) => data.type === "card",
170
+ * edges: ["top", "bottom"], // opt-in closest-edge detection
140
171
  * })
141
172
  *
142
173
  * <div ref={(el) => zoneEl = el} class={isOver() ? "bg-blue-50" : ""}>
@@ -145,8 +176,12 @@ function useDraggable(options) {
145
176
  * ```
146
177
  */
147
178
  function useDroppable(options) {
148
- if (isServer) return { isOver: () => false };
179
+ if (isServer) return {
180
+ isOver: () => false,
181
+ overEdge: () => null
182
+ };
149
183
  const isOver = signal(false);
184
+ const overEdge = signal(null);
150
185
  let cleanup;
151
186
  let disposed = false;
152
187
  function setup() {
@@ -156,26 +191,49 @@ function useDroppable(options) {
156
191
  if (cleanup) cleanup();
157
192
  const el = options.element();
158
193
  if (!el) return;
194
+ const edges = options.edges;
195
+ const resolveData = () => {
196
+ if (!options.data) return {};
197
+ return typeof options.data === "function" ? options.data() : options.data;
198
+ };
159
199
  cleanup = dropTargetForElements({
160
200
  element: el,
161
- getData: () => {
162
- if (!options.data) return {};
163
- return typeof options.data === "function" ? options.data() : options.data;
201
+ getData: ({ input, element }) => {
202
+ const data = resolveData();
203
+ if (edges && edges.length > 0) return attachClosestEdge(data, {
204
+ input,
205
+ element,
206
+ allowedEdges: edges
207
+ });
208
+ return data;
164
209
  },
210
+ ...options.sticky ? { getIsSticky: () => true } : {},
165
211
  canDrop: ({ source }) => {
166
212
  if (!options.canDrop) return true;
167
213
  return options.canDrop(source.data);
168
214
  },
169
- onDragEnter: ({ source }) => {
170
- isOver.set(true);
215
+ onDragEnter: ({ source, self }) => {
216
+ batch(() => {
217
+ isOver.set(true);
218
+ if (edges) overEdge.set(extractClosestEdge(self.data));
219
+ });
171
220
  options.onDragEnter?.(source.data);
172
221
  },
222
+ ...edges && edges.length > 0 ? { onDrag: ({ self }) => {
223
+ overEdge.set(extractClosestEdge(self.data));
224
+ } } : {},
173
225
  onDragLeave: () => {
174
- isOver.set(false);
226
+ batch(() => {
227
+ isOver.set(false);
228
+ overEdge.set(null);
229
+ });
175
230
  options.onDragLeave?.();
176
231
  },
177
232
  onDrop: ({ source }) => {
178
- isOver.set(false);
233
+ batch(() => {
234
+ isOver.set(false);
235
+ overEdge.set(null);
236
+ });
179
237
  options.onDrop?.(source.data);
180
238
  }
181
239
  });
@@ -185,7 +243,10 @@ function useDroppable(options) {
185
243
  disposed = true;
186
244
  if (cleanup) cleanup();
187
245
  });
188
- return { isOver };
246
+ return {
247
+ isOver,
248
+ overEdge
249
+ };
189
250
  }
190
251
 
191
252
  //#endregion
@@ -282,6 +343,7 @@ const SORT_KEY = "__pyreon_sortable_key";
282
343
  const SORT_ID = "__pyreon_sortable_id";
283
344
  const SORT_GROUP = "__pyreon_sortable_group";
284
345
  const SORT_PAYLOAD = "__pyreon_sortable_payload";
346
+ const SR_ONLY = "position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0";
285
347
  let _sortableCounter = 0;
286
348
  const _sortableRegistry = /* @__PURE__ */ new Map();
287
349
  /**
@@ -307,10 +369,11 @@ const _sortableRegistry = /* @__PURE__ */ new Map();
307
369
  * { id: "3", name: "Charlie" },
308
370
  * ])
309
371
  *
310
- * const { containerRef, itemRef, activeId, overId, overEdge } = useSortable({
372
+ * const { containerRef, itemRef, isActive, isOverKey, overEdge } = useSortable({
311
373
  * items,
312
374
  * by: (item) => item.id,
313
375
  * onReorder: (newItems) => items.set(newItems),
376
+ * label: (item) => item.name, // screen-reader announcements
314
377
  * })
315
378
  *
316
379
  * <ul ref={containerRef}>
@@ -318,8 +381,8 @@ const _sortableRegistry = /* @__PURE__ */ new Map();
318
381
  * {(item) => (
319
382
  * <li
320
383
  * ref={itemRef(item.id)}
321
- * class={activeId() === item.id ? "dragging" : ""}
322
- * style={overId() === item.id ? `border-${overEdge()}: 2px solid blue` : ""}
384
+ * class={isActive(item.id) ? "dragging" : ""}
385
+ * style={isOverKey(item.id) ? `border-${overEdge()}: 2px solid blue` : ""}
323
386
  * >
324
387
  * {item.name}
325
388
  * </li>
@@ -327,6 +390,11 @@ const _sortableRegistry = /* @__PURE__ */ new Map();
327
390
  * </For>
328
391
  * </ul>
329
392
  * ```
393
+ *
394
+ * Prefer `isActive(key)` / `isOverKey(key)` over `activeId() === key` /
395
+ * `overId() === key` in row templates — the equality read subscribes EVERY
396
+ * row to the id signal (O(N) notifies per change); the selectors notify
397
+ * only the two affected rows (O(2), `createSelector` semantics).
330
398
  */
331
399
  function useSortable(options) {
332
400
  if (isServer) {
@@ -334,17 +402,32 @@ function useSortable(options) {
334
402
  return {
335
403
  containerRef: noop,
336
404
  itemRef: () => noop,
405
+ itemHandleRef: () => noop,
337
406
  activeId: () => null,
338
407
  overId: () => null,
339
- overEdge: () => null
408
+ overEdge: () => null,
409
+ isActive: () => false,
410
+ isOverKey: () => false
340
411
  };
341
412
  }
342
413
  const sortableId = `sortable-${++_sortableCounter}`;
414
+ const instructionsId = `${sortableId}-instructions`;
343
415
  const activeId = signal(null);
344
416
  const overId = signal(null);
345
417
  const overEdge = signal(null);
418
+ const isActiveSelector = createSelector(activeId);
419
+ const isOverSelector = createSelector(overId);
346
420
  const axis = options.axis ?? "vertical";
347
421
  const groupId = options.groupId;
422
+ /** Resolve the announcement label for an item: `label(item)` else the key. */
423
+ function labelOf(item, key) {
424
+ if (item !== void 0 && options.label) return options.label(item);
425
+ return String(key);
426
+ }
427
+ /** Resolve the announcement label for a key by looking the item up. */
428
+ function labelFor(key) {
429
+ return labelOf(options.items().find((i) => options.by(i) === key), key);
430
+ }
348
431
  _sortableRegistry.set(sortableId, {
349
432
  groupId,
350
433
  onCrossListDrop: options.onCrossListDrop
@@ -372,6 +455,12 @@ function useSortable(options) {
372
455
  const insertAt = Math.max(0, Math.min(rawInsert, reordered.length));
373
456
  reordered.splice(insertAt, 0, moved);
374
457
  options.onReorder(reordered);
458
+ announce(`Dropped ${labelOf(moved, dragId)} at position ${insertAt + 1} of ${reordered.length}`);
459
+ }
460
+ /** Announce a cross-list receive on THIS (destination) sortable. */
461
+ function announceCrossListReceive(item, insertAt) {
462
+ const count = Math.max(options.items().length, insertAt + 1);
463
+ announce(`Dropped ${labelOf(item, options.by(item))} at position ${insertAt + 1} of ${count} in the receiving list`);
375
464
  }
376
465
  /** Returns true when `source` belongs to this sortable or to a sibling
377
466
  * in the same `groupId`. */
@@ -387,6 +476,13 @@ function useSortable(options) {
387
476
  }
388
477
  if (!el) return;
389
478
  const containerCleanups = [];
479
+ const instructions = document.createElement("div");
480
+ instructions.id = instructionsId;
481
+ instructions.setAttribute("data-pyreon-sortable-instructions", "");
482
+ instructions.style.cssText = SR_ONLY;
483
+ instructions.textContent = "Press Alt plus arrow keys to reorder";
484
+ el.appendChild(instructions);
485
+ containerCleanups.push(() => instructions.remove());
390
486
  containerCleanups.push(autoScrollForElements({
391
487
  element: el,
392
488
  canScroll: ({ source }) => acceptsSource(source)
@@ -407,6 +503,7 @@ function useSortable(options) {
407
503
  const targetIndex = options.items().length;
408
504
  options.onCrossListReceive(item, targetIndex);
409
505
  _sortableRegistry.get(sourceSortableId)?.onCrossListDrop?.(item);
506
+ announceCrossListReceive(item, targetIndex);
410
507
  }
411
508
  batch(() => {
412
509
  activeId.set(null);
@@ -436,6 +533,7 @@ function useSortable(options) {
436
533
  reordered[currentIndex] = reordered[targetIndex];
437
534
  reordered[targetIndex] = temp;
438
535
  options.onReorder(reordered);
536
+ announce(`Moved ${labelOf(temp, focusedKey)} to position ${targetIndex + 1} of ${currentItems.length}`);
439
537
  requestAnimationFrame(() => {
440
538
  const items = el.querySelectorAll("[data-pyreon-sort-key]");
441
539
  for (const item of items) if (item.dataset.pyreonSortKey === focusedKey) {
@@ -450,6 +548,8 @@ function useSortable(options) {
450
548
  for (const fn of containerCleanups) fn();
451
549
  };
452
550
  }
551
+ const itemEls = /* @__PURE__ */ new Map();
552
+ const itemHandles = /* @__PURE__ */ new Map();
453
553
  function itemRef(key) {
454
554
  return (el) => {
455
555
  const prev = itemCleanups.get(key);
@@ -457,76 +557,110 @@ function useSortable(options) {
457
557
  prev();
458
558
  itemCleanups.delete(key);
459
559
  }
460
- if (!el) return;
461
- el.dataset.pyreonSortKey = String(key);
462
- if (!el.hasAttribute("tabindex")) el.setAttribute("tabindex", "0");
463
- el.setAttribute("role", "listitem");
464
- el.setAttribute("aria-roledescription", "sortable item");
465
- const allowedEdges = axis === "vertical" ? ["top", "bottom"] : ["left", "right"];
466
- const cleanup = combine(draggable({
467
- element: el,
468
- getInitialData: () => {
469
- const item = options.items().find((i) => options.by(i) === key);
470
- return {
471
- [SORT_KEY]: key,
472
- [SORT_ID]: sortableId,
473
- [SORT_GROUP]: groupId,
474
- [SORT_PAYLOAD]: groupId ? item : void 0
475
- };
476
- },
477
- onDragStart: () => activeId.set(key),
478
- onDrop: () => {
479
- queueMicrotask(() => {
480
- batch(() => {
481
- activeId.set(null);
482
- overId.set(null);
483
- overEdge.set(null);
484
- });
485
- });
486
- }
487
- }), dropTargetForElements({
488
- element: el,
489
- getData: ({ input, element }) => attachClosestEdge({
560
+ if (!el) {
561
+ itemEls.delete(key);
562
+ return;
563
+ }
564
+ itemEls.set(key, el);
565
+ registerItem(key, el);
566
+ };
567
+ }
568
+ /**
569
+ * OPTIONAL drag-handle registrar mirroring `itemRef`. When a handle is
570
+ * (un)registered for an already-mounted item, the item's pdnd
571
+ * registration is torn down and re-created so `dragHandle` takes
572
+ * effect — pdnd captures the handle at registration time.
573
+ */
574
+ function itemHandleRef(key) {
575
+ return (el) => {
576
+ if (el) itemHandles.set(key, el);
577
+ else itemHandles.delete(key);
578
+ const itemEl = itemEls.get(key);
579
+ if (!itemEl) return;
580
+ /* v8 ignore next — defensive optional call; a live itemEl implies a live cleanup */
581
+ itemCleanups.get(key)?.();
582
+ itemCleanups.delete(key);
583
+ registerItem(key, itemEl);
584
+ };
585
+ }
586
+ function registerItem(key, el) {
587
+ el.dataset.pyreonSortKey = String(key);
588
+ if (!el.hasAttribute("tabindex")) el.setAttribute("tabindex", "0");
589
+ el.setAttribute("role", "listitem");
590
+ el.setAttribute("aria-roledescription", "sortable item");
591
+ if (!el.hasAttribute("aria-describedby")) el.setAttribute("aria-describedby", instructionsId);
592
+ const allowedEdges = axis === "vertical" ? ["top", "bottom"] : ["left", "right"];
593
+ const handle = itemHandles.get(key);
594
+ const cleanup = combine(draggable({
595
+ element: el,
596
+ ...handle ? { dragHandle: handle } : {},
597
+ getInitialData: () => {
598
+ const item = options.items().find((i) => options.by(i) === key);
599
+ return {
490
600
  [SORT_KEY]: key,
491
601
  [SORT_ID]: sortableId,
492
- [SORT_GROUP]: groupId
493
- }, {
494
- input,
495
- element,
496
- allowedEdges
497
- }),
498
- canDrop: ({ source }) => acceptsSource(source),
499
- onDragEnter: ({ self }) => {
500
- overId.set(key);
501
- overEdge.set(extractClosestEdge(self.data));
502
- },
503
- onDrag: ({ self }) => {
504
- overEdge.set(extractClosestEdge(self.data));
505
- },
506
- onDragLeave: () => {
507
- if (overId.peek() === key) {
602
+ [SORT_GROUP]: groupId,
603
+ [SORT_PAYLOAD]: groupId ? item : void 0
604
+ };
605
+ },
606
+ onDragStart: () => {
607
+ activeId.set(key);
608
+ announce(`Picked up ${labelFor(key)}`);
609
+ },
610
+ onDrop: () => {
611
+ queueMicrotask(() => {
612
+ batch(() => {
613
+ activeId.set(null);
508
614
  overId.set(null);
509
615
  overEdge.set(null);
510
- }
511
- },
512
- onDrop: ({ source, self }) => {
513
- if (source.data[SORT_ID] === sortableId) return;
514
- if (!groupId || source.data[SORT_GROUP] !== groupId || !options.onCrossListReceive) return;
515
- const item = source.data[SORT_PAYLOAD];
516
- const edge = extractClosestEdge(self.data);
517
- const targetIndex = options.items().findIndex((i) => options.by(i) === key);
518
- /* v8 ignore next — defensive findIndex guard */
519
- if (targetIndex === -1) return;
520
- /* v8 ignore next 4 — ternary combinatorics */
521
- const insertAt = edge === "bottom" || edge === "right" ? targetIndex + 1 : Math.max(0, targetIndex);
522
- options.onCrossListReceive(item, insertAt);
523
- const sourceSortableId = source.data[SORT_ID];
524
- _sortableRegistry.get(sourceSortableId)?.onCrossListDrop?.(item);
525
- source.data.__pyreon_sortable_handled = true;
526
- }
527
- }));
528
- itemCleanups.set(key, cleanup);
529
- };
616
+ });
617
+ });
618
+ }
619
+ }), dropTargetForElements({
620
+ element: el,
621
+ getData: ({ input, element }) => attachClosestEdge({
622
+ [SORT_KEY]: key,
623
+ [SORT_ID]: sortableId,
624
+ [SORT_GROUP]: groupId
625
+ }, {
626
+ input,
627
+ element,
628
+ allowedEdges
629
+ }),
630
+ canDrop: ({ source }) => acceptsSource(source),
631
+ onDragEnter: ({ self }) => {
632
+ batch(() => {
633
+ overId.set(key);
634
+ overEdge.set(extractClosestEdge(self.data));
635
+ });
636
+ },
637
+ onDrag: ({ self }) => {
638
+ overEdge.set(extractClosestEdge(self.data));
639
+ },
640
+ onDragLeave: () => {
641
+ if (overId.peek() === key) batch(() => {
642
+ overId.set(null);
643
+ overEdge.set(null);
644
+ });
645
+ },
646
+ onDrop: ({ source, self }) => {
647
+ if (source.data[SORT_ID] === sortableId) return;
648
+ if (!groupId || source.data[SORT_GROUP] !== groupId || !options.onCrossListReceive) return;
649
+ const item = source.data[SORT_PAYLOAD];
650
+ const edge = extractClosestEdge(self.data);
651
+ const targetIndex = options.items().findIndex((i) => options.by(i) === key);
652
+ /* v8 ignore next — defensive findIndex guard */
653
+ if (targetIndex === -1) return;
654
+ /* v8 ignore next 4 — ternary combinatorics */
655
+ const insertAt = edge === "bottom" || edge === "right" ? targetIndex + 1 : Math.max(0, targetIndex);
656
+ options.onCrossListReceive(item, insertAt);
657
+ const sourceSortableId = source.data[SORT_ID];
658
+ _sortableRegistry.get(sourceSortableId)?.onCrossListDrop?.(item);
659
+ announceCrossListReceive(item, insertAt);
660
+ source.data.__pyreon_sortable_handled = true;
661
+ }
662
+ }));
663
+ itemCleanups.set(key, cleanup);
530
664
  }
531
665
  onCleanup(() => {
532
666
  if (containerCleanup) {
@@ -535,7 +669,11 @@ function useSortable(options) {
535
669
  }
536
670
  for (const cleanup of itemCleanups.values()) cleanup();
537
671
  itemCleanups.clear();
672
+ itemEls.clear();
673
+ itemHandles.clear();
538
674
  _sortableRegistry.delete(sortableId);
675
+ isActiveSelector.dispose();
676
+ isOverSelector.dispose();
539
677
  batch(() => {
540
678
  activeId.set(null);
541
679
  overId.set(null);
@@ -545,9 +683,12 @@ function useSortable(options) {
545
683
  return {
546
684
  containerRef,
547
685
  itemRef,
686
+ itemHandleRef,
548
687
  activeId,
549
688
  overId,
550
- overEdge
689
+ overEdge,
690
+ isActive: (key) => isActiveSelector(key),
691
+ isOverKey: (key) => isOverSelector(key)
551
692
  };
552
693
  }
553
694
 
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["__pkgName","__pkgVersion"],"sources":["../package.json","../src/use-drag-monitor.ts","../src/use-draggable.ts","../src/use-droppable.ts","../src/use-file-drop.ts","../src/use-sortable.ts","../src/index.ts"],"sourcesContent":["","import { monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData } from './types'\n\nexport interface UseDragMonitorOptions {\n /** Called on any drag start in the page. */\n onDragStart?: (data: DragData) => void\n /** Called on any drop in the page. */\n onDrop?: (sourceData: DragData, targetData: DragData) => void\n /** Filter which drags to monitor. */\n canMonitor?: (data: DragData) => boolean\n}\n\nexport interface UseDragMonitorResult {\n /** Whether any element is currently being dragged. */\n isDragging: () => boolean\n /** Data of the currently dragging element (null if not dragging). */\n dragData: () => DragData | null\n}\n\n/**\n * Monitor all drag operations on the page.\n * Useful for global drag indicators, analytics, or coordination between\n * multiple drag-and-drop areas.\n *\n * @example\n * ```tsx\n * const { isDragging, dragData } = useDragMonitor({\n * canMonitor: (data) => data.type === \"card\",\n * onDrop: (source, target) => logDrop(source, target),\n * })\n *\n * <Show when={isDragging()}>\n * <div class=\"global-drag-overlay\">\n * Dragging: {() => dragData()?.name}\n * </div>\n * </Show>\n * ```\n */\nexport function useDragMonitor(options?: UseDragMonitorOptions): UseDragMonitorResult {\n if (isServer) return { isDragging: () => false, dragData: () => null }\n\n const isDragging = signal(false)\n const dragData = signal<DragData | null>(null)\n\n /* v8 ignore next 4 — opt-in canMonitor predicate; both arms structurally exercised but counted as one */\n const canMonitorFn = options?.canMonitor\n ? ({ source }: { source: { data: Record<string, unknown> } }) =>\n options.canMonitor?.(source.data as DragData) ?? true\n : null\n\n const cleanup = monitorForElements({\n ...(canMonitorFn ? { canMonitor: canMonitorFn } : {}),\n onDragStart: ({ source }) => {\n // batch() so subscribers to isDragging + dragData get notified once,\n // not twice. Drag events fire frequently; doubling subscriber work\n // per event compounds visibly on UIs with many drag-monitor consumers.\n batch(() => {\n isDragging.set(true)\n dragData.set(source.data as DragData)\n })\n options?.onDragStart?.(source.data as DragData)\n },\n onDrop: ({ source, location }) => {\n batch(() => {\n isDragging.set(false)\n dragData.set(null)\n })\n const targetData = location.current.dropTargets[0]?.data ?? {}\n options?.onDrop?.(source.data as DragData, targetData as DragData)\n },\n })\n\n onCleanup(cleanup)\n\n return { isDragging, dragData }\n}\n","import { draggable } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData, UseDraggableOptions, UseDraggableResult } from './types'\n\n/**\n * Make an element draggable with signal-driven state.\n *\n * @example\n * ```tsx\n * let cardEl: HTMLElement | null = null\n *\n * const { isDragging } = useDraggable({\n * element: () => cardEl,\n * data: { id: card.id, type: \"card\" },\n * })\n *\n * <div ref={(el) => cardEl = el} class={isDragging() ? \"opacity-50\" : \"\"}>\n * {card.title}\n * </div>\n * ```\n */\nexport function useDraggable<T extends DragData = DragData>(\n options: UseDraggableOptions<T>,\n): UseDraggableResult {\n if (isServer) return { isDragging: () => false }\n\n const isDragging = signal(false)\n let cleanup: (() => void) | undefined\n let disposed = false\n\n function setup() {\n // The hook may have unmounted before this deferred (queueMicrotask) setup\n // ran. onCleanup fired with `cleanup` still undefined (a no-op), so a\n // registration created here would never be torn down — bail instead.\n /* v8 ignore next — defensive disposed-during-setup guard; tested implicitly via lifecycle */\n if (disposed) return\n // Defensive re-setup teardown: `setup` is scheduled exactly once\n // (`queueMicrotask(setup)`) and never re-invoked, so `cleanup` is always\n // undefined here — this branch never fires in the current single-shot\n // design. Kept so a future re-setup trigger (element-change re-registration)\n // can't leak a double registration.\n /* v8 ignore next — defensive re-setup teardown; unreachable with single-shot queueMicrotask */\n if (cleanup) cleanup()\n\n const el = options.element()\n if (!el) return\n\n const resolveData = () =>\n typeof options.data === 'function' ? (options.data as () => T)() : options.data\n\n const handle = options.handle?.()\n cleanup = draggable({\n element: el,\n ...(handle ? { dragHandle: handle } : {}),\n getInitialData: resolveData,\n canDrag: () => {\n const disabled = options.disabled\n if (typeof disabled === 'function') return !disabled()\n return !disabled\n },\n onDragStart: () => {\n isDragging.set(true)\n options.onDragStart?.()\n },\n onDrop: () => {\n isDragging.set(false)\n options.onDragEnd?.()\n },\n })\n }\n\n // Defer setup to next microtask so refs are populated\n queueMicrotask(setup)\n\n onCleanup(() => {\n disposed = true\n if (cleanup) cleanup()\n })\n\n return { isDragging }\n}\n","import { dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData, UseDroppableOptions, UseDroppableResult } from './types'\n\n/**\n * Make an element a drop target with signal-driven state.\n *\n * @example\n * ```tsx\n * let zoneEl: HTMLElement | null = null\n *\n * const { isOver } = useDroppable({\n * element: () => zoneEl,\n * onDrop: (data) => handleDrop(data),\n * canDrop: (data) => data.type === \"card\",\n * })\n *\n * <div ref={(el) => zoneEl = el} class={isOver() ? \"bg-blue-50\" : \"\"}>\n * Drop here\n * </div>\n * ```\n */\nexport function useDroppable<T extends DragData = DragData>(\n options: UseDroppableOptions<T>,\n): UseDroppableResult {\n if (isServer) return { isOver: () => false }\n\n const isOver = signal(false)\n let cleanup: (() => void) | undefined\n let disposed = false\n\n function setup() {\n // Unmounted before this deferred setup ran — don't register a target that\n // onCleanup (already fired with `cleanup` undefined) can never tear down.\n /* v8 ignore next — defensive disposed-during-setup guard */\n if (disposed) return\n // Defensive re-setup teardown: `setup` runs exactly once\n // (`queueMicrotask(setup)`, never re-invoked), so `cleanup` is always\n // undefined here — this branch never fires in the current single-shot\n // design. Kept so a future re-setup trigger can't leak a double target.\n /* v8 ignore next — defensive re-setup teardown; unreachable with single-shot queueMicrotask */\n if (cleanup) cleanup()\n\n const el = options.element()\n if (!el) return\n\n cleanup = dropTargetForElements({\n element: el,\n getData: () => {\n if (!options.data) return {}\n return typeof options.data === 'function' ? (options.data as () => T)() : options.data\n },\n canDrop: ({ source }) => {\n if (!options.canDrop) return true\n return options.canDrop(source.data as DragData)\n },\n onDragEnter: ({ source }) => {\n isOver.set(true)\n options.onDragEnter?.(source.data as DragData)\n },\n onDragLeave: () => {\n isOver.set(false)\n options.onDragLeave?.()\n },\n onDrop: ({ source }) => {\n isOver.set(false)\n options.onDrop?.(source.data as DragData)\n },\n })\n }\n\n queueMicrotask(setup)\n\n onCleanup(() => {\n disposed = true\n if (cleanup) cleanup()\n })\n\n return { isOver }\n}\n","import {\n dropTargetForExternal,\n monitorForExternal,\n} from '@atlaskit/pragmatic-drag-and-drop/external/adapter'\nimport { containsFiles, getFiles } from '@atlaskit/pragmatic-drag-and-drop/external/file'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\n\nexport interface UseFileDropOptions {\n /** Element getter for the drop zone. */\n element: () => HTMLElement | null\n /** Called when files are dropped. */\n onDrop: (files: File[]) => void\n /** Filter accepted file types (e.g. [\"image/*\", \".pdf\"]). */\n accept?: string[]\n /** Maximum number of files. */\n maxFiles?: number\n /** Whether drop is disabled. */\n disabled?: boolean | (() => boolean)\n}\n\nexport interface UseFileDropResult {\n /** Whether files are being dragged over the drop zone. */\n isOver: () => boolean\n /** Whether files are being dragged anywhere on the page. */\n isDraggingFiles: () => boolean\n}\n\n/**\n * File drop zone with signal-driven state.\n * Uses the native file drag events via pragmatic-drag-and-drop.\n *\n * @example\n * ```tsx\n * let dropZone: HTMLElement | null = null\n *\n * const { isOver, isDraggingFiles } = useFileDrop({\n * element: () => dropZone,\n * accept: [\"image/*\", \".pdf\"],\n * maxFiles: 5,\n * onDrop: (files) => upload(files),\n * })\n *\n * <div\n * ref={(el) => dropZone = el}\n * class={isOver() ? \"drop-active\" : isDraggingFiles() ? \"drop-ready\" : \"\"}\n * >\n * Drop files here\n * </div>\n * ```\n */\nexport function useFileDrop(options: UseFileDropOptions): UseFileDropResult {\n if (isServer) return { isOver: () => false, isDraggingFiles: () => false }\n\n const isOver = signal(false)\n const isDraggingFiles = signal(false)\n let cleanup: (() => void) | undefined\n let disposed = false\n\n function matchesAccept(file: File, accept: string[]): boolean {\n return accept.some((pattern) => {\n if (pattern.startsWith('.')) {\n return file.name.toLowerCase().endsWith(pattern.toLowerCase())\n }\n if (pattern.endsWith('/*')) {\n return file.type.startsWith(pattern.slice(0, -1))\n }\n return file.type === pattern\n })\n }\n\n function setup() {\n // Unmounted before this deferred setup ran — don't register a drop target\n // that onCleanup (already fired with `cleanup` undefined) can never remove.\n /* v8 ignore next — defensive disposed-during-setup guard */\n if (disposed) return\n if (cleanup) cleanup()\n\n const el = options.element()\n if (!el) return\n\n const cleanups: (() => void)[] = []\n\n // Monitor for file drags anywhere on the page\n cleanups.push(\n monitorForExternal({\n canMonitor: ({ source }) => containsFiles({ source }),\n onDragStart: () => isDraggingFiles.set(true),\n onDrop: () => isDraggingFiles.set(false),\n }),\n )\n\n // Drop target on the specific element\n cleanups.push(\n dropTargetForExternal({\n element: el,\n canDrop: ({ source }) => {\n const disabled = options.disabled\n if (typeof disabled === 'function' ? disabled() : disabled) return false\n return containsFiles({ source })\n },\n onDragEnter: () => isOver.set(true),\n onDragLeave: () => isOver.set(false),\n onDrop: ({ source }) => {\n // batch() so onDrop subscribers don't get notified twice\n // (isOver + isDraggingFiles) per file-drop event.\n batch(() => {\n isOver.set(false)\n isDraggingFiles.set(false)\n })\n\n let files = getFiles({ source })\n\n // Filter by accept\n if (options.accept && options.accept.length > 0) {\n files = files.filter((f) => matchesAccept(f, options.accept as string[]))\n }\n\n // Limit count\n if (options.maxFiles && files.length > options.maxFiles) {\n files = files.slice(0, options.maxFiles)\n }\n\n if (files.length > 0) {\n options.onDrop(files)\n }\n },\n }),\n )\n\n cleanup = () => {\n for (const fn of cleanups) fn()\n }\n }\n\n queueMicrotask(setup)\n\n onCleanup(() => {\n disposed = true\n if (cleanup) cleanup()\n })\n\n return { isOver, isDraggingFiles }\n}\n","import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'\nimport { draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { autoScrollForElements } from '@atlaskit/pragmatic-drag-and-drop-auto-scroll/element'\nimport {\n attachClosestEdge,\n type Edge,\n extractClosestEdge,\n} from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DropEdge, UseSortableOptions, UseSortableResult } from './types'\n\nconst SORT_KEY = '__pyreon_sortable_key'\nconst SORT_ID = '__pyreon_sortable_id'\nconst SORT_GROUP = '__pyreon_sortable_group'\nconst SORT_PAYLOAD = '__pyreon_sortable_payload'\n\nlet _sortableCounter = 0\n\n// Module-level registry of live sortable instances — used to dispatch\n// cross-list drop notifications from the destination back to the source\n// (W18). Keyed by sortableId.\nconst _sortableRegistry = new Map<\n string,\n {\n groupId: string | undefined\n onCrossListDrop: ((item: unknown) => void) | undefined\n }\n>()\n\n/**\n * Sortable list with signal-driven state, auto-scroll, and edge detection.\n *\n * Features:\n * - Keyed drag items matching `<For by={...}>` pattern\n * - Auto-scroll when dragging near container edges\n * - Closest-edge detection (drop above/below or left/right)\n * - Axis constraint (vertical/horizontal)\n * - Keyboard reordering (Alt+Arrow keys)\n * - Optional cross-list `groupId` for Trello/Notion/Linear board layouts\n * (W18) — share the same `groupId` between two\n * sortable instances and items can be dragged between them. The\n * source's `onCrossListDrop(item)` removes; the destination's\n * `onCrossListReceive(item, index)` inserts.\n *\n * @example\n * ```tsx\n * const items = signal([\n * { id: \"1\", name: \"Alice\" },\n * { id: \"2\", name: \"Bob\" },\n * { id: \"3\", name: \"Charlie\" },\n * ])\n *\n * const { containerRef, itemRef, activeId, overId, overEdge } = useSortable({\n * items,\n * by: (item) => item.id,\n * onReorder: (newItems) => items.set(newItems),\n * })\n *\n * <ul ref={containerRef}>\n * <For each={items()} by={item => item.id}>\n * {(item) => (\n * <li\n * ref={itemRef(item.id)}\n * class={activeId() === item.id ? \"dragging\" : \"\"}\n * style={overId() === item.id ? `border-${overEdge()}: 2px solid blue` : \"\"}\n * >\n * {item.name}\n * </li>\n * )}\n * </For>\n * </ul>\n * ```\n */\nexport function useSortable<T>(options: UseSortableOptions<T>): UseSortableResult {\n if (isServer) {\n const noop = (_el: HTMLElement | null) => {}\n return {\n containerRef: noop,\n itemRef: () => noop,\n activeId: () => null,\n overId: () => null,\n overEdge: () => null,\n }\n }\n\n const sortableId = `sortable-${++_sortableCounter}`\n const activeId = signal<string | number | null>(null)\n const overId = signal<string | number | null>(null)\n const overEdge = signal<DropEdge | null>(null)\n const axis = options.axis ?? 'vertical'\n const groupId = options.groupId\n\n // Register so siblings in the same group can call our onCrossListDrop\n // when they receive one of our items.\n _sortableRegistry.set(sortableId, {\n groupId,\n onCrossListDrop: options.onCrossListDrop as ((item: unknown) => void) | undefined,\n })\n\n // Container-level pdnd teardown (auto-scroll + reorder drop-target + the\n // keydown listener). A SINGLE disposer, replaced on re-register and cleared\n // on unmount — symmetric with the per-item map below. A collapsible board\n // whose `<ul ref={containerRef}>` sits behind a `<Show>` (with the hook in\n // the parent) re-fires `containerRef` on every toggle; without disposal each\n // toggle leaked the auto-scroll + drop-target + keydown listener on the now-\n // detached element (the container sibling of the F3 per-item leak).\n let containerCleanup: (() => void) | undefined\n // Per-item pdnd cleanups, keyed by sort key. Disposed individually on\n // item unmount / re-register so a churning list doesn't accumulate\n // dead registrations for the sortable's whole lifetime.\n const itemCleanups = new Map<string | number, () => void>()\n\n /** Perform the reorder based on current active/over/edge state. */\n function performReorder() {\n const dragId = activeId.peek()\n const dropId = overId.peek()\n const edge = overEdge.peek()\n /* v8 ignore next — defensive null/equal id guards */\n if (dragId == null || dropId == null || dragId === dropId) return\n\n const currentItems = options.items()\n const dragIndex = currentItems.findIndex((item) => options.by(item) === dragId)\n const dropIndex = currentItems.findIndex((item) => options.by(item) === dropId)\n /* v8 ignore next — defensive findIndex-not-found guards; ids come from active drag */\n if (dragIndex === -1 || dropIndex === -1) return\n\n const reordered = [...currentItems]\n const [moved] = reordered.splice(dragIndex, 1)\n /* v8 ignore next — defensive splice fallback; dragIndex was just verified */\n if (!moved) return\n\n // Determine insert position based on closest edge\n /* v8 ignore next 7 — ternary combinatorics; structurally exercised in browser e2e but not unit-coverable per arm */\n const rawInsert =\n edge === 'bottom' || edge === 'right'\n ? dropIndex >= dragIndex\n ? dropIndex\n : dropIndex + 1\n : dropIndex <= dragIndex\n ? dropIndex\n : dropIndex - 1\n const insertAt = Math.max(0, Math.min(rawInsert, reordered.length))\n\n reordered.splice(insertAt, 0, moved)\n options.onReorder(reordered)\n }\n\n /** Returns true when `source` belongs to this sortable or to a sibling\n * in the same `groupId`. */\n function acceptsSource(source: { data: Record<string, unknown> }): boolean {\n if (source.data[SORT_ID] === sortableId) return true\n if (groupId && source.data[SORT_GROUP] === groupId) return true\n return false\n }\n\n function containerRef(el: HTMLElement | null) {\n // Dispose the prior container registration on BOTH unmount (el === null,\n // fired by Pyreon's runtime) AND re-register (a new container element) so\n // a toggled/re-mounted container can't leak its auto-scroll + drop-target +\n // keydown listener. Symmetric with the per-item disposal below (F3).\n if (containerCleanup) {\n containerCleanup()\n containerCleanup = undefined\n }\n if (!el) return\n\n const containerCleanups: (() => void)[] = []\n // Auto-scroll when dragging near container edges\n containerCleanups.push(\n autoScrollForElements({\n element: el,\n canScroll: ({ source }) => acceptsSource(source),\n }),\n )\n\n // Container is a drop target for reorder finalization OR for\n // appending a cross-list item at the end of this column.\n containerCleanups.push(\n dropTargetForElements({\n element: el,\n getData: () => ({ [SORT_ID]: sortableId, [SORT_GROUP]: groupId }),\n canDrop: ({ source }) => acceptsSource(source),\n onDrop: ({ source }) => {\n // Item-level dropTarget for cross-list drops marks the source\n // data as handled — container skips so we don't insert twice.\n const handled = (source.data as Record<string, unknown>)\n .__pyreon_sortable_handled\n if (source.data[SORT_ID] === sortableId) {\n // Same-list drop on container edge → reorder finalization.\n performReorder()\n } else if (\n !handled &&\n groupId &&\n source.data[SORT_GROUP] === groupId &&\n options.onCrossListReceive\n ) {\n // Cross-list drop on the container itself (not on an item) →\n // append to the end of this column.\n const item = source.data[SORT_PAYLOAD] as T\n const sourceSortableId = source.data[SORT_ID] as string\n const targetIndex = options.items().length\n options.onCrossListReceive(item, targetIndex)\n const sourceInstance = _sortableRegistry.get(sourceSortableId)\n sourceInstance?.onCrossListDrop?.(item)\n }\n // batch() the 3-signal reset so subscribers reading any of\n // activeId/overId/overEdge get notified once per drop, not\n // three times. Fires on every container-level drop.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n },\n }),\n )\n\n // Keyboard reordering: Alt+Arrow keys\n const keyHandler = (e: KeyboardEvent) => {\n if (!e.altKey) return\n\n const isUp = axis === 'vertical' ? e.key === 'ArrowUp' : e.key === 'ArrowLeft'\n const isDown = axis === 'vertical' ? e.key === 'ArrowDown' : e.key === 'ArrowRight'\n if (!isUp && !isDown) return\n\n const focused = document.activeElement as HTMLElement | null\n if (!focused || !el.contains(focused)) return\n\n const focusedKey = focused.dataset.pyreonSortKey\n if (!focusedKey) return\n\n e.preventDefault()\n\n const currentItems = options.items()\n const currentIndex = currentItems.findIndex((item) => String(options.by(item)) === focusedKey)\n /* v8 ignore next — defensive findIndex guard; focusedKey is from active item */\n if (currentIndex === -1) return\n\n const targetIndex = isUp ? currentIndex - 1 : currentIndex + 1\n if (targetIndex < 0 || targetIndex >= currentItems.length) return\n\n const reordered = [...currentItems]\n const temp = reordered[currentIndex]\n reordered[currentIndex] = reordered[targetIndex] as T\n reordered[targetIndex] = temp as T\n options.onReorder(reordered)\n\n // Restore focus after DOM update\n requestAnimationFrame(() => {\n const items = el.querySelectorAll('[data-pyreon-sort-key]')\n for (const item of items) {\n if ((item as HTMLElement).dataset.pyreonSortKey === focusedKey) {\n ;(item as HTMLElement).focus()\n break\n }\n }\n })\n }\n\n el.addEventListener('keydown', keyHandler)\n containerCleanups.push(() => el.removeEventListener('keydown', keyHandler))\n\n containerCleanup = () => {\n for (const fn of containerCleanups) fn()\n }\n }\n\n function itemRef(key: string | number): (el: HTMLElement | null) => void {\n return (el: HTMLElement | null) => {\n // Per-key disposal. The ref fires with the element on mount and\n // with `null` on unmount. The old code pushed every registration\n // onto the shared `cleanups[]` and made the null branch a pure\n // no-op — so for a `<For>`-rendered sortable (the documented usage:\n // todo list / kanban) every removed item's pdnd `draggable` /\n // `dropTargetForElements` registration (and its pointer/drag\n // listeners on the now-detached node) leaked until the WHOLE\n // sortable unmounted. Dispose the prior registration for this key\n // on BOTH unmount (el === null) and re-registration (same key,\n // new element) so the live set tracks live items, not all-ever.\n const prev = itemCleanups.get(key)\n if (prev) {\n prev()\n itemCleanups.delete(key)\n }\n if (!el) return\n el.dataset.pyreonSortKey = String(key)\n if (!el.hasAttribute('tabindex')) el.setAttribute('tabindex', '0')\n el.setAttribute('role', 'listitem')\n el.setAttribute('aria-roledescription', 'sortable item')\n\n const allowedEdges: Edge[] = axis === 'vertical' ? ['top', 'bottom'] : ['left', 'right']\n\n const cleanup = combine(\n draggable({\n element: el,\n getInitialData: () => {\n const currentItems = options.items()\n const item = currentItems.find((i) => options.by(i) === key)\n return {\n [SORT_KEY]: key,\n [SORT_ID]: sortableId,\n [SORT_GROUP]: groupId,\n // Carry the actual item value when groupId is set so a\n // sibling sortable's onDrop can receive it without a\n // separate registry lookup. Plain reference (pdnd doesn't\n // serialize) — safe within a single document.\n [SORT_PAYLOAD]: groupId ? item : undefined,\n }\n },\n onDragStart: () => activeId.set(key),\n onDrop: () => {\n queueMicrotask(() => {\n // batch() — same 3-signal reset shape as the container\n // onDrop above. Per-item drops fire this branch.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n })\n },\n }),\n dropTargetForElements({\n element: el,\n getData: ({ input, element }) =>\n attachClosestEdge(\n { [SORT_KEY]: key, [SORT_ID]: sortableId, [SORT_GROUP]: groupId },\n { input, element, allowedEdges },\n ),\n canDrop: ({ source }) => acceptsSource(source),\n onDragEnter: ({ self }) => {\n overId.set(key)\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n },\n onDrag: ({ self }) => {\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n },\n onDragLeave: () => {\n if (overId.peek() === key) {\n overId.set(null)\n overEdge.set(null)\n }\n },\n onDrop: ({ source, self }) => {\n // Same-list drops are handled by the container's onDrop via\n // performReorder. Item-level onDrop fires for cross-list\n // shapes — insert at THIS item's index, then propagate to\n // the source to remove.\n if (source.data[SORT_ID] === sortableId) return\n if (\n !groupId ||\n source.data[SORT_GROUP] !== groupId ||\n !options.onCrossListReceive\n ) {\n return\n }\n const item = source.data[SORT_PAYLOAD] as T\n const edge = extractClosestEdge(self.data) as DropEdge | null\n const currentItems = options.items()\n const targetIndex = currentItems.findIndex(\n (i) => options.by(i) === key,\n )\n /* v8 ignore next — defensive findIndex guard */\n if (targetIndex === -1) return\n /* v8 ignore next 4 — ternary combinatorics */\n const insertAt =\n edge === 'bottom' || edge === 'right'\n ? targetIndex + 1\n : Math.max(0, targetIndex)\n options.onCrossListReceive(item, insertAt)\n const sourceSortableId = source.data[SORT_ID] as string\n const sourceInstance = _sortableRegistry.get(sourceSortableId)\n sourceInstance?.onCrossListDrop?.(item)\n // Mark so the container's onDrop (which also fires) skips\n // re-inserting at the end of the list.\n ;(source.data as Record<string, unknown>).__pyreon_sortable_handled =\n true\n },\n }),\n )\n\n itemCleanups.set(key, cleanup)\n }\n }\n\n onCleanup(() => {\n // Drain the live container registration (idempotent — containerRef(null)\n // may already have cleared it) plus every per-item registration.\n if (containerCleanup) {\n containerCleanup()\n containerCleanup = undefined\n }\n for (const cleanup of itemCleanups.values()) cleanup()\n itemCleanups.clear()\n _sortableRegistry.delete(sortableId)\n // batch() the final 3-signal reset so any subscriber that survives\n // the dispose order (unusual but possible — e.g. an external store\n // holding refs) sees one notify, not three.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n })\n\n return { containerRef, itemRef, activeId, overId, overEdge }\n}\n","import { name as __pkgName, version as __pkgVersion } from '../package.json' with { type: 'json' }\nimport { registerSingleton } from '@pyreon/reactivity'\n\n// Singleton sentinel — fail-loud detection of duplicate @pyreon/dnd\n// instances in the same heap. See @pyreon/reactivity/singleton-sentinel for\n// full rationale. Hardcoded version is acceptable here — it's a diagnostic\n// aid, not a load-bearing identity check.\nregisterSingleton(__pkgName, __pkgVersion, import.meta.url)\n\nexport type {\n DragData,\n DropEdge,\n DropLocation,\n UseDraggableOptions,\n UseDraggableResult,\n UseDroppableOptions,\n UseDroppableResult,\n UseSortableOptions,\n UseSortableResult,\n} from './types'\n\nexport type { UseDragMonitorOptions, UseDragMonitorResult } from './use-drag-monitor'\nexport { useDragMonitor } from './use-drag-monitor'\n\nexport { useDraggable } from './use-draggable'\nexport { useDroppable } from './use-droppable'\nexport type { UseFileDropOptions, UseFileDropResult } from './use-file-drop'\nexport { useFileDrop } from './use-file-drop'\nexport { useSortable } from './use-sortable'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuCA,SAAgB,eAAe,SAAuD;CACpF,IAAI,UAAU,OAAO;EAAE,kBAAkB;EAAO,gBAAgB;CAAK;CAErE,MAAM,aAAa,OAAO,KAAK;CAC/B,MAAM,WAAW,OAAwB,IAAI;;CAG7C,MAAM,eAAe,SAAS,cACzB,EAAE,aACD,QAAQ,aAAa,OAAO,IAAgB,KAAK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E,CAAC,WACD,OAAO,KAAK,gBAAgB,WAC5B,CAAC,QAAQ,oBAET;KAEF,MAAM,OAAO,OAAO,KAAK;KACzB,MAAM,OAAO,mBAAmB,KAAK,IAAI;KAEzC,MAAM,cADe,QAAQ,MACE,CAAC,CAAC,WAC9B,MAAM,QAAQ,GAAG,CAAC,MAAM,GAC3B;;KAEA,IAAI,gBAAgB,IAAI;;KAExB,MAAM,WACJ,SAAS,YAAY,SAAS,UAC1B,cAAc,IACd,KAAK,IAAI,GAAG,WAAW;KAC7B,QAAQ,mBAAmB,MAAM,QAAQ;KACzC,MAAM,mBAAmB,OAAO,KAAK;KAErC,AADuB,kBAAkB,IAAI,gBAChC,CAAC,EAAE,kBAAkB,IAAI;KAGrC,AAAC,OAAO,KAAiC,4BACxC;IACJ;GACF,CAAC,CACH;GAEA,aAAa,IAAI,KAAK,OAAO;EAC/B;CACF;CAEA,gBAAgB;EAGd,IAAI,kBAAkB;GACpB,iBAAiB;GACjB,mBAAmB;EACrB;EACA,KAAK,MAAM,WAAW,aAAa,OAAO,GAAG,QAAQ;EACrD,aAAa,MAAM;EACnB,kBAAkB,OAAO,UAAU;EAInC,YAAY;GACV,SAAS,IAAI,IAAI;GACjB,OAAO,IAAI,IAAI;GACf,SAAS,IAAI,IAAI;EACnB,CAAC;CACH,CAAC;CAED,OAAO;EAAE;EAAc;EAAS;EAAU;EAAQ;CAAS;AAC7D;;;;AC/YA,kBAAkBA,MAAWC,SAAc,OAAO,KAAK,GAAG"}
1
+ {"version":3,"file":"index.js","names":["__pkgName","__pkgVersion"],"sources":["../package.json","../src/use-drag-monitor.ts","../src/use-draggable.ts","../src/use-droppable.ts","../src/use-file-drop.ts","../src/use-sortable.ts","../src/index.ts"],"sourcesContent":["","import { monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData } from './types'\n\nexport interface UseDragMonitorOptions {\n /** Called on any drag start in the page. */\n onDragStart?: (data: DragData) => void\n /** Called on any drop in the page. */\n onDrop?: (sourceData: DragData, targetData: DragData) => void\n /** Filter which drags to monitor. */\n canMonitor?: (data: DragData) => boolean\n}\n\nexport interface UseDragMonitorResult {\n /** Whether any element is currently being dragged. */\n isDragging: () => boolean\n /** Data of the currently dragging element (null if not dragging). */\n dragData: () => DragData | null\n}\n\n/**\n * Monitor all drag operations on the page.\n * Useful for global drag indicators, analytics, or coordination between\n * multiple drag-and-drop areas.\n *\n * @example\n * ```tsx\n * const { isDragging, dragData } = useDragMonitor({\n * canMonitor: (data) => data.type === \"card\",\n * onDrop: (source, target) => logDrop(source, target),\n * })\n *\n * <Show when={isDragging()}>\n * <div class=\"global-drag-overlay\">\n * Dragging: {() => dragData()?.name}\n * </div>\n * </Show>\n * ```\n */\nexport function useDragMonitor(options?: UseDragMonitorOptions): UseDragMonitorResult {\n if (isServer) return { isDragging: () => false, dragData: () => null }\n\n const isDragging = signal(false)\n const dragData = signal<DragData | null>(null)\n\n /* v8 ignore next 4 — opt-in canMonitor predicate; both arms structurally exercised but counted as one */\n const canMonitorFn = options?.canMonitor\n ? ({ source }: { source: { data: Record<string, unknown> } }) =>\n options.canMonitor?.(source.data as DragData) ?? true\n : null\n\n const cleanup = monitorForElements({\n ...(canMonitorFn ? { canMonitor: canMonitorFn } : {}),\n onDragStart: ({ source }) => {\n // batch() so subscribers to isDragging + dragData get notified once,\n // not twice. Drag events fire frequently; doubling subscriber work\n // per event compounds visibly on UIs with many drag-monitor consumers.\n batch(() => {\n isDragging.set(true)\n dragData.set(source.data as DragData)\n })\n options?.onDragStart?.(source.data as DragData)\n },\n onDrop: ({ source, location }) => {\n batch(() => {\n isDragging.set(false)\n dragData.set(null)\n })\n const targetData = location.current.dropTargets[0]?.data ?? {}\n options?.onDrop?.(source.data as DragData, targetData as DragData)\n },\n })\n\n onCleanup(cleanup)\n\n return { isDragging, dragData }\n}\n","import { draggable } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { centerUnderPointer } from '@atlaskit/pragmatic-drag-and-drop/element/center-under-pointer'\nimport { pointerOutsideOfPreview } from '@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview'\nimport { preserveOffsetOnSource } from '@atlaskit/pragmatic-drag-and-drop/element/preserve-offset-on-source'\nimport { setCustomNativeDragPreview } from '@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview'\nimport { isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData, DragPreviewOptions, UseDraggableOptions, UseDraggableResult } from './types'\n\n/**\n * Resolve a preview `offset` preset to pdnd's `GetOffsetFn`. Split out so\n * the ternary chain is directly unit-testable; `undefined` keeps the\n * browser default (top-left of the preview under the pointer).\n */\nfunction resolvePreviewOffset(\n offset: DragPreviewOptions['offset'],\n source: { element: HTMLElement },\n input: Parameters<typeof preserveOffsetOnSource>[0]['input'],\n): ReturnType<typeof pointerOutsideOfPreview> | undefined {\n if (offset === 'pointer-outside') return pointerOutsideOfPreview({ x: '16px', y: '8px' })\n if (offset === 'center') return centerUnderPointer\n if (offset === 'preserve-offset') {\n return preserveOffsetOnSource({ element: source.element, input })\n }\n return undefined\n}\n\n/**\n * Make an element draggable with signal-driven state.\n *\n * @example\n * ```tsx\n * let cardEl: HTMLElement | null = null\n *\n * const { isDragging } = useDraggable({\n * element: () => cardEl,\n * data: { id: card.id, type: \"card\" },\n * })\n *\n * <div ref={(el) => cardEl = el} class={isDragging() ? \"opacity-50\" : \"\"}>\n * {card.title}\n * </div>\n * ```\n */\nexport function useDraggable<T extends DragData = DragData>(\n options: UseDraggableOptions<T>,\n): UseDraggableResult {\n if (isServer) return { isDragging: () => false }\n\n const isDragging = signal(false)\n let cleanup: (() => void) | undefined\n let disposed = false\n\n function setup() {\n // The hook may have unmounted before this deferred (queueMicrotask) setup\n // ran. onCleanup fired with `cleanup` still undefined (a no-op), so a\n // registration created here would never be torn down — bail instead.\n /* v8 ignore next — defensive disposed-during-setup guard; tested implicitly via lifecycle */\n if (disposed) return\n // Defensive re-setup teardown: `setup` is scheduled exactly once\n // (`queueMicrotask(setup)`) and never re-invoked, so `cleanup` is always\n // undefined here — this branch never fires in the current single-shot\n // design. Kept so a future re-setup trigger (element-change re-registration)\n // can't leak a double registration.\n /* v8 ignore next — defensive re-setup teardown; unreachable with single-shot queueMicrotask */\n if (cleanup) cleanup()\n\n const el = options.element()\n if (!el) return\n\n const resolveData = () =>\n typeof options.data === 'function' ? (options.data as () => T)() : options.data\n\n const handle = options.handle?.()\n const preview = options.preview\n cleanup = draggable({\n element: el,\n ...(handle ? { dragHandle: handle } : {}),\n // Custom native drag preview — thin pass-through to pdnd's\n // setCustomNativeDragPreview + offset presets. Only wired when the\n // consumer opts in, so the default path is byte-identical.\n ...(preview\n ? {\n onGenerateDragPreview: ({\n nativeSetDragImage,\n source,\n location,\n }: {\n nativeSetDragImage: Parameters<\n typeof setCustomNativeDragPreview\n >[0]['nativeSetDragImage']\n source: { element: HTMLElement }\n location: {\n initial: { input: Parameters<typeof preserveOffsetOnSource>[0]['input'] }\n }\n }) => {\n const getOffset = resolvePreviewOffset(preview.offset, source, location.initial.input)\n setCustomNativeDragPreview({\n render: ({ container }) => preview.render(container),\n nativeSetDragImage,\n ...(getOffset ? { getOffset } : {}),\n })\n },\n }\n : {}),\n getInitialData: resolveData,\n canDrag: () => {\n const disabled = options.disabled\n if (typeof disabled === 'function') return !disabled()\n return !disabled\n },\n onDragStart: () => {\n isDragging.set(true)\n options.onDragStart?.()\n },\n onDrop: () => {\n isDragging.set(false)\n options.onDragEnd?.()\n },\n })\n }\n\n // Defer setup to next microtask so refs are populated\n queueMicrotask(setup)\n\n onCleanup(() => {\n disposed = true\n if (cleanup) cleanup()\n })\n\n return { isDragging }\n}\n","import { dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport {\n attachClosestEdge,\n type Edge,\n extractClosestEdge,\n} from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData, DropEdge, UseDroppableOptions, UseDroppableResult } from './types'\n\n/**\n * Make an element a drop target with signal-driven state.\n *\n * @example\n * ```tsx\n * let zoneEl: HTMLElement | null = null\n *\n * const { isOver, overEdge } = useDroppable({\n * element: () => zoneEl,\n * onDrop: (data) => handleDrop(data),\n * canDrop: (data) => data.type === \"card\",\n * edges: [\"top\", \"bottom\"], // opt-in closest-edge detection\n * })\n *\n * <div ref={(el) => zoneEl = el} class={isOver() ? \"bg-blue-50\" : \"\"}>\n * Drop here\n * </div>\n * ```\n */\nexport function useDroppable<T extends DragData = DragData>(\n options: UseDroppableOptions<T>,\n): UseDroppableResult {\n if (isServer) return { isOver: () => false, overEdge: () => null }\n\n const isOver = signal(false)\n const overEdge = signal<DropEdge | null>(null)\n let cleanup: (() => void) | undefined\n let disposed = false\n\n function setup() {\n // Unmounted before this deferred setup ran — don't register a target that\n // onCleanup (already fired with `cleanup` undefined) can never tear down.\n /* v8 ignore next — defensive disposed-during-setup guard */\n if (disposed) return\n // Defensive re-setup teardown: `setup` runs exactly once\n // (`queueMicrotask(setup)`, never re-invoked), so `cleanup` is always\n // undefined here — this branch never fires in the current single-shot\n // design. Kept so a future re-setup trigger can't leak a double target.\n /* v8 ignore next — defensive re-setup teardown; unreachable with single-shot queueMicrotask */\n if (cleanup) cleanup()\n\n const el = options.element()\n if (!el) return\n\n const edges = options.edges\n\n const resolveData = (): DragData => {\n if (!options.data) return {}\n return typeof options.data === 'function' ? (options.data as () => T)() : options.data\n }\n\n cleanup = dropTargetForElements({\n element: el,\n getData: ({ input, element }) => {\n const data = resolveData()\n // Opt-in closest-edge detection — wraps the target data with\n // pdnd hitbox metadata so extractClosestEdge can read the live\n // edge on enter/drag.\n if (edges && edges.length > 0) {\n return attachClosestEdge(data, { input, element, allowedEdges: edges as Edge[] })\n }\n return data\n },\n // pdnd stickiness — keep \"held\" drop-target status while the\n // pointer crosses gaps between targets. Pass-through of getIsSticky.\n ...(options.sticky ? { getIsSticky: () => true } : {}),\n canDrop: ({ source }) => {\n if (!options.canDrop) return true\n return options.canDrop(source.data as DragData)\n },\n onDragEnter: ({ source, self }) => {\n // batch — isOver + overEdge settle in ONE notify pass for\n // subscribers reading both (matches useSortable's batching).\n batch(() => {\n isOver.set(true)\n if (edges) overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n })\n options.onDragEnter?.(source.data as DragData)\n },\n // Live edge tracking while the pointer moves over the target —\n // only meaningful (and only wired) when edges are configured.\n ...(edges && edges.length > 0\n ? {\n onDrag: ({ self }: { self: { data: Record<string | symbol, unknown> } }) => {\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n },\n }\n : {}),\n onDragLeave: () => {\n batch(() => {\n isOver.set(false)\n overEdge.set(null)\n })\n options.onDragLeave?.()\n },\n onDrop: ({ source }) => {\n batch(() => {\n isOver.set(false)\n overEdge.set(null)\n })\n options.onDrop?.(source.data as DragData)\n },\n })\n }\n\n queueMicrotask(setup)\n\n onCleanup(() => {\n disposed = true\n if (cleanup) cleanup()\n })\n\n return { isOver, overEdge }\n}\n","import {\n dropTargetForExternal,\n monitorForExternal,\n} from '@atlaskit/pragmatic-drag-and-drop/external/adapter'\nimport { containsFiles, getFiles } from '@atlaskit/pragmatic-drag-and-drop/external/file'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\n\nexport interface UseFileDropOptions {\n /** Element getter for the drop zone. */\n element: () => HTMLElement | null\n /** Called when files are dropped. */\n onDrop: (files: File[]) => void\n /** Filter accepted file types (e.g. [\"image/*\", \".pdf\"]). */\n accept?: string[]\n /** Maximum number of files. */\n maxFiles?: number\n /** Whether drop is disabled. */\n disabled?: boolean | (() => boolean)\n}\n\nexport interface UseFileDropResult {\n /** Whether files are being dragged over the drop zone. */\n isOver: () => boolean\n /** Whether files are being dragged anywhere on the page. */\n isDraggingFiles: () => boolean\n}\n\n/**\n * File drop zone with signal-driven state.\n * Uses the native file drag events via pragmatic-drag-and-drop.\n *\n * @example\n * ```tsx\n * let dropZone: HTMLElement | null = null\n *\n * const { isOver, isDraggingFiles } = useFileDrop({\n * element: () => dropZone,\n * accept: [\"image/*\", \".pdf\"],\n * maxFiles: 5,\n * onDrop: (files) => upload(files),\n * })\n *\n * <div\n * ref={(el) => dropZone = el}\n * class={isOver() ? \"drop-active\" : isDraggingFiles() ? \"drop-ready\" : \"\"}\n * >\n * Drop files here\n * </div>\n * ```\n */\nexport function useFileDrop(options: UseFileDropOptions): UseFileDropResult {\n if (isServer) return { isOver: () => false, isDraggingFiles: () => false }\n\n const isOver = signal(false)\n const isDraggingFiles = signal(false)\n let cleanup: (() => void) | undefined\n let disposed = false\n\n function matchesAccept(file: File, accept: string[]): boolean {\n return accept.some((pattern) => {\n if (pattern.startsWith('.')) {\n return file.name.toLowerCase().endsWith(pattern.toLowerCase())\n }\n if (pattern.endsWith('/*')) {\n return file.type.startsWith(pattern.slice(0, -1))\n }\n return file.type === pattern\n })\n }\n\n function setup() {\n // Unmounted before this deferred setup ran — don't register a drop target\n // that onCleanup (already fired with `cleanup` undefined) can never remove.\n /* v8 ignore next — defensive disposed-during-setup guard */\n if (disposed) return\n if (cleanup) cleanup()\n\n const el = options.element()\n if (!el) return\n\n const cleanups: (() => void)[] = []\n\n // Monitor for file drags anywhere on the page\n cleanups.push(\n monitorForExternal({\n canMonitor: ({ source }) => containsFiles({ source }),\n onDragStart: () => isDraggingFiles.set(true),\n onDrop: () => isDraggingFiles.set(false),\n }),\n )\n\n // Drop target on the specific element\n cleanups.push(\n dropTargetForExternal({\n element: el,\n canDrop: ({ source }) => {\n const disabled = options.disabled\n if (typeof disabled === 'function' ? disabled() : disabled) return false\n return containsFiles({ source })\n },\n onDragEnter: () => isOver.set(true),\n onDragLeave: () => isOver.set(false),\n onDrop: ({ source }) => {\n // batch() so onDrop subscribers don't get notified twice\n // (isOver + isDraggingFiles) per file-drop event.\n batch(() => {\n isOver.set(false)\n isDraggingFiles.set(false)\n })\n\n let files = getFiles({ source })\n\n // Filter by accept\n if (options.accept && options.accept.length > 0) {\n files = files.filter((f) => matchesAccept(f, options.accept as string[]))\n }\n\n // Limit count\n if (options.maxFiles && files.length > options.maxFiles) {\n files = files.slice(0, options.maxFiles)\n }\n\n if (files.length > 0) {\n options.onDrop(files)\n }\n },\n }),\n )\n\n cleanup = () => {\n for (const fn of cleanups) fn()\n }\n }\n\n queueMicrotask(setup)\n\n onCleanup(() => {\n disposed = true\n if (cleanup) cleanup()\n })\n\n return { isOver, isDraggingFiles }\n}\n","import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'\nimport { draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { autoScrollForElements } from '@atlaskit/pragmatic-drag-and-drop-auto-scroll/element'\nimport {\n attachClosestEdge,\n type Edge,\n extractClosestEdge,\n} from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge'\nimport { announce } from '@pyreon/a11y'\nimport { batch, createSelector, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DropEdge, UseSortableOptions, UseSortableResult } from './types'\n\nconst SORT_KEY = '__pyreon_sortable_key'\nconst SORT_ID = '__pyreon_sortable_id'\nconst SORT_GROUP = '__pyreon_sortable_group'\nconst SORT_PAYLOAD = '__pyreon_sortable_payload'\n\n// Same sr-only recipe as @pyreon/a11y's live regions — inline (not a CSS\n// class) so the instructions node needs zero stylesheet wiring.\nconst SR_ONLY =\n 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0'\n\nlet _sortableCounter = 0\n\n// Module-level registry of live sortable instances — used to dispatch\n// cross-list drop notifications from the destination back to the source\n// (W18). Keyed by sortableId.\nconst _sortableRegistry = new Map<\n string,\n {\n groupId: string | undefined\n onCrossListDrop: ((item: unknown) => void) | undefined\n }\n>()\n\n/**\n * Sortable list with signal-driven state, auto-scroll, and edge detection.\n *\n * Features:\n * - Keyed drag items matching `<For by={...}>` pattern\n * - Auto-scroll when dragging near container edges\n * - Closest-edge detection (drop above/below or left/right)\n * - Axis constraint (vertical/horizontal)\n * - Keyboard reordering (Alt+Arrow keys)\n * - Optional cross-list `groupId` for Trello/Notion/Linear board layouts\n * (W18) — share the same `groupId` between two\n * sortable instances and items can be dragged between them. The\n * source's `onCrossListDrop(item)` removes; the destination's\n * `onCrossListReceive(item, index)` inserts.\n *\n * @example\n * ```tsx\n * const items = signal([\n * { id: \"1\", name: \"Alice\" },\n * { id: \"2\", name: \"Bob\" },\n * { id: \"3\", name: \"Charlie\" },\n * ])\n *\n * const { containerRef, itemRef, isActive, isOverKey, overEdge } = useSortable({\n * items,\n * by: (item) => item.id,\n * onReorder: (newItems) => items.set(newItems),\n * label: (item) => item.name, // screen-reader announcements\n * })\n *\n * <ul ref={containerRef}>\n * <For each={items()} by={item => item.id}>\n * {(item) => (\n * <li\n * ref={itemRef(item.id)}\n * class={isActive(item.id) ? \"dragging\" : \"\"}\n * style={isOverKey(item.id) ? `border-${overEdge()}: 2px solid blue` : \"\"}\n * >\n * {item.name}\n * </li>\n * )}\n * </For>\n * </ul>\n * ```\n *\n * Prefer `isActive(key)` / `isOverKey(key)` over `activeId() === key` /\n * `overId() === key` in row templates — the equality read subscribes EVERY\n * row to the id signal (O(N) notifies per change); the selectors notify\n * only the two affected rows (O(2), `createSelector` semantics).\n */\nexport function useSortable<T>(options: UseSortableOptions<T>): UseSortableResult {\n if (isServer) {\n const noop = (_el: HTMLElement | null) => {}\n return {\n containerRef: noop,\n itemRef: () => noop,\n itemHandleRef: () => noop,\n activeId: () => null,\n overId: () => null,\n overEdge: () => null,\n isActive: () => false,\n isOverKey: () => false,\n }\n }\n\n const sortableId = `sortable-${++_sortableCounter}`\n const instructionsId = `${sortableId}-instructions`\n const activeId = signal<string | number | null>(null)\n const overId = signal<string | number | null>(null)\n const overEdge = signal<DropEdge | null>(null)\n // createSelector-backed per-key predicates (the krausest select-row\n // pattern): `activeId() === key` in a row template subscribes EVERY row\n // to activeId (O(N) notifies per change); the selector notifies only\n // the two affected keys (deselected + newly selected) — O(2).\n const isActiveSelector = createSelector<string | number | null>(activeId)\n const isOverSelector = createSelector<string | number | null>(overId)\n const axis = options.axis ?? 'vertical'\n const groupId = options.groupId\n\n /** Resolve the announcement label for an item: `label(item)` else the key. */\n function labelOf(item: T | undefined, key: string | number): string {\n if (item !== undefined && options.label) return options.label(item)\n return String(key)\n }\n\n /** Resolve the announcement label for a key by looking the item up. */\n function labelFor(key: string | number): string {\n const item = options.items().find((i) => options.by(i) === key)\n return labelOf(item, key)\n }\n\n // Register so siblings in the same group can call our onCrossListDrop\n // when they receive one of our items.\n _sortableRegistry.set(sortableId, {\n groupId,\n onCrossListDrop: options.onCrossListDrop as ((item: unknown) => void) | undefined,\n })\n\n // Container-level pdnd teardown (auto-scroll + reorder drop-target + the\n // keydown listener). A SINGLE disposer, replaced on re-register and cleared\n // on unmount — symmetric with the per-item map below. A collapsible board\n // whose `<ul ref={containerRef}>` sits behind a `<Show>` (with the hook in\n // the parent) re-fires `containerRef` on every toggle; without disposal each\n // toggle leaked the auto-scroll + drop-target + keydown listener on the now-\n // detached element (the container sibling of the F3 per-item leak).\n let containerCleanup: (() => void) | undefined\n // Per-item pdnd cleanups, keyed by sort key. Disposed individually on\n // item unmount / re-register so a churning list doesn't accumulate\n // dead registrations for the sortable's whole lifetime.\n const itemCleanups = new Map<string | number, () => void>()\n\n /** Perform the reorder based on current active/over/edge state. */\n function performReorder() {\n const dragId = activeId.peek()\n const dropId = overId.peek()\n const edge = overEdge.peek()\n /* v8 ignore next — defensive null/equal id guards */\n if (dragId == null || dropId == null || dragId === dropId) return\n\n const currentItems = options.items()\n const dragIndex = currentItems.findIndex((item) => options.by(item) === dragId)\n const dropIndex = currentItems.findIndex((item) => options.by(item) === dropId)\n /* v8 ignore next — defensive findIndex-not-found guards; ids come from active drag */\n if (dragIndex === -1 || dropIndex === -1) return\n\n const reordered = [...currentItems]\n const [moved] = reordered.splice(dragIndex, 1)\n /* v8 ignore next — defensive splice fallback; dragIndex was just verified */\n if (!moved) return\n\n // Determine insert position based on closest edge\n /* v8 ignore next 7 — ternary combinatorics; structurally exercised in browser e2e but not unit-coverable per arm */\n const rawInsert =\n edge === 'bottom' || edge === 'right'\n ? dropIndex >= dragIndex\n ? dropIndex\n : dropIndex + 1\n : dropIndex <= dragIndex\n ? dropIndex\n : dropIndex - 1\n const insertAt = Math.max(0, Math.min(rawInsert, reordered.length))\n\n reordered.splice(insertAt, 0, moved)\n options.onReorder(reordered)\n // Screen-reader announcement — position is 1-based for humans.\n announce(`Dropped ${labelOf(moved, dragId)} at position ${insertAt + 1} of ${reordered.length}`)\n }\n\n /** Announce a cross-list receive on THIS (destination) sortable. */\n function announceCrossListReceive(item: T, insertAt: number) {\n // `items()` reflects the post-insert length when the consumer commits\n // synchronously inside onCrossListReceive (the documented shape); the\n // max() keeps the count honest if the commit is deferred.\n const count = Math.max(options.items().length, insertAt + 1)\n const key = options.by(item)\n announce(\n `Dropped ${labelOf(item, key)} at position ${insertAt + 1} of ${count} in the receiving list`,\n )\n }\n\n /** Returns true when `source` belongs to this sortable or to a sibling\n * in the same `groupId`. */\n function acceptsSource(source: { data: Record<string, unknown> }): boolean {\n if (source.data[SORT_ID] === sortableId) return true\n if (groupId && source.data[SORT_GROUP] === groupId) return true\n return false\n }\n\n function containerRef(el: HTMLElement | null) {\n // Dispose the prior container registration on BOTH unmount (el === null,\n // fired by Pyreon's runtime) AND re-register (a new container element) so\n // a toggled/re-mounted container can't leak its auto-scroll + drop-target +\n // keydown listener. Symmetric with the per-item disposal below (F3).\n if (containerCleanup) {\n containerCleanup()\n containerCleanup = undefined\n }\n if (!el) return\n\n const containerCleanups: (() => void)[] = []\n\n // Visually-hidden keyboard instructions, referenced by every item via\n // aria-describedby (the dnd-kit pattern — screen-reader users land on\n // an item and hear how to reorder it). Created once per container\n // mount, removed with the container registration.\n const instructions = document.createElement('div')\n instructions.id = instructionsId\n instructions.setAttribute('data-pyreon-sortable-instructions', '')\n instructions.style.cssText = SR_ONLY\n instructions.textContent = 'Press Alt plus arrow keys to reorder'\n el.appendChild(instructions)\n containerCleanups.push(() => instructions.remove())\n\n // Auto-scroll when dragging near container edges\n containerCleanups.push(\n autoScrollForElements({\n element: el,\n canScroll: ({ source }) => acceptsSource(source),\n }),\n )\n\n // Container is a drop target for reorder finalization OR for\n // appending a cross-list item at the end of this column.\n containerCleanups.push(\n dropTargetForElements({\n element: el,\n getData: () => ({ [SORT_ID]: sortableId, [SORT_GROUP]: groupId }),\n canDrop: ({ source }) => acceptsSource(source),\n onDrop: ({ source }) => {\n // Item-level dropTarget for cross-list drops marks the source\n // data as handled — container skips so we don't insert twice.\n const handled = (source.data as Record<string, unknown>).__pyreon_sortable_handled\n if (source.data[SORT_ID] === sortableId) {\n // Same-list drop on container edge → reorder finalization.\n performReorder()\n } else if (\n !handled &&\n groupId &&\n source.data[SORT_GROUP] === groupId &&\n options.onCrossListReceive\n ) {\n // Cross-list drop on the container itself (not on an item) →\n // append to the end of this column.\n const item = source.data[SORT_PAYLOAD] as T\n const sourceSortableId = source.data[SORT_ID] as string\n const targetIndex = options.items().length\n options.onCrossListReceive(item, targetIndex)\n const sourceInstance = _sortableRegistry.get(sourceSortableId)\n sourceInstance?.onCrossListDrop?.(item)\n announceCrossListReceive(item, targetIndex)\n }\n // batch() the 3-signal reset so subscribers reading any of\n // activeId/overId/overEdge get notified once per drop, not\n // three times. Fires on every container-level drop.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n },\n }),\n )\n\n // Keyboard reordering: Alt+Arrow keys\n const keyHandler = (e: KeyboardEvent) => {\n if (!e.altKey) return\n\n const isUp = axis === 'vertical' ? e.key === 'ArrowUp' : e.key === 'ArrowLeft'\n const isDown = axis === 'vertical' ? e.key === 'ArrowDown' : e.key === 'ArrowRight'\n if (!isUp && !isDown) return\n\n const focused = document.activeElement as HTMLElement | null\n if (!focused || !el.contains(focused)) return\n\n const focusedKey = focused.dataset.pyreonSortKey\n if (!focusedKey) return\n\n e.preventDefault()\n\n const currentItems = options.items()\n const currentIndex = currentItems.findIndex((item) => String(options.by(item)) === focusedKey)\n /* v8 ignore next — defensive findIndex guard; focusedKey is from active item */\n if (currentIndex === -1) return\n\n const targetIndex = isUp ? currentIndex - 1 : currentIndex + 1\n if (targetIndex < 0 || targetIndex >= currentItems.length) return\n\n const reordered = [...currentItems]\n const temp = reordered[currentIndex]\n reordered[currentIndex] = reordered[targetIndex] as T\n reordered[targetIndex] = temp as T\n options.onReorder(reordered)\n // Screen-reader announcement for the keyboard path (1-based).\n announce(\n `Moved ${labelOf(temp, focusedKey)} to position ${targetIndex + 1} of ${currentItems.length}`,\n )\n\n // Restore focus after DOM update\n requestAnimationFrame(() => {\n const items = el.querySelectorAll('[data-pyreon-sort-key]')\n for (const item of items) {\n if ((item as HTMLElement).dataset.pyreonSortKey === focusedKey) {\n ;(item as HTMLElement).focus()\n break\n }\n }\n })\n }\n\n el.addEventListener('keydown', keyHandler)\n containerCleanups.push(() => el.removeEventListener('keydown', keyHandler))\n\n containerCleanup = () => {\n for (const fn of containerCleanups) fn()\n }\n }\n\n // Live item elements + registered drag handles, keyed by sort key.\n // `itemEls` lets the handle registrar re-register an already-mounted\n // item when its handle arrives (child refs fire AFTER the parent's,\n // so the handle is never available at itemRef time).\n const itemEls = new Map<string | number, HTMLElement>()\n const itemHandles = new Map<string | number, HTMLElement>()\n\n function itemRef(key: string | number): (el: HTMLElement | null) => void {\n return (el: HTMLElement | null) => {\n // Per-key disposal. The ref fires with the element on mount and\n // with `null` on unmount. The old code pushed every registration\n // onto the shared `cleanups[]` and made the null branch a pure\n // no-op — so for a `<For>`-rendered sortable (the documented usage:\n // todo list / kanban) every removed item's pdnd `draggable` /\n // `dropTargetForElements` registration (and its pointer/drag\n // listeners on the now-detached node) leaked until the WHOLE\n // sortable unmounted. Dispose the prior registration for this key\n // on BOTH unmount (el === null) and re-registration (same key,\n // new element) so the live set tracks live items, not all-ever.\n const prev = itemCleanups.get(key)\n if (prev) {\n prev()\n itemCleanups.delete(key)\n }\n if (!el) {\n itemEls.delete(key)\n return\n }\n itemEls.set(key, el)\n registerItem(key, el)\n }\n }\n\n /**\n * OPTIONAL drag-handle registrar mirroring `itemRef`. When a handle is\n * (un)registered for an already-mounted item, the item's pdnd\n * registration is torn down and re-created so `dragHandle` takes\n * effect — pdnd captures the handle at registration time.\n */\n function itemHandleRef(key: string | number): (el: HTMLElement | null) => void {\n return (el: HTMLElement | null) => {\n if (el) itemHandles.set(key, el)\n else itemHandles.delete(key)\n const itemEl = itemEls.get(key)\n if (!itemEl) return\n // itemEls and itemCleanups are set together (itemRef → registerItem),\n // so a live itemEl implies a live cleanup — dispose it before the\n // re-registration below replaces it.\n /* v8 ignore next — defensive optional call; a live itemEl implies a live cleanup */\n itemCleanups.get(key)?.()\n itemCleanups.delete(key)\n registerItem(key, itemEl)\n }\n }\n\n function registerItem(key: string | number, el: HTMLElement) {\n el.dataset.pyreonSortKey = String(key)\n if (!el.hasAttribute('tabindex')) el.setAttribute('tabindex', '0')\n el.setAttribute('role', 'listitem')\n el.setAttribute('aria-roledescription', 'sortable item')\n // Link the container's visually-hidden keyboard instructions so a\n // screen-reader user focusing the item hears how to reorder it.\n // A consumer-supplied aria-describedby wins.\n if (!el.hasAttribute('aria-describedby')) {\n el.setAttribute('aria-describedby', instructionsId)\n }\n\n const allowedEdges: Edge[] = axis === 'vertical' ? ['top', 'bottom'] : ['left', 'right']\n const handle = itemHandles.get(key)\n\n const cleanup = combine(\n draggable({\n element: el,\n // Per-item drag handle (pdnd dragHandle) — drag initiation is\n // scoped to the registered handle element when one exists.\n ...(handle ? { dragHandle: handle } : {}),\n getInitialData: () => {\n const currentItems = options.items()\n const item = currentItems.find((i) => options.by(i) === key)\n return {\n [SORT_KEY]: key,\n [SORT_ID]: sortableId,\n [SORT_GROUP]: groupId,\n // Carry the actual item value when groupId is set so a\n // sibling sortable's onDrop can receive it without a\n // separate registry lookup. Plain reference (pdnd doesn't\n // serialize) — safe within a single document.\n [SORT_PAYLOAD]: groupId ? item : undefined,\n }\n },\n onDragStart: () => {\n activeId.set(key)\n announce(`Picked up ${labelFor(key)}`)\n },\n onDrop: () => {\n queueMicrotask(() => {\n // batch() — same 3-signal reset shape as the container\n // onDrop above. Per-item drops fire this branch.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n })\n },\n }),\n dropTargetForElements({\n element: el,\n getData: ({ input, element }) =>\n attachClosestEdge(\n { [SORT_KEY]: key, [SORT_ID]: sortableId, [SORT_GROUP]: groupId },\n { input, element, allowedEdges },\n ),\n canDrop: ({ source }) => acceptsSource(source),\n onDragEnter: ({ self }) => {\n // batch — overId + overEdge settle in ONE notify pass (same\n // shape as every other multi-signal write in this hook).\n batch(() => {\n overId.set(key)\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n })\n },\n onDrag: ({ self }) => {\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n },\n onDragLeave: () => {\n if (overId.peek() === key) {\n batch(() => {\n overId.set(null)\n overEdge.set(null)\n })\n }\n },\n onDrop: ({ source, self }) => {\n // Same-list drops are handled by the container's onDrop via\n // performReorder. Item-level onDrop fires for cross-list\n // shapes — insert at THIS item's index, then propagate to\n // the source to remove.\n if (source.data[SORT_ID] === sortableId) return\n if (!groupId || source.data[SORT_GROUP] !== groupId || !options.onCrossListReceive) {\n return\n }\n const item = source.data[SORT_PAYLOAD] as T\n const edge = extractClosestEdge(self.data) as DropEdge | null\n const currentItems = options.items()\n const targetIndex = currentItems.findIndex((i) => options.by(i) === key)\n /* v8 ignore next — defensive findIndex guard */\n if (targetIndex === -1) return\n /* v8 ignore next 4 — ternary combinatorics */\n const insertAt =\n edge === 'bottom' || edge === 'right' ? targetIndex + 1 : Math.max(0, targetIndex)\n options.onCrossListReceive(item, insertAt)\n const sourceSortableId = source.data[SORT_ID] as string\n const sourceInstance = _sortableRegistry.get(sourceSortableId)\n sourceInstance?.onCrossListDrop?.(item)\n announceCrossListReceive(item, insertAt)\n // Mark so the container's onDrop (which also fires) skips\n // re-inserting at the end of the list.\n ;(source.data as Record<string, unknown>).__pyreon_sortable_handled = true\n },\n }),\n )\n\n itemCleanups.set(key, cleanup)\n }\n\n onCleanup(() => {\n // Drain the live container registration (idempotent — containerRef(null)\n // may already have cleared it) plus every per-item registration.\n if (containerCleanup) {\n containerCleanup()\n containerCleanup = undefined\n }\n for (const cleanup of itemCleanups.values()) cleanup()\n itemCleanups.clear()\n itemEls.clear()\n itemHandles.clear()\n _sortableRegistry.delete(sortableId)\n // Selectors own a source-tracking effect + per-key buckets — release\n // them with the sortable (keys are unbounded across list churn).\n isActiveSelector.dispose()\n isOverSelector.dispose()\n // batch() the final 3-signal reset so any subscriber that survives\n // the dispose order (unusual but possible — e.g. an external store\n // holding refs) sees one notify, not three.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n })\n\n return {\n containerRef,\n itemRef,\n itemHandleRef,\n activeId,\n overId,\n overEdge,\n isActive: (key: string | number) => isActiveSelector(key),\n isOverKey: (key: string | number) => isOverSelector(key),\n }\n}\n","import { name as __pkgName, version as __pkgVersion } from '../package.json' with { type: 'json' }\nimport { registerSingleton } from '@pyreon/reactivity'\n\n// Singleton sentinel — fail-loud detection of duplicate @pyreon/dnd\n// instances in the same heap. See @pyreon/reactivity/singleton-sentinel for\n// full rationale. Hardcoded version is acceptable here — it's a diagnostic\n// aid, not a load-bearing identity check.\nregisterSingleton(__pkgName, __pkgVersion, import.meta.url)\n\nexport type {\n DragData,\n DragPreviewOptions,\n DropEdge,\n DropLocation,\n UseDraggableOptions,\n UseDraggableResult,\n UseDroppableOptions,\n UseDroppableResult,\n UseSortableOptions,\n UseSortableResult,\n} from './types'\n\nexport type { UseDragMonitorOptions, UseDragMonitorResult } from './use-drag-monitor'\nexport { useDragMonitor } from './use-drag-monitor'\n\nexport { useDraggable } from './use-draggable'\nexport { useDroppable } from './use-droppable'\nexport type { UseFileDropOptions, UseFileDropResult } from './use-file-drop'\nexport { useFileDrop } from './use-file-drop'\nexport { useSortable } from './use-sortable'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuCA,SAAgB,eAAe,SAAuD;CACpF,IAAI,UAAU,OAAO;EAAE,kBAAkB;EAAO,gBAAgB;CAAK;CAErE,MAAM,aAAa,OAAO,KAAK;CAC/B,MAAM,WAAW,OAAwB,IAAI;;CAG7C,MAAM,eAAe,SAAS,cACzB,EAAE,aACD,QAAQ,aAAa,OAAO,IAAgB,KAAK,OACnD;CAwBJ,UAtBgB,mBAAmB;EACjC,GAAI,eAAe,EAAE,YAAY,aAAa,IAAI,CAAC;EACnD,cAAc,EAAE,aAAa;GAI3B,YAAY;IACV,WAAW,IAAI,IAAI;IACnB,SAAS,IAAI,OAAO,IAAgB;GACtC,CAAC;GACD,SAAS,cAAc,OAAO,IAAgB;EAChD;EACA,SAAS,EAAE,QAAQ,eAAe;GAChC,YAAY;IACV,WAAW,IAAI,KAAK;IACpB,SAAS,IAAI,IAAI;GACnB,CAAC;GACD,MAAM,aAAa,SAAS,QAAQ,YAAY,EAAE,EAAE,QAAQ,CAAC;GAC7D,SAAS,SAAS,OAAO,MAAkB,UAAsB;EACnE;CACF,CAEgB,CAAC;CAEjB,OAAO;EAAE;EAAY;CAAS;AAChC;;;;;;;;;AC/DA,SAAS,qBACP,QACA,QACA,OACwD;CACxD,IAAI,WAAW,mBAAmB,OAAO,wBAAwB;EAAE,GAAG;EAAQ,GAAG;CAAM,CAAC;CACxF,IAAI,WAAW,UAAU,OAAO;CAChC,IAAI,WAAW,mBACb,OAAO,uBAAuB;EAAE,SAAS,OAAO;EAAS;CAAM,CAAC;AAGpE;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,aACd,SACoB;CACpB,IAAI,UAAU,OAAO,EAAE,kBAAkB,MAAM;CAE/C,MAAM,aAAa,OAAO,KAAK;CAC/B,IAAI;CACJ,IAAI,WA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,EAAE,kBAAkB,IAAI;IACtC,yBAAyB,MAAM,QAAQ;IAGtC,AAAC,OAAO,KAAiC,4BAA4B;GACxE;EACF,CAAC,CACH;EAEA,aAAa,IAAI,KAAK,OAAO;CAC/B;CAEA,gBAAgB;EAGd,IAAI,kBAAkB;GACpB,iBAAiB;GACjB,mBAAmB;EACrB;EACA,KAAK,MAAM,WAAW,aAAa,OAAO,GAAG,QAAQ;EACrD,aAAa,MAAM;EACnB,QAAQ,MAAM;EACd,YAAY,MAAM;EAClB,kBAAkB,OAAO,UAAU;EAGnC,iBAAiB,QAAQ;EACzB,eAAe,QAAQ;EAIvB,YAAY;GACV,SAAS,IAAI,IAAI;GACjB,OAAO,IAAI,IAAI;GACf,SAAS,IAAI,IAAI;EACnB,CAAC;CACH,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,WAAW,QAAyB,iBAAiB,GAAG;EACxD,YAAY,QAAyB,eAAe,GAAG;CACzD;AACF;;;;AC/gBA,kBAAkBA,MAAWC,SAAc,OAAO,KAAK,GAAG"}
@@ -10,6 +10,30 @@ interface DropLocation {
10
10
  /** Custom data attached to the drop target. */
11
11
  data: DragData;
12
12
  }
13
+ /**
14
+ * Custom native drag-preview configuration — a thin surface over pdnd's
15
+ * `onGenerateDragPreview` + `setCustomNativeDragPreview` + offset presets.
16
+ */
17
+ interface DragPreviewOptions {
18
+ /**
19
+ * Render the preview into the pdnd-provided `container` (appended to
20
+ * `document.body` for the lifetime of the drag). Return a cleanup
21
+ * function to tear down whatever you rendered — it runs when the
22
+ * preview is unmounted after the drag starts.
23
+ */
24
+ render: (container: HTMLElement) => (() => void) | void;
25
+ /**
26
+ * Offset preset for where the preview sits relative to the pointer:
27
+ * - `'pointer-outside'` → preview pushed in front of the pointer
28
+ * (pdnd's `pointerOutsideOfPreview`, RTL-aware)
29
+ * - `'center'` → preview centered under the pointer
30
+ * - `'preserve-offset'` → preview keeps the grab point's offset on the
31
+ * source element (feels like dragging the original)
32
+ *
33
+ * Omit for the browser default (top-left corner under the pointer).
34
+ */
35
+ offset?: 'pointer-outside' | 'center' | 'preserve-offset';
36
+ }
13
37
  interface UseDraggableOptions<T extends DragData = DragData> {
14
38
  /** Ref callback or element getter for the draggable element. */
15
39
  element: () => HTMLElement | null;
@@ -23,6 +47,12 @@ interface UseDraggableOptions<T extends DragData = DragData> {
23
47
  onDragStart?: () => void;
24
48
  /** Called when drag ends (drop or cancel). */
25
49
  onDragEnd?: () => void;
50
+ /**
51
+ * Custom native drag preview. When set, the browser's default snapshot
52
+ * preview is replaced by whatever `preview.render` draws into the
53
+ * provided container. See {@link DragPreviewOptions}.
54
+ */
55
+ preview?: DragPreviewOptions;
26
56
  }
27
57
  interface UseDraggableResult {
28
58
  /** Whether this element is currently being dragged. */
@@ -41,10 +71,29 @@ interface UseDroppableOptions<T extends DragData = DragData> {
41
71
  onDragLeave?: () => void;
42
72
  /** Called when an item is dropped on this target. */
43
73
  onDrop?: (sourceData: DragData) => void;
74
+ /**
75
+ * Opt into closest-edge detection (pdnd hitbox `attachClosestEdge` /
76
+ * `extractClosestEdge`). Pass the edges you care about (e.g.
77
+ * `['top', 'bottom']` for a vertical list) and read the live edge from
78
+ * the result's `overEdge` signal accessor while a drag hovers this
79
+ * target.
80
+ */
81
+ edges?: DropEdge[];
82
+ /**
83
+ * pdnd stickiness (`getIsSticky`) — when `true`, this target keeps
84
+ * "held" drop-target status while the pointer moves over gaps between
85
+ * targets (useful for lists with margins between items).
86
+ */
87
+ sticky?: boolean;
44
88
  }
45
89
  interface UseDroppableResult {
46
90
  /** Whether something is currently being dragged over this target. */
47
91
  isOver: () => boolean;
92
+ /**
93
+ * The closest configured edge while a drag hovers this target, `null`
94
+ * otherwise. Always `null` unless the `edges` option is set.
95
+ */
96
+ overEdge: () => DropEdge | null;
48
97
  }
49
98
  interface UseSortableOptions<T> {
50
99
  /** Reactive list of items to sort. */
@@ -82,6 +131,13 @@ interface UseSortableOptions<T> {
82
131
  * `groupId` is set.
83
132
  */
84
133
  onCrossListReceive?: (item: T, targetIndex: number) => void;
134
+ /**
135
+ * Human-readable label for an item, used in screen-reader
136
+ * announcements ("Picked up Alice", "Moved Alice to position 2 of 3").
137
+ * Falls back to `String(by(item))` when omitted — supply it whenever
138
+ * your keys are opaque ids.
139
+ */
140
+ label?: (item: T) => string;
85
141
  }
86
142
  interface UseSortableResult {
87
143
  /**
@@ -97,12 +153,35 @@ interface UseSortableResult {
97
153
  * compatibility reason as `containerRef` above.
98
154
  */
99
155
  itemRef: (key: string | number) => (el: HTMLElement | null) => void;
156
+ /**
157
+ * OPTIONAL per-item drag handle registrar — mirrors `itemRef`. Attach
158
+ * the returned callback as the `ref` of a sub-element inside the item
159
+ * (a grip icon) and dragging is scoped to that element only (pdnd
160
+ * `dragHandle`): pointer-drags starting elsewhere on the item are
161
+ * rejected. Items without a registered handle stay fully draggable.
162
+ */
163
+ itemHandleRef: (key: string | number) => (el: HTMLElement | null) => void;
100
164
  /** The key of the currently dragging item. */
101
165
  activeId: () => string | number | null;
102
166
  /** The key of the item being hovered over. */
103
167
  overId: () => string | number | null;
104
168
  /** The closest edge of the hovered item ("top"/"bottom" or "left"/"right"). */
105
169
  overEdge: () => DropEdge | null;
170
+ /**
171
+ * `createSelector`-backed predicate: `true` only for the currently
172
+ * dragging item's key. **Prefer this over `activeId() === key` in row
173
+ * templates** — the equality read makes EVERY row subscribe to
174
+ * `activeId` (O(N) notifies per change); the selector notifies only
175
+ * the deselected + newly-selected rows (O(2), the krausest
176
+ * select-row pattern).
177
+ */
178
+ isActive: (key: string | number) => boolean;
179
+ /**
180
+ * `createSelector`-backed predicate: `true` only for the currently
181
+ * hovered item's key. Same O(2) rationale as `isActive` — prefer it
182
+ * over `overId() === key` in row templates.
183
+ */
184
+ isOverKey: (key: string | number) => boolean;
106
185
  }
107
186
  //#endregion
108
187
  //#region src/use-drag-monitor.d.ts
@@ -169,10 +248,11 @@ declare function useDraggable<T extends DragData = DragData>(options: UseDraggab
169
248
  * ```tsx
170
249
  * let zoneEl: HTMLElement | null = null
171
250
  *
172
- * const { isOver } = useDroppable({
251
+ * const { isOver, overEdge } = useDroppable({
173
252
  * element: () => zoneEl,
174
253
  * onDrop: (data) => handleDrop(data),
175
254
  * canDrop: (data) => data.type === "card",
255
+ * edges: ["top", "bottom"], // opt-in closest-edge detection
176
256
  * })
177
257
  *
178
258
  * <div ref={(el) => zoneEl = el} class={isOver() ? "bg-blue-50" : ""}>
@@ -250,10 +330,11 @@ declare function useFileDrop(options: UseFileDropOptions): UseFileDropResult;
250
330
  * { id: "3", name: "Charlie" },
251
331
  * ])
252
332
  *
253
- * const { containerRef, itemRef, activeId, overId, overEdge } = useSortable({
333
+ * const { containerRef, itemRef, isActive, isOverKey, overEdge } = useSortable({
254
334
  * items,
255
335
  * by: (item) => item.id,
256
336
  * onReorder: (newItems) => items.set(newItems),
337
+ * label: (item) => item.name, // screen-reader announcements
257
338
  * })
258
339
  *
259
340
  * <ul ref={containerRef}>
@@ -261,8 +342,8 @@ declare function useFileDrop(options: UseFileDropOptions): UseFileDropResult;
261
342
  * {(item) => (
262
343
  * <li
263
344
  * ref={itemRef(item.id)}
264
- * class={activeId() === item.id ? "dragging" : ""}
265
- * style={overId() === item.id ? `border-${overEdge()}: 2px solid blue` : ""}
345
+ * class={isActive(item.id) ? "dragging" : ""}
346
+ * style={isOverKey(item.id) ? `border-${overEdge()}: 2px solid blue` : ""}
266
347
  * >
267
348
  * {item.name}
268
349
  * </li>
@@ -270,7 +351,12 @@ declare function useFileDrop(options: UseFileDropOptions): UseFileDropResult;
270
351
  * </For>
271
352
  * </ul>
272
353
  * ```
354
+ *
355
+ * Prefer `isActive(key)` / `isOverKey(key)` over `activeId() === key` /
356
+ * `overId() === key` in row templates — the equality read subscribes EVERY
357
+ * row to the id signal (O(N) notifies per change); the selectors notify
358
+ * only the two affected rows (O(2), `createSelector` semantics).
273
359
  */
274
360
  declare function useSortable<T>(options: UseSortableOptions<T>): UseSortableResult;
275
361
  //#endregion
276
- export { type DragData, type DropEdge, type DropLocation, type UseDragMonitorOptions, type UseDragMonitorResult, type UseDraggableOptions, type UseDraggableResult, type UseDroppableOptions, type UseDroppableResult, type UseFileDropOptions, type UseFileDropResult, type UseSortableOptions, type UseSortableResult, useDragMonitor, useDraggable, useDroppable, useFileDrop, useSortable };
362
+ export { type DragData, type DragPreviewOptions, type DropEdge, type DropLocation, type UseDragMonitorOptions, type UseDragMonitorResult, type UseDraggableOptions, type UseDraggableResult, type UseDroppableOptions, type UseDroppableResult, type UseFileDropOptions, type UseFileDropResult, type UseSortableOptions, type UseSortableResult, useDragMonitor, useDraggable, useDroppable, useFileDrop, useSortable };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyreon/dnd",
3
- "version": "0.49.0",
3
+ "version": "0.50.0",
4
4
  "description": "Signal-driven drag and drop for Pyreon — wraps @atlaskit/pragmatic-drag-and-drop",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/pyreon/pyreon/tree/main/packages/fundamentals/dnd#readme",
@@ -35,19 +35,21 @@
35
35
  "lint": "oxlint ."
36
36
  },
37
37
  "peerDependencies": {
38
- "@pyreon/core": "^0.49.0",
39
- "@pyreon/reactivity": "^0.49.0"
38
+ "@pyreon/core": "^0.50.0",
39
+ "@pyreon/reactivity": "^0.50.0"
40
40
  },
41
41
  "dependencies": {
42
42
  "@atlaskit/pragmatic-drag-and-drop": "^2.0.1",
43
43
  "@atlaskit/pragmatic-drag-and-drop-auto-scroll": "^3.0.0",
44
- "@atlaskit/pragmatic-drag-and-drop-hitbox": "^2.0.0"
44
+ "@atlaskit/pragmatic-drag-and-drop-hitbox": "^2.0.0",
45
+ "@pyreon/a11y": "^0.50.0"
45
46
  },
46
47
  "devDependencies": {
47
48
  "@happy-dom/global-registrator": "^20.9.0",
48
49
  "@pyreon/manifest": "0.13.2",
49
- "@pyreon/test-utils": "^0.13.37",
50
- "@pyreon/typescript": "^0.49.0",
50
+ "@pyreon/test-utils": "^0.13.38",
51
+ "@pyreon/tsconfig": "0.0.2",
52
+ "@pyreon/typescript": "^0.50.0",
51
53
  "@pyreon/vitest-config": "0.13.3",
52
54
  "@vitest/browser-playwright": "^4.1.10"
53
55
  },