@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,581 @@
1
+ /**
2
+ * An autocomplete: a text field that filters, and drives, a collection beside
3
+ * it.
4
+ *
5
+ * Unlike a combo box it owns neither the field nor the list. A search field, a
6
+ * text field or a token field writes the query; a listbox or a menu shows
7
+ * what matches and does what it does with a choice. The autocomplete sits
8
+ * between them and adds three things:
9
+ *
10
+ * - **The query filters the collection.** The collection reads `filter` and
11
+ * narrows its own nodes, so its keyboard, selection and typeahead all see
12
+ * only what is shown.
13
+ * - **Focus stays in the field.** The highlighted item is named with
14
+ * `aria-activedescendant`; the arrows, Home, End and Page keys are passed
15
+ * on to the collection as if they had been pressed there, and Enter to the
16
+ * highlighted item, so typing and choosing are one gesture. A mobile screen
17
+ * reader is the exception: it has no keyboard and cannot follow a virtual
18
+ * highlight, so there the collection is focused for real.
19
+ * - **Typing forward highlights the first match**, and does it half a second
20
+ * later on the field: a screen reader reading the letter just typed must not
21
+ * be interrupted by the item it brought up. Deleting, pasting or undoing
22
+ * clears the highlight instead, because the list under it changed for a
23
+ * reason other than narrowing.
24
+ *
25
+ * The parts connect through context, as upstream's do: an input reads
26
+ * {@link useAutocompleteInput}, a collection reads
27
+ * {@link useAutocompleteCollection} and calls `connect` with its state. The
28
+ * hook {@link autocomplete} is the same thing for markup of one's own.
29
+ */
30
+
31
+ import {
32
+ cells,
33
+ type Accessor,
34
+ type Child,
35
+ createContext,
36
+ createEffect,
37
+ createSignal,
38
+ getContext,
39
+ onCleanup,
40
+ provide,
41
+ untrack,
42
+ } from "@barqjs/core";
43
+ import { isServer } from "@barqjs/web";
44
+ import { ref as makeRef } from "@barqjs/primitives/refs";
45
+ import {
46
+ ListCollection,
47
+ type Key,
48
+ type ListState,
49
+ type Node,
50
+ type SelectionManager,
51
+ } from "./collections.ts";
52
+ import { ownerDocument, targetElement } from "./dom.ts";
53
+ import { getInteractionModality } from "./interactions/modality.ts";
54
+ import type { ElementRef } from "./interactions/press.ts";
55
+ import { isAndroid, isIOS } from "./platform.ts";
56
+ import { isCtrlKeyPressed, ListKeyboardDelegate } from "./selection.ts";
57
+ import { access, callback, controllable, type DOMProps, id, type MaybeAccessor } from "./utils.ts";
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // State
61
+ // ---------------------------------------------------------------------------
62
+
63
+ export interface AutocompleteStateOptions {
64
+ inputValue?: MaybeAccessor<string | undefined>;
65
+ defaultInputValue?: MaybeAccessor<string | undefined>;
66
+ onInputChange?: (value: string) => void;
67
+ }
68
+
69
+ export interface AutocompleteState {
70
+ /** What is typed in the field. */
71
+ inputValue: Accessor<string>;
72
+ setInputValue(value: string): void;
73
+ /** The id the field names with `aria-activedescendant`, if any. */
74
+ focusedNodeId: Accessor<string | null>;
75
+ setFocusedNodeId(value: string | null): void;
76
+ }
77
+
78
+ export function autocompleteState(options: AutocompleteStateOptions = {}): AutocompleteState {
79
+ const [inputValue, setInputValue] = controllable<string>(
80
+ () => access(options.inputValue),
81
+ () => access(options.defaultInputValue) ?? "",
82
+ options.onInputChange,
83
+ );
84
+ const [focusedNodeId, setFocusedNodeId] = createSignal<string | null>(null);
85
+ return { inputValue, setInputValue, focusedNodeId, setFocusedNodeId };
86
+ }
87
+
88
+ // ---------------------------------------------------------------------------
89
+ // The hook
90
+ // ---------------------------------------------------------------------------
91
+
92
+ /** Whether a node stays, given what it reads as and what is typed. */
93
+ export type AutocompleteFilter = (
94
+ textValue: string,
95
+ inputValue: string,
96
+ node: Node<unknown>,
97
+ ) => boolean;
98
+
99
+ /** What a collection hands the autocomplete when it connects. */
100
+ export interface AutocompleteCollection {
101
+ /** The collection's element, which the field's keys are passed on to. */
102
+ ref: ElementRef;
103
+ state: ListState<unknown>;
104
+ /** The id the item with this key renders under. */
105
+ idFor(key: Key): string;
106
+ }
107
+
108
+ export interface AutocompleteOptions {
109
+ /** The field the query is typed in. */
110
+ inputRef: ElementRef;
111
+ filter?: AutocompleteFilter;
112
+ /** Typing forward leaves the highlight where it is. @default false */
113
+ disableAutoFocusFirst?: MaybeAccessor<boolean | undefined>;
114
+ /** The collection is focused for real, and is a Tab stop of its own. @default false */
115
+ disableVirtualFocus?: MaybeAccessor<boolean | undefined>;
116
+ }
117
+
118
+ /** Options for a `textField` or `searchField`: the field's value is the query. */
119
+ export interface AutocompleteInputOptions {
120
+ value: Accessor<string>;
121
+ onChange(value: string): void;
122
+ }
123
+
124
+ /** Options for a `listBox` or `menu`. */
125
+ export interface AutocompleteCollectionProps {
126
+ id: Accessor<string>;
127
+ "aria-label": string;
128
+ shouldUseVirtualFocus: Accessor<boolean>;
129
+ disallowTypeAhead: Accessor<boolean>;
130
+ autoFocus: Accessor<"first" | false>;
131
+ }
132
+
133
+ export interface AutocompleteResult {
134
+ /** For the field's element, after the field's own props. */
135
+ inputProps: DOMProps;
136
+ /** For the field's hook. */
137
+ inputOptions: AutocompleteInputOptions;
138
+ /** For the collection's hook. */
139
+ collectionProps: AutocompleteCollectionProps;
140
+ /** Whether a node is shown. Absent when no `filter` was given: everything is. */
141
+ filter: ((textValue: string, node: Node<unknown>) => boolean) | undefined;
142
+ /** `filter` in the shape `listState({ filter })` takes. */
143
+ filterNodes: ((nodes: Iterable<Node<unknown>>) => Iterable<Node<unknown>>) | undefined;
144
+ /** Called by the collection with its state; returns what disconnects it. */
145
+ connect(collection: AutocompleteCollection): () => void;
146
+ }
147
+
148
+ /** How long the field waits before naming the item typing brought up. */
149
+ const ANNOUNCE_DELAY = 500;
150
+
151
+ /** The keys that move the highlight rather than the caret. */
152
+ const NAVIGATION = new Set([
153
+ "Home",
154
+ "End",
155
+ "PageDown",
156
+ "PageUp",
157
+ "ArrowUp",
158
+ "ArrowDown",
159
+ "ArrowRight",
160
+ "ArrowLeft",
161
+ ]);
162
+
163
+ function copyKeyboardEvent(event: KeyboardEvent): KeyboardEvent {
164
+ return new KeyboardEvent(event.type, {
165
+ key: event.key,
166
+ code: event.code,
167
+ location: event.location,
168
+ repeat: event.repeat,
169
+ isComposing: event.isComposing,
170
+ shiftKey: event.shiftKey,
171
+ ctrlKey: event.ctrlKey,
172
+ altKey: event.altKey,
173
+ metaKey: event.metaKey,
174
+ bubbles: true,
175
+ cancelable: true,
176
+ composed: true,
177
+ });
178
+ }
179
+
180
+ export function autocomplete(
181
+ options: AutocompleteOptions,
182
+ state: AutocompleteState,
183
+ ): AutocompleteResult {
184
+ const collectionId = id();
185
+ const input = (): HTMLElement | null => (access(options.inputRef) as HTMLElement | null) ?? null;
186
+
187
+ // A mobile screen reader cannot follow a virtual highlight, so it gets the
188
+ // collection itself.
189
+ const isMobileScreenReader = getInteractionModality() === "virtual" && (isIOS() || isAndroid());
190
+ const [connected, setConnected] = createSignal<AutocompleteCollection | null>(null, {
191
+ ownedWrite: true,
192
+ });
193
+ const [autoFocusOnMount, setAutoFocusOnMount] = createSignal(false, { ownedWrite: true });
194
+
195
+ const shouldUseVirtualFocus = (): boolean => {
196
+ if (isMobileScreenReader || access(options.disableVirtualFocus) === true) return false;
197
+ // A collection that put itself in the Tab order anyway cannot be driven
198
+ // virtually, and the field must not pretend otherwise.
199
+ const element = connected()?.ref;
200
+ const node = element === undefined ? null : (access(element) as Element | null);
201
+ return node === null || !node.hasAttribute("tabindex");
202
+ };
203
+ const hasCollection = (): boolean => connected() !== null;
204
+
205
+ const manager = (): SelectionManager | null =>
206
+ untrack(() => connected()?.state.selectionManager() ?? null);
207
+ const itemElement = (key: Key): HTMLElement | null => {
208
+ const collection = untrack(connected);
209
+ const field = input();
210
+ if (collection === null || field === null) return null;
211
+ return ownerDocument(field).getElementById(collection.idFor(key));
212
+ };
213
+
214
+ let focusFirstPending = false;
215
+ let delayNext = false;
216
+ let timer: ReturnType<typeof setTimeout> | null = null;
217
+ const clearTimer = (): void => {
218
+ if (timer !== null) clearTimeout(timer);
219
+ timer = null;
220
+ };
221
+ onCleanup(clearTimer);
222
+
223
+ const focusFirstItem = (): void => {
224
+ if (untrack(connected) === null) {
225
+ setAutoFocusOnMount(true);
226
+ return;
227
+ }
228
+ delayNext = true;
229
+ focusFirstPending = true;
230
+ manager()?.setFocused(true);
231
+ };
232
+
233
+ const clearVirtualFocus = (clearFocusKey = false): void => {
234
+ setAutoFocusOnMount(false);
235
+ clearTimer();
236
+ delayNext = false;
237
+ focusFirstPending = false;
238
+ state.setFocusedNodeId(null);
239
+ const active = manager();
240
+ active?.setFocused(false);
241
+ if (clearFocusKey) active?.setFocusedKey(null);
242
+ };
243
+
244
+ if (!isServer) {
245
+ // The first item, once the narrowed collection has one: an effect, because
246
+ // the collection narrows on the flush after the keystroke.
247
+ createEffect(
248
+ () => {
249
+ const collection = connected();
250
+ if (collection === null) return null;
251
+ const delegate = new ListKeyboardDelegate({
252
+ collection: collection.state.collection,
253
+ ref: collection.ref,
254
+ disabledKeys: collection.state.disabledKeys,
255
+ });
256
+ return { first: delegate.getFirstKey(), size: collection.state.collection().size };
257
+ },
258
+ (now) => {
259
+ if (now === null || !focusFirstPending) return;
260
+ if (now.first === null) {
261
+ state.setFocusedNodeId(null);
262
+ // Every item disabled, rather than a collection still loading: stop waiting.
263
+ if (now.size > 0) focusFirstPending = false;
264
+ return;
265
+ }
266
+ const active = manager();
267
+ active?.setFocused(true);
268
+ active?.setFocusedKey(now.first);
269
+ focusFirstPending = false;
270
+ },
271
+ );
272
+
273
+ // The field names what the collection has focused, while it has it.
274
+ createEffect(
275
+ () => {
276
+ const collection = connected();
277
+ if (collection === null || !shouldUseVirtualFocus()) return null;
278
+ const active = collection.state.selectionManager();
279
+ const key = active.focusedKey;
280
+ if (!active.isFocused || key === null) return null;
281
+ if (collection.state.collection().getItem(key) === null) return null;
282
+ return collection.idFor(key);
283
+ },
284
+ (next) => {
285
+ clearTimer();
286
+ if (next !== null && delayNext) {
287
+ delayNext = false;
288
+ timer = setTimeout(() => {
289
+ timer = null;
290
+ state.setFocusedNodeId(next);
291
+ }, ANNOUNCE_DELAY);
292
+ return;
293
+ }
294
+ state.setFocusedNodeId(next);
295
+ },
296
+ );
297
+ }
298
+
299
+ let lastInputType = "";
300
+ const onBeforeInput = (event: InputEvent): void => {
301
+ lastInputType = event.inputType;
302
+ };
303
+
304
+ const onChange = (value: string): void => {
305
+ const typed =
306
+ lastInputType === "insertText" ||
307
+ lastInputType === "insertCompositionText" ||
308
+ lastInputType === "insertFromComposition";
309
+ if (typed && access(options.disableAutoFocusFirst) !== true) {
310
+ focusFirstItem();
311
+ } else if (
312
+ lastInputType.includes("insert") ||
313
+ lastInputType.includes("delete") ||
314
+ lastInputType.includes("history")
315
+ ) {
316
+ clearVirtualFocus(true);
317
+ }
318
+ state.setInputValue(value);
319
+ };
320
+
321
+ let keyDownTarget: Element | null = null;
322
+
323
+ const focusedItem = (): HTMLElement | null => {
324
+ const key = manager()?.focusedKey ?? null;
325
+ if (key === null || untrack(state.focusedNodeId) === null) return null;
326
+ return itemElement(key);
327
+ };
328
+
329
+ const onKeyDown = (event: KeyboardEvent): void => {
330
+ keyDownTarget = targetElement(event);
331
+ if (event.isComposing) return;
332
+ if (!untrack(hasCollection) || !untrack(shouldUseVirtualFocus)) return;
333
+
334
+ const item = focusedItem();
335
+ switch (event.key) {
336
+ case "a":
337
+ if (isCtrlKeyPressed(event)) return;
338
+ break;
339
+ case "Escape":
340
+ // The field may have used it; a dialog around it must not also close.
341
+ if (event.defaultPrevented) return;
342
+ break;
343
+ case " ":
344
+ return;
345
+ case "Tab":
346
+ return;
347
+ default:
348
+ break;
349
+ }
350
+
351
+ if (NAVIGATION.has(event.key)) {
352
+ if ((event.key === "Home" || event.key === "End") && item === null && event.shiftKey) return;
353
+ // With nothing highlighted, left and right move the caret.
354
+ if ((event.key === "ArrowLeft" || event.key === "ArrowRight") && item === null) {
355
+ event.stopPropagation();
356
+ return;
357
+ }
358
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") event.preventDefault();
359
+ manager()?.setFocused(true);
360
+ }
361
+
362
+ event.stopPropagation();
363
+ const collection = untrack(connected);
364
+ const collectionElement =
365
+ collection === null ? null : ((access(collection.ref) as Element | null) ?? null);
366
+ const target = item ?? collectionElement;
367
+ const proceeds = target === null ? true : target.dispatchEvent(copyKeyboardEvent(event));
368
+
369
+ if (!proceeds) {
370
+ event.preventDefault();
371
+ return;
372
+ }
373
+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
374
+ // Silenced rather than lost: the next arrow up or down starts from it.
375
+ clearVirtualFocus();
376
+ } else if (event.key === "Enter" && item !== null) {
377
+ item.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
378
+ }
379
+ };
380
+
381
+ if (!isServer) {
382
+ // The release of a key passed on goes where the press went, ahead of
383
+ // anything listening on the field, so the item sees a whole press.
384
+ createEffect(input, (field) => {
385
+ if (field === null) return undefined;
386
+ const doc = ownerDocument(field);
387
+ const onKeyUp = (event: KeyboardEvent): void => {
388
+ if (targetElement(event) !== keyDownTarget || keyDownTarget === null) return;
389
+ if (!untrack(hasCollection) || !untrack(shouldUseVirtualFocus)) return;
390
+ event.stopImmediatePropagation();
391
+ const collection = untrack(connected);
392
+ const target =
393
+ focusedItem() ??
394
+ (collection === null ? null : ((access(collection.ref) as Element | null) ?? null));
395
+ target?.dispatchEvent(copyKeyboardEvent(event));
396
+ };
397
+ doc.addEventListener("keyup", onKeyUp, true);
398
+ return () => doc.removeEventListener("keyup", onKeyUp, true);
399
+ });
400
+ }
401
+
402
+ const onBlur = (): void => {
403
+ // The highlight is left where it was and its ring taken off; coming back
404
+ // puts the ring back on it.
405
+ manager()?.setFocused(false);
406
+ };
407
+
408
+ const onFocus = (): void => {
409
+ const active = manager();
410
+ if (active !== null && active.focusedKey !== null) active.setFocused(true);
411
+ };
412
+
413
+ const onPointerDown = (event: PointerEvent): void => {
414
+ if (event.button !== 0 || event.pointerType === "touch") return;
415
+ if (untrack(state.focusedNodeId) === null || input() === null) return;
416
+ if (targetElement(event) === input()) clearVirtualFocus();
417
+ };
418
+
419
+ const virtual = (): boolean => hasCollection() && shouldUseVirtualFocus();
420
+
421
+ const filter =
422
+ options.filter === undefined
423
+ ? undefined
424
+ : (textValue: string, node: Node<unknown>): boolean =>
425
+ options.filter?.(textValue, state.inputValue(), node) ?? true;
426
+
427
+ return {
428
+ inputOptions: { value: state.inputValue, onChange },
429
+ inputProps: {
430
+ onBeforeInput,
431
+ onKeyDown: (event: KeyboardEvent) => {
432
+ if (virtual()) onKeyDown(event);
433
+ },
434
+ onFocus: () => {
435
+ if (virtual()) onFocus();
436
+ },
437
+ onBlur: () => {
438
+ if (virtual()) onBlur();
439
+ },
440
+ onPointerDown: (event: PointerEvent) => {
441
+ if (virtual()) onPointerDown(event);
442
+ },
443
+ "aria-activedescendant": () => (virtual() ? (state.focusedNodeId() ?? undefined) : undefined),
444
+ "aria-controls": () => (hasCollection() ? collectionId() : undefined),
445
+ "aria-autocomplete": "list",
446
+ enterkeyhint: "go",
447
+ // The suggestions are the autocomplete's: iOS's autocorrect and
448
+ // Safari's spelling fixes would rewrite the query under them.
449
+ autocorrect: "off",
450
+ spellcheck: "false",
451
+ autocomplete: "off",
452
+ },
453
+ collectionProps: {
454
+ id: collectionId,
455
+ "aria-label": "Suggestions",
456
+ shouldUseVirtualFocus,
457
+ disallowTypeAhead: shouldUseVirtualFocus,
458
+ autoFocus: () => (autoFocusOnMount() ? "first" : false),
459
+ },
460
+ filter,
461
+ filterNodes:
462
+ filter === undefined
463
+ ? undefined
464
+ : (nodes) =>
465
+ (nodes instanceof ListCollection ? nodes : new ListCollection([...nodes])).filter(
466
+ filter,
467
+ ),
468
+ connect(collection) {
469
+ setConnected(collection);
470
+ return () => {
471
+ if (untrack(connected) === collection) setConnected(null);
472
+ };
473
+ },
474
+ };
475
+ }
476
+
477
+ // ---------------------------------------------------------------------------
478
+ // Components
479
+ // ---------------------------------------------------------------------------
480
+
481
+ export interface AutocompleteInputValue {
482
+ /** Goes on the field's element. */
483
+ ref: (element: Element | null) => void;
484
+ inputProps: DOMProps;
485
+ inputOptions: AutocompleteInputOptions;
486
+ }
487
+
488
+ export interface AutocompleteCollectionValue {
489
+ collectionProps: AutocompleteCollectionProps;
490
+ filter: AutocompleteResult["filter"];
491
+ filterNodes: AutocompleteResult["filterNodes"];
492
+ connect: AutocompleteResult["connect"];
493
+ }
494
+
495
+ interface AutocompleteValue {
496
+ state: AutocompleteState;
497
+ input: AutocompleteInputValue;
498
+ collection: AutocompleteCollectionValue;
499
+ }
500
+
501
+ const AutocompleteContext = createContext<AutocompleteValue | null>(null);
502
+
503
+ /** The enclosing {@link Autocomplete}'s state. */
504
+ export function useAutocompleteState(): AutocompleteState | null {
505
+ return getContext(AutocompleteContext)?.state ?? null;
506
+ }
507
+
508
+ /** What the field inside an {@link Autocomplete} takes, or `null` outside one. */
509
+ export function useAutocompleteInput(): AutocompleteInputValue | null {
510
+ return getContext(AutocompleteContext)?.input ?? null;
511
+ }
512
+
513
+ /** What the collection inside an {@link Autocomplete} takes, or `null` outside one. */
514
+ export function useAutocompleteCollection(): AutocompleteCollectionValue | null {
515
+ return getContext(AutocompleteContext)?.collection ?? null;
516
+ }
517
+
518
+ export interface AutocompleteComponentProps {
519
+ /** A field and a collection. */
520
+ children?: Child;
521
+ inputValue?: string;
522
+ defaultInputValue?: string;
523
+ onInputChange?: (value: string) => void;
524
+ /** Narrows the collection as the user types. Without it the collection is shown whole. */
525
+ filter?: AutocompleteFilter;
526
+ /** @default false */
527
+ disableAutoFocusFirst?: boolean;
528
+ /** @default false */
529
+ disableVirtualFocus?: boolean;
530
+ }
531
+
532
+ /**
533
+ * ```tsx
534
+ * <Autocomplete filter={contains}>
535
+ * <SearchField label="Search commands" />
536
+ * <Menu items={commands()}>{(command) => <MenuItem>{command.name}</MenuItem>}</Menu>
537
+ * </Autocomplete>
538
+ * ```
539
+ */
540
+ export function Autocomplete(props: AutocompleteComponentProps) {
541
+ const inputRef = makeRef<HTMLElement>();
542
+ const state = autocompleteState({
543
+ inputValue: () => props.inputValue,
544
+ defaultInputValue: () => props.defaultInputValue,
545
+ onInputChange: (value) => props.onInputChange?.(value),
546
+ });
547
+ const result = autocomplete(
548
+ {
549
+ inputRef,
550
+ filter: callback<[string, string, Node<unknown>], boolean>(cells(props).filter),
551
+ disableAutoFocusFirst: () => props.disableAutoFocusFirst,
552
+ disableVirtualFocus: () => props.disableVirtualFocus,
553
+ },
554
+ state,
555
+ );
556
+
557
+ const value: AutocompleteValue = {
558
+ state,
559
+ input: {
560
+ ref: (element) => inputRef.set(element as HTMLElement | null),
561
+ inputProps: result.inputProps,
562
+ inputOptions: result.inputOptions,
563
+ },
564
+ collection: {
565
+ collectionProps: result.collectionProps,
566
+ filter: result.filter,
567
+ filterNodes: result.filterNodes,
568
+ connect: (collection) => result.connect(collection),
569
+ },
570
+ };
571
+
572
+ return <AutocompleteProvider value={value}>{props.children}</AutocompleteProvider>;
573
+ }
574
+
575
+ function AutocompleteProvider(props: { value: AutocompleteValue; children?: Child }) {
576
+ return provide(
577
+ AutocompleteContext,
578
+ () => props.value,
579
+ () => props.children as unknown,
580
+ );
581
+ }