@barqjs/aria 0.0.0-stage → 0.2.0-next.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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -2
  3. package/package.json +347 -4
  4. package/src/breadcrumbs.tsx +296 -0
  5. package/src/button.tsx +342 -0
  6. package/src/calendar.tsx +1389 -0
  7. package/src/checkbox.tsx +570 -0
  8. package/src/collections.ts +976 -0
  9. package/src/color.ts +562 -0
  10. package/src/colorpicker.tsx +1478 -0
  11. package/src/combobox.tsx +2481 -0
  12. package/src/command.tsx +1184 -0
  13. package/src/date.ts +652 -0
  14. package/src/datefield.tsx +951 -0
  15. package/src/datepicker.tsx +556 -0
  16. package/src/dialog.tsx +890 -0
  17. package/src/disclosure.tsx +659 -0
  18. package/src/dom.ts +706 -0
  19. package/src/drawer.ts +674 -0
  20. package/src/focus.ts +1370 -0
  21. package/src/form.tsx +94 -0
  22. package/src/gridlist.tsx +563 -0
  23. package/src/i18n.ts +823 -0
  24. package/src/index.ts +1270 -0
  25. package/src/interactions/description.ts +73 -0
  26. package/src/interactions/flags.ts +35 -0
  27. package/src/interactions/focus-events.ts +218 -0
  28. package/src/interactions/focusable.ts +86 -0
  29. package/src/interactions/hover.ts +213 -0
  30. package/src/interactions/interact-outside.ts +123 -0
  31. package/src/interactions/keyboard.ts +105 -0
  32. package/src/interactions/listeners.ts +78 -0
  33. package/src/interactions/long-press.ts +160 -0
  34. package/src/interactions/modality.ts +416 -0
  35. package/src/interactions/move.ts +257 -0
  36. package/src/interactions/open-link.ts +193 -0
  37. package/src/interactions/press.ts +898 -0
  38. package/src/interactions/prevent-focus.ts +102 -0
  39. package/src/interactions/scroll-wheel.ts +43 -0
  40. package/src/interactions/text-selection.ts +77 -0
  41. package/src/interactions.ts +81 -0
  42. package/src/label.ts +128 -0
  43. package/src/link.tsx +381 -0
  44. package/src/listbox.tsx +721 -0
  45. package/src/live.ts +204 -0
  46. package/src/menu.tsx +2290 -0
  47. package/src/menubar.tsx +575 -0
  48. package/src/navigation.ts +735 -0
  49. package/src/numberfield.tsx +838 -0
  50. package/src/otp.ts +430 -0
  51. package/src/overlays.ts +1247 -0
  52. package/src/platform.ts +74 -0
  53. package/src/presence.ts +164 -0
  54. package/src/questionnaire.tsx +1712 -0
  55. package/src/radio.tsx +567 -0
  56. package/src/register-dom.ts +12 -0
  57. package/src/scroller.ts +1165 -0
  58. package/src/select.tsx +1665 -0
  59. package/src/selection.ts +1415 -0
  60. package/src/slider.tsx +1042 -0
  61. package/src/splitter.ts +1152 -0
  62. package/src/static-collection.ts +211 -0
  63. package/src/switch.tsx +186 -0
  64. package/src/table.tsx +0 -0
  65. package/src/tabs.tsx +1018 -0
  66. package/src/tag.tsx +452 -0
  67. package/src/textfield.tsx +417 -0
  68. package/src/toast.ts +658 -0
  69. package/src/toggle-input.tsx +48 -0
  70. package/src/toggle.ts +321 -0
  71. package/src/togglegroup.ts +365 -0
  72. package/src/toolbar.tsx +179 -0
  73. package/src/tooltip.tsx +657 -0
  74. package/src/utils.ts +758 -0
  75. package/src/validation.ts +447 -0
  76. package/src/virtualizer.tsx +674 -0
@@ -0,0 +1,1415 @@
1
+ /**
2
+ * Keyboard and pointer behaviour over a collection.
3
+ *
4
+ * A listbox is one Tab stop, not one per option. Inside it the arrow keys
5
+ * move a roving `tabindex`, typing jumps to a matching item, Home and End go
6
+ * to the ends, Shift extends a range and Escape clears. None of that is
7
+ * something the platform does for a `<div role="listbox">`, and all of it is
8
+ * what the ARIA authoring practices require before a listbox is a listbox.
9
+ *
10
+ * Three details separate this from an arrow-key handler:
11
+ *
12
+ * - Selection follows focus, or it does not, depending on the selection
13
+ * behaviour: a file-manager list selects as you arrow through it, a checkbox
14
+ * list does not.
15
+ * - Where focus lands when the collection is entered depends on which way the
16
+ * user tabbed into it, which `relatedTarget` answers.
17
+ * - A press selects on pointer DOWN in a list and on pointer UP in a menu,
18
+ * because a menu closes on selection and selecting on down would swallow the
19
+ * press that opened it.
20
+ */
21
+
22
+ import { type Accessor, createEffect, createSignal } from "@barqjs/core";
23
+ import { tryCleanup } from "@barqjs/primitives/utils";
24
+ import {
25
+ activeElement,
26
+ contains,
27
+ focusWithoutScrolling,
28
+ isScrollable,
29
+ isTabbable,
30
+ ownerDocument,
31
+ scrollIntoView,
32
+ scrollIntoViewport,
33
+ targetElement,
34
+ } from "./dom.ts";
35
+ import type {
36
+ Collection,
37
+ Key,
38
+ LayoutDelegate,
39
+ Node,
40
+ Rect,
41
+ SelectionManager,
42
+ Size,
43
+ } from "./collections.ts";
44
+ import { focusableWalker } from "./focus.ts";
45
+ import { collator, useLocale } from "./i18n.ts";
46
+ import { focusSafely } from "./interactions/focusable.ts";
47
+ import type { BaseEvent } from "./interactions/keyboard.ts";
48
+ import { getInteractionModality, type PointerType } from "./interactions/modality.ts";
49
+ import { longPress } from "./interactions/long-press.ts";
50
+ import { router } from "./interactions/open-link.ts";
51
+ import { press, type ElementRef, type PressEvent } from "./interactions/press.ts";
52
+ import { isAppleDevice, isMac } from "./platform.ts";
53
+ import { access, chain, id, mergeProps, type DOMProps, type MaybeAccessor } from "./utils.ts";
54
+
55
+ /**
56
+ * The modifier that adds to a selection without extending it.
57
+ *
58
+ * Control with an arrow key has a system-wide meaning on macOS, so Alt takes
59
+ * its place there; Alt with Space has one on Windows and Linux, so it cannot
60
+ * be used everywhere.
61
+ */
62
+ export function isNonContiguousSelectionModifier(event: {
63
+ altKey?: boolean;
64
+ ctrlKey?: boolean;
65
+ }): boolean {
66
+ return isAppleDevice() ? event.altKey === true : event.ctrlKey === true;
67
+ }
68
+
69
+ /** The platform's "select several" modifier. */
70
+ export function isCtrlKeyPressed(event: { ctrlKey?: boolean; metaKey?: boolean }): boolean {
71
+ return isMac() ? event.metaKey === true : event.ctrlKey === true;
72
+ }
73
+
74
+ /** The rendered element for a key, if it is rendered at all. */
75
+ export function itemElement(container: Element | null | undefined, key: Key): Element | null {
76
+ if (container === null || container === undefined) return null;
77
+ let selector = `[data-key="${CSS.escape(String(key))}"]`;
78
+ const collection = (container as HTMLElement).dataset?.collection;
79
+ // Scoped to this collection, so a nested one — a tag group inside a table
80
+ // cell — does not answer for its parent.
81
+ if (collection !== undefined)
82
+ selector = `[data-collection="${CSS.escape(collection)}"]${selector}`;
83
+ return container.querySelector(selector);
84
+ }
85
+
86
+ // ---------------------------------------------------------------------------
87
+ // Layout and keyboard delegates
88
+ // ---------------------------------------------------------------------------
89
+
90
+ export type { LayoutDelegate, Rect, Size } from "./collections.ts";
91
+
92
+ /** Geometry read from the rendered DOM. */
93
+ export class DOMLayoutDelegate implements LayoutDelegate {
94
+ #ref: ElementRef;
95
+
96
+ constructor(ref: ElementRef) {
97
+ this.#ref = ref;
98
+ }
99
+
100
+ #container(): HTMLElement | null {
101
+ return (access(this.#ref) as HTMLElement | null) ?? null;
102
+ }
103
+
104
+ getItemRect(key: Key): Rect | null {
105
+ const container = this.#container();
106
+ if (container === null) return null;
107
+ const item = itemElement(container, key);
108
+ if (item === null) return null;
109
+
110
+ const bounds = container.getBoundingClientRect();
111
+ const rect = item.getBoundingClientRect();
112
+ return {
113
+ x: rect.left - bounds.left - container.clientLeft + container.scrollLeft,
114
+ y: rect.top - bounds.top - container.clientTop + container.scrollTop,
115
+ width: rect.width,
116
+ height: rect.height,
117
+ };
118
+ }
119
+
120
+ getContentSize(): Size {
121
+ const container = this.#container();
122
+ return { width: container?.scrollWidth ?? 0, height: container?.scrollHeight ?? 0 };
123
+ }
124
+
125
+ getVisibleRect(): Rect {
126
+ const container = this.#container();
127
+ return {
128
+ x: container?.scrollLeft ?? 0,
129
+ y: container?.scrollTop ?? 0,
130
+ width: container?.clientWidth ?? 0,
131
+ height: container?.clientHeight ?? 0,
132
+ };
133
+ }
134
+ }
135
+
136
+ /** Which key each navigation lands on. */
137
+ export interface KeyboardDelegate {
138
+ getKeyBelow?(key: Key): Key | null;
139
+ getKeyAbove?(key: Key): Key | null;
140
+ getKeyLeftOf?(key: Key): Key | null;
141
+ getKeyRightOf?(key: Key): Key | null;
142
+ getKeyPageBelow?(key: Key): Key | null;
143
+ getKeyPageAbove?(key: Key): Key | null;
144
+ getFirstKey?(fromKey?: Key | null, global?: boolean): Key | null;
145
+ getLastKey?(fromKey?: Key | null, global?: boolean): Key | null;
146
+ getKeyForSearch?(search: string, fromKey?: Key | null): Key | null;
147
+ }
148
+
149
+ export type Orientation = "horizontal" | "vertical";
150
+ export type Direction = "ltr" | "rtl";
151
+
152
+ export interface ListKeyboardDelegateOptions {
153
+ collection: Accessor<Collection<unknown>>;
154
+ ref: ElementRef;
155
+ disabledKeys?: Accessor<Set<Key>>;
156
+ disabledBehavior?: Accessor<"selection" | "all">;
157
+ collator?: Accessor<Intl.Collator>;
158
+ layout?: "stack" | "grid";
159
+ orientation?: MaybeAccessor<Orientation | undefined>;
160
+ direction?: MaybeAccessor<Direction | undefined>;
161
+ layoutDelegate?: LayoutDelegate;
162
+ }
163
+
164
+ /**
165
+ * Navigation for a list or a grid of items.
166
+ *
167
+ * Disabled items are skipped rather than focused-and-ignored, so holding Down
168
+ * through a list of ten disabled rows takes one keypress, not ten.
169
+ */
170
+ export class ListKeyboardDelegate implements KeyboardDelegate {
171
+ #options: ListKeyboardDelegateOptions;
172
+ #layout: LayoutDelegate;
173
+
174
+ constructor(options: ListKeyboardDelegateOptions) {
175
+ this.#options = options;
176
+ this.#layout = options.layoutDelegate ?? new DOMLayoutDelegate(options.ref);
177
+ }
178
+
179
+ get #collection(): Collection<unknown> {
180
+ return this.#options.collection();
181
+ }
182
+
183
+ get #orientation(): Orientation {
184
+ return access(this.#options.orientation) ?? "vertical";
185
+ }
186
+
187
+ get #direction(): Direction {
188
+ return access(this.#options.direction) ?? "ltr";
189
+ }
190
+
191
+ #isDisabled(item: Node<unknown>): boolean {
192
+ const behavior = this.#options.disabledBehavior?.() ?? "all";
193
+ const disabled = this.#options.disabledKeys?.() ?? new Set<Key>();
194
+ return (
195
+ behavior === "all" &&
196
+ (item.props?.isDisabled === true || disabled.has(item.key)) &&
197
+ item.props?.disabledBehavior !== "selection"
198
+ );
199
+ }
200
+
201
+ #nextEnabled(key: Key | null, step: (key: Key) => Key | null): Key | null {
202
+ let at = key;
203
+ while (at !== null) {
204
+ const item = this.#collection.getItem(at);
205
+ if (item?.type === "item" && !this.#isDisabled(item)) return at;
206
+ at = step(at);
207
+ }
208
+ return null;
209
+ }
210
+
211
+ getNextKey(key: Key): Key | null {
212
+ return this.#nextEnabled(this.#collection.getKeyAfter(key), (k) =>
213
+ this.#collection.getKeyAfter(k),
214
+ );
215
+ }
216
+
217
+ getPreviousKey(key: Key): Key | null {
218
+ return this.#nextEnabled(this.#collection.getKeyBefore(key), (k) =>
219
+ this.#collection.getKeyBefore(k),
220
+ );
221
+ }
222
+
223
+ #sameRow(previous: Rect, current: Rect): boolean {
224
+ return previous.y === current.y || previous.x !== current.x;
225
+ }
226
+
227
+ #sameColumn(previous: Rect, current: Rect): boolean {
228
+ return previous.x === current.x || previous.y !== current.y;
229
+ }
230
+
231
+ /** Step until the geometry says we have left the row or column. */
232
+ #findKey(
233
+ key: Key,
234
+ step: (key: Key) => Key | null,
235
+ skip: (previous: Rect, current: Rect) => boolean,
236
+ ): Key | null {
237
+ let at: Key | null = key;
238
+ let rect = this.#layout.getItemRect(at);
239
+ if (rect === null) return null;
240
+
241
+ const from = rect;
242
+ do {
243
+ at = step(at);
244
+ if (at === null) break;
245
+ rect = this.#layout.getItemRect(at);
246
+ } while (rect !== null && skip(from, rect) && at !== null);
247
+
248
+ return at;
249
+ }
250
+
251
+ getKeyBelow(key: Key): Key | null {
252
+ if (this.#options.layout === "grid" && this.#orientation === "vertical") {
253
+ return this.#findKey(
254
+ key,
255
+ (k) => this.getNextKey(k),
256
+ (a, b) => this.#sameRow(a, b),
257
+ );
258
+ }
259
+ return this.getNextKey(key);
260
+ }
261
+
262
+ getKeyAbove(key: Key): Key | null {
263
+ if (this.#options.layout === "grid" && this.#orientation === "vertical") {
264
+ return this.#findKey(
265
+ key,
266
+ (k) => this.getPreviousKey(k),
267
+ (a, b) => this.#sameRow(a, b),
268
+ );
269
+ }
270
+ return this.getPreviousKey(key);
271
+ }
272
+
273
+ #nextColumn(key: Key, reversed: boolean): Key | null {
274
+ return reversed ? this.getPreviousKey(key) : this.getNextKey(key);
275
+ }
276
+
277
+ getKeyRightOf(key: Key): Key | null {
278
+ const rtl = this.#direction === "rtl";
279
+ if (this.#options.layout === "grid") {
280
+ if (this.#orientation === "vertical") return this.#nextColumn(key, rtl);
281
+ return this.#findKey(
282
+ key,
283
+ (k) => this.#nextColumn(k, rtl),
284
+ (a, b) => this.#sameColumn(a, b),
285
+ );
286
+ }
287
+ if (this.#orientation === "horizontal") return this.#nextColumn(key, rtl);
288
+ return null;
289
+ }
290
+
291
+ getKeyLeftOf(key: Key): Key | null {
292
+ const ltr = this.#direction === "ltr";
293
+ if (this.#options.layout === "grid") {
294
+ if (this.#orientation === "vertical") return this.#nextColumn(key, ltr);
295
+ return this.#findKey(
296
+ key,
297
+ (k) => this.#nextColumn(k, ltr),
298
+ (a, b) => this.#sameColumn(a, b),
299
+ );
300
+ }
301
+ if (this.#orientation === "horizontal") return this.#nextColumn(key, ltr);
302
+ return null;
303
+ }
304
+
305
+ getFirstKey(): Key | null {
306
+ return this.#nextEnabled(this.#collection.getFirstKey(), (k) =>
307
+ this.#collection.getKeyAfter(k),
308
+ );
309
+ }
310
+
311
+ getLastKey(): Key | null {
312
+ return this.#nextEnabled(this.#collection.getLastKey(), (k) =>
313
+ this.#collection.getKeyBefore(k),
314
+ );
315
+ }
316
+
317
+ getKeyPageAbove(key: Key): Key | null {
318
+ const container = access(this.#options.ref) as HTMLElement | null;
319
+ let rect = this.#layout.getItemRect(key);
320
+ if (rect === null) return null;
321
+
322
+ // Nothing scrolls, so a page is the whole list.
323
+ if (container !== null && !isScrollable(container)) return this.getFirstKey();
324
+
325
+ const visible = this.#layout.getVisibleRect();
326
+ let at: Key | null = key;
327
+
328
+ if (this.#orientation === "horizontal") {
329
+ const pageX = Math.max(0, rect.x + rect.width - visible.width);
330
+ while (rect !== null && rect.x > pageX && at !== null) {
331
+ at = this.getKeyAbove(at);
332
+ rect = at === null ? null : this.#layout.getItemRect(at);
333
+ }
334
+ } else {
335
+ const pageY = Math.max(0, rect.y + rect.height - visible.height);
336
+ while (rect !== null && rect.y > pageY && at !== null) {
337
+ at = this.getKeyAbove(at);
338
+ rect = at === null ? null : this.#layout.getItemRect(at);
339
+ }
340
+ }
341
+
342
+ return at ?? this.getFirstKey();
343
+ }
344
+
345
+ getKeyPageBelow(key: Key): Key | null {
346
+ const container = access(this.#options.ref) as HTMLElement | null;
347
+ let rect = this.#layout.getItemRect(key);
348
+ if (rect === null) return null;
349
+
350
+ if (container !== null && !isScrollable(container)) return this.getLastKey();
351
+
352
+ const visible = this.#layout.getVisibleRect();
353
+ const content = this.#layout.getContentSize();
354
+ let at: Key | null = key;
355
+
356
+ if (this.#orientation === "horizontal") {
357
+ const pageX = Math.min(content.width, rect.x - rect.width + visible.width);
358
+ while (rect !== null && rect.x < pageX && at !== null) {
359
+ at = this.getKeyBelow(at);
360
+ rect = at === null ? null : this.#layout.getItemRect(at);
361
+ }
362
+ } else {
363
+ const pageY = Math.min(content.height, rect.y - rect.height + visible.height);
364
+ while (rect !== null && rect.y < pageY && at !== null) {
365
+ at = this.getKeyBelow(at);
366
+ rect = at === null ? null : this.#layout.getItemRect(at);
367
+ }
368
+ }
369
+
370
+ return at ?? this.getLastKey();
371
+ }
372
+
373
+ getKeyForSearch(search: string, fromKey?: Key | null): Key | null {
374
+ const compare = this.#options.collator?.();
375
+ if (compare === undefined) return null;
376
+
377
+ let key = fromKey ?? this.getFirstKey();
378
+ while (key !== null) {
379
+ const item = this.#collection.getItem(key);
380
+ if (item === null) return null;
381
+ const prefix = item.textValue.slice(0, search.length);
382
+ if (item.textValue !== "" && compare.compare(prefix, search) === 0) return key;
383
+ key = this.getNextKey(key);
384
+ }
385
+
386
+ return null;
387
+ }
388
+ }
389
+
390
+ // ---------------------------------------------------------------------------
391
+ // Typeahead
392
+ // ---------------------------------------------------------------------------
393
+
394
+ const TYPEAHEAD_TIMEOUT = 1000;
395
+
396
+ export interface TypeSelectOptions {
397
+ keyboardDelegate: KeyboardDelegate;
398
+ selectionManager: Accessor<SelectionManager>;
399
+ onTypeSelect?: (key: Key) => void;
400
+ }
401
+
402
+ export interface TypeSelectResult {
403
+ typeSelectProps: DOMProps;
404
+ }
405
+
406
+ /**
407
+ * Jump to an item by typing its first letters.
408
+ *
409
+ * Space is the awkward case: it is a selection key when nothing has been
410
+ * typed, and part of the search once something has. The two are told apart by
411
+ * whether the buffer is empty, which is why the Space branch has to run before
412
+ * the selection handler sees the key.
413
+ */
414
+ export function typeSelect(options: TypeSelectOptions): TypeSelectResult {
415
+ const state = { search: "", timeout: undefined as ReturnType<typeof setTimeout> | undefined };
416
+
417
+ tryCleanup(() => clearTimeout(state.timeout));
418
+
419
+ const restartTimer = (): void => {
420
+ clearTimeout(state.timeout);
421
+ state.timeout = setTimeout(() => {
422
+ state.search = "";
423
+ }, TYPEAHEAD_TIMEOUT);
424
+ };
425
+
426
+ const jump = (): boolean => {
427
+ const manager = options.selectionManager();
428
+ // After the focused item first, so repeated letters cycle forwards rather
429
+ // than always landing on the first match.
430
+ let key = options.keyboardDelegate.getKeyForSearch?.(state.search, manager.focusedKey) ?? null;
431
+ if (key === null) key = options.keyboardDelegate.getKeyForSearch?.(state.search) ?? null;
432
+ if (key === null) return false;
433
+
434
+ manager.setFocusedKey(key);
435
+ options.onTypeSelect?.(key);
436
+ return true;
437
+ };
438
+
439
+ const onKeyDown = (event: KeyboardEvent): void => {
440
+ const character = characterFor(event.key);
441
+ const currentTarget = event.currentTarget as Element | null;
442
+ if (
443
+ character === "" ||
444
+ event.ctrlKey ||
445
+ event.metaKey ||
446
+ event.altKey ||
447
+ currentTarget === null ||
448
+ !contains(currentTarget, targetElement(event)) ||
449
+ (state.search.length === 0 && character === " ")
450
+ ) {
451
+ return;
452
+ }
453
+
454
+ state.search += character;
455
+
456
+ if (jump()) {
457
+ event.preventDefault();
458
+ event.stopPropagation();
459
+ } else {
460
+ state.search = "";
461
+ clearTimeout(state.timeout);
462
+ state.timeout = undefined;
463
+ return;
464
+ }
465
+
466
+ restartTimer();
467
+ };
468
+
469
+ /**
470
+ * A Space typed MID-SEARCH is a search character, not "select the focused
471
+ * item", and the two are told apart only by whether the buffer is empty.
472
+ *
473
+ * It is claimed in the CAPTURE phase, before the selection handler in the
474
+ * bubble phase sees it.
475
+ */
476
+ const onKeyDownCapture = (event: KeyboardEvent): void => {
477
+ if (state.search.length === 0 || event.key !== " ") return;
478
+ event.preventDefault();
479
+ event.stopPropagation();
480
+ state.search += " ";
481
+ jump();
482
+ restartTimer();
483
+ };
484
+
485
+ return { typeSelectProps: { onKeyDown, onKeyDownCapture } };
486
+ }
487
+
488
+ function characterFor(key: string): string {
489
+ // A single character is what was typed. A longer name that starts with a
490
+ // letter is a named key ("Enter", "ArrowDown"); one that does not is a
491
+ // Unicode character with a multi-code-point name.
492
+ if (key.length === 1 || !/^[A-Z]/i.test(key)) return key;
493
+ return "";
494
+ }
495
+
496
+ // ---------------------------------------------------------------------------
497
+ // One item
498
+ // ---------------------------------------------------------------------------
499
+
500
+ export type LinkBehavior = "action" | "selection" | "override" | "none";
501
+
502
+ export interface SelectableItemOptions {
503
+ selectionManager: Accessor<SelectionManager>;
504
+ key: Key;
505
+ ref: ElementRef;
506
+ id?: MaybeAccessor<string | undefined>;
507
+ /**
508
+ * Select on pointer up rather than down.
509
+ *
510
+ * A menu closes when an item is chosen, so selecting on pointer down would
511
+ * consume the very press that opened it.
512
+ */
513
+ shouldSelectOnPressUp?: MaybeAccessor<boolean | undefined>;
514
+ /** Allow the press to start on one element and finish on another. */
515
+ allowsDifferentPressOrigin?: MaybeAccessor<boolean | undefined>;
516
+ /** Track focus with `aria-activedescendant` rather than moving it. */
517
+ shouldUseVirtualFocus?: MaybeAccessor<boolean | undefined>;
518
+ isDisabled?: MaybeAccessor<boolean | undefined>;
519
+ onAction?: () => void;
520
+ /**
521
+ * Whether there is an action to perform. @default `onAction !== undefined`
522
+ *
523
+ * Whether an item ACTS changes what a press does: an action is primary while
524
+ * nothing is selected, so the first press performs it instead of selecting.
525
+ * A caller whose own `onAction` is a prop therefore cannot decide by passing
526
+ * or withholding the handler, because the prop is a Cell and the decision
527
+ * would be frozen at construction. It says so here instead, and passes
528
+ * `onAction` unconditionally.
529
+ */
530
+ hasAction?: MaybeAccessor<boolean | undefined>;
531
+ /** @default "action" */
532
+ linkBehavior?: MaybeAccessor<LinkBehavior | undefined>;
533
+ /**
534
+ * Press handling on top of the item's own, chained after it.
535
+ *
536
+ * A menu closes when an item is chosen, and only the press knows which
537
+ * interaction chose it: Enter closes a multi-select menu where a click does
538
+ * not. Reimplementing the press to learn that would mean two press hooks on
539
+ * one element, which is two roving-focus effects and two pressed states.
540
+ */
541
+ onPressStart?: (event: PressEvent) => void;
542
+ onPressUp?: (event: PressEvent) => void;
543
+ onPressEnd?: (event: PressEvent) => void;
544
+ onPress?: (event: PressEvent) => void;
545
+ onPressChange?: (isPressed: boolean) => void;
546
+ }
547
+
548
+ export interface SelectableItemResult {
549
+ itemProps: DOMProps;
550
+ isPressed: Accessor<boolean>;
551
+ isSelected: Accessor<boolean>;
552
+ isFocused: Accessor<boolean>;
553
+ isDisabled: Accessor<boolean>;
554
+ /** Whether the item responds to selection at all. */
555
+ allowsSelection: Accessor<boolean>;
556
+ /** Whether pressing it does something other than select it. */
557
+ hasAction: Accessor<boolean>;
558
+ }
559
+
560
+ function isActionKey(key: string | undefined): boolean {
561
+ return key === "Enter";
562
+ }
563
+
564
+ function isSelectionKey(key: string | undefined): boolean {
565
+ return key === " ";
566
+ }
567
+
568
+ /**
569
+ * One item in a selectable collection.
570
+ *
571
+ * When and what a press does is decided by three things at once: the selection
572
+ * behaviour, whether the item has an action, and the pointer type. With
573
+ * checkbox selection an action is primary and happens on a single click; with
574
+ * highlight selection a click selects and a double click acts; on touch a tap
575
+ * acts and a long press enters selection mode.
576
+ */
577
+ export function selectableItem(options: SelectableItemOptions): SelectableItemResult {
578
+ const itemId = id(options.id);
579
+ const navigate = router();
580
+
581
+ const manager = (): SelectionManager => options.selectionManager();
582
+ const linkBehavior = (): LinkBehavior => access(options.linkBehavior) ?? "action";
583
+ const virtualFocus = (): boolean => access(options.shouldUseVirtualFocus) === true;
584
+
585
+ const isDisabled = (): boolean =>
586
+ access(options.isDisabled) === true || manager().isDisabled(options.key);
587
+
588
+ const isLinkOverride = (): boolean =>
589
+ manager().isLink(options.key) && linkBehavior() === "override";
590
+
591
+ const hasLinkAction = (): boolean =>
592
+ manager().isLink(options.key) && linkBehavior() !== "selection" && linkBehavior() !== "none";
593
+
594
+ const allowsSelection = (): boolean =>
595
+ !isDisabled() && manager().canSelectItem(options.key) && !isLinkOverride();
596
+
597
+ const declaresAction = (): boolean => access(options.hasAction) ?? options.onAction !== undefined;
598
+
599
+ const allowsActions = (): boolean => (declaresAction() || hasLinkAction()) && !isDisabled();
600
+
601
+ const hasPrimaryAction = (): boolean => {
602
+ if (!allowsActions()) return false;
603
+ return manager().selectionBehavior === "replace"
604
+ ? !allowsSelection()
605
+ : !allowsSelection() || manager().isEmpty;
606
+ };
607
+
608
+ const hasSecondaryAction = (): boolean =>
609
+ allowsActions() && allowsSelection() && manager().selectionBehavior === "replace";
610
+
611
+ const hasAction = (): boolean => hasPrimaryAction() || hasSecondaryAction();
612
+
613
+ const select = (event: PressEvent | { pointerType?: string; shiftKey?: boolean }): void => {
614
+ const active = manager();
615
+ const pointerType = (event as PressEvent).pointerType;
616
+
617
+ if (pointerType === "keyboard" && isNonContiguousSelectionModifier(event as PressEvent)) {
618
+ active.toggleSelection(options.key);
619
+ return;
620
+ }
621
+
622
+ if (active.selectionMode === "none") return;
623
+
624
+ if (active.isLink(options.key)) {
625
+ const behavior = linkBehavior();
626
+ const element = access(options.ref) as Element | null;
627
+ if (behavior === "selection" && element !== null) {
628
+ const props = active.getItemProps(options.key);
629
+ navigate.open(element, event, props?.href as string);
630
+ // The selection is put back as it was, so a select or combobox that
631
+ // closes on change does not also change.
632
+ active.setSelectedKeys(active.selectedKeys);
633
+ return;
634
+ }
635
+ if (behavior === "override" || behavior === "none") return;
636
+ }
637
+
638
+ if (active.selectionMode === "single") {
639
+ if (active.isSelected(options.key) && !active.disallowEmptySelection) {
640
+ active.toggleSelection(options.key);
641
+ } else {
642
+ active.replaceSelection(options.key);
643
+ }
644
+ return;
645
+ }
646
+
647
+ if ((event as PressEvent).shiftKey) {
648
+ active.extendSelection(options.key);
649
+ return;
650
+ }
651
+
652
+ if (
653
+ active.selectionBehavior === "toggle" ||
654
+ isCtrlKeyPressed(event as PressEvent) ||
655
+ pointerType === "touch" ||
656
+ pointerType === "virtual"
657
+ ) {
658
+ active.toggleSelection(options.key);
659
+ return;
660
+ }
661
+
662
+ active.replaceSelection(options.key);
663
+ };
664
+
665
+ const performAction = (event: PressEvent): void => {
666
+ const element = access(options.ref) as Element | null;
667
+ if (declaresAction() && options.onAction !== undefined) {
668
+ options.onAction();
669
+ element?.dispatchEvent(new CustomEvent("barq-item-action", { bubbles: true }));
670
+ }
671
+ if (hasLinkAction() && element !== null) {
672
+ const props = manager().getItemProps(options.key);
673
+ navigate.open(element, event, props?.href as string);
674
+ }
675
+ };
676
+
677
+ // Focus the item when it becomes the focused key.
678
+ createEffect(
679
+ () => {
680
+ const active = manager();
681
+ if (active.focusedKey !== options.key || !active.isFocused || virtualFocus()) return null;
682
+ return { element: access(options.ref) as HTMLElement | null };
683
+ },
684
+ (focused) => {
685
+ if (focused === null) return;
686
+ const { element } = focused;
687
+ if (element !== null && activeElement(ownerDocument(element)) !== element) {
688
+ focusSafely(element);
689
+ }
690
+ },
691
+ );
692
+
693
+ // A disabled item cannot hold the roving focus.
694
+ createEffect(
695
+ () => isDisabled() && manager().focusedKey === options.key,
696
+ (stranded) => {
697
+ if (stranded) manager().setFocusedKey(null);
698
+ },
699
+ );
700
+
701
+ let modality: PointerType | null = null;
702
+ let longPressWasEnabled = false;
703
+ let hadPrimaryActionOnPressStart = false;
704
+
705
+ const longPressEnabled = (): boolean => hasAction() && allowsSelection();
706
+
707
+ const pressOptions: Parameters<typeof press>[0] = {
708
+ ref: options.ref,
709
+ preventFocusOnPress: virtualFocus,
710
+ };
711
+
712
+ const onPressStartCommon = (event: PressEvent): void => {
713
+ modality = event.pointerType;
714
+ longPressWasEnabled = longPressEnabled();
715
+ hadPrimaryActionOnPressStart = hasPrimaryAction();
716
+ if (virtualFocus() && event.pointerType !== "touch") {
717
+ manager().setFocused(true);
718
+ manager().setFocusedKey(options.key);
719
+ }
720
+ };
721
+
722
+ if (access(options.shouldSelectOnPressUp) === true) {
723
+ pressOptions.onPressStart = (event) => {
724
+ onPressStartCommon(event);
725
+ // Keyboard selection still happens on key DOWN, as the platform does.
726
+ if (event.pointerType === "keyboard" && (!hasAction() || isSelectionKey(event.key))) {
727
+ select(event);
728
+ }
729
+ };
730
+
731
+ if (access(options.allowsDifferentPressOrigin) !== true) {
732
+ pressOptions.onPress = (event) => {
733
+ if (virtualFocus() && event.pointerType === "touch") {
734
+ manager().setFocused(true);
735
+ manager().setFocusedKey(options.key);
736
+ }
737
+ if (hasPrimaryAction() || (hasSecondaryAction() && event.pointerType !== "mouse")) {
738
+ if (event.pointerType === "keyboard" && !isActionKey(event.key)) return;
739
+ performAction(event);
740
+ } else if (event.pointerType !== "keyboard" && allowsSelection()) {
741
+ select(event);
742
+ }
743
+ };
744
+ } else {
745
+ pressOptions.onPressUp = (event) => {
746
+ if (hasPrimaryAction()) return;
747
+ if (event.pointerType === "mouse" && allowsSelection()) select(event);
748
+ };
749
+ pressOptions.onPress = (event) => {
750
+ if (hasPrimaryAction()) {
751
+ performAction(event);
752
+ return;
753
+ }
754
+ if (
755
+ event.pointerType !== "keyboard" &&
756
+ event.pointerType !== "mouse" &&
757
+ allowsSelection()
758
+ ) {
759
+ select(event);
760
+ }
761
+ };
762
+ }
763
+ } else {
764
+ pressOptions.onPressStart = (event) => {
765
+ onPressStartCommon(event);
766
+ // A mouse selects on the way down unless an action will fire on the way
767
+ // up. Space selects on key down; Enter acts on key up.
768
+ if (
769
+ allowsSelection() &&
770
+ ((event.pointerType === "mouse" && !hasPrimaryAction()) ||
771
+ (event.pointerType === "keyboard" && (!allowsActions() || isSelectionKey(event.key))))
772
+ ) {
773
+ select(event);
774
+ }
775
+ };
776
+
777
+ pressOptions.onPress = (event) => {
778
+ if (virtualFocus() && event.pointerType === "touch") {
779
+ manager().setFocused(true);
780
+ manager().setFocusedKey(options.key);
781
+ }
782
+ if (
783
+ event.pointerType === "touch" ||
784
+ event.pointerType === "pen" ||
785
+ event.pointerType === "virtual" ||
786
+ (event.pointerType === "keyboard" && hasAction() && isActionKey(event.key)) ||
787
+ (event.pointerType === "mouse" && hadPrimaryActionOnPressStart)
788
+ ) {
789
+ if (hasAction()) performAction(event);
790
+ else if (allowsSelection()) select(event);
791
+ }
792
+ };
793
+ }
794
+
795
+ for (const name of ["onPressStart", "onPressUp", "onPressEnd", "onPress"] as const) {
796
+ const own = pressOptions[name];
797
+ const given = options[name];
798
+ if (given === undefined) continue;
799
+ pressOptions[name] = own === undefined ? given : chain(own, given);
800
+ }
801
+ pressOptions.onPressChange = options.onPressChange;
802
+
803
+ const { pressProps, isPressed } = press(pressOptions);
804
+
805
+ // Long pressing with touch under `replace` selection switches to `toggle`,
806
+ // which is how a touch user enters multi-select without a modifier key.
807
+ const { longPressProps } = longPress({
808
+ isDisabled: () => !longPressEnabled(),
809
+ onLongPress: (event) => {
810
+ if (event.pointerType !== "touch") return;
811
+ select(event);
812
+ manager().setSelectionBehavior("toggle");
813
+ },
814
+ });
815
+
816
+ const isFocused = (): boolean => manager().isFocused && manager().focusedKey === options.key;
817
+
818
+ const focusProps: DOMProps = {
819
+ tabIndex: () => {
820
+ // Under virtual focus nothing inside is in the Tab order at all: iOS
821
+ // VoiceOver moves real focus to an item that has a tabIndex, which is
822
+ // exactly what virtual focus exists to avoid.
823
+ if (virtualFocus() || isDisabled()) return undefined;
824
+ // A roving tabindex: exactly one item is in the Tab order.
825
+ return manager().focusedKey === options.key ? 0 : -1;
826
+ },
827
+ onFocus: (event: FocusEvent) => {
828
+ if (virtualFocus() || isDisabled()) return;
829
+ if (targetElement(event) === access(options.ref)) manager().setFocusedKey(options.key);
830
+ },
831
+ onMouseDown: (event: MouseEvent) => {
832
+ // Under virtual focus, focus must stay where it is. On a disabled item,
833
+ // letting focus fall to the body would tear down the roving tabindex.
834
+ if (virtualFocus() || isDisabled()) event.preventDefault();
835
+ },
836
+ };
837
+
838
+ const onDoubleClick = (event: MouseEvent): void => {
839
+ if (!hasSecondaryAction() || modality !== "mouse") return;
840
+ event.stopPropagation();
841
+ event.preventDefault();
842
+ performAction(event as unknown as PressEvent);
843
+ };
844
+
845
+ // A long press that selects must not also start a native drag.
846
+ const onDragStartCapture = (event: DragEvent): void => {
847
+ if (modality === "touch" && longPressWasEnabled) event.preventDefault();
848
+ };
849
+
850
+ // A link's navigation is ours to time, so the browser's is cancelled.
851
+ const onClick = (event: MouseEvent): void => {
852
+ if (linkBehavior() === "none" || !manager().isLink(options.key)) return;
853
+ event.preventDefault();
854
+ };
855
+
856
+ const itemProps = mergeProps(
857
+ focusProps,
858
+ { "data-key": String(options.key), id: itemId },
859
+ pressProps,
860
+ longPressProps,
861
+ { onDoubleClick, onDragStartCapture, onClick },
862
+ );
863
+
864
+ /**
865
+ * Whether a press on `target` belongs to something inside the item rather
866
+ * than to the item itself.
867
+ *
868
+ * A button in a row is such a thing. A CELL is not: `focusPlace` gives
869
+ * whichever cell holds the roving focus `tabindex="0"`, so after the first
870
+ * press on a cell `isTabbable` says yes and every press after it was
871
+ * swallowed before it could reach the row. What tells the two apart is
872
+ * `data-key`, which the collection writes on its own surfaces and nothing
873
+ * else has.
874
+ *
875
+ * A NESTED collection — a tag group inside a table cell — writes
876
+ * `data-collection` on its container, and its items do carry `data-key`. The
877
+ * walk finds that container first, which is why it comes before the
878
+ * `data-key` test.
879
+ */
880
+ const isChildInteraction = (target: Element, element: Element | null): boolean => {
881
+ let at: Element | null = target;
882
+ while (at !== null && at !== element) {
883
+ if (at.hasAttribute("data-collection")) return true;
884
+ at = at.parentElement;
885
+ }
886
+ return isTabbable(target) && !target.hasAttribute("data-key");
887
+ };
888
+
889
+ const basePointerDown = itemProps.onPointerDown as ((event: PointerEvent) => void) | undefined;
890
+ itemProps.onPointerDown = (event: PointerEvent): void => {
891
+ const target = targetElement(event);
892
+ const element = access(options.ref) as Element | null;
893
+ if (target !== null && target !== element && isChildInteraction(target, element)) {
894
+ event.stopPropagation();
895
+ return;
896
+ }
897
+ basePointerDown?.(event);
898
+ };
899
+
900
+ return {
901
+ itemProps,
902
+ isPressed,
903
+ isSelected: () => manager().isSelected(options.key),
904
+ isFocused,
905
+ isDisabled,
906
+ allowsSelection,
907
+ hasAction,
908
+ };
909
+ }
910
+
911
+ // ---------------------------------------------------------------------------
912
+ // The collection
913
+ // ---------------------------------------------------------------------------
914
+
915
+ export interface SelectableCollectionOptions {
916
+ selectionManager: Accessor<SelectionManager>;
917
+ keyboardDelegate: KeyboardDelegate;
918
+ ref: ElementRef;
919
+ /** Focus the collection, or an end of it, on mount. */
920
+ autoFocus?: MaybeAccessor<boolean | "first" | "last" | undefined>;
921
+ /** Wrap around at the ends. @default false */
922
+ shouldFocusWrap?: MaybeAccessor<boolean | undefined>;
923
+ disallowEmptySelection?: MaybeAccessor<boolean | undefined>;
924
+ /** @default false */
925
+ disallowSelectAll?: MaybeAccessor<boolean | undefined>;
926
+ /** @default "clearSelection" */
927
+ escapeKeyBehavior?: MaybeAccessor<"clearSelection" | "none" | undefined>;
928
+ /** Select as focus moves. Defaults to the selection behaviour. */
929
+ selectOnFocus?: MaybeAccessor<boolean | undefined>;
930
+ /** @default false */
931
+ disallowTypeAhead?: MaybeAccessor<boolean | undefined>;
932
+ shouldUseVirtualFocus?: MaybeAccessor<boolean | undefined>;
933
+ /** Let Tab move within the collection rather than out of it. */
934
+ allowsTabNavigation?: MaybeAccessor<boolean | undefined>;
935
+ /** The scrollable element, when it is not the collection itself. */
936
+ scrollRef?: ElementRef;
937
+ linkBehavior?: MaybeAccessor<LinkBehavior | undefined>;
938
+ }
939
+
940
+ export interface SelectableCollectionResult {
941
+ collectionProps: DOMProps;
942
+ }
943
+
944
+ /**
945
+ * Keyboard handling for the element that owns a collection.
946
+ *
947
+ * The collection is one Tab stop: `tabIndex` is 0 while nothing inside is
948
+ * focused and -1 once something is, so Tab enters it once and then leaves.
949
+ */
950
+ export function selectableCollection(
951
+ options: SelectableCollectionOptions,
952
+ ): SelectableCollectionResult {
953
+ const locale = useLocale();
954
+ const navigate = router();
955
+ const delegate = options.keyboardDelegate;
956
+ const collectionId = id();
957
+
958
+ const manager = (): SelectionManager => options.selectionManager();
959
+ const virtualFocus = (): boolean => access(options.shouldUseVirtualFocus) === true;
960
+ const wraps = (): boolean => access(options.shouldFocusWrap) === true;
961
+ const scrollElement = (): HTMLElement | null =>
962
+ (access(options.scrollRef ?? options.ref) as HTMLElement | null) ?? null;
963
+
964
+ const selectOnFocus = (): boolean => {
965
+ const declared = access(options.selectOnFocus);
966
+ return declared ?? manager().selectionBehavior === "replace";
967
+ };
968
+
969
+ const navigateToKey = (
970
+ event: KeyboardEvent,
971
+ key: Key | null | undefined,
972
+ childFocus?: "first" | "last",
973
+ ): void => {
974
+ if (key === null || key === undefined) return;
975
+ const active = manager();
976
+
977
+ if (
978
+ active.isLink(key) &&
979
+ access(options.linkBehavior) === "selection" &&
980
+ selectOnFocus() &&
981
+ !isNonContiguousSelectionModifier(event)
982
+ ) {
983
+ active.setFocusedKey(key, childFocus);
984
+ const element = itemElement(access(options.ref), key);
985
+ if (element !== null) {
986
+ navigate.open(element, event, active.getItemProps(key)?.href as string);
987
+ }
988
+ return;
989
+ }
990
+
991
+ active.setFocusedKey(key, childFocus);
992
+
993
+ if (active.isLink(key) && access(options.linkBehavior) === "override") return;
994
+
995
+ if (event.shiftKey && active.selectionMode === "multiple") active.extendSelection(key);
996
+ else if (selectOnFocus() && !isNonContiguousSelectionModifier(event)) {
997
+ active.replaceSelection(key);
998
+ }
999
+ };
1000
+
1001
+ const onKeyDown = (event: BaseEvent<KeyboardEvent>): void => {
1002
+ const currentTarget = event.currentTarget as Element | null;
1003
+ if (currentTarget === null || !contains(currentTarget, targetElement(event))) {
1004
+ event.continuePropagation();
1005
+ return;
1006
+ }
1007
+
1008
+ const active = manager();
1009
+ const focused = active.focusedKey;
1010
+ const rtl = locale().direction === "rtl";
1011
+
1012
+ switch (event.key) {
1013
+ case "ArrowDown": {
1014
+ if (delegate.getKeyBelow === undefined) break;
1015
+ let next =
1016
+ focused !== null ? delegate.getKeyBelow(focused) : (delegate.getFirstKey?.() ?? null);
1017
+ if (next === null && wraps()) next = delegate.getFirstKey?.() ?? null;
1018
+ if (next === null) break;
1019
+ event.preventDefault();
1020
+ navigateToKey(event, next);
1021
+ return;
1022
+ }
1023
+
1024
+ case "ArrowUp": {
1025
+ if (delegate.getKeyAbove === undefined) break;
1026
+ let next =
1027
+ focused !== null ? delegate.getKeyAbove(focused) : (delegate.getLastKey?.() ?? null);
1028
+ if (next === null && wraps()) next = delegate.getLastKey?.() ?? null;
1029
+ if (next === null) break;
1030
+ event.preventDefault();
1031
+ navigateToKey(event, next);
1032
+ return;
1033
+ }
1034
+
1035
+ case "ArrowLeft": {
1036
+ if (delegate.getKeyLeftOf === undefined) break;
1037
+ let next =
1038
+ focused !== null ? delegate.getKeyLeftOf(focused) : (delegate.getFirstKey?.() ?? null);
1039
+ if (next === null && wraps()) {
1040
+ next = (rtl ? delegate.getFirstKey?.() : delegate.getLastKey?.()) ?? null;
1041
+ }
1042
+ if (next === null) break;
1043
+ event.preventDefault();
1044
+ navigateToKey(event, next, rtl ? "first" : "last");
1045
+ return;
1046
+ }
1047
+
1048
+ case "ArrowRight": {
1049
+ if (delegate.getKeyRightOf === undefined) break;
1050
+ let next =
1051
+ focused !== null ? delegate.getKeyRightOf(focused) : (delegate.getFirstKey?.() ?? null);
1052
+ if (next === null && wraps()) {
1053
+ next = (rtl ? delegate.getLastKey?.() : delegate.getFirstKey?.()) ?? null;
1054
+ }
1055
+ if (next === null) break;
1056
+ event.preventDefault();
1057
+ navigateToKey(event, next, rtl ? "last" : "first");
1058
+ return;
1059
+ }
1060
+
1061
+ case "Home": {
1062
+ if (delegate.getFirstKey === undefined) break;
1063
+ if (focused === null && event.shiftKey) break;
1064
+ const first = delegate.getFirstKey(focused, isCtrlKeyPressed(event));
1065
+ if (first === null) break;
1066
+ event.preventDefault();
1067
+ active.setFocusedKey(first);
1068
+ if (isCtrlKeyPressed(event) && event.shiftKey && active.selectionMode === "multiple") {
1069
+ active.extendSelection(first);
1070
+ } else if (selectOnFocus()) {
1071
+ active.replaceSelection(first);
1072
+ }
1073
+ return;
1074
+ }
1075
+
1076
+ case "End": {
1077
+ if (delegate.getLastKey === undefined) break;
1078
+ if (focused === null && event.shiftKey) break;
1079
+ const last = delegate.getLastKey(focused, isCtrlKeyPressed(event));
1080
+ if (last === null) break;
1081
+ event.preventDefault();
1082
+ active.setFocusedKey(last);
1083
+ if (isCtrlKeyPressed(event) && event.shiftKey && active.selectionMode === "multiple") {
1084
+ active.extendSelection(last);
1085
+ } else if (selectOnFocus()) {
1086
+ active.replaceSelection(last);
1087
+ }
1088
+ return;
1089
+ }
1090
+
1091
+ case "PageDown": {
1092
+ if (delegate.getKeyPageBelow === undefined || focused === null) break;
1093
+ const next = delegate.getKeyPageBelow(focused);
1094
+ if (next === null) break;
1095
+ event.preventDefault();
1096
+ navigateToKey(event, next);
1097
+ return;
1098
+ }
1099
+
1100
+ case "PageUp": {
1101
+ if (delegate.getKeyPageAbove === undefined || focused === null) break;
1102
+ const next = delegate.getKeyPageAbove(focused);
1103
+ if (next === null) break;
1104
+ event.preventDefault();
1105
+ navigateToKey(event, next);
1106
+ return;
1107
+ }
1108
+
1109
+ case "a": {
1110
+ if (!isCtrlKeyPressed(event)) break;
1111
+ if (active.selectionMode !== "multiple" || access(options.disallowSelectAll) === true)
1112
+ break;
1113
+ event.preventDefault();
1114
+ active.selectAll();
1115
+ return;
1116
+ }
1117
+
1118
+ case "Escape": {
1119
+ if ((access(options.escapeKeyBehavior) ?? "clearSelection") !== "clearSelection") break;
1120
+ if (access(options.disallowEmptySelection) === true) break;
1121
+ if (active.selectedKeys.size === 0) break;
1122
+ event.preventDefault();
1123
+ active.clearSelection();
1124
+ return;
1125
+ }
1126
+
1127
+ case "Tab": {
1128
+ if (access(options.allowsTabNavigation) === true) break;
1129
+ const container = access(options.ref) as HTMLElement | null;
1130
+ if (container === null) break;
1131
+
1132
+ if (event.shiftKey) {
1133
+ // Backwards out of the collection: focus the container so the
1134
+ // browser's own Shift+Tab continues from there.
1135
+ container.focus();
1136
+ break;
1137
+ }
1138
+
1139
+ // Forwards out of the collection: move to the LAST tabbable element
1140
+ // inside it, so the browser continues past the whole collection rather
1141
+ // than into it.
1142
+ const walker = focusableWalker(container, { tabbable: true });
1143
+ const next = walker.last() as HTMLElement | null;
1144
+ const active2 = activeElement(ownerDocument(container));
1145
+ if (
1146
+ next !== null &&
1147
+ (!contains(next, active2) || (active2 !== null && !isTabbable(active2)))
1148
+ ) {
1149
+ focusWithoutScrolling(next);
1150
+ }
1151
+ break;
1152
+ }
1153
+
1154
+ default:
1155
+ break;
1156
+ }
1157
+
1158
+ // Everything not handled keeps bubbling: a dialog above still sees Escape.
1159
+ event.continuePropagation();
1160
+ };
1161
+
1162
+ // The scroll position is restored when focus returns, so tabbing away and
1163
+ // back does not jump the list to the focused item.
1164
+ const scrollPosition = { top: 0, left: 0 };
1165
+ createEffect(scrollElement, (element) => {
1166
+ if (element === null) return undefined;
1167
+ const onScroll = (): void => {
1168
+ scrollPosition.top = element.scrollTop;
1169
+ scrollPosition.left = element.scrollLeft;
1170
+ };
1171
+ element.addEventListener("scroll", onScroll);
1172
+ return () => element.removeEventListener("scroll", onScroll);
1173
+ });
1174
+
1175
+ const onFocus = (event: FocusEvent): void => {
1176
+ const active = manager();
1177
+ const currentTarget = event.currentTarget as Element | null;
1178
+
1179
+ if (active.isFocused) {
1180
+ if (currentTarget !== null && !contains(currentTarget, targetElement(event))) {
1181
+ active.setFocused(false);
1182
+ }
1183
+ return;
1184
+ }
1185
+
1186
+ if (currentTarget === null || !contains(currentTarget, targetElement(event))) return;
1187
+
1188
+ const how = getInteractionModality();
1189
+ active.setFocused(true);
1190
+
1191
+ const focusKey = (key: Key | null | undefined): void => {
1192
+ if (key === null || key === undefined) return;
1193
+ active.setFocusedKey(key);
1194
+ if (selectOnFocus() && !active.isSelected(key)) active.replaceSelection(key);
1195
+ };
1196
+
1197
+ if (active.focusedKey === null) {
1198
+ // Which end to enter at: `relatedTarget` is where focus came FROM, so a
1199
+ // Shift+Tab from below enters at the last item.
1200
+ const related = event.relatedTarget as Element | null;
1201
+ const fromAfter =
1202
+ related !== null &&
1203
+ (currentTarget.compareDocumentPosition(related) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0;
1204
+ focusKey(
1205
+ fromAfter
1206
+ ? (active.lastSelectedKey ?? delegate.getLastKey?.())
1207
+ : (active.firstSelectedKey ?? delegate.getFirstKey?.()),
1208
+ );
1209
+ } else {
1210
+ const element = scrollElement();
1211
+ if (element !== null) {
1212
+ element.scrollTop = scrollPosition.top;
1213
+ element.scrollLeft = scrollPosition.left;
1214
+ }
1215
+ }
1216
+
1217
+ const focused = active.focusedKey;
1218
+ const container = access(options.ref) as HTMLElement | null;
1219
+ if (focused !== null && container !== null) {
1220
+ const element = itemElement(container, focused);
1221
+ if (element instanceof HTMLElement) {
1222
+ if (!contains(element, activeElement(ownerDocument(element))) && !virtualFocus()) {
1223
+ focusWithoutScrolling(element);
1224
+ }
1225
+ if (how === "keyboard") scrollIntoViewport(element, { containingElement: container });
1226
+ }
1227
+ }
1228
+ };
1229
+
1230
+ const onBlur = (event: FocusEvent): void => {
1231
+ const currentTarget = event.currentTarget as Element | null;
1232
+ // Moving between two items inside the collection is not leaving it.
1233
+ if (currentTarget !== null && !contains(currentTarget, event.relatedTarget as Element | null)) {
1234
+ manager().setFocused(false);
1235
+ }
1236
+ };
1237
+
1238
+ // Bring the focused item into view when it changes by keyboard.
1239
+ let lastFocusedKey: Key | null = manager().focusedKey;
1240
+ createEffect(
1241
+ () => {
1242
+ const active = manager();
1243
+ return {
1244
+ focused: active.focusedKey,
1245
+ isFocused: active.isFocused,
1246
+ container: access(options.ref) as HTMLElement | null,
1247
+ scroller: scrollElement(),
1248
+ virtual: virtualFocus(),
1249
+ };
1250
+ },
1251
+ ({ focused, isFocused, container, scroller, virtual }) => {
1252
+ if (isFocused && focused !== null && focused !== lastFocusedKey && scroller !== null) {
1253
+ const element = itemElement(container, focused);
1254
+ if (element instanceof HTMLElement && getInteractionModality() === "keyboard") {
1255
+ scrollIntoView(scroller, element);
1256
+ scrollIntoViewport(element, { containingElement: container });
1257
+ }
1258
+ }
1259
+
1260
+ // The focused item was removed: the collection itself takes focus, or the
1261
+ // user is left with focus on the body and no way back in.
1262
+ if (!virtual && isFocused && focused === null && lastFocusedKey !== null) {
1263
+ if (container !== null) focusSafely(container);
1264
+ }
1265
+
1266
+ lastFocusedKey = focused;
1267
+ },
1268
+ );
1269
+
1270
+ const [autoFocused, setAutoFocused] = createSignal(
1271
+ access(options.autoFocus) !== undefined && access(options.autoFocus) !== false,
1272
+ );
1273
+ createEffect(
1274
+ () => {
1275
+ if (!autoFocused()) return null;
1276
+ const active = manager();
1277
+ const where = access(options.autoFocus);
1278
+
1279
+ let key: Key | null = null;
1280
+ if (where === "first") key = delegate.getFirstKey?.() ?? null;
1281
+ if (where === "last") key = delegate.getLastKey?.() ?? null;
1282
+
1283
+ // A selected item wins over an end: re-opening a select lands on what is
1284
+ // already chosen.
1285
+ for (const selected of active.selectedKeys) {
1286
+ if (active.canSelectItem(selected)) {
1287
+ key = selected;
1288
+ break;
1289
+ }
1290
+ }
1291
+
1292
+ return {
1293
+ active,
1294
+ key,
1295
+ selects:
1296
+ key !== null &&
1297
+ selectOnFocus() &&
1298
+ active.selectedKeys.size === 0 &&
1299
+ active.canSelectItem(key),
1300
+ container:
1301
+ key === null && !virtualFocus() ? (access(options.ref) as HTMLElement | null) : null,
1302
+ isLoaded: active.collection.size > 0,
1303
+ };
1304
+ },
1305
+ (next) => {
1306
+ if (next === null) return;
1307
+ const { active, key, container } = next;
1308
+
1309
+ active.setFocused(true);
1310
+ active.setFocusedKey(key);
1311
+
1312
+ if (key !== null && next.selects) active.replaceSelection(key);
1313
+
1314
+ if (container !== null) focusSafely(container);
1315
+
1316
+ if (next.isLoaded) setAutoFocused(false);
1317
+ },
1318
+ );
1319
+
1320
+ // A virtualised collection reuses DOM nodes, so the element a focus scope
1321
+ // wants to restore to may now be a different item.
1322
+ createEffect(
1323
+ () => access(options.ref) as HTMLElement | null,
1324
+ (container) => {
1325
+ if (container === null) return undefined;
1326
+ const onRestore = (event: Event): void => {
1327
+ event.preventDefault();
1328
+ manager().setFocused(true);
1329
+ };
1330
+ container.addEventListener("barq-focus-scope-restore", onRestore);
1331
+ return () => container.removeEventListener("barq-focus-scope-restore", onRestore);
1332
+ },
1333
+ );
1334
+
1335
+ const { typeSelectProps } = typeSelect({
1336
+ keyboardDelegate: delegate,
1337
+ selectionManager: options.selectionManager,
1338
+ });
1339
+
1340
+ const handlers: DOMProps = {
1341
+ onKeyDown: (event: KeyboardEvent) => {
1342
+ // The wrapper adds `continuePropagation`, which the handler uses to let
1343
+ // an unhandled key through to whatever is above.
1344
+ let handled = true;
1345
+ const marked = event as BaseEvent<KeyboardEvent>;
1346
+ Object.defineProperty(event, "continuePropagation", {
1347
+ configurable: true,
1348
+ value: () => {
1349
+ handled = false;
1350
+ },
1351
+ });
1352
+ try {
1353
+ onKeyDown(marked);
1354
+ } finally {
1355
+ delete (event as Partial<BaseEvent<KeyboardEvent>>).continuePropagation;
1356
+ }
1357
+ if (handled) event.stopPropagation();
1358
+ },
1359
+ onFocusIn: onFocus,
1360
+ onFocusOut: onBlur,
1361
+ onMouseDown: (event: MouseEvent) => {
1362
+ // A press on the scrollbar must not move focus into the collection.
1363
+ if (scrollElement() === targetElement(event)) event.preventDefault();
1364
+ },
1365
+ "data-collection": collectionId,
1366
+ tabIndex: () => {
1367
+ if (virtualFocus()) return undefined;
1368
+ return manager().focusedKey === null ? 0 : -1;
1369
+ },
1370
+ };
1371
+
1372
+ return {
1373
+ collectionProps:
1374
+ access(options.disallowTypeAhead) === true ? handlers : mergeProps(typeSelectProps, handlers),
1375
+ };
1376
+ }
1377
+
1378
+ // ---------------------------------------------------------------------------
1379
+ // The two together
1380
+ // ---------------------------------------------------------------------------
1381
+
1382
+ export interface SelectableListOptions extends Omit<
1383
+ SelectableCollectionOptions,
1384
+ "keyboardDelegate"
1385
+ > {
1386
+ collection: Accessor<Collection<unknown>>;
1387
+ disabledKeys?: Accessor<Set<Key>>;
1388
+ keyboardDelegate?: KeyboardDelegate;
1389
+ layoutDelegate?: LayoutDelegate;
1390
+ orientation?: MaybeAccessor<Orientation | undefined>;
1391
+ }
1392
+
1393
+ /** A selectable collection with the default list navigation. */
1394
+ export function selectableList(options: SelectableListOptions): { listProps: DOMProps } {
1395
+ // `base` sensitivity, so typing "e" matches "É": a typeahead the user cannot
1396
+ // reach without an accented keyboard is no typeahead.
1397
+ const search = collator({ usage: "search", sensitivity: "base" });
1398
+ const locale = useLocale();
1399
+
1400
+ const delegate =
1401
+ options.keyboardDelegate ??
1402
+ new ListKeyboardDelegate({
1403
+ collection: options.collection,
1404
+ ref: options.ref,
1405
+ disabledKeys: options.disabledKeys,
1406
+ disabledBehavior: () => options.selectionManager().disabledBehavior,
1407
+ collator: search,
1408
+ orientation: options.orientation,
1409
+ direction: () => locale().direction,
1410
+ layoutDelegate: options.layoutDelegate,
1411
+ });
1412
+
1413
+ const { collectionProps } = selectableCollection({ ...options, keyboardDelegate: delegate });
1414
+ return { listProps: collectionProps };
1415
+ }