@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,1059 @@
1
+ /**
2
+ * The collection: what a listbox, menu, select, tab list or tree is a view of.
3
+ *
4
+ * A widget cannot answer "what is after this item" from the DOM. The next
5
+ * option may be in another section, may be disabled and therefore skipped, may
6
+ * not be rendered at all because the list is virtualised, and in a tree may be
7
+ * a child rather than a sibling. So the structure is modelled separately from
8
+ * what is rendered, and the rendering follows it.
9
+ *
10
+ * This is DATA-DRIVEN, where react-aria's equivalent is built by rendering the
11
+ * children and collecting what they declare. A framework whose components run
12
+ * once and whose children are lazy Blocks makes that dance unnecessary: the
13
+ * items are already a value, so the collection is derived from them directly
14
+ * and rebuilt only when they change.
15
+ *
16
+ * ```tsx
17
+ * const state = listState({
18
+ * items: () => fruits(),
19
+ * selectionMode: "multiple",
20
+ * onSelectionChange: (keys) => selected.set(keys),
21
+ * });
22
+ * ```
23
+ */
24
+
25
+ import { type Accessor, createMemo, createRenderEffect, createSignal, isDev } from "@barqjs/core";
26
+ import { access, callback, controllable, type MaybeAccessor } from "./utils.ts";
27
+
28
+ /** What identifies an item. */
29
+ export type Key = string | number;
30
+
31
+ export type SelectionMode = "none" | "single" | "multiple";
32
+
33
+ /**
34
+ * How a pointer press changes the selection.
35
+ *
36
+ * `toggle` adds and removes, as a list of checkboxes does. `replace` selects
37
+ * only what was pressed unless a modifier is held, as a file manager does.
38
+ */
39
+ export type SelectionBehavior = "toggle" | "replace";
40
+
41
+ /** Whether a disabled key is merely unselectable, or inert entirely. */
42
+ export type DisabledBehavior = "selection" | "all";
43
+
44
+ /** Which end of a newly focused item's children should take focus. */
45
+ export type FocusStrategy = "first" | "last";
46
+
47
+ export interface Node<T> {
48
+ type: "item" | "section" | "separator" | "loader";
49
+ key: Key;
50
+ /** The value the item was built from. */
51
+ value: T | null;
52
+ /** What a typeahead matches against, and what a screen reader reads. */
53
+ textValue: string;
54
+ "aria-label"?: string | undefined;
55
+ /** Nesting depth, for a tree. */
56
+ level: number;
57
+ /** Position among its siblings, counting items only. */
58
+ index: number;
59
+ parentKey?: Key | undefined;
60
+ prevKey?: Key | undefined;
61
+ nextKey?: Key | undefined;
62
+ hasChildNodes: boolean;
63
+ childNodes: Node<T>[];
64
+ /** Per-item options: `isDisabled`, `href`, and anything a widget adds. */
65
+ props: Record<string, unknown>;
66
+ }
67
+
68
+ export interface Collection<T> extends Iterable<Node<T>> {
69
+ /** How many items and sections there are. */
70
+ readonly size: number;
71
+ getKeys(): Iterable<Key>;
72
+ getItem(key: Key): Node<T> | null;
73
+ getKeyBefore(key: Key): Key | null;
74
+ getKeyAfter(key: Key): Key | null;
75
+ getFirstKey(): Key | null;
76
+ getLastKey(): Key | null;
77
+ getChildren(key: Key): Iterable<Node<T>>;
78
+ at(index: number): Node<T> | null;
79
+ }
80
+
81
+ /**
82
+ * A flat collection, with sections one level deep.
83
+ *
84
+ * Keys are linked in document order across section boundaries, which is what
85
+ * makes Down from the last item of one section reach the first of the next.
86
+ */
87
+ export class ListCollection<T> implements Collection<T> {
88
+ #keyMap = new Map<Key, Node<T>>();
89
+ #iterable: Iterable<Node<T>>;
90
+ #firstKey: Key | null = null;
91
+ #lastKey: Key | null = null;
92
+ #size = 0;
93
+
94
+ constructor(nodes: Iterable<Node<T>>) {
95
+ this.#iterable = nodes;
96
+
97
+ const visit = (node: Node<T>): void => {
98
+ this.#keyMap.set(node.key, node);
99
+ if (node.type === "section") {
100
+ for (const child of node.childNodes) visit(child);
101
+ }
102
+ };
103
+ for (const node of nodes) visit(node);
104
+
105
+ let previous: Node<T> | null = null;
106
+ let index = 0;
107
+ for (const [key, node] of this.#keyMap) {
108
+ if (previous !== null) {
109
+ previous.nextKey = key;
110
+ node.prevKey = previous.key;
111
+ } else {
112
+ this.#firstKey = key;
113
+ node.prevKey = undefined;
114
+ }
115
+
116
+ if (node.type === "item") node.index = index++;
117
+ // Loaders and separators do not count towards emptiness.
118
+ if (node.type === "section" || node.type === "item") this.#size++;
119
+
120
+ previous = node;
121
+ previous.nextKey = undefined;
122
+ }
123
+
124
+ this.#lastKey = previous?.key ?? null;
125
+ }
126
+
127
+ *[Symbol.iterator](): IterableIterator<Node<T>> {
128
+ yield* this.#iterable;
129
+ }
130
+
131
+ get size(): number {
132
+ return this.#size;
133
+ }
134
+
135
+ getKeys(): IterableIterator<Key> {
136
+ return this.#keyMap.keys();
137
+ }
138
+
139
+ getItem(key: Key): Node<T> | null {
140
+ return this.#keyMap.get(key) ?? null;
141
+ }
142
+
143
+ getKeyBefore(key: Key): Key | null {
144
+ return this.#keyMap.get(key)?.prevKey ?? null;
145
+ }
146
+
147
+ getKeyAfter(key: Key): Key | null {
148
+ return this.#keyMap.get(key)?.nextKey ?? null;
149
+ }
150
+
151
+ getFirstKey(): Key | null {
152
+ return this.#firstKey;
153
+ }
154
+
155
+ getLastKey(): Key | null {
156
+ return this.#lastKey;
157
+ }
158
+
159
+ getChildren(key: Key): Iterable<Node<T>> {
160
+ return this.#keyMap.get(key)?.childNodes ?? [];
161
+ }
162
+
163
+ at(index: number): Node<T> | null {
164
+ const keys = [...this.getKeys()];
165
+ const key = keys[index];
166
+ return key === undefined ? null : this.getItem(key);
167
+ }
168
+
169
+ /** A collection of only the items whose text matches. */
170
+ filter(match: (textValue: string, node: Node<T>) => boolean): ListCollection<T> {
171
+ const kept: Node<T>[] = [];
172
+ for (const node of this.#iterable) {
173
+ if (node.type === "section") {
174
+ const children = node.childNodes.filter((child) => match(child.textValue, child));
175
+ if (children.length > 0) kept.push({ ...node, childNodes: children });
176
+ } else if (node.type !== "item" || match(node.textValue, node)) {
177
+ kept.push({ ...node });
178
+ }
179
+ }
180
+ return new ListCollection(kept);
181
+ }
182
+ }
183
+
184
+ const keyOrders = new WeakMap<Collection<unknown>, Map<Key, number>>();
185
+
186
+ function keyPositions(collection: Collection<unknown>): Map<Key, number> {
187
+ let positions = keyOrders.get(collection);
188
+ if (positions === undefined) {
189
+ positions = new Map();
190
+ for (const key of collection.getKeys()) positions.set(key, positions.size);
191
+ keyOrders.set(collection, positions);
192
+ }
193
+ return positions;
194
+ }
195
+
196
+ const itemCounts = new WeakMap<Collection<unknown>, number>();
197
+
198
+ /**
199
+ * How many items a collection holds, sections and separators left out.
200
+ *
201
+ * `size` counts a section as one of its entries, which is right for "is it
202
+ * empty" and wrong for `aria-setsize`: a list of two sections of three items
203
+ * is a set of six, not eight.
204
+ */
205
+ export function getItemCount(collection: Collection<unknown>): number {
206
+ const known = itemCounts.get(collection);
207
+ if (known !== undefined) return known;
208
+
209
+ let count = 0;
210
+ const visit = (nodes: Iterable<Node<unknown>>): void => {
211
+ for (const node of nodes) {
212
+ if (node.type === "section") visit(collection.getChildren(node.key));
213
+ else if (node.type === "item") count++;
214
+ }
215
+ };
216
+ visit(collection);
217
+ itemCounts.set(collection, count);
218
+ return count;
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // Building a collection from items
223
+ // ---------------------------------------------------------------------------
224
+
225
+ /** How to read one item. Every accessor has a conventional default. */
226
+ export interface ItemAccessors<T> {
227
+ /** @default `item.id ?? item.key` */
228
+ getKey?: (item: T, index: number) => Key;
229
+ /** @default `item.textValue ?? item.label ?? item.name ?? String(item)` */
230
+ getTextValue?: (item: T) => string;
231
+ /** The children of a section or a tree node. @default `item.children` */
232
+ getChildren?: (item: T) => Iterable<T> | undefined;
233
+ /** @default `"section"` when the item has children, `"item"` otherwise */
234
+ getType?: (item: T) => Node<T>["type"];
235
+ /** Extra per-item options: `isDisabled`, `href`. @default the item itself */
236
+ getProps?: (item: T) => Record<string, unknown>;
237
+ }
238
+
239
+ function defaultKey(item: unknown, index: number): Key {
240
+ const record = item as Record<string, unknown>;
241
+ const id = record?.id ?? record?.key;
242
+ if (typeof id === "string" || typeof id === "number") return id;
243
+ return index;
244
+ }
245
+
246
+ function defaultTextValue(item: unknown): string {
247
+ const record = item as Record<string, unknown>;
248
+ const text = record?.textValue ?? record?.label ?? record?.name ?? record?.title;
249
+ return typeof text === "string" ? text : String(item);
250
+ }
251
+
252
+ function defaultChildren<T>(item: T): Iterable<T> | undefined {
253
+ const children = (item as unknown as Record<string, unknown>)?.children;
254
+ return Array.isArray(children) ? (children as T[]) : undefined;
255
+ }
256
+
257
+ /**
258
+ * A collection from a list of values.
259
+ *
260
+ * An item with children becomes a section (or a tree node); everything else is
261
+ * an item. `level` and `parentKey` come out of the nesting, so a keyboard
262
+ * delegate can move between siblings and into children without the caller
263
+ * describing the shape twice.
264
+ */
265
+ export function buildCollection<T>(
266
+ items: Iterable<T>,
267
+ accessors: ItemAccessors<T> = {},
268
+ ): ListCollection<T> {
269
+ // Every accessor may arrive as a Cell around the callback; see `callback`.
270
+ const getKey = callback(accessors.getKey) ?? defaultKey;
271
+ const getTextValue = callback(accessors.getTextValue) ?? defaultTextValue;
272
+ const getChildren = callback(accessors.getChildren) ?? defaultChildren;
273
+ const getType = callback(accessors.getType);
274
+ const getProps = callback(accessors.getProps);
275
+ // Two items under one key share one entry in the key map, so the second
276
+ // silently replaces the first and the linked order skips or loops.
277
+ const seen = isDev ? new Set<Key>() : null;
278
+
279
+ const build = (source: Iterable<T>, level: number, parentKey: Key | undefined): Node<T>[] => {
280
+ const nodes: Node<T>[] = [];
281
+ let index = 0;
282
+
283
+ for (const item of source) {
284
+ const key = getKey(item, index);
285
+ if (seen !== null) {
286
+ if (seen.has(key)) {
287
+ console.warn(
288
+ `Duplicate key "${String(key)}" in a collection. Every item needs a key of its own.`,
289
+ );
290
+ }
291
+ seen.add(key);
292
+ }
293
+ const children = getChildren(item);
294
+ const childNodes = children === undefined ? [] : build(children, level + 1, key);
295
+ const props =
296
+ getProps === undefined ? ((item ?? {}) as Record<string, unknown>) : getProps(item);
297
+ const type = getType?.(item) ?? (childNodes.length > 0 ? "section" : "item");
298
+
299
+ nodes.push({
300
+ type,
301
+ key,
302
+ value: item,
303
+ textValue: getTextValue(item),
304
+ "aria-label": props["aria-label"] as string | undefined,
305
+ level,
306
+ index,
307
+ parentKey,
308
+ hasChildNodes: childNodes.length > 0,
309
+ childNodes,
310
+ props,
311
+ });
312
+ index++;
313
+ }
314
+
315
+ return nodes;
316
+ };
317
+
318
+ return new ListCollection(build(items, 0, undefined));
319
+ }
320
+
321
+ // ---------------------------------------------------------------------------
322
+ // Selection
323
+ // ---------------------------------------------------------------------------
324
+
325
+ /**
326
+ * The selected keys, plus where a range selection started and ended.
327
+ *
328
+ * Shift-clicking needs both: the anchor is where the range began, and the
329
+ * current key is where it reached, so extending it again can un-select what
330
+ * the previous extension covered.
331
+ */
332
+ export class Selection extends Set<Key> {
333
+ anchorKey: Key | null;
334
+ currentKey: Key | null;
335
+
336
+ constructor(keys?: Iterable<Key> | Selection, anchorKey?: Key | null, currentKey?: Key | null) {
337
+ super(keys);
338
+ if (keys instanceof Selection) {
339
+ this.anchorKey = anchorKey ?? keys.anchorKey;
340
+ this.currentKey = currentKey ?? keys.currentKey;
341
+ } else {
342
+ this.anchorKey = anchorKey ?? null;
343
+ this.currentKey = currentKey ?? null;
344
+ }
345
+ }
346
+ }
347
+
348
+ /** Every item, without listing them: what "select all" means. */
349
+ export type SelectionValue = "all" | Selection;
350
+
351
+ function sameSet(a: Set<Key>, b: Set<Key>): boolean {
352
+ if (a.size !== b.size) return false;
353
+ for (const key of a) if (!b.has(key)) return false;
354
+ return true;
355
+ }
356
+
357
+ function toSelection(
358
+ value: "all" | Iterable<Key> | null | undefined,
359
+ fallback?: Selection,
360
+ ): SelectionValue | undefined {
361
+ if (value === null || value === undefined) return fallback;
362
+ return value === "all" ? "all" : new Selection(value);
363
+ }
364
+
365
+ export interface MultipleSelectionOptions {
366
+ selectionMode?: MaybeAccessor<SelectionMode | undefined>;
367
+ selectionBehavior?: MaybeAccessor<SelectionBehavior | undefined>;
368
+ disallowEmptySelection?: MaybeAccessor<boolean | undefined>;
369
+ selectedKeys?: MaybeAccessor<"all" | Iterable<Key> | undefined>;
370
+ defaultSelectedKeys?: MaybeAccessor<"all" | Iterable<Key> | undefined>;
371
+ disabledKeys?: MaybeAccessor<Iterable<Key> | undefined>;
372
+ disabledBehavior?: MaybeAccessor<DisabledBehavior | undefined>;
373
+ /** Report a selection change even when the set is unchanged. */
374
+ allowDuplicateSelectionEvents?: boolean;
375
+ onSelectionChange?: (keys: SelectionValue) => void;
376
+ }
377
+
378
+ export interface MultipleSelectionState {
379
+ selectionMode: Accessor<SelectionMode>;
380
+ selectionBehavior: Accessor<SelectionBehavior>;
381
+ setSelectionBehavior(behavior: SelectionBehavior): void;
382
+ disallowEmptySelection: Accessor<boolean>;
383
+ selectedKeys: Accessor<SelectionValue>;
384
+ setSelectedKeys(keys: SelectionValue): void;
385
+ disabledKeys: Accessor<Set<Key>>;
386
+ disabledBehavior: Accessor<DisabledBehavior>;
387
+ isFocused: Accessor<boolean>;
388
+ setFocused(focused: boolean): void;
389
+ focusedKey: Accessor<Key | null>;
390
+ childFocusStrategy: Accessor<FocusStrategy | null>;
391
+ setFocusedKey(key: Key | null, child?: FocusStrategy): void;
392
+ }
393
+
394
+ /** Selection and roving focus, as signals. */
395
+ export function multipleSelectionState(
396
+ options: MultipleSelectionOptions = {},
397
+ ): MultipleSelectionState {
398
+ // Roving focus is where the machine IS, not what it intends: a key handler
399
+ // moves it and the very next statement of the same gesture asks where it
400
+ // landed. A staged write would answer with the position before the move, so
401
+ // each of the three keeps the value it was last given: a read subscribes to
402
+ // the signal and answers from that, and only the rendered view waits for the
403
+ // flush.
404
+ let focusedNow = false;
405
+ let focusedKeyNow: Key | null = null;
406
+ let childFocusStrategyNow: FocusStrategy | null = null;
407
+ const [trackFocused, publishFocused] = createSignal(false);
408
+ const [trackFocusedKey, publishFocusedKey] = createSignal<Key | null>(null);
409
+ const [trackChildFocusStrategy, publishChildFocusStrategy] = createSignal<FocusStrategy | null>(
410
+ null,
411
+ );
412
+ const isFocused = (): boolean => {
413
+ trackFocused();
414
+ return focusedNow;
415
+ };
416
+ const focusedKey = (): Key | null => {
417
+ trackFocusedKey();
418
+ return focusedKeyNow;
419
+ };
420
+ const childFocusStrategy = (): FocusStrategy | null => {
421
+ trackChildFocusStrategy();
422
+ return childFocusStrategyNow;
423
+ };
424
+
425
+ const [selectedKeys, setSelectedKeys] = controllable<SelectionValue>(
426
+ () => toSelection(access(options.selectedKeys)),
427
+ () => toSelection(access(options.defaultSelectedKeys), new Selection()) as SelectionValue,
428
+ options.onSelectionChange,
429
+ );
430
+
431
+ // The behaviour can be changed at runtime: a long press on touch enters
432
+ // selection mode, which turns a `replace` list into a `toggle` one until the
433
+ // selection empties again.
434
+ const [behaviorOverride, setBehaviorOverride] = createSignal<SelectionBehavior | null>(null);
435
+
436
+ const selectionBehavior = createMemo<SelectionBehavior>(() => {
437
+ const declared = access(options.selectionBehavior) ?? "toggle";
438
+ const override = behaviorOverride();
439
+ if (override === null) return declared;
440
+ // Back to what the caller asked for once nothing is selected.
441
+ const current = selectedKeys();
442
+ if (
443
+ declared === "replace" &&
444
+ override === "toggle" &&
445
+ current !== "all" &&
446
+ current.size === 0
447
+ ) {
448
+ return declared;
449
+ }
450
+ return override;
451
+ });
452
+
453
+ const disabledKeys = createMemo(() => {
454
+ const declared = access(options.disabledKeys);
455
+ return declared === undefined ? new Set<Key>() : new Set<Key>(declared);
456
+ });
457
+
458
+ return {
459
+ selectionMode: () => access(options.selectionMode) ?? "none",
460
+ selectionBehavior,
461
+ setSelectionBehavior: (behavior) => setBehaviorOverride(behavior),
462
+ disallowEmptySelection: () => access(options.disallowEmptySelection) === true,
463
+ selectedKeys,
464
+ setSelectedKeys(keys) {
465
+ const current = selectedKeys();
466
+ const changed =
467
+ options.allowDuplicateSelectionEvents === true ||
468
+ keys === "all" ||
469
+ current === "all" ||
470
+ !sameSet(keys, current);
471
+ if (changed) setSelectedKeys(keys);
472
+ },
473
+ disabledKeys,
474
+ disabledBehavior: () => access(options.disabledBehavior) ?? "all",
475
+ isFocused,
476
+ setFocused: (focused) => {
477
+ focusedNow = focused;
478
+ publishFocused(focused);
479
+ },
480
+ focusedKey,
481
+ childFocusStrategy,
482
+ setFocusedKey(key, child = "first") {
483
+ focusedKeyNow = key;
484
+ childFocusStrategyNow = child;
485
+ publishFocusedKey(key);
486
+ publishChildFocusStrategy(child);
487
+ },
488
+ };
489
+ }
490
+
491
+ export interface Rect {
492
+ x: number;
493
+ y: number;
494
+ width: number;
495
+ height: number;
496
+ }
497
+
498
+ export interface Size {
499
+ width: number;
500
+ height: number;
501
+ }
502
+
503
+ /**
504
+ * Where items are, for the navigation and virtualisation that need geometry.
505
+ *
506
+ * It lives here rather than beside `DOMLayoutDelegate` in `selection.ts`
507
+ * because `SelectionManager` takes one and `selection.ts` already imports this
508
+ * module; declaring a narrower twin there is what put two `LayoutDelegate`s in
509
+ * the barrel.
510
+ */
511
+ export interface LayoutDelegate {
512
+ getItemRect(key: Key): Rect | null;
513
+ getContentSize(): Size;
514
+ getVisibleRect(): Rect;
515
+ getKeyRange?(from: Key, to: Key): Key[];
516
+ getKeyLeftOf?(key: Key): Key | null;
517
+ getKeyRightOf?(key: Key): Key | null;
518
+ }
519
+
520
+ interface SelectionManagerOptions {
521
+ allowsCellSelection?: boolean;
522
+ layoutDelegate?: LayoutDelegate;
523
+ /** The unfiltered collection, so "select all" covers hidden items too. */
524
+ fullCollection?: Collection<unknown>;
525
+ }
526
+
527
+ /**
528
+ * Reading and changing the selection.
529
+ *
530
+ * Every method here knows the collection, which is what separates it from a
531
+ * `Set<Key>`: extending a selection needs the key order, selecting all needs
532
+ * to know which items are selectable, and toggling a cell has to walk up to
533
+ * the row that owns it.
534
+ */
535
+ export class SelectionManager {
536
+ collection: Collection<unknown>;
537
+
538
+ #state: MultipleSelectionState;
539
+ #allowsCellSelection: boolean;
540
+ #layoutDelegate: LayoutDelegate | null;
541
+ #fullCollection: Collection<unknown> | null;
542
+
543
+ constructor(
544
+ collection: Collection<unknown>,
545
+ state: MultipleSelectionState,
546
+ options: SelectionManagerOptions = {},
547
+ ) {
548
+ this.collection = collection;
549
+ this.#state = state;
550
+ this.#allowsCellSelection = options.allowsCellSelection ?? false;
551
+ this.#layoutDelegate = options.layoutDelegate ?? null;
552
+ this.#fullCollection = options.fullCollection ?? null;
553
+ }
554
+
555
+ get selectionMode(): SelectionMode {
556
+ return this.#state.selectionMode();
557
+ }
558
+
559
+ get disallowEmptySelection(): boolean {
560
+ return this.#state.disallowEmptySelection();
561
+ }
562
+
563
+ get selectionBehavior(): SelectionBehavior {
564
+ return this.#state.selectionBehavior();
565
+ }
566
+
567
+ setSelectionBehavior(behavior: SelectionBehavior): void {
568
+ this.#state.setSelectionBehavior(behavior);
569
+ }
570
+
571
+ get isFocused(): boolean {
572
+ return this.#state.isFocused();
573
+ }
574
+
575
+ setFocused(focused: boolean): void {
576
+ this.#state.setFocused(focused);
577
+ }
578
+
579
+ get focusedKey(): Key | null {
580
+ return this.#state.focusedKey();
581
+ }
582
+
583
+ get childFocusStrategy(): FocusStrategy | null {
584
+ return this.#state.childFocusStrategy();
585
+ }
586
+
587
+ setFocusedKey(key: Key | null, child?: FocusStrategy): void {
588
+ if (key === null || this.collection.getItem(key) !== null) {
589
+ this.#state.setFocusedKey(key, child);
590
+ }
591
+ }
592
+
593
+ /** The selected keys, with "all" materialised. */
594
+ get selectedKeys(): Set<Key> {
595
+ const raw = this.#state.selectedKeys();
596
+ return raw === "all" ? new Set(this.#selectAllKeys()) : raw;
597
+ }
598
+
599
+ /** The selection as stored: "all", or the set. */
600
+ get rawSelection(): SelectionValue {
601
+ return this.#state.selectedKeys();
602
+ }
603
+
604
+ isSelected(key: Key): boolean {
605
+ if (this.selectionMode === "none") return false;
606
+ const mapped = this.#itemKey(key);
607
+ if (mapped === null) return false;
608
+ const raw = this.#state.selectedKeys();
609
+ return raw === "all" ? this.canSelectItem(mapped) : raw.has(mapped);
610
+ }
611
+
612
+ get isEmpty(): boolean {
613
+ const raw = this.#state.selectedKeys();
614
+ return raw !== "all" && raw.size === 0;
615
+ }
616
+
617
+ get isSelectAll(): boolean {
618
+ if (this.isEmpty) return false;
619
+ const raw = this.#state.selectedKeys();
620
+ if (raw === "all") return true;
621
+ return this.#selectAllKeys().every((key) => raw.has(key));
622
+ }
623
+
624
+ get firstSelectedKey(): Key | null {
625
+ let first: Node<unknown> | null = null;
626
+ for (const key of this.#state.selectedKeys() === "all" ? [] : this.selectedKeys) {
627
+ const item = this.collection.getItem(key);
628
+ if (item !== null && (first === null || this.#order(item, first) < 0)) first = item;
629
+ }
630
+ return first?.key ?? null;
631
+ }
632
+
633
+ get lastSelectedKey(): Key | null {
634
+ let last: Node<unknown> | null = null;
635
+ for (const key of this.#state.selectedKeys() === "all" ? [] : this.selectedKeys) {
636
+ const item = this.collection.getItem(key);
637
+ if (item !== null && (last === null || this.#order(item, last) > 0)) last = item;
638
+ }
639
+ return last?.key ?? null;
640
+ }
641
+
642
+ get disabledKeys(): Set<Key> {
643
+ return this.#state.disabledKeys();
644
+ }
645
+
646
+ get disabledBehavior(): DisabledBehavior {
647
+ return this.#state.disabledBehavior();
648
+ }
649
+
650
+ /**
651
+ * Which of two nodes comes first in the document.
652
+ *
653
+ * Siblings compare by index. Otherwise each is walked up to the children of
654
+ * the nearest ancestor they share, and those two compare; a node that is
655
+ * the other's ancestor comes first. Comparing parents alone ties a row with
656
+ * its uncle in a tree, and the selection's first key then depends on the
657
+ * order the set was filled in.
658
+ */
659
+ #order(a: Node<unknown>, b: Node<unknown>): number {
660
+ if (a.parentKey === b.parentKey) return a.index - b.index;
661
+
662
+ // The key order is document order, where the collection lists the keys
663
+ // at all. An index alone cannot say it: a list numbers its items across
664
+ // sections and its sections among siblings, so the two do not compare.
665
+ const positions = keyPositions(this.collection);
666
+ const positionA = positions.get(a.key);
667
+ const positionB = positions.get(b.key);
668
+ if (positionA !== undefined && positionB !== undefined) return positionA - positionB;
669
+
670
+ const lineage = (node: Node<unknown>): Node<unknown>[] => {
671
+ const chain = [node];
672
+ let step = node;
673
+ while (step.parentKey !== undefined) {
674
+ const parent = this.collection.getItem(step.parentKey);
675
+ if (parent === null) break;
676
+ chain.unshift(parent);
677
+ step = parent;
678
+ }
679
+ return chain;
680
+ };
681
+
682
+ const ofA = lineage(a);
683
+ const ofB = lineage(b);
684
+ const depth = Math.min(ofA.length, ofB.length);
685
+ for (let level = 0; level < depth; level++) {
686
+ const x = ofA[level] as Node<unknown>;
687
+ const y = ofB[level] as Node<unknown>;
688
+ if (x.key !== y.key) return x.index - y.index;
689
+ }
690
+ return ofA.length - ofB.length;
691
+ }
692
+
693
+ extendSelection(to: Key): void {
694
+ if (this.selectionMode === "none") return;
695
+ if (this.selectionMode === "single") {
696
+ this.replaceSelection(to);
697
+ return;
698
+ }
699
+
700
+ const mapped = this.#itemKey(to);
701
+ if (mapped === null) return;
702
+
703
+ const raw = this.#state.selectedKeys();
704
+ let next: Selection;
705
+
706
+ if (raw === "all") {
707
+ next = new Selection([mapped], mapped, mapped);
708
+ } else {
709
+ const anchor = raw.anchorKey ?? mapped;
710
+ next = new Selection(raw, anchor, mapped);
711
+ // Un-select what the previous extension covered, then select the new
712
+ // range: dragging back over a range has to shrink it.
713
+ for (const key of this.#keyRange(anchor, raw.currentKey ?? mapped)) next.delete(key);
714
+ for (const key of this.#keyRange(mapped, anchor)) {
715
+ if (this.canSelectItem(key)) next.add(key);
716
+ }
717
+ }
718
+
719
+ this.#state.setSelectedKeys(next);
720
+ }
721
+
722
+ #keyRange(from: Key, to: Key): Key[] {
723
+ const fromItem = this.collection.getItem(from);
724
+ const toItem = this.collection.getItem(to);
725
+ if (fromItem === null || toItem === null) return [];
726
+ return this.#order(fromItem, toItem) <= 0
727
+ ? this.#keyRangeForward(from, to)
728
+ : this.#keyRangeForward(to, from);
729
+ }
730
+
731
+ #keyRangeForward(from: Key, to: Key): Key[] {
732
+ if (this.#layoutDelegate?.getKeyRange !== undefined) {
733
+ return this.#layoutDelegate.getKeyRange(from, to);
734
+ }
735
+
736
+ const keys: Key[] = [];
737
+ let key: Key | null = from;
738
+ while (key !== null) {
739
+ const item = this.collection.getItem(key);
740
+ if (item !== null && (item.type === "item" || this.#allowsCellSelection)) keys.push(key);
741
+ if (key === to) return keys;
742
+ key = this.collection.getKeyAfter(key);
743
+ }
744
+ return [];
745
+ }
746
+
747
+ /** The key that is actually selectable: an item, walking up from a cell. */
748
+ #itemKey(key: Key): Key | null {
749
+ let item = this.collection.getItem(key);
750
+ if (item === null) return key;
751
+ while (item !== null && item.type !== "item" && item.parentKey !== undefined) {
752
+ item = this.collection.getItem(item.parentKey);
753
+ }
754
+ return item !== null && item.type === "item" ? item.key : null;
755
+ }
756
+
757
+ toggleSelection(key: Key): void {
758
+ if (this.selectionMode === "none") return;
759
+ if (this.selectionMode === "single" && !this.isSelected(key)) {
760
+ this.replaceSelection(key);
761
+ return;
762
+ }
763
+
764
+ const mapped = this.#itemKey(key);
765
+ if (mapped === null) return;
766
+
767
+ const raw = this.#state.selectedKeys();
768
+ const next = new Selection(raw === "all" ? this.#selectAllKeys() : raw);
769
+ if (next.has(mapped)) {
770
+ next.delete(mapped);
771
+ } else if (this.canSelectItem(mapped)) {
772
+ next.add(mapped);
773
+ next.anchorKey = mapped;
774
+ next.currentKey = mapped;
775
+ }
776
+
777
+ if (this.disallowEmptySelection && next.size === 0) return;
778
+ this.#state.setSelectedKeys(next);
779
+ }
780
+
781
+ replaceSelection(key: Key): void {
782
+ if (this.selectionMode === "none") return;
783
+ const mapped = this.#itemKey(key);
784
+ if (mapped === null) return;
785
+
786
+ this.#state.setSelectedKeys(
787
+ this.canSelectItem(mapped) ? new Selection([mapped], mapped, mapped) : new Selection(),
788
+ );
789
+ }
790
+
791
+ setSelectedKeys(keys: Iterable<Key>): void {
792
+ if (this.selectionMode === "none") return;
793
+
794
+ const next = new Selection();
795
+ for (const key of keys) {
796
+ const mapped = this.#itemKey(key);
797
+ if (mapped === null) continue;
798
+ next.add(mapped);
799
+ if (this.selectionMode === "single") break;
800
+ }
801
+ this.#state.setSelectedKeys(next);
802
+ }
803
+
804
+ #selectAllKeys(): Key[] {
805
+ // The unfiltered collection when there is one, so an "all" selection
806
+ // survives a filter being applied and removed.
807
+ const collection = this.#fullCollection ?? this.collection;
808
+ const keys: Key[] = [];
809
+
810
+ const walk = (start: Key | null): void => {
811
+ let key = start;
812
+ while (key !== null) {
813
+ if (this.#canSelectIn(key, collection)) {
814
+ const item = collection.getItem(key);
815
+ if (item?.type === "item") keys.push(key);
816
+ if (item?.hasChildNodes === true && (this.#allowsCellSelection || item.type !== "item")) {
817
+ walk(item.childNodes[0]?.key ?? null);
818
+ }
819
+ }
820
+ key = collection.getKeyAfter(key);
821
+ }
822
+ };
823
+
824
+ walk(collection.getFirstKey());
825
+ return keys;
826
+ }
827
+
828
+ selectAll(): void {
829
+ if (!this.isSelectAll && this.selectionMode === "multiple") this.#state.setSelectedKeys("all");
830
+ }
831
+
832
+ clearSelection(): void {
833
+ const raw = this.#state.selectedKeys();
834
+ if (!this.disallowEmptySelection && (raw === "all" || raw.size > 0)) {
835
+ this.#state.setSelectedKeys(new Selection());
836
+ }
837
+ }
838
+
839
+ toggleSelectAll(): void {
840
+ if (this.isSelectAll) this.clearSelection();
841
+ else this.selectAll();
842
+ }
843
+
844
+ /**
845
+ * What a press on an item means.
846
+ *
847
+ * Touch and a virtual cursor always toggle: neither has a modifier key, so
848
+ * `replace` would make multiple selection impossible for them.
849
+ */
850
+ select(key: Key, event?: { pointerType?: string }): void {
851
+ if (this.selectionMode === "none") return;
852
+
853
+ if (this.selectionMode === "single") {
854
+ if (this.isSelected(key) && !this.disallowEmptySelection) this.toggleSelection(key);
855
+ else this.replaceSelection(key);
856
+ return;
857
+ }
858
+
859
+ if (
860
+ this.selectionBehavior === "toggle" ||
861
+ event?.pointerType === "touch" ||
862
+ event?.pointerType === "virtual"
863
+ ) {
864
+ this.toggleSelection(key);
865
+ return;
866
+ }
867
+
868
+ this.replaceSelection(key);
869
+ }
870
+
871
+ isSelectionEqual(other: Set<Key>): boolean {
872
+ const raw = this.#state.selectedKeys();
873
+ if ((other as unknown) === raw) return true;
874
+ return sameSet(other, this.selectedKeys);
875
+ }
876
+
877
+ canSelectItem(key: Key): boolean {
878
+ return this.#canSelectIn(key, this.collection);
879
+ }
880
+
881
+ #canSelectIn(key: Key, collection: Collection<unknown>): boolean {
882
+ if (this.selectionMode === "none" || this.#state.disabledKeys().has(key)) return false;
883
+ const item = collection.getItem(key);
884
+ if (item === null) return false;
885
+ if (item.props?.isDisabled === true) return false;
886
+ return true;
887
+ }
888
+
889
+ /** Whether the item responds to anything at all, not merely to selection. */
890
+ isDisabled(key: Key): boolean {
891
+ const item = this.collection.getItem(key);
892
+ return (
893
+ this.disabledBehavior === "all" &&
894
+ (this.#state.disabledKeys().has(key) || item?.props?.isDisabled === true) &&
895
+ item?.props?.disabledBehavior !== "selection"
896
+ );
897
+ }
898
+
899
+ isLink(key: Key): boolean {
900
+ return this.collection.getItem(key)?.props?.href !== undefined;
901
+ }
902
+
903
+ getItemProps(key: Key): Record<string, unknown> | undefined {
904
+ return this.collection.getItem(key)?.props;
905
+ }
906
+
907
+ /** The same selection, over a different (usually filtered) collection. */
908
+ withCollection(collection: Collection<unknown>): SelectionManager {
909
+ return new SelectionManager(collection, this.#state, {
910
+ allowsCellSelection: this.#allowsCellSelection,
911
+ layoutDelegate: this.#layoutDelegate ?? undefined,
912
+ fullCollection: this.#fullCollection ?? this.collection,
913
+ });
914
+ }
915
+ }
916
+
917
+ // ---------------------------------------------------------------------------
918
+ // List state
919
+ // ---------------------------------------------------------------------------
920
+
921
+ export interface ListStateOptions<T> extends MultipleSelectionOptions, ItemAccessors<T> {
922
+ items?: MaybeAccessor<Iterable<T> | undefined>;
923
+ /** Narrow the collection, for an autocomplete. */
924
+ filter?: (nodes: Iterable<Node<T>>) => Iterable<Node<T>>;
925
+ layoutDelegate?: LayoutDelegate;
926
+ }
927
+
928
+ export interface ListState<T> {
929
+ collection: Accessor<ListCollection<T>>;
930
+ selectionManager: Accessor<SelectionManager>;
931
+ disabledKeys: Accessor<Set<Key>>;
932
+ }
933
+
934
+ /**
935
+ * A collection and its selection, kept in step.
936
+ *
937
+ * The focused key is repaired when the item it names disappears: a list whose
938
+ * focused row is deleted must move focus to the next row that still exists,
939
+ * forwards if there is one and backwards otherwise, or the user is left with
940
+ * an arrow key that does nothing.
941
+ */
942
+ export function listState<T>(options: ListStateOptions<T>): ListState<T> {
943
+ const selection = multipleSelectionState(options);
944
+
945
+ const collection = createMemo(() => {
946
+ const items = access(options.items) ?? [];
947
+ const built = buildCollection(items, options);
948
+ if (options.filter === undefined) return built;
949
+ return new ListCollection(options.filter(built));
950
+ });
951
+
952
+ const selectionManager = createMemo(
953
+ () =>
954
+ new SelectionManager(collection() as Collection<unknown>, selection, {
955
+ layoutDelegate: options.layoutDelegate,
956
+ }),
957
+ );
958
+
959
+ // The search reads, so it is the compute; moving focus writes, so it is the
960
+ // apply. In the render phase, so the repaired key is in place before any
961
+ // effect that moves DOM focus to it runs.
962
+ let previous: ListCollection<T> | null = null;
963
+ createRenderEffect(
964
+ (): { current: ListCollection<T>; repair: boolean; next: Key | null } => {
965
+ const current = collection();
966
+ const focused = selection.focusedKey();
967
+ if (focused === null || current.getItem(focused) !== null || previous === null) {
968
+ return { current, repair: false, next: null };
969
+ }
970
+
971
+ const manager = selectionManager();
972
+ let next: Key | null = null;
973
+
974
+ // Forwards through the OLD collection, for the first key that survives.
975
+ let key = previous.getKeyAfter(focused);
976
+ while (key !== null && next === null) {
977
+ const node = current.getItem(key);
978
+ if (node !== null && node.type === "item" && !manager.isDisabled(key)) next = key;
979
+ key = previous.getKeyAfter(key);
980
+ }
981
+
982
+ if (next === null) {
983
+ key = previous.getKeyBefore(focused);
984
+ while (key !== null && next === null) {
985
+ const node = current.getItem(key);
986
+ if (node !== null && node.type === "item" && !manager.isDisabled(key)) next = key;
987
+ key = previous.getKeyBefore(key);
988
+ }
989
+ }
990
+
991
+ return { current, repair: true, next };
992
+ },
993
+ ({ current, repair, next }) => {
994
+ if (repair) selection.setFocusedKey(next);
995
+ previous = current;
996
+ },
997
+ );
998
+
999
+ return {
1000
+ collection,
1001
+ selectionManager,
1002
+ disabledKeys: selection.disabledKeys,
1003
+ };
1004
+ }
1005
+
1006
+ export interface SingleSelectListOptions<T> extends Omit<
1007
+ ListStateOptions<T>,
1008
+ "selectedKeys" | "defaultSelectedKeys" | "onSelectionChange"
1009
+ > {
1010
+ selectedKey?: MaybeAccessor<Key | null | undefined>;
1011
+ defaultSelectedKey?: MaybeAccessor<Key | null | undefined>;
1012
+ onSelectionChange?: (key: Key | null) => void;
1013
+ }
1014
+
1015
+ export interface SingleSelectListState<T> extends ListState<T> {
1016
+ selectedKey: Accessor<Key | null>;
1017
+ setSelectedKey(key: Key | null): void;
1018
+ selectedItem: Accessor<Node<T> | null>;
1019
+ }
1020
+
1021
+ /** A collection where exactly one item is selected: a select, a tab list. */
1022
+ export function singleSelectListState<T>(
1023
+ options: SingleSelectListOptions<T>,
1024
+ ): SingleSelectListState<T> {
1025
+ const [selectedKey, setSelectedKey] = controllable<Key | null>(
1026
+ () => access(options.selectedKey),
1027
+ () => access(options.defaultSelectedKey) ?? null,
1028
+ options.onSelectionChange,
1029
+ );
1030
+
1031
+ const state = listState<T>({
1032
+ ...options,
1033
+ selectionMode: "single",
1034
+ disallowEmptySelection: true,
1035
+ allowDuplicateSelectionEvents: true,
1036
+ selectedKeys: () => {
1037
+ const key = selectedKey();
1038
+ return key === null ? [] : [key];
1039
+ },
1040
+ onSelectionChange: (keys) => {
1041
+ if (keys === "all") return;
1042
+ const key = keys.values().next().value ?? null;
1043
+ // Reported even when unchanged: pressing the already-selected tab is an
1044
+ // event a caller may want, and `controllable` swallows a no-op set.
1045
+ if (key === selectedKey()) options.onSelectionChange?.(key);
1046
+ setSelectedKey(key);
1047
+ },
1048
+ });
1049
+
1050
+ return {
1051
+ ...state,
1052
+ selectedKey,
1053
+ setSelectedKey,
1054
+ selectedItem: () => {
1055
+ const key = selectedKey();
1056
+ return key === null ? null : state.collection().getItem(key);
1057
+ },
1058
+ };
1059
+ }