@barqjs/aria 0.0.0-stage → 0.2.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
@@ -0,0 +1,726 @@
1
+ /** Drop targets in a collection: by sibling, by arrow key, and by point. */
2
+
3
+ import type { Accessor } from "@barqjs/core";
4
+ import type { Collection, Key, Node } from "../collections.ts";
5
+ import type { ElementRef } from "../interactions/press.ts";
6
+ import type { KeyboardDelegate } from "../selection.ts";
7
+ import { access, type MaybeAccessor } from "../utils.ts";
8
+ import { refElement } from "./data.ts";
9
+ import type { DropPosition, DropTarget, DropTargetDelegate, ItemDropTarget } from "./types.ts";
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Siblings, in a collection whose keys are linked in document order
13
+ // ---------------------------------------------------------------------------
14
+
15
+ /**
16
+ * The next node with the same parent, or null.
17
+ *
18
+ * A collection links its keys in DOCUMENT order, through sections and
19
+ * children, so the item after the last one of a section is the first of the
20
+ * next. Drop positions are about siblings: "after the last item of a section"
21
+ * is a different place from "before the first of the next".
22
+ */
23
+ export function nextSiblingNode(
24
+ collection: Collection<unknown>,
25
+ node: Node<unknown>,
26
+ ): Node<unknown> | null {
27
+ let key = collection.getKeyAfter(node.key);
28
+ while (key !== null) {
29
+ const next = collection.getItem(key);
30
+ if (next === null || next.level < node.level) return null;
31
+ if (next.level === node.level && next.parentKey === node.parentKey) return next;
32
+ key = collection.getKeyAfter(key);
33
+ }
34
+ return null;
35
+ }
36
+
37
+ /** The previous node with the same parent, or null. */
38
+ export function previousSiblingNode(
39
+ collection: Collection<unknown>,
40
+ node: Node<unknown>,
41
+ ): Node<unknown> | null {
42
+ let key = collection.getKeyBefore(node.key);
43
+ while (key !== null) {
44
+ const previous = collection.getItem(key);
45
+ if (previous === null || previous.level < node.level) return null;
46
+ if (previous.level === node.level && previous.parentKey === node.parentKey) return previous;
47
+ key = collection.getKeyBefore(key);
48
+ }
49
+ return null;
50
+ }
51
+
52
+ function nextSiblingItem(
53
+ collection: Collection<unknown>,
54
+ node: Node<unknown>,
55
+ ): Node<unknown> | null {
56
+ let next = nextSiblingNode(collection, node);
57
+ while (next !== null && next.type !== "item") next = nextSiblingNode(collection, next);
58
+ return next;
59
+ }
60
+
61
+ /** The next or previous ITEM in document order, past sections and loaders. */
62
+ function nextItemKey(
63
+ collection: Collection<unknown>,
64
+ key: Key,
65
+ step: (key: Key) => Key | null,
66
+ ): Key | null {
67
+ let at = step(key);
68
+ let node = at === null ? null : collection.getItem(at);
69
+ while (node !== null && node.type !== "item") {
70
+ at = step(node.key);
71
+ node = at === null ? null : collection.getItem(at);
72
+ }
73
+ return at;
74
+ }
75
+
76
+ /**
77
+ * The "after" positions that need an indicator of their own below `node`.
78
+ *
79
+ * Usually none: "after this item" is the same place as "before the next", and
80
+ * that one is drawn. The exception is the last item of a level, and in a tree
81
+ * the last item of each level being left at once.
82
+ */
83
+ export function afterDropIndicatorTargets(
84
+ collection: Collection<unknown>,
85
+ node: Node<unknown>,
86
+ ): ItemDropTarget[] {
87
+ const keyAfter = nextItemKey(collection, node.key, (key) => collection.getKeyAfter(key));
88
+ const nextInFlattened = keyAfter === null ? null : collection.getItem(keyAfter);
89
+ if (nextSiblingItem(collection, node) !== null) return [];
90
+
91
+ const isLeftBehind = (current: Node<unknown>): boolean =>
92
+ nextInFlattened === null ||
93
+ (current.parentKey !== nextInFlattened.parentKey && nextInFlattened.level < current.level);
94
+
95
+ const targets: ItemDropTarget[] = [];
96
+ let current: Node<unknown> | null = node;
97
+ while (current?.type === "item" && isLeftBehind(current)) {
98
+ targets.push({ type: "item", key: current.key, dropPosition: "after" });
99
+ current = current.parentKey === undefined ? null : collection.getItem(current.parentKey);
100
+ }
101
+ return targets;
102
+ }
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // Drop target keyboard navigation
106
+ // ---------------------------------------------------------------------------
107
+
108
+ export type DropNavigationDirection = "left" | "right" | "up" | "down";
109
+
110
+ /**
111
+ * The drop target the arrow key `direction` moves to from `target`.
112
+ *
113
+ * Every item offers three positions, before, on and after, but "after one" and
114
+ * "before the next" are the same place, so only one of the two is visited.
115
+ * `null` means there is nowhere further; `wrap` returns to the root instead.
116
+ */
117
+ export function navigateDropTarget(
118
+ keyboardDelegate: KeyboardDelegate,
119
+ collection: Collection<unknown>,
120
+ target: DropTarget | null | undefined,
121
+ direction: DropNavigationDirection,
122
+ rtl = false,
123
+ wrap = false,
124
+ ): DropTarget | null {
125
+ if (direction === "left") {
126
+ return rtl
127
+ ? nextDropTarget(keyboardDelegate, collection, target, wrap, "left")
128
+ : previousDropTarget(keyboardDelegate, collection, target, wrap, "left");
129
+ }
130
+ if (direction === "right") {
131
+ return rtl
132
+ ? previousDropTarget(keyboardDelegate, collection, target, wrap, "right")
133
+ : nextDropTarget(keyboardDelegate, collection, target, wrap, "right");
134
+ }
135
+ return direction === "up"
136
+ ? previousDropTarget(keyboardDelegate, collection, target, wrap)
137
+ : nextDropTarget(keyboardDelegate, collection, target, wrap);
138
+ }
139
+
140
+ function nextDropTarget(
141
+ keyboardDelegate: KeyboardDelegate,
142
+ collection: Collection<unknown>,
143
+ target: DropTarget | null | undefined,
144
+ wrap: boolean,
145
+ horizontal: "left" | "right" | null = null,
146
+ ): DropTarget | null {
147
+ if (target === null || target === undefined) return { type: "root" };
148
+
149
+ if (target.type === "root") {
150
+ const nextKey = keyboardDelegate.getFirstKey?.() ?? null;
151
+ return nextKey === null ? null : { type: "item", key: nextKey, dropPosition: "before" };
152
+ }
153
+
154
+ let nextKey: Key | null | undefined;
155
+ if (horizontal !== null) {
156
+ nextKey =
157
+ horizontal === "right"
158
+ ? keyboardDelegate.getKeyRightOf?.(target.key)
159
+ : keyboardDelegate.getKeyLeftOf?.(target.key);
160
+ } else {
161
+ nextKey = keyboardDelegate.getKeyBelow?.(target.key);
162
+ }
163
+ const nextCollectionKey = nextItemKey(collection, target.key, (key) =>
164
+ collection.getKeyAfter(key),
165
+ );
166
+
167
+ // The delegate jumped somewhere other than the next item (a grid moving a
168
+ // row): keep the position. Otherwise step through this item's positions.
169
+ if (nextKey !== null && nextKey !== undefined && nextKey !== nextCollectionKey) {
170
+ return { type: "item", key: nextKey, dropPosition: target.dropPosition };
171
+ }
172
+
173
+ switch (target.dropPosition) {
174
+ case "before":
175
+ return { type: "item", key: target.key, dropPosition: "on" };
176
+ case "on": {
177
+ // Into the children before past this item; and a next item on this
178
+ // level's "before" is the same place as this one's "after".
179
+ const targetNode = collection.getItem(target.key);
180
+ const nextNode =
181
+ nextKey === null || nextKey === undefined ? null : collection.getItem(nextKey);
182
+ if (targetNode !== null && nextNode !== null && nextNode.level >= targetNode.level) {
183
+ return { type: "item", key: nextNode.key, dropPosition: "before" };
184
+ }
185
+ return { type: "item", key: target.key, dropPosition: "after" };
186
+ }
187
+ case "after": {
188
+ // The last child of a level goes on to its parent's position.
189
+ const targetNode = collection.getItem(target.key);
190
+ const nextInLevel = targetNode === null ? null : nextSiblingItem(collection, targetNode);
191
+
192
+ if (targetNode !== null && nextInLevel === null && targetNode.parentKey !== undefined) {
193
+ const parentNode = collection.getItem(targetNode.parentKey);
194
+ const afterParent = parentNode === null ? null : nextSiblingNode(collection, parentNode);
195
+ if (afterParent?.type === "item") {
196
+ return { type: "item", key: afterParent.key, dropPosition: "before" };
197
+ }
198
+ if (parentNode?.type === "item") {
199
+ return { type: "item", key: parentNode.key, dropPosition: "after" };
200
+ }
201
+ }
202
+
203
+ if (nextInLevel !== null) {
204
+ return { type: "item", key: nextInLevel.key, dropPosition: "on" };
205
+ }
206
+ }
207
+ }
208
+
209
+ return wrap ? { type: "root" } : null;
210
+ }
211
+
212
+ function previousDropTarget(
213
+ keyboardDelegate: KeyboardDelegate,
214
+ collection: Collection<unknown>,
215
+ target: DropTarget | null | undefined,
216
+ wrap: boolean,
217
+ horizontal: "left" | "right" | null = null,
218
+ ): DropTarget | null {
219
+ // From the start: after the last item at the top level. The delegate's last
220
+ // key is the deepest one, so it is walked up to its top-level ancestor.
221
+ if (target === null || target === undefined || (wrap && target.type === "root")) {
222
+ let previousKey: Key | null = null;
223
+ let lastKey: Key | null | undefined = keyboardDelegate.getLastKey?.();
224
+ while (lastKey !== null && lastKey !== undefined) {
225
+ const node = collection.getItem(lastKey);
226
+ if (node?.type !== "item") break;
227
+ previousKey = lastKey;
228
+ lastKey = node.parentKey;
229
+ }
230
+ return previousKey === null ? null : { type: "item", key: previousKey, dropPosition: "after" };
231
+ }
232
+
233
+ if (target.type === "item") {
234
+ let previousKey: Key | null | undefined;
235
+ if (horizontal !== null) {
236
+ previousKey =
237
+ horizontal === "left"
238
+ ? keyboardDelegate.getKeyLeftOf?.(target.key)
239
+ : keyboardDelegate.getKeyRightOf?.(target.key);
240
+ } else {
241
+ previousKey = keyboardDelegate.getKeyAbove?.(target.key);
242
+ }
243
+ const previousCollectionKey = nextItemKey(collection, target.key, (key) =>
244
+ collection.getKeyBefore(key),
245
+ );
246
+
247
+ if (
248
+ previousKey !== null &&
249
+ previousKey !== undefined &&
250
+ previousKey !== previousCollectionKey
251
+ ) {
252
+ return { type: "item", key: previousKey, dropPosition: target.dropPosition };
253
+ }
254
+
255
+ switch (target.dropPosition) {
256
+ case "before": {
257
+ // After the last child of the previous item, when it shows children.
258
+ const targetNode = collection.getItem(target.key);
259
+ const previousNode =
260
+ targetNode === null ? null : previousSiblingNode(collection, targetNode);
261
+ if (previousNode !== null) {
262
+ const lastChild = lastChildTarget(collection, previousNode.key);
263
+ if (lastChild !== null) return lastChild;
264
+ }
265
+ if (previousKey !== null && previousKey !== undefined) {
266
+ return { type: "item", key: previousKey, dropPosition: "on" };
267
+ }
268
+ return { type: "root" };
269
+ }
270
+ case "on":
271
+ return { type: "item", key: target.key, dropPosition: "before" };
272
+ case "after":
273
+ return (
274
+ lastChildTarget(collection, target.key) ?? {
275
+ type: "item",
276
+ key: target.key,
277
+ dropPosition: "on",
278
+ }
279
+ );
280
+ }
281
+ }
282
+
283
+ return target.type !== "root" ? { type: "root" } : null;
284
+ }
285
+
286
+ function lastChildTarget(collection: Collection<unknown>, key: Key): ItemDropTarget | null {
287
+ // A collapsed node still has its children, so whether they are shown is
288
+ // read from whether the next row is deeper.
289
+ const targetNode = collection.getItem(key);
290
+ const nextKey = nextItemKey(collection, key, (at) => collection.getKeyAfter(at));
291
+ const nextNode = nextKey === null ? null : collection.getItem(nextKey);
292
+ if (targetNode === null || nextNode === null || nextNode.level <= targetNode.level) return null;
293
+ const lastChild = targetNode.childNodes.findLast((child) => child.type === "item");
294
+ return lastChild === undefined
295
+ ? null
296
+ : { type: "item", key: lastChild.key, dropPosition: "after" };
297
+ }
298
+
299
+ // ---------------------------------------------------------------------------
300
+ // Drop targets from a point
301
+ // ---------------------------------------------------------------------------
302
+
303
+ export interface ListDropTargetDelegateOptions {
304
+ /** @default "stack" */
305
+ layout?: MaybeAccessor<"stack" | "grid" | undefined>;
306
+ /** The direction the collection scrolls. @default "vertical" */
307
+ orientation?: MaybeAccessor<"horizontal" | "vertical" | undefined>;
308
+ /** @default "ltr" */
309
+ direction?: MaybeAccessor<"ltr" | "rtl" | undefined>;
310
+ }
311
+
312
+ /**
313
+ * Which drop target a point in a list or grid of items is over.
314
+ *
315
+ * Over the middle of an item is "on" it; within five pixels of its leading or
316
+ * trailing edge is "before" or "after", where those are accepted. Between
317
+ * items, the nearer edge decides. The items are found by `data-key`.
318
+ */
319
+ export class ListDropTargetDelegate implements DropTargetDelegate {
320
+ #collection: MaybeAccessor<Iterable<Node<unknown>>>;
321
+ #ref: ElementRef;
322
+ #options: ListDropTargetDelegateOptions;
323
+
324
+ constructor(
325
+ collection: MaybeAccessor<Iterable<Node<unknown>>>,
326
+ ref: ElementRef,
327
+ options: ListDropTargetDelegateOptions = {},
328
+ ) {
329
+ this.#collection = collection;
330
+ this.#ref = ref;
331
+ this.#options = options;
332
+ }
333
+
334
+ get #layout(): "stack" | "grid" {
335
+ return access(this.#options.layout) ?? "stack";
336
+ }
337
+
338
+ get #orientation(): "horizontal" | "vertical" {
339
+ return access(this.#options.orientation) ?? "vertical";
340
+ }
341
+
342
+ get #direction(): "ltr" | "rtl" {
343
+ return access(this.#options.direction) ?? "ltr";
344
+ }
345
+
346
+ #primaryStart(rect: DOMRect): number {
347
+ return this.#orientation === "horizontal" ? rect.left : rect.top;
348
+ }
349
+
350
+ #primaryEnd(rect: DOMRect): number {
351
+ return this.#orientation === "horizontal" ? rect.right : rect.bottom;
352
+ }
353
+
354
+ #secondaryStart(rect: DOMRect): number {
355
+ return this.#orientation === "horizontal" ? rect.top : rect.left;
356
+ }
357
+
358
+ #secondaryEnd(rect: DOMRect): number {
359
+ return this.#orientation === "horizontal" ? rect.bottom : rect.right;
360
+ }
361
+
362
+ #flowStart(rect: DOMRect): number {
363
+ return this.#layout === "stack" ? this.#primaryStart(rect) : this.#secondaryStart(rect);
364
+ }
365
+
366
+ #flowEnd(rect: DOMRect): number {
367
+ return this.#layout === "stack" ? this.#primaryEnd(rect) : this.#secondaryEnd(rect);
368
+ }
369
+
370
+ /**
371
+ * Every item, in order, with a section's items in its place. A collection
372
+ * that answers `getChildren` for a section answers with the rows it shows,
373
+ * nested ones included, which is what a tree's section needs.
374
+ */
375
+ #items(): Node<unknown>[] {
376
+ const collection = access(this.#collection);
377
+ const sectionRows = (section: Node<unknown>): Iterable<Node<unknown>> =>
378
+ typeof (collection as Partial<Collection<unknown>>).getChildren === "function"
379
+ ? (collection as Collection<unknown>).getChildren(section.key)
380
+ : section.childNodes;
381
+ const items: Node<unknown>[] = [];
382
+ for (const node of collection) {
383
+ if (node.type === "item") items.push(node);
384
+ else if (node.type === "section") {
385
+ for (const child of sectionRows(node)) if (child.type === "item") items.push(child);
386
+ }
387
+ }
388
+ return items;
389
+ }
390
+
391
+ getDropTargetFromPoint(
392
+ x: number,
393
+ y: number,
394
+ isValidTarget: (target: DropTarget) => boolean,
395
+ ): DropTarget {
396
+ const container = refElement(this.#ref) as HTMLElement | null;
397
+ const items = this.#items();
398
+ if (container === null || items.length === 0) return { type: "root" };
399
+
400
+ let rect: DOMRect | undefined = container.getBoundingClientRect();
401
+ let primary = this.#orientation === "horizontal" ? x : y;
402
+ let secondary = this.#orientation === "horizontal" ? y : x;
403
+ primary += this.#primaryStart(rect);
404
+ secondary += this.#secondaryStart(rect);
405
+
406
+ const flow = this.#layout === "stack" ? primary : secondary;
407
+ const isPrimaryRTL = this.#orientation === "horizontal" && this.#direction === "rtl";
408
+ const isSecondaryRTL =
409
+ this.#layout === "grid" && this.#orientation === "vertical" && this.#direction === "rtl";
410
+ const isFlowRTL = this.#layout === "stack" ? isPrimaryRTL : isSecondaryRTL;
411
+
412
+ // Scoped to this collection: the nearest collection around an item has to
413
+ // be this one, so a nested one does not answer for it.
414
+ const scope = container.getAttribute("data-collection");
415
+ const elementMap = new Map<string, HTMLElement>();
416
+ for (const element of container.querySelectorAll("[data-key]")) {
417
+ if (!(element instanceof HTMLElement) || element.dataset.key === undefined) continue;
418
+ if (scope !== null) {
419
+ const owner = element.closest("[data-collection]");
420
+ if (owner !== container && owner?.getAttribute("data-collection") !== scope) continue;
421
+ }
422
+ elementMap.set(element.dataset.key, element);
423
+ }
424
+
425
+ let low = 0;
426
+ let high = items.length;
427
+ while (low < high) {
428
+ const mid = Math.floor((low + high) / 2);
429
+ const item = items[mid] as Node<unknown>;
430
+ const element = elementMap.get(String(item.key));
431
+ if (element === undefined) break;
432
+ const itemRect = element.getBoundingClientRect();
433
+ // Which way the point lies past this item, or null when it is over it.
434
+ let isGreater: boolean | null = null;
435
+ if (primary < this.#primaryStart(itemRect)) isGreater = isPrimaryRTL;
436
+ else if (primary > this.#primaryEnd(itemRect)) isGreater = !isPrimaryRTL;
437
+ else if (secondary < this.#secondaryStart(itemRect)) isGreater = isSecondaryRTL;
438
+ else if (secondary > this.#secondaryEnd(itemRect)) isGreater = !isSecondaryRTL;
439
+
440
+ if (isGreater === true) {
441
+ low = mid + 1;
442
+ } else if (isGreater === false) {
443
+ high = mid;
444
+ } else {
445
+ const target: ItemDropTarget = { type: "item", key: item.key, dropPosition: "on" };
446
+ const before: DropPosition = isFlowRTL ? "after" : "before";
447
+ const after: DropPosition = isFlowRTL ? "before" : "after";
448
+
449
+ if (isValidTarget(target)) {
450
+ // On is accepted, so before and after only claim the edges.
451
+ if (
452
+ flow <= this.#flowStart(itemRect) + 5 &&
453
+ isValidTarget({ ...target, dropPosition: "before" })
454
+ ) {
455
+ target.dropPosition = before;
456
+ } else if (
457
+ flow >= this.#flowEnd(itemRect) - 5 &&
458
+ isValidTarget({ ...target, dropPosition: "after" })
459
+ ) {
460
+ target.dropPosition = after;
461
+ }
462
+ } else {
463
+ const middle =
464
+ this.#flowStart(itemRect) + (this.#flowEnd(itemRect) - this.#flowStart(itemRect)) / 2;
465
+ if (flow <= middle && isValidTarget({ ...target, dropPosition: "before" })) {
466
+ target.dropPosition = before;
467
+ } else if (flow >= middle && isValidTarget({ ...target, dropPosition: "after" })) {
468
+ target.dropPosition = after;
469
+ }
470
+ }
471
+ return target;
472
+ }
473
+ }
474
+
475
+ const item = items[Math.min(low, items.length - 1)] as Node<unknown>;
476
+ rect = elementMap.get(String(item.key))?.getBoundingClientRect();
477
+
478
+ if (
479
+ rect !== undefined &&
480
+ (primary < this.#primaryStart(rect) ||
481
+ Math.abs(flow - this.#flowStart(rect)) < Math.abs(flow - this.#flowEnd(rect)))
482
+ ) {
483
+ return { type: "item", key: item.key, dropPosition: isFlowRTL ? "after" : "before" };
484
+ }
485
+ return { type: "item", key: item.key, dropPosition: isFlowRTL ? "before" : "after" };
486
+ }
487
+ }
488
+
489
+ // ---------------------------------------------------------------------------
490
+ // Drop targets from a point, in a tree
491
+ // ---------------------------------------------------------------------------
492
+
493
+ export interface TreeDropTargetState {
494
+ collection: Accessor<Collection<unknown>>;
495
+ expandedKeys: Accessor<Set<Key>>;
496
+ }
497
+
498
+ interface PointerTracking {
499
+ lastY: number;
500
+ lastX: number;
501
+ yDirection: "up" | "down" | null;
502
+ xDirection: "left" | "right" | null;
503
+ boundaryContext: {
504
+ parentKey: Key;
505
+ lastSwitchY: number;
506
+ lastSwitchX: number;
507
+ preferredTargetIndex: number;
508
+ } | null;
509
+ }
510
+
511
+ const X_SWITCH_THRESHOLD = 10;
512
+ const Y_SWITCH_THRESHOLD = 5;
513
+
514
+ /**
515
+ * Which drop target a point in a tree is over, on top of a flat delegate.
516
+ *
517
+ * Below the last child of a branch, one point is several places: after the
518
+ * child, after its parent, after the grandparent. The pointer's vertical
519
+ * movement picks the innermost or outermost on arrival, and horizontal
520
+ * movement walks between them, outwards to the left in a left-to-right
521
+ * layout, as an indented outline suggests. "Before" a row is read as "after"
522
+ * the row above it, and "after" an expanded parent as "before its first
523
+ * child", so each place has one name.
524
+ */
525
+ export class TreeDropTargetDelegate implements DropTargetDelegate {
526
+ #delegate: DropTargetDelegate;
527
+ #state: TreeDropTargetState;
528
+ #direction: MaybeAccessor<"ltr" | "rtl" | undefined>;
529
+ #tracking: PointerTracking = {
530
+ lastY: 0,
531
+ lastX: 0,
532
+ yDirection: null,
533
+ xDirection: null,
534
+ boundaryContext: null,
535
+ };
536
+
537
+ constructor(
538
+ delegate: DropTargetDelegate,
539
+ state: TreeDropTargetState,
540
+ direction: MaybeAccessor<"ltr" | "rtl" | undefined> = "ltr",
541
+ ) {
542
+ this.#delegate = delegate;
543
+ this.#state = state;
544
+ this.#direction = direction;
545
+ }
546
+
547
+ getDropTargetFromPoint(
548
+ x: number,
549
+ y: number,
550
+ isValidTarget: (target: DropTarget) => boolean,
551
+ ): DropTarget | null {
552
+ const base = this.#delegate.getDropTargetFromPoint(x, y, isValidTarget);
553
+ if (base === null || base.type === "root") return base;
554
+ return this.#resolve({ ...base }, x, y, isValidTarget);
555
+ }
556
+
557
+ #resolve(
558
+ start: ItemDropTarget,
559
+ x: number,
560
+ y: number,
561
+ isValidTarget: (target: DropTarget) => boolean,
562
+ ): DropTarget {
563
+ const tracking = this.#tracking;
564
+ const collection = this.#state.collection();
565
+ let target = start;
566
+
567
+ const deltaY = y - tracking.lastY;
568
+ const deltaX = x - tracking.lastX;
569
+ let yMovement = tracking.yDirection;
570
+ let xMovement = tracking.xDirection;
571
+ if (Math.abs(deltaY) > Y_SWITCH_THRESHOLD) {
572
+ yMovement = deltaY > 0 ? "down" : "up";
573
+ tracking.yDirection = yMovement;
574
+ tracking.lastY = y;
575
+ }
576
+ if (Math.abs(deltaX) > X_SWITCH_THRESHOLD) {
577
+ xMovement = deltaX > 0 ? "right" : "left";
578
+ tracking.xDirection = xMovement;
579
+ tracking.lastX = x;
580
+ }
581
+
582
+ if (target.dropPosition === "before") {
583
+ let keyBefore = collection.getKeyBefore(target.key);
584
+ while (keyBefore !== null) {
585
+ const node = collection.getItem(keyBefore);
586
+ if (node?.type === "item") break;
587
+ keyBefore = node?.parentKey ?? null;
588
+ }
589
+ if (keyBefore !== null) {
590
+ const after: ItemDropTarget = { type: "item", key: keyBefore, dropPosition: "after" };
591
+ if (isValidTarget(after)) target = after;
592
+ }
593
+ }
594
+
595
+ const candidates = this.#candidates(target, isValidTarget);
596
+ if (candidates.length === 0) return { type: "root" };
597
+ if (candidates.length === 1) {
598
+ tracking.boundaryContext = null;
599
+ return candidates[0] as ItemDropTarget;
600
+ }
601
+ return this.#select(candidates, target, x, y, yMovement, xMovement);
602
+ }
603
+
604
+ /** The places a target may mean, innermost first. */
605
+ #candidates(
606
+ original: ItemDropTarget,
607
+ isValidTarget: (target: DropTarget) => boolean,
608
+ ): ItemDropTarget[] {
609
+ if (original.dropPosition === "on") return [original];
610
+
611
+ const collection = this.#state.collection();
612
+ const target: ItemDropTarget = { ...original };
613
+ let current = collection.getItem(target.key);
614
+ while (current !== null && current.type !== "item") {
615
+ const next = nextSiblingNode(collection, current);
616
+ if (next === null) break;
617
+ target.key = next.key;
618
+ current = next;
619
+ }
620
+
621
+ // After an expanded parent is before its first child.
622
+ if (
623
+ current !== null &&
624
+ current.hasChildNodes &&
625
+ this.#state.expandedKeys().has(current.key) &&
626
+ target.dropPosition === "after"
627
+ ) {
628
+ const firstChild = current.childNodes.find((child) => child.type === "item");
629
+ if (firstChild !== undefined) {
630
+ const before: ItemDropTarget = {
631
+ type: "item",
632
+ key: firstChild.key,
633
+ dropPosition: "before",
634
+ };
635
+ return isValidTarget(before) ? [before] : [];
636
+ }
637
+ }
638
+
639
+ if (current !== null && nextSiblingNode(collection, current) !== null) return [target];
640
+
641
+ // The last child of a level is also after each ancestor it closes.
642
+ const ancestors: ItemDropTarget[] = [];
643
+ let parentKey = current?.parentKey;
644
+ while (parentKey !== undefined) {
645
+ const parent = collection.getItem(parentKey);
646
+ const afterParent = parent === null ? null : nextSiblingNode(collection, parent);
647
+ // Only an item: a section's key is not one a caller can drop after.
648
+ if (parent?.type === "item") {
649
+ const after: ItemDropTarget = { type: "item", key: parentKey, dropPosition: "after" };
650
+ if (isValidTarget(after)) ancestors.push(after);
651
+ }
652
+ if (afterParent !== null) break;
653
+ parentKey = parent?.parentKey;
654
+ }
655
+
656
+ const candidates = [target, ...ancestors];
657
+
658
+ if (candidates.length === 1) {
659
+ const nextKey = collection.getKeyAfter(target.key);
660
+ const nextNode = nextKey === null ? null : collection.getItem(nextKey);
661
+ if (nextNode !== null && current !== null && nextNode.level > current.level) {
662
+ const before: ItemDropTarget = {
663
+ type: "item",
664
+ key: nextNode.key,
665
+ dropPosition: "before",
666
+ };
667
+ if (isValidTarget(before)) return [before];
668
+ }
669
+ }
670
+
671
+ return candidates.filter(isValidTarget);
672
+ }
673
+
674
+ #select(
675
+ candidates: ItemDropTarget[],
676
+ original: ItemDropTarget,
677
+ x: number,
678
+ y: number,
679
+ yMovement: "up" | "down" | null,
680
+ xMovement: "left" | "right" | null,
681
+ ): ItemDropTarget {
682
+ const tracking = this.#tracking;
683
+ const last = candidates.length - 1;
684
+ const parentKey = this.#state.collection().getItem(original.key)?.parentKey;
685
+ if (parentKey === undefined) return candidates[0] as ItemDropTarget;
686
+
687
+ // Arriving from below starts at the outermost place, from above at the innermost.
688
+ if (tracking.boundaryContext?.parentKey !== parentKey) {
689
+ tracking.boundaryContext = {
690
+ parentKey,
691
+ preferredTargetIndex: tracking.yDirection === "up" ? last : 0,
692
+ lastSwitchY: y,
693
+ lastSwitchX: x,
694
+ };
695
+ }
696
+ const context = tracking.boundaryContext;
697
+
698
+ if (Math.abs(y - context.lastSwitchY) > Y_SWITCH_THRESHOLD && yMovement !== null) {
699
+ if (yMovement === "down" && context.preferredTargetIndex === 0) {
700
+ context.preferredTargetIndex = last;
701
+ } else if (yMovement === "up" && context.preferredTargetIndex === last) {
702
+ context.preferredTargetIndex = 0;
703
+ }
704
+ // Moving diagonally would otherwise switch on both axes and flicker.
705
+ tracking.xDirection = null;
706
+ }
707
+
708
+ if (Math.abs(x - context.lastSwitchX) > X_SWITCH_THRESHOLD && xMovement !== null) {
709
+ const index = context.preferredTargetIndex;
710
+ const outwards = (access(this.#direction) ?? "ltr") === "ltr" ? "left" : "right";
711
+ if (xMovement === outwards) {
712
+ if (index < last) {
713
+ context.preferredTargetIndex = index + 1;
714
+ context.lastSwitchX = x;
715
+ }
716
+ } else if (index > 0) {
717
+ context.preferredTargetIndex = index - 1;
718
+ context.lastSwitchX = x;
719
+ }
720
+ tracking.yDirection = null;
721
+ }
722
+
723
+ const index = Math.max(0, Math.min(context.preferredTargetIndex, last));
724
+ return candidates[index] as ItemDropTarget;
725
+ }
726
+ }