@barqjs/aria 0.2.0-next.0 → 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 (78) hide show
  1. package/README.md +24 -13
  2. package/package.json +127 -37
  3. package/src/autocomplete.tsx +581 -0
  4. package/src/breadcrumbs.tsx +21 -20
  5. package/src/button.tsx +151 -25
  6. package/src/calendar.tsx +1019 -92
  7. package/src/checkbox.tsx +214 -52
  8. package/src/collections.ts +88 -5
  9. package/src/color.ts +1580 -23
  10. package/src/colorpicker.tsx +698 -153
  11. package/src/colorswatchpicker.tsx +240 -0
  12. package/src/combobox.tsx +635 -113
  13. package/src/command.tsx +78 -59
  14. package/src/date.ts +31 -9
  15. package/src/datefield.tsx +1451 -336
  16. package/src/datepicker.tsx +465 -114
  17. package/src/dialog.tsx +302 -115
  18. package/src/disclosure.tsx +81 -29
  19. package/src/dnd/clipboard.ts +125 -0
  20. package/src/dnd/collection.ts +1265 -0
  21. package/src/dnd/data.ts +409 -0
  22. package/src/dnd/drag-drop.ts +801 -0
  23. package/src/dnd/index.ts +133 -0
  24. package/src/dnd/manager.ts +639 -0
  25. package/src/dnd/strings.ts +1279 -0
  26. package/src/dnd/targets.ts +726 -0
  27. package/src/dnd/types.ts +212 -0
  28. package/src/dom.ts +3 -6
  29. package/src/drag-and-drop.tsx +669 -0
  30. package/src/dropzone.tsx +208 -0
  31. package/src/file-trigger.tsx +103 -0
  32. package/src/form.tsx +18 -18
  33. package/src/gridlist.tsx +912 -121
  34. package/src/group.tsx +146 -0
  35. package/src/index.ts +402 -0
  36. package/src/interactions/focus-events.ts +13 -5
  37. package/src/interactions/keyboard.ts +195 -2
  38. package/src/interactions/modality.ts +18 -6
  39. package/src/interactions/open-link.ts +46 -13
  40. package/src/interactions/press.ts +35 -18
  41. package/src/label.ts +18 -6
  42. package/src/link.tsx +146 -50
  43. package/src/listbox.tsx +615 -89
  44. package/src/live.ts +4 -0
  45. package/src/menu.tsx +182 -89
  46. package/src/menubar.tsx +21 -17
  47. package/src/navigation-tree.tsx +357 -0
  48. package/src/numberfield.tsx +164 -60
  49. package/src/overlay-arrow.tsx +157 -0
  50. package/src/overlays.ts +364 -62
  51. package/src/platform.ts +2 -1
  52. package/src/preview-trigger.tsx +582 -0
  53. package/src/progress-bar-context.ts +15 -0
  54. package/src/questionnaire.tsx +109 -104
  55. package/src/radio.tsx +101 -27
  56. package/src/select.tsx +225 -145
  57. package/src/selection-indicator.tsx +74 -0
  58. package/src/selection.ts +73 -16
  59. package/src/shared-element-transition.tsx +316 -0
  60. package/src/sheet.tsx +1461 -0
  61. package/src/slider.tsx +139 -44
  62. package/src/switch.tsx +47 -21
  63. package/src/table.tsx +0 -0
  64. package/src/tabs.tsx +198 -89
  65. package/src/tag.tsx +217 -32
  66. package/src/textarea.tsx +186 -0
  67. package/src/textfield.tsx +103 -37
  68. package/src/toast-components.tsx +589 -0
  69. package/src/toggle-button-group.tsx +175 -0
  70. package/src/toggle-input.tsx +38 -0
  71. package/src/toggle.ts +68 -5
  72. package/src/tokenfield.tsx +1673 -0
  73. package/src/toolbar.tsx +15 -10
  74. package/src/tooltip.tsx +46 -29
  75. package/src/tree.tsx +2075 -0
  76. package/src/utils.ts +30 -1
  77. package/src/validation.ts +79 -22
  78. package/src/virtualizer.tsx +186 -23
@@ -0,0 +1,639 @@
1
+ /**
2
+ * The drag manager: drags driven by a keyboard or a screen reader.
3
+ *
4
+ * The platform's drag and drop cannot be operated without a pointer, so these
5
+ * drags run here instead: a session that starts on Enter or a screen reader's
6
+ * click, walks the registered drop targets with Tab, and drops on Enter.
7
+ */
8
+
9
+ import { type Accessor, createSignal } from "@barqjs/core";
10
+ import { activeElement, contains } from "../dom.ts";
11
+ import type { StringFormatter } from "../i18n.ts";
12
+ import {
13
+ getInteractionModality,
14
+ isVirtualClick,
15
+ isVirtualPointerEvent,
16
+ modality,
17
+ } from "../interactions/modality.ts";
18
+ import type { ElementRef } from "../interactions/press.ts";
19
+ import { announce } from "../live.ts";
20
+ import { ariaHideOutside } from "../overlays.ts";
21
+ import { getTypes, refElement } from "./data.ts";
22
+ import type { DndMessage } from "./strings.ts";
23
+ import type {
24
+ DragEndEvent,
25
+ DragItem,
26
+ DragTypes,
27
+ DropActivateEvent,
28
+ DropEnterEvent,
29
+ DropEvent,
30
+ DropExitEvent,
31
+ DropItem,
32
+ DropOperation,
33
+ DropTarget,
34
+ } from "./types.ts";
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // Modality
38
+ // ---------------------------------------------------------------------------
39
+
40
+ export type DragModality = "keyboard" | "touch" | "virtual";
41
+
42
+ function mapModality(value: string | null): DragModality {
43
+ let next = value ?? "virtual";
44
+ if (next === "pointer") next = "virtual";
45
+ if (
46
+ next === "virtual" &&
47
+ typeof window !== "undefined" &&
48
+ typeof window.matchMedia === "function" &&
49
+ window.matchMedia("(pointer: coarse)").matches
50
+ ) {
51
+ next = "touch";
52
+ }
53
+ return next as DragModality;
54
+ }
55
+
56
+ /** How a drag that does not use a mouse is being driven, right now. */
57
+ export function getDragModality(): DragModality {
58
+ return mapModality(getInteractionModality());
59
+ }
60
+
61
+ /** {@link getDragModality}, as a signal. */
62
+ export function dragModality(): Accessor<DragModality> {
63
+ const current = modality();
64
+ return () => mapModality(current());
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // The drag manager: drags driven by a keyboard or a screen reader
69
+ // ---------------------------------------------------------------------------
70
+
71
+ export interface DragTarget {
72
+ element: HTMLElement;
73
+ items: DragItem[];
74
+ allowedDropOperations: DropOperation[];
75
+ onDragEnd?: (event: DragEndEvent) => void;
76
+ }
77
+
78
+ export interface ManagedDropTarget {
79
+ element: HTMLElement;
80
+ /** Leave focus where the target put it after a drop, rather than re-announcing it. */
81
+ preventFocusOnDrop?: boolean;
82
+ getDropOperation?: (types: DragTypes, allowedOperations: DropOperation[]) => DropOperation;
83
+ onDropEnter?: (event: DropEnterEvent, drag: DragTarget) => void;
84
+ onDropExit?: (event: DropExitEvent) => void;
85
+ onDropTargetEnter?: (target: DropTarget | null) => void;
86
+ onDropActivate?: (event: DropActivateEvent, target: DropTarget | null) => void;
87
+ onDrop?: (event: DropEvent, target: DropTarget | null) => void;
88
+ onKeyDown?: (event: KeyboardEvent, drag: DragTarget) => void;
89
+ activateButtonRef?: ElementRef<HTMLElement>;
90
+ }
91
+
92
+ export interface ManagedDropItem {
93
+ element: HTMLElement;
94
+ target: DropTarget;
95
+ getDropOperation?: (types: DragTypes, allowedOperations: DropOperation[]) => DropOperation;
96
+ activateButtonRef?: ElementRef<HTMLElement>;
97
+ }
98
+
99
+ const dropTargets = new Map<Element, ManagedDropTarget>();
100
+ const dropItems = new Map<Element, ManagedDropItem>();
101
+ let currentSession: DragSession | null = null;
102
+ // Published beside the plain variable: the manager acts on the session in the
103
+ // same handler that started it, before any flush has delivered the signal.
104
+ const [sessionVersion, publishSession] = createSignal(0, { equals: false, ownedWrite: true });
105
+
106
+ /** Make an element a place a keyboard or screen reader drag can be dropped. */
107
+ export function registerDropTarget(target: ManagedDropTarget): () => void {
108
+ dropTargets.set(target.element, target);
109
+ currentSession?.updateValidDropTargets();
110
+ return () => {
111
+ dropTargets.delete(target.element);
112
+ currentSession?.updateValidDropTargets();
113
+ };
114
+ }
115
+
116
+ /** Make an element inside a drop target one of its finer targets: between, or on, an item. */
117
+ export function registerDropItem(item: ManagedDropItem): () => void {
118
+ dropItems.set(item.element, item);
119
+ return () => {
120
+ dropItems.delete(item.element);
121
+ };
122
+ }
123
+
124
+ /** Start a drag that the keyboard or a screen reader will finish. */
125
+ export function beginDragging(target: DragTarget, strings: Accessor<StringFormatter>): void {
126
+ if (currentSession !== null) throw new Error("Cannot begin dragging while already dragging");
127
+
128
+ currentSession = new DragSession(target, strings);
129
+ // A frame later, so the keyup that started the drag is not also read as the
130
+ // first key of the session.
131
+ requestAnimationFrame(() => {
132
+ if (currentSession === null) return;
133
+ currentSession.setup();
134
+ if (getDragModality() === "keyboard") currentSession.next();
135
+ });
136
+ publishSession(0);
137
+ }
138
+
139
+ /** The drag the keyboard or a screen reader is performing, if any. */
140
+ export function dragSession(): DragSession | null {
141
+ sessionVersion();
142
+ return currentSession;
143
+ }
144
+
145
+ /** Whether a keyboard or screen reader drag is in progress. Reactive. */
146
+ export function isVirtualDragging(): boolean {
147
+ return dragSession() !== null;
148
+ }
149
+
150
+ function endDragging(): void {
151
+ currentSession = null;
152
+ publishSession(0);
153
+ }
154
+
155
+ /** Whether `element` is, or is inside, a registered drop target. */
156
+ export function isValidDropTarget(element: Element): boolean {
157
+ for (const target of dropTargets.keys()) {
158
+ if (contains(target, element)) return true;
159
+ }
160
+ return false;
161
+ }
162
+
163
+ const CANCELED_EVENTS = [
164
+ "pointerdown",
165
+ "pointermove",
166
+ "pointerenter",
167
+ "pointerleave",
168
+ "pointerover",
169
+ "pointerout",
170
+ "pointerup",
171
+ "mousedown",
172
+ "mousemove",
173
+ "mouseenter",
174
+ "mouseleave",
175
+ "mouseover",
176
+ "mouseout",
177
+ "mouseup",
178
+ "touchstart",
179
+ "touchmove",
180
+ "touchend",
181
+ "focusin",
182
+ "focusout",
183
+ ];
184
+
185
+ const CLICK_EVENTS = new Set(["pointerup", "mouseup", "touchend"]);
186
+
187
+ const STARTED_MESSAGES: Record<DragModality, DndMessage> = {
188
+ keyboard: "dragStartedKeyboard",
189
+ touch: "dragStartedTouch",
190
+ virtual: "dragStartedVirtual",
191
+ };
192
+
193
+ const HIDDEN_SELECTOR = '[aria-hidden="true"], [inert]';
194
+
195
+ export function centre(element: Element): { x: number; y: number } {
196
+ const rect = element.getBoundingClientRect();
197
+ return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
198
+ }
199
+
200
+ /**
201
+ * One drag without a pointer, from start to drop or cancel.
202
+ *
203
+ * While it runs, the page is reduced to the drag source and the valid drop
204
+ * targets: everything else is made inert, pointer and focus events elsewhere
205
+ * are swallowed, and focus that wanders off is brought back.
206
+ */
207
+ export class DragSession {
208
+ dragTarget: DragTarget;
209
+ validDropTargets: ManagedDropTarget[] = [];
210
+ currentDropTarget: ManagedDropTarget | null = null;
211
+ currentDropItem: ManagedDropItem | null = null;
212
+ dropOperation: DropOperation | null = null;
213
+ #mutationObserver: MutationObserver | null = null;
214
+ #restoreAriaHidden: (() => void) | null = null;
215
+ #strings: Accessor<StringFormatter>;
216
+ #isVirtualClick = false;
217
+ #initialFocused = false;
218
+
219
+ constructor(target: DragTarget, strings: Accessor<StringFormatter>) {
220
+ this.dragTarget = target;
221
+ this.#strings = strings;
222
+ }
223
+
224
+ setup(): void {
225
+ document.addEventListener("keydown", this.onKeyDown, true);
226
+ document.addEventListener("keyup", this.onKeyUp, true);
227
+ window.addEventListener("focus", this.onFocus, true);
228
+ window.addEventListener("blur", this.onBlur, true);
229
+ document.addEventListener("click", this.onClick, true);
230
+ document.addEventListener("pointerdown", this.onPointerDown, true);
231
+ for (const event of CANCELED_EVENTS) {
232
+ document.addEventListener(event, this.cancelEvent, true);
233
+ }
234
+
235
+ this.#mutationObserver = new MutationObserver(() => this.updateValidDropTargets());
236
+ this.updateValidDropTargets();
237
+
238
+ announce(this.#strings().format(STARTED_MESSAGES[getDragModality()]));
239
+ }
240
+
241
+ teardown(): void {
242
+ document.removeEventListener("keydown", this.onKeyDown, true);
243
+ document.removeEventListener("keyup", this.onKeyUp, true);
244
+ window.removeEventListener("focus", this.onFocus, true);
245
+ window.removeEventListener("blur", this.onBlur, true);
246
+ document.removeEventListener("click", this.onClick, true);
247
+ document.removeEventListener("pointerdown", this.onPointerDown, true);
248
+ for (const event of CANCELED_EVENTS) {
249
+ document.removeEventListener(event, this.cancelEvent, true);
250
+ }
251
+
252
+ this.#mutationObserver?.disconnect();
253
+ this.#mutationObserver = null;
254
+ this.#restoreAriaHidden?.();
255
+ this.#restoreAriaHidden = null;
256
+ }
257
+
258
+ onKeyDown = (event: KeyboardEvent): void => {
259
+ this.cancelEvent(event);
260
+
261
+ if (event.key === "Escape") {
262
+ this.cancel();
263
+ return;
264
+ }
265
+
266
+ if (event.key === "Tab" && !(event.metaKey || event.altKey || event.ctrlKey)) {
267
+ if (event.shiftKey) this.previous();
268
+ else this.next();
269
+ }
270
+
271
+ this.currentDropTarget?.onKeyDown?.(event, this.dragTarget);
272
+ };
273
+
274
+ onKeyUp = (event: KeyboardEvent): void => {
275
+ this.cancelEvent(event);
276
+
277
+ if (event.key !== "Enter") return;
278
+ const target = event.target instanceof Node ? event.target : null;
279
+ if (event.altKey || contains(this.#activateButton(), target)) {
280
+ this.activate(this.currentDropTarget, this.currentDropItem);
281
+ } else {
282
+ this.drop();
283
+ }
284
+ };
285
+
286
+ #activateButton(): HTMLElement | null {
287
+ return (refElement(this.currentDropItem?.activateButtonRef) ??
288
+ refElement(this.currentDropTarget?.activateButtonRef)) as HTMLElement | null;
289
+ }
290
+
291
+ onFocus = (event: FocusEvent): void => {
292
+ const target = event.target;
293
+ if (target !== null && target === this.#activateButton()) {
294
+ this.cancelEvent(event);
295
+ return;
296
+ }
297
+
298
+ // Focus goes nowhere but back to the source and to the drop targets.
299
+ if (target !== this.dragTarget.element) this.cancelEvent(event);
300
+
301
+ // The window or the document taking focus is dealt with by `onBlur`.
302
+ if (!(target instanceof HTMLElement) || target === this.dragTarget.element) return;
303
+
304
+ const dropTarget =
305
+ this.validDropTargets.find((candidate) => candidate.element === target) ??
306
+ this.validDropTargets.find((candidate) => contains(candidate.element, target));
307
+
308
+ if (dropTarget === undefined) {
309
+ if (this.currentDropTarget !== null) this.currentDropTarget.element.focus();
310
+ else this.dragTarget.element.focus();
311
+ return;
312
+ }
313
+
314
+ this.setCurrentDropTarget(dropTarget, dropItems.get(target));
315
+ };
316
+
317
+ onBlur = (event: FocusEvent): void => {
318
+ const activateButton = this.#activateButton();
319
+ if (activateButton !== null && event.relatedTarget === activateButton) {
320
+ this.cancelEvent(event);
321
+ return;
322
+ }
323
+
324
+ if (event.target !== this.dragTarget.element) this.cancelEvent(event);
325
+
326
+ // Focus leaving for nothing, or for the window itself: put it back.
327
+ if (event.relatedTarget === null || !(event.relatedTarget instanceof HTMLElement)) {
328
+ if (this.currentDropTarget !== null) this.currentDropTarget.element.focus();
329
+ else this.dragTarget.element.focus();
330
+ }
331
+ };
332
+
333
+ onClick = (event: MouseEvent): void => {
334
+ this.cancelEvent(event);
335
+ if (!isVirtualClick(event) && !this.#isVirtualClick) return;
336
+
337
+ const target = event.target instanceof HTMLElement ? event.target : null;
338
+ const item = [...dropItems.values()].find(
339
+ (candidate) =>
340
+ candidate.element === target || contains(refElement(candidate.activateButtonRef), target),
341
+ );
342
+ const dropTarget = this.validDropTargets.find((candidate) =>
343
+ contains(candidate.element, target),
344
+ );
345
+ const activateButton =
346
+ refElement(item?.activateButtonRef) ?? refElement(dropTarget?.activateButtonRef);
347
+ if (dropTarget !== undefined && contains(activateButton, target)) {
348
+ this.activate(dropTarget, item);
349
+ return;
350
+ }
351
+
352
+ if (target === this.dragTarget.element) {
353
+ this.cancel();
354
+ return;
355
+ }
356
+
357
+ if (dropTarget !== undefined) {
358
+ this.setCurrentDropTarget(dropTarget, item);
359
+ this.drop(item);
360
+ }
361
+ };
362
+
363
+ onPointerDown = (event: PointerEvent): void => {
364
+ // TalkBack's double tap reports `detail` 1 on its click, so whether it is
365
+ // virtual has to be read here, before the click arrives.
366
+ this.cancelEvent(event);
367
+ this.#isVirtualClick = isVirtualPointerEvent(event);
368
+ };
369
+
370
+ cancelEvent = (event: Event): void => {
371
+ // The source and the activate button keep their focus events, or their
372
+ // focus rings would never update.
373
+ if (
374
+ (event.type === "focusin" || event.type === "focusout") &&
375
+ (event.target === this.dragTarget.element || event.target === this.#activateButton())
376
+ ) {
377
+ return;
378
+ }
379
+
380
+ // A cancelled pointerup, mouseup or touchend cancels the click after it.
381
+ if (!CLICK_EVENTS.has(event.type)) event.preventDefault();
382
+ event.stopPropagation();
383
+ event.stopImmediatePropagation();
384
+ };
385
+
386
+ updateValidDropTargets(): void {
387
+ if (this.#mutationObserver === null) return;
388
+
389
+ this.#mutationObserver.disconnect();
390
+ this.#restoreAriaHidden?.();
391
+ this.#restoreAriaHidden = null;
392
+
393
+ this.validDropTargets = findValidDropTargets(this.dragTarget);
394
+
395
+ // Start from the target nearest the source, so Tab goes where the eye does.
396
+ if (this.validDropTargets.length > 0) {
397
+ const nearest = this.#findNearestDropTarget();
398
+ this.validDropTargets = [
399
+ ...this.validDropTargets.slice(nearest),
400
+ ...this.validDropTargets.slice(0, nearest),
401
+ ];
402
+ }
403
+
404
+ if (
405
+ this.currentDropTarget !== null &&
406
+ !this.validDropTargets.includes(this.currentDropTarget)
407
+ ) {
408
+ this.setCurrentDropTarget(this.validDropTargets[0] ?? null);
409
+ }
410
+
411
+ const types = getTypes(this.dragTarget.items);
412
+ const validDropItems = [...dropItems.values()].filter(
413
+ (item) =>
414
+ item.getDropOperation === undefined ||
415
+ item.getDropOperation(types, this.dragTarget.allowedDropOperations) !== "cancel",
416
+ );
417
+
418
+ // A target that holds valid items stays hidden around them: only the
419
+ // items inside it are revealed.
420
+ const visibleDropTargets = this.validDropTargets.filter(
421
+ (target) => !validDropItems.some((item) => contains(target.element, item.element)),
422
+ );
423
+
424
+ const withButton = (element: HTMLElement, button: ElementRef | undefined): Element[] => {
425
+ const activate = refElement(button);
426
+ return activate === null ? [element] : [element, activate];
427
+ };
428
+
429
+ this.#restoreAriaHidden = ariaHideOutside(
430
+ [
431
+ this.dragTarget.element,
432
+ ...validDropItems.flatMap((item) => withButton(item.element, item.activateButtonRef)),
433
+ ...visibleDropTargets.flatMap((target) =>
434
+ withButton(target.element, target.activateButtonRef),
435
+ ),
436
+ ],
437
+ { shouldUseInert: true },
438
+ );
439
+
440
+ this.#mutationObserver.observe(document.body, {
441
+ subtree: true,
442
+ attributes: true,
443
+ attributeFilter: ["aria-hidden", "inert"],
444
+ });
445
+ }
446
+
447
+ next(): void {
448
+ if (this.currentDropTarget === null) {
449
+ this.setCurrentDropTarget(this.validDropTargets[0] ?? null);
450
+ return;
451
+ }
452
+
453
+ const index = this.validDropTargets.indexOf(this.currentDropTarget);
454
+ if (index < 0) {
455
+ this.setCurrentDropTarget(this.validDropTargets[0] ?? null);
456
+ return;
457
+ }
458
+
459
+ // Past the last target, back to the source, which is how a keyboard with
460
+ // no Escape key (an iPad's) cancels.
461
+ if (index === this.validDropTargets.length - 1) {
462
+ if (this.dragTarget.element.closest(HIDDEN_SELECTOR) === null) {
463
+ this.setCurrentDropTarget(null);
464
+ this.dragTarget.element.focus();
465
+ } else {
466
+ this.setCurrentDropTarget(this.validDropTargets[0] ?? null);
467
+ }
468
+ } else {
469
+ this.setCurrentDropTarget(this.validDropTargets[index + 1] ?? null);
470
+ }
471
+ }
472
+
473
+ previous(): void {
474
+ const last = this.validDropTargets[this.validDropTargets.length - 1] ?? null;
475
+ if (this.currentDropTarget === null) {
476
+ this.setCurrentDropTarget(last);
477
+ return;
478
+ }
479
+
480
+ const index = this.validDropTargets.indexOf(this.currentDropTarget);
481
+ if (index < 0) {
482
+ this.setCurrentDropTarget(last);
483
+ return;
484
+ }
485
+
486
+ if (index === 0) {
487
+ if (this.dragTarget.element.closest(HIDDEN_SELECTOR) === null) {
488
+ this.setCurrentDropTarget(null);
489
+ this.dragTarget.element.focus();
490
+ } else {
491
+ this.setCurrentDropTarget(last);
492
+ }
493
+ } else {
494
+ this.setCurrentDropTarget(this.validDropTargets[index - 1] ?? null);
495
+ }
496
+ }
497
+
498
+ /** The target containing the source wins; otherwise the closest by top-left corner. */
499
+ #findNearestDropTarget(): number {
500
+ const source = this.dragTarget.element.getBoundingClientRect();
501
+ let minDistance = Infinity;
502
+ let nearest = -1;
503
+ let ancestor = -1;
504
+ for (let i = 0; i < this.validDropTargets.length; i++) {
505
+ const target = this.validDropTargets[i] as ManagedDropTarget;
506
+ if (ancestor < 0 && contains(target.element, this.dragTarget.element)) ancestor = i;
507
+ const rect = target.element.getBoundingClientRect();
508
+ const dx = rect.left - source.left;
509
+ const dy = rect.top - source.top;
510
+ const distance = dx * dx + dy * dy;
511
+ if (distance < minDistance) {
512
+ minDistance = distance;
513
+ nearest = i;
514
+ }
515
+ }
516
+ return ancestor >= 0 ? ancestor : nearest;
517
+ }
518
+
519
+ setCurrentDropTarget(dropTarget: ManagedDropTarget | null, item?: ManagedDropItem): void {
520
+ if (dropTarget !== this.currentDropTarget) {
521
+ if (this.currentDropTarget?.onDropExit !== undefined) {
522
+ const { x, y } = centre(this.currentDropTarget.element);
523
+ this.currentDropTarget.onDropExit({ type: "dropexit", x, y });
524
+ }
525
+
526
+ this.currentDropTarget = dropTarget;
527
+
528
+ if (dropTarget !== null) {
529
+ if (dropTarget.onDropEnter !== undefined) {
530
+ const { x, y } = centre(dropTarget.element);
531
+ dropTarget.onDropEnter({ type: "dropenter", x, y }, this.dragTarget);
532
+ }
533
+ if (item === undefined) dropTarget.element.focus();
534
+ }
535
+ }
536
+
537
+ if (item !== undefined && item !== this.currentDropItem) {
538
+ this.currentDropTarget?.onDropTargetEnter?.(item.target);
539
+ item.element.focus();
540
+ this.currentDropItem = item;
541
+
542
+ // The first target is announced politely, after the assertive "started
543
+ // dragging", which would otherwise talk over it.
544
+ if (!this.#initialFocused) {
545
+ const label = item.element.getAttribute("aria-label");
546
+ if (label !== null && label !== "") announce(label, "polite");
547
+ this.#initialFocused = true;
548
+ }
549
+ }
550
+ }
551
+
552
+ end(): void {
553
+ this.teardown();
554
+ endDragging();
555
+
556
+ if (this.dragTarget.onDragEnd !== undefined) {
557
+ const target =
558
+ this.currentDropTarget !== null && this.dropOperation !== "cancel"
559
+ ? this.currentDropTarget
560
+ : this.dragTarget;
561
+ const { x, y } = centre(target.element);
562
+ this.dragTarget.onDragEnd({
563
+ type: "dragend",
564
+ x,
565
+ y,
566
+ dropOperation: this.dropOperation ?? "cancel",
567
+ });
568
+ }
569
+
570
+ // Focus events were swallowed during the drag, so whatever holds focus now
571
+ // never heard it arrive. A collection repairs its own focus after a drop.
572
+ if (this.currentDropTarget !== null && this.currentDropTarget.preventFocusOnDrop !== true) {
573
+ activeElement()?.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
574
+ }
575
+
576
+ this.setCurrentDropTarget(null);
577
+ }
578
+
579
+ cancel(): void {
580
+ this.setCurrentDropTarget(null);
581
+ this.end();
582
+ if (this.dragTarget.element.closest(HIDDEN_SELECTOR) === null) {
583
+ this.dragTarget.element.focus();
584
+ }
585
+ activeElement()?.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
586
+ announce(this.#strings().format("dropCanceled"));
587
+ }
588
+
589
+ drop(item?: ManagedDropItem): void {
590
+ const target = this.currentDropTarget;
591
+ if (target === null) {
592
+ this.cancel();
593
+ return;
594
+ }
595
+
596
+ const types = getTypes(this.dragTarget.items);
597
+ if (item?.getDropOperation !== undefined) {
598
+ this.dropOperation = item.getDropOperation(types, this.dragTarget.allowedDropOperations);
599
+ } else if (target.getDropOperation !== undefined) {
600
+ this.dropOperation = target.getDropOperation(types, this.dragTarget.allowedDropOperations);
601
+ } else {
602
+ this.dropOperation = this.dragTarget.allowedDropOperations[0] ?? "cancel";
603
+ }
604
+
605
+ if (target.onDrop !== undefined) {
606
+ const items: DropItem[] = this.dragTarget.items.map((dragged) => ({
607
+ kind: "text",
608
+ types: new Set(Object.keys(dragged)),
609
+ getText: (type: string) => Promise.resolve(dragged[type] as string),
610
+ }));
611
+ const { x, y } = centre(target.element);
612
+ target.onDrop(
613
+ { type: "drop", x, y, items, dropOperation: this.dropOperation },
614
+ item?.target ?? null,
615
+ );
616
+ }
617
+
618
+ this.end();
619
+ announce(this.#strings().format("dropComplete"));
620
+ }
621
+
622
+ activate(
623
+ dropTarget: ManagedDropTarget | null,
624
+ dropItem: ManagedDropItem | null | undefined,
625
+ ): void {
626
+ if (dropTarget?.onDropActivate === undefined) return;
627
+ const { x, y } = centre(dropTarget.element);
628
+ dropTarget.onDropActivate({ type: "dropactivate", x, y }, dropItem?.target ?? null);
629
+ }
630
+ }
631
+
632
+ function findValidDropTargets(dragTarget: DragTarget): ManagedDropTarget[] {
633
+ const types = getTypes(dragTarget.items);
634
+ return [...dropTargets.values()].filter((target) => {
635
+ if (target.element.closest(HIDDEN_SELECTOR) !== null) return false;
636
+ if (target.getDropOperation === undefined) return true;
637
+ return target.getDropOperation(types, dragTarget.allowedDropOperations) !== "cancel";
638
+ });
639
+ }