@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,3003 @@
1
+ /**
2
+ * A combo box: a text field that filters a list of options.
3
+ *
4
+ * The hard part is that focus is in two places at once. The caret stays in the
5
+ * input — a user typing must not lose it — while the arrow keys move a
6
+ * highlight through the list. That is VIRTUAL focus: the input keeps DOM
7
+ * focus and names the highlighted option with `aria-activedescendant`, and no
8
+ * option is ever focused itself. Moving real focus into the list would take
9
+ * the caret with it and make typing impossible.
10
+ *
11
+ * Everything else follows from what the input value means at a given moment:
12
+ *
13
+ * - Typing filters, opens the list, and un-highlights whatever was
14
+ * highlighted, because the old highlight was for a list that no longer
15
+ * exists.
16
+ * - Enter COMMITS the highlighted option: it becomes the selection, its text
17
+ * replaces what was typed, and the list closes.
18
+ * - Escape REVERTS to the selected option's text, so a half-typed query never
19
+ * survives as the value.
20
+ * - Blur commits, for the same reason. Leaving a field showing text that is
21
+ * not its value is how a form submits something the user never saw.
22
+ *
23
+ * `allowsCustomValue` is the opt-out: with it, text matching nothing is a
24
+ * value in its own right and committing keeps it.
25
+ */
26
+
27
+ import {
28
+ cells,
29
+ type Accessor,
30
+ type Child,
31
+ For,
32
+ createMemo,
33
+ createContext,
34
+ createProjection,
35
+ createEffect,
36
+ getContext,
37
+ getOwner,
38
+ type Incoming,
39
+ install,
40
+ isBlock,
41
+ createSignal,
42
+ onCleanup,
43
+ onSettled,
44
+ provide,
45
+ Show,
46
+ untrack,
47
+ } from "@barqjs/core";
48
+ import { isServer, Portal } from "@barqjs/web";
49
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
50
+ import { button } from "./button.tsx";
51
+ import {
52
+ buildCollection,
53
+ getItemCount,
54
+ listState,
55
+ type FocusStrategy,
56
+ type ItemAccessors,
57
+ type Key,
58
+ type ListState,
59
+ type ListStateOptions,
60
+ type Node,
61
+ type SelectionValue,
62
+ } from "./collections.ts";
63
+ import { Popover } from "./dialog.tsx";
64
+ import { focusRing, focusScope } from "./focus.ts";
65
+ import {
66
+ declaredDirection,
67
+ filter as makeFilter,
68
+ StringDictionary,
69
+ stringFormatter,
70
+ useLocale,
71
+ } from "./i18n.ts";
72
+ import { hover } from "./interactions/hover.ts";
73
+ import type { ElementRef, PressEvent } from "./interactions/press.ts";
74
+ import { field, type FieldOptions } from "./label.ts";
75
+ import {
76
+ fieldValidation,
77
+ type FormValidationState,
78
+ type ValidateFunction,
79
+ type ValidationBehavior,
80
+ } from "./validation.ts";
81
+ import {
82
+ listBox,
83
+ ListBoxProvider,
84
+ Option,
85
+ optionIdFor,
86
+ provideItemNode,
87
+ provideItemRender,
88
+ type ListBoxContextValue,
89
+ } from "./listbox.tsx";
90
+ import { announce } from "./live.ts";
91
+ import { isAppleDevice } from "./platform.ts";
92
+ import { formReset } from "./toggle.ts";
93
+ import {
94
+ alignOf,
95
+ ariaHideOutside,
96
+ followOpen,
97
+ overlay as dismissal,
98
+ overlayPosition,
99
+ overlayTriggerState,
100
+ placementFor,
101
+ portalContainer,
102
+ usePortalTarget,
103
+ type Align,
104
+ type OverlayTriggerState,
105
+ type OverlayTriggerStateOptions,
106
+ type Placement,
107
+ type Side,
108
+ } from "./overlays.ts";
109
+ import { presence } from "./presence.ts";
110
+ import { ListKeyboardDelegate, selectableCollection, type KeyboardDelegate } from "./selection.ts";
111
+ import {
112
+ provideStaticSection,
113
+ staticAccessors,
114
+ staticCollection,
115
+ staticItem,
116
+ type StaticCollection,
117
+ type StaticEntry,
118
+ } from "./static-collection.ts";
119
+ import {
120
+ access,
121
+ callback,
122
+ controllable,
123
+ filterDOMProps,
124
+ fromProps,
125
+ id,
126
+ mergeProps,
127
+ provideTriggerSlot,
128
+ styleProps,
129
+ type DOMProps,
130
+ type MaybeAccessor,
131
+ type StyleProps,
132
+ } from "./utils.ts";
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // State
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /** What asked for the list. Only a manual open shows everything. */
139
+ export type MenuTriggerAction = "focus" | "input" | "manual";
140
+
141
+ export type FilterFn = (textValue: string, inputValue: string) => boolean;
142
+
143
+ export interface ComboBoxStateOptions<T> extends Omit<
144
+ ListStateOptions<T>,
145
+ "onSelectionChange" | "filter"
146
+ > {
147
+ selectedKey?: MaybeAccessor<Key | null | undefined>;
148
+ defaultSelectedKey?: MaybeAccessor<Key | null | undefined>;
149
+ inputValue?: MaybeAccessor<string | undefined>;
150
+ defaultInputValue?: MaybeAccessor<string | undefined>;
151
+ /**
152
+ * Which options the typed text keeps.
153
+ *
154
+ * Locale-aware `contains` by default, so "resume" finds "résumé". Pass
155
+ * `() => true` when the caller filters `items` itself.
156
+ */
157
+ filterBy?: FilterFn;
158
+ /** Text matching no option is a value of its own. @default false */
159
+ allowsCustomValue?: MaybeAccessor<boolean | undefined>;
160
+ /** @default false */
161
+ allowsEmptyCollection?: MaybeAccessor<boolean | undefined>;
162
+ /** @default true */
163
+ shouldCloseOnBlur?: MaybeAccessor<boolean | undefined>;
164
+ /** What opens the list. @default "input" */
165
+ menuTrigger?: MaybeAccessor<"input" | "focus" | "manual" | undefined>;
166
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
167
+ isOpen?: MaybeAccessor<boolean | undefined>;
168
+ defaultOpen?: MaybeAccessor<boolean | undefined>;
169
+ onOpenChange?: (isOpen: boolean, trigger?: MenuTriggerAction) => void;
170
+ onSelectionChange?: (key: Key | null) => void;
171
+ onInputChange?: (value: string) => void;
172
+ }
173
+
174
+ export interface ComboBoxState<T>
175
+ extends ListState<T>, Omit<OverlayTriggerState, "open" | "toggle"> {
176
+ selectedKey: Accessor<Key | null>;
177
+ setSelectedKey(key: Key | null): void;
178
+ selectedItem: Accessor<Node<T> | null>;
179
+ inputValue: Accessor<string>;
180
+ setInputValue(value: string): void;
181
+ defaultInputValue: Accessor<string>;
182
+ isFocused: Accessor<boolean>;
183
+ setFocused(isFocused: boolean): void;
184
+ focusStrategy: Accessor<FocusStrategy | null>;
185
+ open(focusStrategy?: FocusStrategy | null, trigger?: MenuTriggerAction): void;
186
+ toggle(focusStrategy?: FocusStrategy | null, trigger?: MenuTriggerAction): void;
187
+ /** Take the highlighted option, or the typed text, as the value. */
188
+ commit(): void;
189
+ /** Put the selected option's text back and close. */
190
+ revert(): void;
191
+ }
192
+
193
+ /**
194
+ * The nodes the typed text keeps, looking inside sections.
195
+ *
196
+ * A section stays while any of its items does, holding only those, and goes
197
+ * when it is left empty. Copies, because a collection links the nodes it is
198
+ * built from, and the unfiltered collection shares them.
199
+ */
200
+ function filterNodes<T>(nodes: Iterable<Node<T>>, keeps: (text: string) => boolean): Node<T>[] {
201
+ const kept: Node<T>[] = [];
202
+ for (const node of nodes) {
203
+ if (node.type === "section" && node.hasChildNodes) {
204
+ const children = filterNodes(node.childNodes, keeps);
205
+ if (children.some((child) => child.type === "item")) {
206
+ kept.push({ ...node, childNodes: children });
207
+ }
208
+ } else if (node.type !== "item" || keeps(node.textValue)) {
209
+ kept.push({ ...node });
210
+ }
211
+ }
212
+ return kept;
213
+ }
214
+
215
+ export function comboBoxState<T>(options: ComboBoxStateOptions<T>): ComboBoxState<T> {
216
+ const overlay = overlayTriggerState({
217
+ ...(options as OverlayTriggerStateOptions),
218
+ onOpenChange: (open) => options.onOpenChange?.(open, open ? lastTrigger : undefined),
219
+ });
220
+ const [showAll, setShowAll] = createSignal(false);
221
+ const [isFocused, setIsFocused] = createSignal(false);
222
+ const [strategy, setStrategy] = createSignal<FocusStrategy | null>(null);
223
+ let lastTrigger: MenuTriggerAction | undefined = "focus";
224
+
225
+ const match = makeFilter({ sensitivity: "base" });
226
+ const keeps = (): FilterFn => options.filterBy ?? match.contains;
227
+
228
+ const [selectedKey, setSelectedKey] = controllable<Key | null>(
229
+ () => access(options.selectedKey),
230
+ () => access(options.defaultSelectedKey) ?? null,
231
+ options.onSelectionChange,
232
+ );
233
+
234
+ /** The whole list, before anything typed narrows it. */
235
+ const full = createMemo(() => buildCollection(access(options.items) ?? [], options));
236
+
237
+ const initialInput = (): string => {
238
+ const declared = access(options.defaultInputValue);
239
+ if (declared !== undefined) return declared;
240
+ const key = access(options.selectedKey) ?? access(options.defaultSelectedKey) ?? null;
241
+ return key === null ? "" : (full().getItem(key)?.textValue ?? "");
242
+ };
243
+
244
+ const [inputValue, setInputValueRaw] = controllable<string>(
245
+ () => access(options.inputValue),
246
+ initialInput,
247
+ options.onInputChange,
248
+ );
249
+
250
+ const list = listState<T>({
251
+ ...options,
252
+ selectionMode: "single",
253
+ disallowEmptySelection: true,
254
+ allowDuplicateSelectionEvents: true,
255
+ selectedKeys: () => {
256
+ const key = selectedKey();
257
+ return key === null ? [] : [key];
258
+ },
259
+ filter: (nodes) => {
260
+ if (showAll()) return nodes;
261
+ const query = inputValue();
262
+ const keep = keeps();
263
+ return filterNodes(nodes, (text) => keep(text, query));
264
+ },
265
+ onSelectionChange: (keys: SelectionValue) => {
266
+ const key = keys === "all" ? null : (keys.values().next().value ?? null);
267
+ setSelectedKey(key);
268
+ // Choosing puts the option's own text in the field: what the field shows
269
+ // and what the field IS have to agree the moment the list closes.
270
+ syncedKey = key;
271
+ setInputValueRaw(key === null ? "" : (list.collection().getItem(key)?.textValue ?? ""));
272
+ overlay.close();
273
+ },
274
+ });
275
+
276
+ const selectedItem = (): Node<T> | null => {
277
+ const key = selectedKey();
278
+ return key === null ? null : (full().getItem(key) ?? null);
279
+ };
280
+
281
+ const selectedText = (): string => selectedItem()?.textValue ?? "";
282
+
283
+ const canShow = (displayAll: boolean): boolean => {
284
+ if (access(options.allowsEmptyCollection) === true) return true;
285
+ if (displayAll) return full().size > 0;
286
+ return list.collection().size > 0;
287
+ };
288
+
289
+ const displaysAll = (trigger?: MenuTriggerAction): boolean =>
290
+ trigger === "manual" || (trigger === "focus" && access(options.menuTrigger) === "focus");
291
+
292
+ const open = (focusStrategy: FocusStrategy | null = null, trigger?: MenuTriggerAction): void => {
293
+ const all = displaysAll(trigger);
294
+ if (!canShow(all)) return;
295
+ closedForEmpty = false;
296
+ if (all) setShowAll(true);
297
+ lastTrigger = trigger;
298
+ setStrategy(focusStrategy);
299
+ overlay.open();
300
+ };
301
+
302
+ const toggle = (
303
+ focusStrategy: FocusStrategy | null = null,
304
+ trigger?: MenuTriggerAction,
305
+ ): void => {
306
+ if (overlay.isOpen()) {
307
+ overlay.close();
308
+ return;
309
+ }
310
+ open(focusStrategy, trigger);
311
+ };
312
+
313
+ /**
314
+ * The key the field's text was last written FOR.
315
+ *
316
+ * Without it, following an outside change to `selectedKey` cannot be told
317
+ * from following one this component just made — and a custom value, which
318
+ * deliberately clears the key while keeping the text, looks like the second.
319
+ */
320
+ let syncedKey: Key | null = untrack(selectedKey);
321
+
322
+ /** Closed by the effect below for having nothing to show, not by the user. */
323
+ let closedForEmpty = false;
324
+
325
+ const resetInput = (): void => {
326
+ syncedKey = selectedKey();
327
+ setInputValueRaw(selectedText());
328
+ };
329
+
330
+ const commitValue = (): void => {
331
+ // Leaving the query, or settling it, is the end of the search that came
332
+ // back empty: an answer arriving after it must not open the list.
333
+ closedForEmpty = false;
334
+ if (access(options.allowsCustomValue) === true && inputValue() !== selectedText()) {
335
+ // Text matching nothing IS the value, so the selection goes away rather
336
+ // than the text.
337
+ syncedKey = null;
338
+ setSelectedKey(null);
339
+ overlay.close();
340
+ return;
341
+ }
342
+ resetInput();
343
+ overlay.close();
344
+ };
345
+
346
+ const commit = (): void => {
347
+ const manager = list.selectionManager();
348
+ if (overlay.isOpen() && manager.focusedKey !== null) {
349
+ // Committing the option that is already selected changes nothing to
350
+ // report, so the close and the text reset happen here instead.
351
+ if (manager.isSelected(manager.focusedKey)) {
352
+ resetInput();
353
+ overlay.close();
354
+ return;
355
+ }
356
+ manager.select(manager.focusedKey);
357
+ return;
358
+ }
359
+ commitValue();
360
+ };
361
+
362
+ const revert = (): void => {
363
+ closedForEmpty = false;
364
+ if (access(options.allowsCustomValue) === true && selectedKey() === null) {
365
+ overlay.close();
366
+ return;
367
+ }
368
+ resetInput();
369
+ overlay.close();
370
+ };
371
+
372
+ const setInputValue = (value: string): void => {
373
+ const changed = value !== inputValue();
374
+ setInputValueRaw(value);
375
+ if (!changed) return;
376
+
377
+ // The highlight was for a list that no longer exists.
378
+ setShowAll(false);
379
+ list.selectionManager().setFocusedKey(null);
380
+
381
+ // Clearing the field clears the value. Not when the caller controls it:
382
+ // then the value is theirs to decide.
383
+ if (value === "" && access(options.selectedKey) === undefined) {
384
+ syncedKey = null;
385
+ setSelectedKey(null);
386
+ }
387
+
388
+ if (access(options.menuTrigger) !== "manual" && isFocused() && !overlay.isOpen()) {
389
+ open(null, "input");
390
+ }
391
+ };
392
+
393
+ const setFocused = (next: boolean): void => {
394
+ if (next) {
395
+ if (access(options.menuTrigger) === "focus" && access(options.isReadOnly) !== true) {
396
+ open(null, "focus");
397
+ }
398
+ } else if (access(options.shouldCloseOnBlur) !== false) {
399
+ commitValue();
400
+ }
401
+ setIsFocused(next);
402
+ };
403
+
404
+ if (!isServer) {
405
+ // The list is only ever the FOCUSED collection while it is open, and the
406
+ // highlight does not survive a close: reopening starts from the selection.
407
+ createEffect(
408
+ () => [overlay.isOpen(), list.selectionManager()] as const,
409
+ ([isOpen, manager]) => {
410
+ manager.setFocused(isOpen);
411
+ if (!isOpen) manager.setFocusedKey(null);
412
+ },
413
+ );
414
+
415
+ // A list that has filtered down to nothing is a dead end.
416
+ createEffect(
417
+ () =>
418
+ !overlay.isOpen() || showAll() || access(options.allowsEmptyCollection) === true
419
+ ? null
420
+ : list.collection(),
421
+ (collection) => {
422
+ if (collection !== null && collection.size === 0) {
423
+ closedForEmpty = true;
424
+ overlay.close();
425
+ }
426
+ },
427
+ );
428
+
429
+ // And one closed for being empty opens again when items arrive, which is
430
+ // what an asynchronous search answering after an empty answer looks like.
431
+ createEffect(
432
+ () =>
433
+ [
434
+ list.collection().size,
435
+ isFocused(),
436
+ overlay.isOpen(),
437
+ access(options.menuTrigger) === "manual",
438
+ ] as const,
439
+ ([size, focused, isOpen, isManual]) => {
440
+ if (!closedForEmpty || !focused || isOpen || isManual || size === 0) return;
441
+ closedForEmpty = false;
442
+ lastTrigger = "input";
443
+ setStrategy(null);
444
+ overlay.open();
445
+ },
446
+ );
447
+
448
+ // The field follows a selection made from OUTSIDE, and the selected
449
+ // item's text if it arrives late. Never one this component just made, and
450
+ // never while the user is in the field: either would rewrite what they
451
+ // are typing.
452
+ createEffect(
453
+ () =>
454
+ [
455
+ selectedKey(),
456
+ selectedItem(),
457
+ access(options.inputValue),
458
+ isFocused(),
459
+ inputValue(),
460
+ ] as const,
461
+ ([key, item, controlled, focused, text]) => {
462
+ if (controlled !== undefined) return;
463
+ if (key !== syncedKey) {
464
+ syncedKey = key;
465
+ setInputValueRaw(item?.textValue ?? "");
466
+ return;
467
+ }
468
+ if (focused || item === null) return;
469
+ if (text !== item.textValue) setInputValueRaw(item.textValue);
470
+ },
471
+ );
472
+ }
473
+
474
+ return {
475
+ ...list,
476
+ isOpen: overlay.isOpen,
477
+ setOpen: overlay.setOpen,
478
+ close: overlay.close,
479
+ selectedKey,
480
+ setSelectedKey: (key) => {
481
+ syncedKey = key;
482
+ setSelectedKey(key);
483
+ setInputValueRaw(key === null ? "" : (full().getItem(key)?.textValue ?? ""));
484
+ },
485
+ selectedItem,
486
+ inputValue,
487
+ setInputValue,
488
+ defaultInputValue: () => initialInput(),
489
+ isFocused,
490
+ setFocused,
491
+ focusStrategy: strategy,
492
+ open,
493
+ toggle,
494
+ commit,
495
+ revert,
496
+ };
497
+ }
498
+
499
+ // ---------------------------------------------------------------------------
500
+ // Hooks
501
+ // ---------------------------------------------------------------------------
502
+
503
+ const comboBoxStrings = new StringDictionary<
504
+ | "buttonLabel"
505
+ | "listboxLabel"
506
+ | "countAnnouncement"
507
+ | "focusAnnouncement"
508
+ | "selectedAnnouncement"
509
+ >({
510
+ "ar-AE": {
511
+ buttonLabel: "عرض المقترحات",
512
+ listboxLabel: "مقترحات",
513
+ countAnnouncement: (values, format) =>
514
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} خيار`, other: () => `${format.number(Number(values?.optionCount))} خيارات` })} متاحة.`,
515
+ focusAnnouncement: (values, format) =>
516
+ `${format.select({ true: () => `المجموعة المدخلة ${String(values?.groupTitle ?? "")}, مع ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} خيار`, other: () => `${format.number(Number(values?.groupCount))} خيارات` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", محدد", other: () => "" }, String(values?.isSelected))}`,
517
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}، محدد`,
518
+ },
519
+ "bg-BG": {
520
+ buttonLabel: "Покажи предложения",
521
+ listboxLabel: "Предложения",
522
+ countAnnouncement: (values, format) =>
523
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} опция`, other: () => `${format.number(Number(values?.optionCount))} опции` })} на разположение.`,
524
+ focusAnnouncement: (values, format) =>
525
+ `${format.select({ true: () => `Въведена група ${String(values?.groupTitle ?? "")}, с ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} опция`, other: () => `${format.number(Number(values?.groupCount))} опции` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", избрани", other: () => "" }, String(values?.isSelected))}`,
526
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, избрани`,
527
+ },
528
+ "cs-CZ": {
529
+ buttonLabel: "Zobrazit doporučení",
530
+ listboxLabel: "Návrhy",
531
+ countAnnouncement: (values, format) =>
532
+ `K dispozici ${format.plural(Number(values?.optionCount), { one: () => `je ${format.number(Number(values?.optionCount))} možnost`, other: () => `jsou/je ${format.number(Number(values?.optionCount))} možnosti/-í` })}.`,
533
+ focusAnnouncement: (values, format) =>
534
+ `${format.select({ true: () => `Zadaná skupina „${String(values?.groupTitle ?? "")}“ ${format.plural(Number(values?.groupCount), { one: () => `s ${format.number(Number(values?.groupCount))} možností`, other: () => `se ${format.number(Number(values?.groupCount))} možnostmi` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => " (vybráno)", other: () => "" }, String(values?.isSelected))}`,
535
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, vybráno`,
536
+ },
537
+ "da-DK": {
538
+ buttonLabel: "Vis forslag",
539
+ listboxLabel: "Forslag",
540
+ countAnnouncement: (values, format) =>
541
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} mulighed tilgængelig`, other: () => `${format.number(Number(values?.optionCount))} muligheder tilgængelige` })}.`,
542
+ focusAnnouncement: (values, format) =>
543
+ `${format.select({ true: () => `Angivet gruppe ${String(values?.groupTitle ?? "")}, med ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} mulighed`, other: () => `${format.number(Number(values?.groupCount))} muligheder` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", valgt", other: () => "" }, String(values?.isSelected))}`,
544
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, valgt`,
545
+ },
546
+ "de-DE": {
547
+ buttonLabel: "Empfehlungen anzeigen",
548
+ listboxLabel: "Empfehlungen",
549
+ countAnnouncement: (values, format) =>
550
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} Option`, other: () => `${format.number(Number(values?.optionCount))} Optionen` })} verfügbar.`,
551
+ focusAnnouncement: (values, format) =>
552
+ `${format.select({ true: () => `Eingetretene Gruppe ${String(values?.groupTitle ?? "")}, mit ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} Option`, other: () => `${format.number(Number(values?.groupCount))} Optionen` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", ausgewählt", other: () => "" }, String(values?.isSelected))}`,
553
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, ausgewählt`,
554
+ },
555
+ "el-GR": {
556
+ buttonLabel: "Προβολή προτάσεων",
557
+ listboxLabel: "Προτάσεις",
558
+ countAnnouncement: (values, format) =>
559
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} επιλογή`, other: () => `${format.number(Number(values?.optionCount))} επιλογές ` })} διαθέσιμες.`,
560
+ focusAnnouncement: (values, format) =>
561
+ `${format.select({ true: () => `Εισαγμένη ομάδα ${String(values?.groupTitle ?? "")}, με ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} επιλογή`, other: () => `${format.number(Number(values?.groupCount))} επιλογές` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", επιλεγμένο", other: () => "" }, String(values?.isSelected))}`,
562
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, επιλέχθηκε`,
563
+ },
564
+ "en-US": {
565
+ buttonLabel: "Show suggestions",
566
+ listboxLabel: "Suggestions",
567
+ countAnnouncement: (values, format) =>
568
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} option`, other: () => `${format.number(Number(values?.optionCount))} options` })} available.`,
569
+ focusAnnouncement: (values, format) =>
570
+ `${format.select({ true: () => `Entered group ${String(values?.groupTitle ?? "")}, with ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} option`, other: () => `${format.number(Number(values?.groupCount))} options` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", selected", other: () => "" }, String(values?.isSelected))}`,
571
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, selected`,
572
+ },
573
+ "es-ES": {
574
+ buttonLabel: "Mostrar sugerencias",
575
+ listboxLabel: "Sugerencias",
576
+ countAnnouncement: (values, format) =>
577
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opción`, other: () => `${format.number(Number(values?.optionCount))} opciones` })} disponible(s).`,
578
+ focusAnnouncement: (values, format) =>
579
+ `${format.select({ true: () => `Se ha unido al grupo ${String(values?.groupTitle ?? "")}, con ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opción`, other: () => `${format.number(Number(values?.groupCount))} opciones` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", seleccionado", other: () => "" }, String(values?.isSelected))}`,
580
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, seleccionado`,
581
+ },
582
+ "et-EE": {
583
+ buttonLabel: "Kuva soovitused",
584
+ listboxLabel: "Soovitused",
585
+ countAnnouncement: (values, format) =>
586
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} valik`, other: () => `${format.number(Number(values?.optionCount))} valikud` })} saadaval.`,
587
+ focusAnnouncement: (values, format) =>
588
+ `${format.select({ true: () => `Sisestatud rühm ${String(values?.groupTitle ?? "")}, valikuga ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} valik`, other: () => `${format.number(Number(values?.groupCount))} valikud` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", valitud", other: () => "" }, String(values?.isSelected))}`,
589
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, valitud`,
590
+ },
591
+ "fi-FI": {
592
+ buttonLabel: "Näytä ehdotukset",
593
+ listboxLabel: "Ehdotukset",
594
+ countAnnouncement: (values, format) =>
595
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} vaihtoehto`, other: () => `${format.number(Number(values?.optionCount))} vaihtoehtoa` })} saatavilla.`,
596
+ focusAnnouncement: (values, format) =>
597
+ `${format.select({ true: () => `Siirtyi ryhmään ${String(values?.groupTitle ?? "")}, jossa ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} vaihtoehto`, other: () => `${format.number(Number(values?.groupCount))} vaihtoehtoa` })}.`, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", valittu", other: () => "" }, String(values?.isSelected))}`,
598
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, valittu`,
599
+ },
600
+ "fr-FR": {
601
+ buttonLabel: "Afficher les suggestions",
602
+ listboxLabel: "Suggestions",
603
+ countAnnouncement: (values, format) =>
604
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} option`, other: () => `${format.number(Number(values?.optionCount))} options` })} disponible(s).`,
605
+ focusAnnouncement: (values, format) =>
606
+ `${format.select({ true: () => `Groupe ${String(values?.groupTitle ?? "")} rejoint, avec ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} option`, other: () => `${format.number(Number(values?.groupCount))} options` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", sélectionné(s)", other: () => "" }, String(values?.isSelected))}`,
607
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, sélectionné`,
608
+ },
609
+ "he-IL": {
610
+ buttonLabel: "הצג הצעות",
611
+ listboxLabel: "הצעות",
612
+ countAnnouncement: (values, format) =>
613
+ `${format.plural(Number(values?.optionCount), { one: () => `אפשרות ${format.number(Number(values?.optionCount))}`, other: () => `${format.number(Number(values?.optionCount))} אפשרויות` })} במצב זמין.`,
614
+ focusAnnouncement: (values, format) =>
615
+ `${format.select({ true: () => `נכנס לקבוצה ${String(values?.groupTitle ?? "")}, עם ${format.plural(Number(values?.groupCount), { one: () => `אפשרות ${format.number(Number(values?.groupCount))}`, other: () => `${format.number(Number(values?.groupCount))} אפשרויות` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", נבחר", other: () => "" }, String(values?.isSelected))}`,
616
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, נבחר`,
617
+ },
618
+ "hr-HR": {
619
+ buttonLabel: "Prikaži prijedloge",
620
+ listboxLabel: "Prijedlozi",
621
+ countAnnouncement: (values, format) =>
622
+ `Dostupno još: ${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opcija`, other: () => `${format.number(Number(values?.optionCount))} opcije/a` })}.`,
623
+ focusAnnouncement: (values, format) =>
624
+ `${format.select({ true: () => `Unesena skupina ${String(values?.groupTitle ?? "")}, s ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opcijom`, other: () => `${format.number(Number(values?.groupCount))} opcije/a` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", odabranih", other: () => "" }, String(values?.isSelected))}`,
625
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, odabrano`,
626
+ },
627
+ "hu-HU": {
628
+ buttonLabel: "Javaslatok megjelenítése",
629
+ listboxLabel: "Javaslatok",
630
+ countAnnouncement: (values, format) =>
631
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} lehetőség`, other: () => `${format.number(Number(values?.optionCount))} lehetőség` })} áll rendelkezésre.`,
632
+ focusAnnouncement: (values, format) =>
633
+ `${format.select({ true: () => `Belépett a(z) ${String(values?.groupTitle ?? "")} csoportba, amely ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} lehetőséget`, other: () => `${format.number(Number(values?.groupCount))} lehetőséget` })} tartalmaz. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", kijelölve", other: () => "" }, String(values?.isSelected))}`,
634
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, kijelölve`,
635
+ },
636
+ "it-IT": {
637
+ buttonLabel: "Mostra suggerimenti",
638
+ listboxLabel: "Suggerimenti",
639
+ countAnnouncement: (values, format) =>
640
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opzione disponibile`, other: () => `${format.number(Number(values?.optionCount))} opzioni disponibili` })}.`,
641
+ focusAnnouncement: (values, format) =>
642
+ `${format.select({ true: () => `Ingresso nel gruppo ${String(values?.groupTitle ?? "")}, con ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opzione`, other: () => `${format.number(Number(values?.groupCount))} opzioni` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", selezionato", other: () => "" }, String(values?.isSelected))}`,
643
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, selezionato`,
644
+ },
645
+ "ja-JP": {
646
+ buttonLabel: "候補を表示",
647
+ listboxLabel: "候補",
648
+ countAnnouncement: (values, format) =>
649
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} 個のオプション`, other: () => `${format.number(Number(values?.optionCount))} 個のオプション` })}を利用できます。`,
650
+ focusAnnouncement: (values, format) =>
651
+ `${format.select({ true: () => `入力されたグループ ${String(values?.groupTitle ?? "")}、${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} 個のオプション`, other: () => `${format.number(Number(values?.groupCount))} 個のオプション` })}を含む。`, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => "、選択済み", other: () => "" }, String(values?.isSelected))}`,
652
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}、選択済み`,
653
+ },
654
+ "ko-KR": {
655
+ buttonLabel: "제안 사항 표시",
656
+ listboxLabel: "제안",
657
+ countAnnouncement: (values, format) =>
658
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))}개 옵션`, other: () => `${format.number(Number(values?.optionCount))}개 옵션` })}을 사용할 수 있습니다.`,
659
+ focusAnnouncement: (values, format) =>
660
+ `${format.select({ true: () => `입력한 그룹 ${String(values?.groupTitle ?? "")}, ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))}개 옵션`, other: () => `${format.number(Number(values?.groupCount))}개 옵션` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", 선택됨", other: () => "" }, String(values?.isSelected))}`,
661
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, 선택됨`,
662
+ },
663
+ "lt-LT": {
664
+ buttonLabel: "Rodyti pasiūlymus",
665
+ listboxLabel: "Pasiūlymai",
666
+ countAnnouncement: (values, format) =>
667
+ `Yra ${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} parinktis`, other: () => `${format.number(Number(values?.optionCount))} parinktys (-ių)` })}.`,
668
+ focusAnnouncement: (values, format) =>
669
+ `${format.select({ true: () => `Įvesta grupė ${String(values?.groupTitle ?? "")}, su ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} parinktimi`, other: () => `${format.number(Number(values?.groupCount))} parinktimis (-ių)` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", pasirinkta", other: () => "" }, String(values?.isSelected))}`,
670
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, pasirinkta`,
671
+ },
672
+ "lv-LV": {
673
+ buttonLabel: "Rādīt ieteikumus",
674
+ listboxLabel: "Ieteikumi",
675
+ countAnnouncement: (values, format) =>
676
+ `Pieejamo opciju skaits: ${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opcija`, other: () => `${format.number(Number(values?.optionCount))} opcijas` })}.`,
677
+ focusAnnouncement: (values, format) =>
678
+ `${format.select({ true: () => `Ievadīta grupa ${String(values?.groupTitle ?? "")}, ar ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opciju`, other: () => `${format.number(Number(values?.groupCount))} opcijām` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", atlasīta", other: () => "" }, String(values?.isSelected))}`,
679
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, atlasīta`,
680
+ },
681
+ "nb-NO": {
682
+ buttonLabel: "Vis forslag",
683
+ listboxLabel: "Forslag",
684
+ countAnnouncement: (values, format) =>
685
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} alternativ`, other: () => `${format.number(Number(values?.optionCount))} alternativer` })} finnes.`,
686
+ focusAnnouncement: (values, format) =>
687
+ `${format.select({ true: () => `Angitt gruppe ${String(values?.groupTitle ?? "")}, med ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} alternativ`, other: () => `${format.number(Number(values?.groupCount))} alternativer` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", valgt", other: () => "" }, String(values?.isSelected))}`,
688
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, valgt`,
689
+ },
690
+ "nl-NL": {
691
+ buttonLabel: "Suggesties weergeven",
692
+ listboxLabel: "Suggesties",
693
+ countAnnouncement: (values, format) =>
694
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} optie`, other: () => `${format.number(Number(values?.optionCount))} opties` })} beschikbaar.`,
695
+ focusAnnouncement: (values, format) =>
696
+ `${format.select({ true: () => `Groep ${String(values?.groupTitle ?? "")} ingevoerd met ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} optie`, other: () => `${format.number(Number(values?.groupCount))} opties` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", geselecteerd", other: () => "" }, String(values?.isSelected))}`,
697
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, geselecteerd`,
698
+ },
699
+ "pl-PL": {
700
+ buttonLabel: "Wyświetlaj sugestie",
701
+ listboxLabel: "Sugestie",
702
+ countAnnouncement: (values, format) =>
703
+ `dostępna/dostępne(-nych) ${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opcja`, other: () => `${format.number(Number(values?.optionCount))} opcje(-i)` })}.`,
704
+ focusAnnouncement: (values, format) =>
705
+ `${format.select({ true: () => `Dołączono do grupy ${String(values?.groupTitle ?? "")}, z ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opcją`, other: () => `${format.number(Number(values?.groupCount))} opcjami` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", wybrano", other: () => "" }, String(values?.isSelected))}`,
706
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, wybrano`,
707
+ },
708
+ "pt-BR": {
709
+ buttonLabel: "Mostrar sugestões",
710
+ listboxLabel: "Sugestões",
711
+ countAnnouncement: (values, format) =>
712
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opção`, other: () => `${format.number(Number(values?.optionCount))} opções` })} disponível.`,
713
+ focusAnnouncement: (values, format) =>
714
+ `${format.select({ true: () => `Grupo inserido ${String(values?.groupTitle ?? "")}, com ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opção`, other: () => `${format.number(Number(values?.groupCount))} opções` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", selecionado", other: () => "" }, String(values?.isSelected))}`,
715
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, selecionado`,
716
+ },
717
+ "pt-PT": {
718
+ buttonLabel: "Apresentar sugestões",
719
+ listboxLabel: "Sugestões",
720
+ countAnnouncement: (values, format) =>
721
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opção`, other: () => `${format.number(Number(values?.optionCount))} opções` })} disponível.`,
722
+ focusAnnouncement: (values, format) =>
723
+ `${format.select({ true: () => `Grupo introduzido ${String(values?.groupTitle ?? "")}, com ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opção`, other: () => `${format.number(Number(values?.groupCount))} opções` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", selecionado", other: () => "" }, String(values?.isSelected))}`,
724
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, selecionado`,
725
+ },
726
+ "ro-RO": {
727
+ buttonLabel: "Afișare sugestii",
728
+ listboxLabel: "Sugestii",
729
+ countAnnouncement: (values, format) =>
730
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opțiune`, other: () => `${format.number(Number(values?.optionCount))} opțiuni` })} disponibile.`,
731
+ focusAnnouncement: (values, format) =>
732
+ `${format.select({ true: () => `Grup ${String(values?.groupTitle ?? "")} introdus, cu ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opțiune`, other: () => `${format.number(Number(values?.groupCount))} opțiuni` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", selectat", other: () => "" }, String(values?.isSelected))}`,
733
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, selectat`,
734
+ },
735
+ "ru-RU": {
736
+ buttonLabel: "Показать предложения",
737
+ listboxLabel: "Предложения",
738
+ countAnnouncement: (values, format) =>
739
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} параметр`, other: () => `${format.number(Number(values?.optionCount))} параметров` })} доступно.`,
740
+ focusAnnouncement: (values, format) =>
741
+ `${format.select({ true: () => `Введенная группа ${String(values?.groupTitle ?? "")}, с ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} параметром`, other: () => `${format.number(Number(values?.groupCount))} параметрами` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", выбранными", other: () => "" }, String(values?.isSelected))}`,
742
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, выбрано`,
743
+ },
744
+ "sk-SK": {
745
+ buttonLabel: "Zobraziť návrhy",
746
+ listboxLabel: "Návrhy",
747
+ countAnnouncement: (values, format) =>
748
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} možnosť`, other: () => `${format.number(Number(values?.optionCount))} možnosti/-í` })} k dispozícii.`,
749
+ focusAnnouncement: (values, format) =>
750
+ `${format.select({ true: () => `Zadaná skupina ${String(values?.groupTitle ?? "")}, s ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} možnosťou`, other: () => `${format.number(Number(values?.groupCount))} možnosťami` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", vybraté", other: () => "" }, String(values?.isSelected))}`,
751
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, vybraté`,
752
+ },
753
+ "sl-SI": {
754
+ buttonLabel: "Prikaži predloge",
755
+ listboxLabel: "Predlogi",
756
+ countAnnouncement: (values, format) =>
757
+ `Na voljo je ${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opcija`, other: () => `${format.number(Number(values?.optionCount))} opcije` })}.`,
758
+ focusAnnouncement: (values, format) =>
759
+ `${format.select({ true: () => `Vnesena skupina ${String(values?.groupTitle ?? "")}, z ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opcija`, other: () => `${format.number(Number(values?.groupCount))} opcije` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", izbrano", other: () => "" }, String(values?.isSelected))}`,
760
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, izbrano`,
761
+ },
762
+ "sr-SP": {
763
+ buttonLabel: "Prikaži predloge",
764
+ listboxLabel: "Predlozi",
765
+ countAnnouncement: (values, format) =>
766
+ `Dostupno još: ${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} opcija`, other: () => `${format.number(Number(values?.optionCount))} opcije/a` })}.`,
767
+ focusAnnouncement: (values, format) =>
768
+ `${format.select({ true: () => `Unesena grupa ${String(values?.groupTitle ?? "")}, s ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} opcijom`, other: () => `${format.number(Number(values?.groupCount))} optione/a` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", izabranih", other: () => "" }, String(values?.isSelected))}`,
769
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, izabrano`,
770
+ },
771
+ "sv-SE": {
772
+ buttonLabel: "Visa förslag",
773
+ listboxLabel: "Förslag",
774
+ countAnnouncement: (values, format) =>
775
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} alternativ`, other: () => `${format.number(Number(values?.optionCount))} alternativ` })} tillgängliga.`,
776
+ focusAnnouncement: (values, format) =>
777
+ `${format.select({ true: () => `Ingick i gruppen ${String(values?.groupTitle ?? "")} med ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} alternativ`, other: () => `${format.number(Number(values?.groupCount))} alternativ` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", valda", other: () => "" }, String(values?.isSelected))}`,
778
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, valda`,
779
+ },
780
+ "tr-TR": {
781
+ buttonLabel: "Önerileri göster",
782
+ listboxLabel: "Öneriler",
783
+ countAnnouncement: (values, format) =>
784
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} seçenek`, other: () => `${format.number(Number(values?.optionCount))} seçenekler` })} kullanılabilir.`,
785
+ focusAnnouncement: (values, format) =>
786
+ `${format.select({ true: () => `Girilen grup ${String(values?.groupTitle ?? "")}, ile ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} seçenek`, other: () => `${format.number(Number(values?.groupCount))} seçenekler` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", seçildi", other: () => "" }, String(values?.isSelected))}`,
787
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, seçildi`,
788
+ },
789
+ "uk-UA": {
790
+ buttonLabel: "Показати пропозиції",
791
+ listboxLabel: "Пропозиції",
792
+ countAnnouncement: (values, format) =>
793
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} параметр`, other: () => `${format.number(Number(values?.optionCount))} параметри(-ів)` })} доступно.`,
794
+ focusAnnouncement: (values, format) =>
795
+ `${format.select({ true: () => `Введена група ${String(values?.groupTitle ?? "")}, з ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} параметр`, other: () => `${format.number(Number(values?.groupCount))} параметри(-ів)` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", вибрано", other: () => "" }, String(values?.isSelected))}`,
796
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, вибрано`,
797
+ },
798
+ "zh-CN": {
799
+ buttonLabel: "显示建议",
800
+ listboxLabel: "建议",
801
+ countAnnouncement: (values, format) =>
802
+ `有 ${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} 个选项`, other: () => `${format.number(Number(values?.optionCount))} 个选项` })}可用。`,
803
+ focusAnnouncement: (values, format) =>
804
+ `${format.select({ true: () => `进入了 ${String(values?.groupTitle ?? "")} 组,其中有 ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} 个选项`, other: () => `${format.number(Number(values?.groupCount))} 个选项` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", 已选择", other: () => "" }, String(values?.isSelected))}`,
805
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, 已选择`,
806
+ },
807
+ "zh-TW": {
808
+ buttonLabel: "顯示建議",
809
+ listboxLabel: "建議",
810
+ countAnnouncement: (values, format) =>
811
+ `${format.plural(Number(values?.optionCount), { one: () => `${format.number(Number(values?.optionCount))} 選項`, other: () => `${format.number(Number(values?.optionCount))} 選項` })} 可用。`,
812
+ focusAnnouncement: (values, format) =>
813
+ `${format.select({ true: () => `輸入的群組 ${String(values?.groupTitle ?? "")}, 有 ${format.plural(Number(values?.groupCount), { one: () => `${format.number(Number(values?.groupCount))} 選項`, other: () => `${format.number(Number(values?.groupCount))} 選項` })}. `, other: () => "" }, String(values?.isGroupChange))}${String(values?.optionText ?? "")}${format.select({ true: () => ", 已選取", other: () => "" }, String(values?.isSelected))}`,
814
+ selectedAnnouncement: (values) => `${String(values?.optionText ?? "")}, 已選取`,
815
+ },
816
+ });
817
+
818
+ export interface ComboBoxOptions extends FieldOptions {
819
+ inputRef: ElementRef<HTMLInputElement>;
820
+ listBoxRef: ElementRef;
821
+ popoverRef?: ElementRef;
822
+ buttonRef?: ElementRef;
823
+ isDisabled?: MaybeAccessor<boolean | undefined>;
824
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
825
+ isRequired?: MaybeAccessor<boolean | undefined>;
826
+ shouldFocusWrap?: MaybeAccessor<boolean | undefined>;
827
+ name?: MaybeAccessor<string | undefined>;
828
+ form?: MaybeAccessor<string | undefined>;
829
+ /**
830
+ * What the field's own `name` submits. With "key" the field carries no
831
+ * `name`, and the caller renders a hidden input holding the key; the name
832
+ * still matches the form's server errors to this field.
833
+ *
834
+ * @default "text"
835
+ */
836
+ formValue?: MaybeAccessor<"key" | "text" | undefined>;
837
+ placeholder?: MaybeAccessor<string | undefined>;
838
+ keyboardDelegate?: KeyboardDelegate;
839
+ /** What the page thinks of the choice, checked as it changes. */
840
+ validate?: ValidateFunction<Key | null>;
841
+ /** @default "aria" */
842
+ validationBehavior?: MaybeAccessor<ValidationBehavior | undefined>;
843
+ }
844
+
845
+ export interface ComboBoxResult {
846
+ labelProps: DOMProps;
847
+ inputProps: DOMProps;
848
+ /** Options for {@link button}, not props for an element. */
849
+ buttonProps: DOMProps;
850
+ listBoxProps: DOMProps;
851
+ descriptionProps: DOMProps;
852
+ errorMessageProps: DOMProps;
853
+ /** The base every option id is derived from, shared with the listbox. */
854
+ baseId: Accessor<string>;
855
+ /** What is wrong with the choice, and whether the user is being told. */
856
+ validation: FormValidationState;
857
+ errors: Accessor<string[]>;
858
+ isInvalid: Accessor<boolean>;
859
+ }
860
+
861
+ export function comboBox(options: ComboBoxOptions, state: ComboBoxState<unknown>): ComboBoxResult {
862
+ const baseId = id();
863
+ const listBoxId = id();
864
+
865
+ const {
866
+ state: validation,
867
+ behavior,
868
+ isInvalid,
869
+ errors,
870
+ errorMessage,
871
+ } = fieldValidation<Key | null>({
872
+ value: state.selectedKey,
873
+ validate: options.validate,
874
+ validationBehavior: options.validationBehavior,
875
+ isInvalid: options.isInvalid,
876
+ errorMessage: options.errorMessage,
877
+ name: options.name,
878
+ });
879
+
880
+ const { labelProps, fieldProps, descriptionProps, errorMessageProps } = field({
881
+ ...options,
882
+ isInvalid,
883
+ errorMessage,
884
+ });
885
+
886
+ const delegate =
887
+ options.keyboardDelegate ??
888
+ new ListKeyboardDelegate({
889
+ collection: state.collection,
890
+ ref: options.listBoxRef,
891
+ disabledKeys: state.disabledKeys,
892
+ });
893
+
894
+ // The arrows drive the LIST while the caret stays in the input, so the
895
+ // collection's key handling is bound to the input rather than to the list.
896
+ const { collectionProps } = selectableCollection({
897
+ ref: options.inputRef,
898
+ selectionManager: state.selectionManager,
899
+ keyboardDelegate: delegate,
900
+ shouldUseVirtualFocus: true,
901
+ disallowTypeAhead: true,
902
+ disallowEmptySelection: true,
903
+ shouldFocusWrap: options.shouldFocusWrap,
904
+ });
905
+
906
+ const focusedItem = (): Node<unknown> | null => {
907
+ if (!state.isOpen()) return null;
908
+ const key = state.selectionManager().focusedKey;
909
+ return key === null ? null : state.collection().getItem(key);
910
+ };
911
+
912
+ const onKeyDown = (event: KeyboardEvent): void => {
913
+ if (access(options.isReadOnly) === true) return;
914
+
915
+ switch (event.key) {
916
+ case "Enter": {
917
+ // Only swallow it while the list is open: a closed combo box inside a
918
+ // form must still submit on Enter.
919
+ if (state.isOpen()) event.preventDefault();
920
+ state.commit();
921
+ return;
922
+ }
923
+ case "Tab": {
924
+ if (state.isOpen()) state.commit();
925
+ return;
926
+ }
927
+ case "Escape": {
928
+ state.revert();
929
+ return;
930
+ }
931
+ case "ArrowDown": {
932
+ if (!state.isOpen()) {
933
+ event.preventDefault();
934
+ state.open("first", "manual");
935
+ }
936
+ return;
937
+ }
938
+ case "ArrowUp": {
939
+ if (!state.isOpen()) {
940
+ event.preventDefault();
941
+ state.open("last", "manual");
942
+ }
943
+ return;
944
+ }
945
+ // The caret is the point of these: moving it un-highlights, so the next
946
+ // Down starts from the top rather than from where the user left off.
947
+ case "ArrowLeft":
948
+ case "ArrowRight": {
949
+ state.selectionManager().setFocusedKey(null);
950
+ return;
951
+ }
952
+ default:
953
+ return;
954
+ }
955
+ };
956
+
957
+ const message = stringFormatter(comboBoxStrings);
958
+
959
+ // What a screen reader is told that it cannot see for itself. The input
960
+ // keeps focus throughout, so moving through the list, the list changing
961
+ // under the typing and a choice being made are all silent otherwise.
962
+ if (!isServer) {
963
+ let first = true;
964
+ let lastOpen = false;
965
+ let lastCount = 0;
966
+ createEffect(
967
+ () =>
968
+ [
969
+ state.isOpen(),
970
+ getItemCount(state.collection()),
971
+ state.selectionManager().focusedKey,
972
+ message(),
973
+ ] as const,
974
+ ([isOpen, count, focusedKey, format]) => {
975
+ // Only when the list opens with nothing highlighted: a highlighted
976
+ // option is read as "1 of 6" already. VoiceOver reads no such count.
977
+ const opened = isOpen && !lastOpen && (focusedKey === null || isAppleDevice());
978
+ if (!first && isOpen && (opened || count !== lastCount)) {
979
+ announce(format.format("countAnnouncement", { optionCount: count }));
980
+ }
981
+ first = false;
982
+ lastOpen = isOpen;
983
+ lastCount = count;
984
+ },
985
+ );
986
+
987
+ // VoiceOver reads each option on its own, but says nothing on entering a
988
+ // section, so the section is named the moment the highlight crosses into
989
+ // one.
990
+ let lastSection: Key | null = null;
991
+ let lastItem: Key | null = null;
992
+ createEffect(
993
+ () => {
994
+ const item = focusedItem();
995
+ const sectionKey = item?.parentKey ?? null;
996
+ return [
997
+ item,
998
+ sectionKey === null ? null : state.collection().getItem(sectionKey),
999
+ item === null ? false : state.selectionManager().isSelected(item.key),
1000
+ message(),
1001
+ ] as const;
1002
+ },
1003
+ ([item, section, isSelected, format]) => {
1004
+ const itemKey = item?.key ?? null;
1005
+ const sectionKey = section?.key ?? null;
1006
+ if (isAppleDevice() && item !== null && itemKey !== lastItem) {
1007
+ if (section !== null && sectionKey !== lastSection) {
1008
+ announce(
1009
+ format.format("focusAnnouncement", {
1010
+ isGroupChange: true,
1011
+ groupTitle: section["aria-label"] ?? section.textValue,
1012
+ groupCount: section.childNodes.filter((child) => child.type === "item").length,
1013
+ optionText: item["aria-label"] ?? item.textValue,
1014
+ isSelected,
1015
+ }),
1016
+ );
1017
+ }
1018
+ }
1019
+ lastSection = sectionKey;
1020
+ lastItem = itemKey;
1021
+ },
1022
+ );
1023
+
1024
+ // Other screen readers announce a selection themselves; VoiceOver does not.
1025
+ let lastSelected: Key | null = untrack(state.selectedKey);
1026
+ createEffect(
1027
+ () => [state.selectedKey(), state.selectedItem(), state.isFocused(), message()] as const,
1028
+ ([key, item, focused, format]) => {
1029
+ if (isAppleDevice() && focused && item !== null && key !== lastSelected) {
1030
+ announce(
1031
+ format.format("selectedAnnouncement", {
1032
+ optionText: item["aria-label"] ?? item.textValue,
1033
+ }),
1034
+ );
1035
+ }
1036
+ lastSelected = key;
1037
+ },
1038
+ );
1039
+ }
1040
+
1041
+ // While the list is open, nothing but the field and the list is there for a
1042
+ // screen reader: its virtual cursor would otherwise walk off the field into
1043
+ // the page with the list still open over it.
1044
+ followOpen(
1045
+ () =>
1046
+ state.isOpen()
1047
+ ? ([
1048
+ access(options.inputRef) as Element | null,
1049
+ access(options.popoverRef ?? options.listBoxRef) as Element | null,
1050
+ ] as const)
1051
+ : null,
1052
+ (targets) => {
1053
+ if (targets === null) return undefined;
1054
+ const present = targets.filter((target): target is Element => target !== null);
1055
+ return present.length === 0 ? undefined : ariaHideOutside(present);
1056
+ },
1057
+ );
1058
+
1059
+ // A form reset puts the selection back to where it started, and the text
1060
+ // with it: the browser resets only the text, which then names one option
1061
+ // while the selection is another.
1062
+ const initialKey = untrack(state.selectedKey);
1063
+ formReset(options.inputRef, initialKey, (key) => state.setSelectedKey(key));
1064
+
1065
+ const onInput = (event: Event): void => {
1066
+ const input = event.target as HTMLInputElement;
1067
+ state.setInputValue(input.value);
1068
+ // The field has already changed itself; a controlled owner that declined
1069
+ // re-renders nothing, so the DOM has to be put back by hand.
1070
+ if (input.value !== state.inputValue()) input.value = state.inputValue();
1071
+ };
1072
+
1073
+ return {
1074
+ baseId,
1075
+ descriptionProps,
1076
+ errorMessageProps,
1077
+ validation,
1078
+ errors,
1079
+ isInvalid,
1080
+ labelProps: mergeProps(labelProps, {
1081
+ onClick: () => {
1082
+ if (access(options.isDisabled) === true) return;
1083
+ (access(options.inputRef) as HTMLInputElement | null)?.focus();
1084
+ },
1085
+ }),
1086
+ inputProps: mergeProps(
1087
+ filterDOMProps(options, { labelable: true }),
1088
+ fieldProps,
1089
+ // Only while the list is open: the arrows belong to the caret otherwise.
1090
+ {
1091
+ onKeyDown: (event: KeyboardEvent) => {
1092
+ if (state.isOpen()) (collectionProps.onKeyDown as (e: KeyboardEvent) => void)?.(event);
1093
+ },
1094
+ },
1095
+ { onKeyDown },
1096
+ {
1097
+ role: "combobox",
1098
+ type: "text",
1099
+ value: state.inputValue,
1100
+ disabled: () => access(options.isDisabled) === true,
1101
+ readOnly: () => access(options.isReadOnly) === true,
1102
+ // Only native validation blocks the submit; under "aria" the page decides.
1103
+ required: () => behavior() === "native" && access(options.isRequired) === true,
1104
+ name: () => (access(options.formValue) === "key" ? undefined : access(options.name)),
1105
+ form: () => access(options.form),
1106
+ placeholder: () => access(options.placeholder),
1107
+ "aria-expanded": () => state.isOpen(),
1108
+ "aria-controls": () => (state.isOpen() ? listBoxId() : undefined),
1109
+ "aria-autocomplete": "list",
1110
+ "aria-invalid": () => isInvalid() || undefined,
1111
+ "aria-required": () => access(options.isRequired) === true || undefined,
1112
+ // Virtual focus: the input keeps DOM focus and NAMES the highlighted
1113
+ // option, so the caret never moves and the highlight still travels.
1114
+ "aria-activedescendant": () => {
1115
+ const item = focusedItem();
1116
+ return item === null ? undefined : optionIdFor(baseId(), item.key);
1117
+ },
1118
+ // The combo box has its own suggestions; the browser's would cover
1119
+ // them, and iOS autocorrect would rewrite the query as it is typed.
1120
+ autocomplete: "off",
1121
+ autocorrect: "off",
1122
+ spellcheck: "false",
1123
+ onInput,
1124
+ onFocus: () => state.setFocused(true),
1125
+ onBlur: (event: FocusEvent) => {
1126
+ // Focus moving to the toggle button or into the popover is still
1127
+ // focus on the combo box.
1128
+ const related = event.relatedTarget as Element | null;
1129
+ if (related !== null) {
1130
+ const toggle = access(options.buttonRef ?? options.inputRef) as Element | null;
1131
+ const popover = access(options.popoverRef ?? options.listBoxRef) as Element | null;
1132
+ if (toggle?.contains(related) === true || popover?.contains(related) === true) return;
1133
+ }
1134
+ state.setFocused(false);
1135
+ validation.commitValidation();
1136
+ },
1137
+ },
1138
+ ),
1139
+ buttonProps: {
1140
+ id: () => `${baseId()}-button`,
1141
+ // The input is the control; the button is a shortcut to the same list,
1142
+ // and a second Tab stop for it would be a stop that does nothing new.
1143
+ excludeFromTabOrder: true,
1144
+ preventFocusOnPress: true,
1145
+ isDisabled: () => access(options.isDisabled) === true || access(options.isReadOnly) === true,
1146
+ "aria-haspopup": true,
1147
+ "aria-expanded": () => state.isOpen(),
1148
+ "aria-controls": () => (state.isOpen() ? listBoxId() : undefined),
1149
+ "aria-labelledby": () =>
1150
+ [
1151
+ access(fieldProps["aria-labelledby"] as MaybeAccessor<string | undefined>),
1152
+ `${baseId()}-button`,
1153
+ ]
1154
+ .filter(Boolean)
1155
+ .join(" "),
1156
+ "aria-label": () => message().format("buttonLabel"),
1157
+ onPressStart: (event: { pointerType: string }) => {
1158
+ if (event.pointerType === "touch") return;
1159
+ (access(options.inputRef) as HTMLInputElement | null)?.focus();
1160
+ state.toggle(
1161
+ event.pointerType === "keyboard" || event.pointerType === "virtual" ? "first" : null,
1162
+ "manual",
1163
+ );
1164
+ },
1165
+ onPress: (event: { pointerType: string }) => {
1166
+ if (event.pointerType !== "touch") return;
1167
+ (access(options.inputRef) as HTMLInputElement | null)?.focus();
1168
+ state.toggle(null, "manual");
1169
+ },
1170
+ },
1171
+ listBoxProps: {
1172
+ id: listBoxId,
1173
+ baseId,
1174
+ "aria-labelledby": fieldProps["aria-labelledby"],
1175
+ autoFocus: () => state.focusStrategy() ?? true,
1176
+ shouldUseVirtualFocus: true,
1177
+ shouldSelectOnPressUp: true,
1178
+ disallowEmptySelection: true,
1179
+ linkBehavior: "selection",
1180
+ },
1181
+ };
1182
+ }
1183
+
1184
+ // ---------------------------------------------------------------------------
1185
+ // Components
1186
+ // ---------------------------------------------------------------------------
1187
+
1188
+ interface ComboBoxContextValue {
1189
+ state: ComboBoxState<unknown>;
1190
+ }
1191
+
1192
+ const ComboBoxContext = createContext<ComboBoxContextValue | null>(null);
1193
+
1194
+ export function useComboBox(): ComboBoxContextValue {
1195
+ const value = getContext(ComboBoxContext);
1196
+ if (value === null || value === undefined) {
1197
+ throw new Error("This must be rendered inside a ComboBox.");
1198
+ }
1199
+ return value;
1200
+ }
1201
+
1202
+ export interface ComboBoxComponentProps<T> extends StyleProps, ItemAccessors<T> {
1203
+ /** Everything that can be chosen, before the typed text narrows it. */
1204
+ items: Iterable<T>;
1205
+ /** How one value renders. Return an `<Option>`. */
1206
+ children: (item: T) => Child;
1207
+ label?: Child;
1208
+ description?: Child;
1209
+ errorMessage?: Child;
1210
+ placeholder?: string;
1211
+ selectedKey?: Key | null;
1212
+ defaultSelectedKey?: Key | null;
1213
+ inputValue?: string;
1214
+ defaultInputValue?: string;
1215
+ disabledKeys?: Iterable<Key>;
1216
+ /** @default a locale-aware `contains` */
1217
+ filterBy?: FilterFn;
1218
+ allowsCustomValue?: boolean;
1219
+ allowsEmptyCollection?: boolean;
1220
+ shouldFocusWrap?: boolean;
1221
+ /** @default "input" */
1222
+ menuTrigger?: "input" | "focus" | "manual";
1223
+ isDisabled?: boolean;
1224
+ isReadOnly?: boolean;
1225
+ isRequired?: boolean;
1226
+ isInvalid?: boolean;
1227
+ /** What the page thinks of the choice, checked as it changes. */
1228
+ validate?: ValidateFunction<Key | null>;
1229
+ /** @default "aria" */
1230
+ validationBehavior?: ValidationBehavior;
1231
+ name?: string;
1232
+ form?: string;
1233
+ /**
1234
+ * What `name` submits: the chosen option's key, or the text in the field.
1235
+ * With `allowsCustomValue` the text is the value, and it is always the text.
1236
+ *
1237
+ * @default "key"
1238
+ */
1239
+ formValue?: "key" | "text";
1240
+ /** @default "bottom start" */
1241
+ placement?: Placement;
1242
+ "aria-label"?: string;
1243
+ "aria-labelledby"?: string;
1244
+ ref?: RefTarget<HTMLInputElement>;
1245
+ onSelectionChange?: (key: Key | null) => void;
1246
+ onInputChange?: (value: string) => void;
1247
+ onOpenChange?: (isOpen: boolean) => void;
1248
+ }
1249
+
1250
+ /**
1251
+ * ```tsx
1252
+ * <ComboBox label="Fruit" items={fruits()} onSelectionChange={(key) => picked.set(key)}>
1253
+ * {(fruit) => <Option>{fruit.name}</Option>}
1254
+ * </ComboBox>
1255
+ * ```
1256
+ */
1257
+ export function ComboBox<T>(props: ComboBoxComponentProps<T>) {
1258
+ const inputRef = makeRef<HTMLInputElement>();
1259
+ const listRef = makeRef<HTMLUListElement>();
1260
+ const buttonRef = makeRef<HTMLButtonElement>();
1261
+ const popoverRef = makeRef<HTMLDivElement>();
1262
+ const options = fromProps(cells(props) as unknown as Incoming<Record<string, unknown>>);
1263
+ const submitsText = (): boolean => props.allowsCustomValue === true || props.formValue === "text";
1264
+
1265
+ const state = comboBoxState<T>({
1266
+ ...(options as ComboBoxStateOptions<T>),
1267
+ filterBy: callback<[string, string], boolean>(cells(props).filterBy),
1268
+ onSelectionChange: (key) => props.onSelectionChange?.(key),
1269
+ onInputChange: (value) => props.onInputChange?.(value),
1270
+ onOpenChange: (isOpen) => props.onOpenChange?.(isOpen),
1271
+ });
1272
+
1273
+ const {
1274
+ labelProps,
1275
+ inputProps,
1276
+ buttonProps: buttonOptions,
1277
+ listBoxProps,
1278
+ descriptionProps,
1279
+ errorMessageProps,
1280
+ errors,
1281
+ isInvalid,
1282
+ } = comboBox(
1283
+ {
1284
+ ...(options as unknown as ComboBoxOptions),
1285
+ inputRef,
1286
+ listBoxRef: listRef,
1287
+ buttonRef,
1288
+ popoverRef,
1289
+ formValue: () => (submitsText() ? "text" : "key"),
1290
+ validate: callback(cells(props).validate),
1291
+ validationBehavior: () => props.validationBehavior,
1292
+ },
1293
+ state,
1294
+ );
1295
+
1296
+ const { buttonProps } = button(buttonOptions, buttonRef);
1297
+ const { hoverProps, isHovered } = hover({ isDisabled: () => props.isDisabled });
1298
+ const { focusProps, isFocusVisible } = focusRing();
1299
+
1300
+ const inputElementProps = mergeProps(
1301
+ inputProps,
1302
+ focusProps,
1303
+ filterDOMProps(options, { global: true }),
1304
+ styleProps(cells(props)),
1305
+ {
1306
+ "data-focus-visible": isFocusVisible,
1307
+ "data-open": state.isOpen,
1308
+ "data-disabled": () => props.isDisabled === true,
1309
+ "data-invalid": isInvalid,
1310
+ "data-testid": () => props["data-testid"],
1311
+ },
1312
+ );
1313
+
1314
+ const buttonElementProps = mergeProps(buttonProps, hoverProps, {
1315
+ // The button names itself with "Show suggestions" AND the field's label,
1316
+ // so the id it points at has to be on the element.
1317
+ id: buttonOptions.id,
1318
+ "data-hovered": isHovered,
1319
+ "data-open": state.isOpen,
1320
+ });
1321
+
1322
+ const renderOption = props.children;
1323
+
1324
+ const owner = getOwner();
1325
+ if (owner !== null) {
1326
+ install(owner, ComboBoxContext, () => ({
1327
+ state: state as unknown as ComboBoxState<unknown>,
1328
+ }));
1329
+ }
1330
+
1331
+ return (
1332
+ <>
1333
+ <span {...labelProps}>{props.label}</span>
1334
+ <input {...inputElementProps} ref={mergeRefs(inputRef.set, props.ref)} />
1335
+ <Show when={props.name !== undefined && !submitsText()}>
1336
+ <input
1337
+ type="hidden"
1338
+ name={props.name}
1339
+ form={props.form}
1340
+ value={String(state.selectedKey() ?? "")}
1341
+ />
1342
+ </Show>
1343
+ <button {...buttonElementProps} type="button" ref={buttonRef.set}>
1344
+ <span aria-hidden="true">▾</span>
1345
+ </button>
1346
+ <Popover
1347
+ triggerRef={inputRef}
1348
+ isOpen={state.isOpen()}
1349
+ onOpenChange={state.setOpen}
1350
+ placement={props.placement ?? "bottom start"}
1351
+ isDismissable
1352
+ ref={popoverRef.set}
1353
+ >
1354
+ <ComboBoxList
1355
+ options={listBoxProps}
1356
+ state={state}
1357
+ listRef={listRef}
1358
+ render={renderOption as unknown as (item: unknown) => Child}
1359
+ />
1360
+ </Popover>
1361
+ <span {...descriptionProps}>{props.description}</span>
1362
+ <span {...errorMessageProps}>
1363
+ {() => {
1364
+ const given = props.errorMessage;
1365
+ if (given !== undefined && given !== null && given !== "") return given;
1366
+ const found = errors();
1367
+ return found.length === 0 ? null : found.join(" ");
1368
+ }}
1369
+ </span>
1370
+ </>
1371
+ );
1372
+ }
1373
+
1374
+ interface ComboBoxListProps {
1375
+ options: DOMProps;
1376
+ state: ComboBoxState<unknown>;
1377
+ listRef: ReturnType<typeof makeRef<HTMLUListElement>>;
1378
+ render: (item: unknown) => Child;
1379
+ }
1380
+
1381
+ /**
1382
+ * The listbox inside the popover.
1383
+ *
1384
+ * Built only once the list is open, so its autofocus reads the focus strategy
1385
+ * the opening keypress set rather than the one from before it.
1386
+ */
1387
+ function ComboBoxList(props: ComboBoxListProps) {
1388
+ const state = props.state;
1389
+ const listRef = props.listRef;
1390
+ const render = props.render;
1391
+ const options = props.options;
1392
+
1393
+ const { listBoxProps, baseId } = listBox(
1394
+ { ...(options as unknown as Record<string, MaybeAccessor<never>>), ref: listRef },
1395
+ state,
1396
+ );
1397
+
1398
+ const elementProps = mergeProps(listBoxProps, {
1399
+ id: options.id,
1400
+ "aria-labelledby": options["aria-labelledby"],
1401
+ });
1402
+
1403
+ const value: ListBoxContextValue = {
1404
+ state: state,
1405
+ baseId,
1406
+ shouldSelectOnPressUp: () => true,
1407
+ shouldUseVirtualFocus: () => true,
1408
+ };
1409
+
1410
+ // A section builds its options with the same callback.
1411
+ provideItemRender(render);
1412
+
1413
+ return (
1414
+ <ListBoxProvider value={value}>
1415
+ <ul {...elementProps} ref={listRef.set}>
1416
+ <For each={() => [...state.collection()]}>
1417
+ {(node: Node<unknown>) => {
1418
+ provideItemNode(node);
1419
+ return render(node.value);
1420
+ }}
1421
+ </For>
1422
+ </ul>
1423
+ </ListBoxProvider>
1424
+ );
1425
+ }
1426
+
1427
+ export { Option };
1428
+
1429
+ // ---------------------------------------------------------------------------
1430
+ // The combobox as parts
1431
+ // ---------------------------------------------------------------------------
1432
+
1433
+ /**
1434
+ * The same widget, taken apart: a root that holds the state and an input, a
1435
+ * popup, a list and its items that each render their own element and find one
1436
+ * another through it. {@link ComboBox} above builds all of it from `items`;
1437
+ * this is for a design system that has to put its own markup between the
1438
+ * pieces.
1439
+ *
1440
+ * The decisions that are not the pattern's own:
1441
+ *
1442
+ * - **The collection is whatever rendered.** An item registers itself, whether
1443
+ * a callback built it from `items` or it was written as a child, so the two
1444
+ * forms share one keyboard model and one selection.
1445
+ * - **A value is the item itself, not a key.** `onValueChange` hands back what
1446
+ * `<ComboboxItem value>` was given. Identity is `itemToStringValue`, so two
1447
+ * objects describing the same thing are the same choice.
1448
+ * - **The text in the field is a query only once it has been typed.** A field
1449
+ * showing its value's label would otherwise open on a list filtered down to
1450
+ * the one thing already chosen.
1451
+ * - **Where the input is decides what the popup is.** An input outside it
1452
+ * keeps focus and the popup takes none; with no input outside, the popup is
1453
+ * where the keyboard goes, so it takes focus, holds it and gives it back.
1454
+ */
1455
+
1456
+ /** Whether an item survives the typed text. */
1457
+ export type ComboboxFilter<V> = (
1458
+ item: V,
1459
+ query: string,
1460
+ itemToStringLabel: (item: V) => string,
1461
+ ) => boolean;
1462
+
1463
+ /** A run of items under one heading, as `items` may hold them. */
1464
+ export interface ComboboxItemGroup<V> {
1465
+ items: readonly V[];
1466
+ }
1467
+
1468
+ export interface ComboboxRootProps<V> {
1469
+ children?: Child;
1470
+ /**
1471
+ * Everything that can be chosen, for a list written as a callback. Leave it
1472
+ * out and the `<ComboboxItem>`s written as children are the list.
1473
+ */
1474
+ items?: Iterable<V | ComboboxItemGroup<V>>;
1475
+ /** One item, or an array of them with `multiple`. */
1476
+ value?: V | readonly V[] | null;
1477
+ defaultValue?: V | readonly V[] | null;
1478
+ onValueChange?: (value: V | readonly V[] | null) => void;
1479
+ inputValue?: string;
1480
+ defaultInputValue?: string;
1481
+ onInputValueChange?: (value: string) => void;
1482
+ open?: boolean;
1483
+ defaultOpen?: boolean;
1484
+ onOpenChange?: (open: boolean) => void;
1485
+ /** Several values rather than one. The list stays open while choosing. */
1486
+ multiple?: boolean;
1487
+ disabled?: boolean;
1488
+ readOnly?: boolean;
1489
+ /** Puts the value in the enclosing form, one field per chosen item. */
1490
+ name?: string;
1491
+ form?: string;
1492
+ /** Highlight the first match as the text changes. @default false */
1493
+ autoHighlight?: boolean;
1494
+ /** @default true */
1495
+ openOnInputClick?: boolean;
1496
+ /** What an item reads as. @default its `label`, or the text it rendered */
1497
+ itemToStringLabel?: (item: V) => string;
1498
+ /** What identifies an item and is submitted for it. @default its `value` */
1499
+ itemToStringValue?: (item: V) => string;
1500
+ /** @default a locale-aware `contains` on the label; `null` keeps everything */
1501
+ filter?: ComboboxFilter<V> | null;
1502
+ }
1503
+
1504
+ type ItemRender = (item: unknown, index: number) => Child;
1505
+
1506
+ /**
1507
+ * The callback among a part's children, if that is what they are.
1508
+ *
1509
+ * Children arrive as a Block either way. One that takes the item has a
1510
+ * parameter; children that were simply written have none.
1511
+ */
1512
+ function renderCallback(children: unknown): ItemRender | null {
1513
+ if (typeof children !== "function") return null;
1514
+ if (children.length > 0) return children as ItemRender;
1515
+ if (isBlock(children)) return null;
1516
+ const inner: unknown = (children as () => unknown)();
1517
+ return typeof inner === "function" && inner.length > 0 ? (inner as ItemRender) : null;
1518
+ }
1519
+
1520
+ /** `text` with everything an id cannot hold escaped, and no two texts made the same. */
1521
+ function idSafe(text: string): string {
1522
+ return text.replace(
1523
+ /[^A-Za-z0-9-]/g,
1524
+ (character) => `_${(character.codePointAt(0) ?? 0).toString(36)}_`,
1525
+ );
1526
+ }
1527
+
1528
+ function isItemGroup(item: unknown): item is ComboboxItemGroup<unknown> {
1529
+ return (
1530
+ typeof item === "object" && item !== null && Array.isArray((item as { items?: unknown }).items)
1531
+ );
1532
+ }
1533
+
1534
+ interface ChipsValue {
1535
+ /** The chips that rendered, in order: a chip is the value at its own position. */
1536
+ registry: StaticCollection;
1537
+ count: () => number;
1538
+ focus: (index: number) => void;
1539
+ }
1540
+
1541
+ export interface ComboboxRootValue {
1542
+ isOpen: Accessor<boolean>;
1543
+ setOpen: (open: boolean) => void;
1544
+ /** Open and highlight an end of the list once it has rendered. */
1545
+ openWith: (strategy: FocusStrategy | null) => void;
1546
+ isMultiple: Accessor<boolean>;
1547
+ isDisabled: Accessor<boolean>;
1548
+ isReadOnly: Accessor<boolean>;
1549
+ /** Every chosen item: one or none of them when the combobox holds one value. */
1550
+ values: Accessor<readonly unknown[]>;
1551
+ inputValue: Accessor<string>;
1552
+ /** What narrows the list, which is not always what the field shows. */
1553
+ query: Accessor<string>;
1554
+ /** `items`, less what the query rules out. */
1555
+ filteredItems: Accessor<unknown[]>;
1556
+ matches: (item: unknown) => boolean;
1557
+ labelOf: (item: unknown) => string;
1558
+ /** The label an item has without having rendered. */
1559
+ ownLabelOf: (item: unknown) => string | undefined;
1560
+ stringValueOf: (item: unknown) => string;
1561
+ keyOf: (item: unknown) => Key;
1562
+ list: ListState<StaticEntry>;
1563
+ registry: StaticCollection;
1564
+ baseId: Accessor<string>;
1565
+ listId: Accessor<string>;
1566
+ isEmpty: Accessor<boolean>;
1567
+ /** Whether an input sits outside the popup, which makes the popup take no focus. */
1568
+ hasOuterInput: Accessor<boolean>;
1569
+ hasChips: Accessor<boolean>;
1570
+ name: Accessor<string | undefined>;
1571
+ form: Accessor<string | undefined>;
1572
+ clear: () => void;
1573
+ removeAt: (index: number) => void;
1574
+ focusInput: () => void;
1575
+ highlight: (key: Key | null) => void;
1576
+ /** What the popup is placed against when it is not told. */
1577
+ anchor: () => Element | null;
1578
+ /** Whether a press there is a press on the combobox, not outside it. */
1579
+ owns: (element: Element) => boolean;
1580
+ listRef: ReturnType<typeof makeRef<HTMLUListElement>>;
1581
+ inputRef: ReturnType<typeof makeRef<HTMLInputElement>>;
1582
+ triggerRef: ReturnType<typeof makeRef<HTMLElement>>;
1583
+ clearRef: ReturnType<typeof makeRef<HTMLElement>>;
1584
+ chipsRef: ReturnType<typeof makeRef<HTMLElement>>;
1585
+ popupRef: ReturnType<typeof makeRef<HTMLDivElement>>;
1586
+ /** The list is named after the input, which is the only named part. */
1587
+ listName: Accessor<{ label: string | undefined; labelledBy: string | undefined }>;
1588
+ attachInput: (input: {
1589
+ isInside: boolean;
1590
+ isDisabled: Accessor<boolean>;
1591
+ label: Accessor<string | undefined>;
1592
+ labelledBy: Accessor<string | undefined>;
1593
+ }) => void;
1594
+ attachChips: () => void;
1595
+ attachItem: (key: Key, item: unknown) => void;
1596
+ rememberLabel: (key: Key, text: string) => void;
1597
+ inputProps: (chips: ChipsValue | null) => DOMProps;
1598
+ }
1599
+
1600
+ const ComboboxRootContext = createContext<ComboboxRootValue | null>(null);
1601
+ const ComboboxPopupContext = createContext<boolean>(false);
1602
+ const ComboboxChipsContext = createContext<ChipsValue | null>(null);
1603
+
1604
+ /** The enclosing {@link ComboboxRoot}. */
1605
+ export function useComboboxRoot(): ComboboxRootValue {
1606
+ const value = getContext(ComboboxRootContext);
1607
+ if (value === null || value === undefined) {
1608
+ throw new Error("This must be rendered inside a ComboboxRoot.");
1609
+ }
1610
+ return value;
1611
+ }
1612
+
1613
+ /** The enclosing {@link ComboboxRoot}, or `null` outside one. */
1614
+ export function useOptionalComboboxRoot(): ComboboxRootValue | null {
1615
+ return getContext(ComboboxRootContext) ?? null;
1616
+ }
1617
+
1618
+ function createComboboxRoot<V>(props: Incoming<ComboboxRootProps<V>>): ComboboxRootValue {
1619
+ const locale = useLocale();
1620
+ const match = makeFilter({ sensitivity: "base" });
1621
+
1622
+ const inputRef = makeRef<HTMLInputElement>();
1623
+ const listRef = makeRef<HTMLUListElement>();
1624
+ const triggerRef = makeRef<HTMLElement>();
1625
+ const clearRef = makeRef<HTMLElement>();
1626
+ const chipsRef = makeRef<HTMLElement>();
1627
+ const popupRef = makeRef<HTMLDivElement>();
1628
+ const baseId = id();
1629
+ const listId = id();
1630
+
1631
+ const isMultiple = (): boolean => props.multiple?.() === true;
1632
+ const isReadOnly = (): boolean => props.readOnly?.() === true;
1633
+
1634
+ // Parts register from component bodies, which is an owned scope.
1635
+ const [outerInputs, setOuterInputs] = createSignal(0, { ownedWrite: true });
1636
+ const [chipBoxes, setChipBoxes] = createSignal(0, { ownedWrite: true });
1637
+ const [inputDisabled, setInputDisabled] = createSignal<Accessor<boolean> | null>(null, {
1638
+ ownedWrite: true,
1639
+ });
1640
+ const [named, setNamed] = createSignal<{
1641
+ label: Accessor<string | undefined>;
1642
+ labelledBy: Accessor<string | undefined>;
1643
+ } | null>(null, { ownedWrite: true });
1644
+ const hasOuterInput = (): boolean => outerInputs() > 0;
1645
+ const isDisabled = (): boolean => props.disabled?.() === true || inputDisabled()?.() === true;
1646
+
1647
+ const [raw, setRaw] = controllable<V | readonly V[] | null>(
1648
+ () => props.value?.(),
1649
+ () => props.defaultValue?.() ?? (isMultiple() ? [] : null),
1650
+ (next) => props.onValueChange?.()?.(next),
1651
+ );
1652
+
1653
+ const values = createMemo((): readonly V[] => {
1654
+ const current = raw();
1655
+ if (isMultiple()) return Array.isArray(current) ? (current as readonly V[]) : [];
1656
+ return current === null || current === undefined ? [] : [current as V];
1657
+ });
1658
+
1659
+ const ownLabelOf = (item: unknown): string | undefined => {
1660
+ const given = props.itemToStringLabel?.()?.(item as V);
1661
+ if (given !== undefined) return given;
1662
+ if (typeof item === "object" && item !== null) {
1663
+ const record = item as Record<string, unknown>;
1664
+ const text = record.label ?? record.name ?? record.title;
1665
+ if (typeof text === "string") return text;
1666
+ }
1667
+ return undefined;
1668
+ };
1669
+
1670
+ const stringValueOf = (item: unknown): string => {
1671
+ const given = props.itemToStringValue?.()?.(item as V);
1672
+ if (given !== undefined) return given;
1673
+ if (typeof item === "object" && item !== null) {
1674
+ const record = item as Record<string, unknown>;
1675
+ const own = record.value ?? record.id ?? record.key;
1676
+ if (typeof own === "string" || typeof own === "number") return String(own);
1677
+ return ownLabelOf(item) ?? "";
1678
+ }
1679
+ return String(item);
1680
+ };
1681
+
1682
+ // An option's id is derived from its key, and an id cannot hold a space:
1683
+ // "New York" as a key would make `aria-activedescendant` name two things,
1684
+ // neither of which exists. The key is internal, so it is escaped rather than
1685
+ // asking every caller for values that happen to be valid identifiers.
1686
+ const keyOf = (item: unknown): Key =>
1687
+ typeof item === "number" ? item : idSafe(typeof item === "string" ? item : stringValueOf(item));
1688
+
1689
+ // What an item rendered as, kept after it has gone: the field shows a chosen
1690
+ // item's text long after the list that held it has closed.
1691
+ const rendered = new Map<Key, string>();
1692
+ const [renderedVersion, setRenderedVersion] = createSignal(0, { ownedWrite: true });
1693
+
1694
+ const labelOf = (item: unknown): string => {
1695
+ const own = ownLabelOf(item);
1696
+ if (own !== undefined) return own;
1697
+ renderedVersion();
1698
+ return rendered.get(keyOf(item)) ?? stringValueOf(item);
1699
+ };
1700
+
1701
+ const [isOpen, setOpenState] = controllable<boolean>(
1702
+ () => props.open?.(),
1703
+ () => props.defaultOpen?.() ?? false,
1704
+ (next) => props.onOpenChange?.()?.(next),
1705
+ );
1706
+
1707
+ // `null` is "nothing typed": the field then shows what the value reads as,
1708
+ // and goes on following it if the value's label arrives late.
1709
+ const [typedText, setTypedText] = createSignal<string | null>(
1710
+ props.defaultInputValue?.() ?? null,
1711
+ );
1712
+ const [isQuery, setIsQuery] = createSignal(false);
1713
+ const restingText = (): string => {
1714
+ if (isMultiple() || !hasOuterInput()) return "";
1715
+ const [chosen] = values();
1716
+ return chosen === undefined ? "" : labelOf(chosen);
1717
+ };
1718
+ const inputValue = (): string => props.inputValue?.() ?? typedText() ?? restingText();
1719
+
1720
+ const writeInput = (next: string | null): void => {
1721
+ const before = untrack(inputValue);
1722
+ setTypedText(next);
1723
+ const after = next ?? untrack(restingText);
1724
+ if (after !== before) props.onInputValueChange?.()?.(after);
1725
+ };
1726
+
1727
+ const query = (): string => (isQuery() || isMultiple() || !hasOuterInput() ? inputValue() : "");
1728
+
1729
+ const matches = (item: unknown): boolean => {
1730
+ const text = query();
1731
+ if (text === "") return true;
1732
+ const given = props.filter?.();
1733
+ if (given === null) return true;
1734
+ if (given !== undefined) return given(item as V, text, labelOf);
1735
+ return match.contains(labelOf(item), text);
1736
+ };
1737
+
1738
+ const filteredItems = createMemo((): unknown[] => {
1739
+ const kept: unknown[] = [];
1740
+ for (const item of props.items?.() ?? []) {
1741
+ if (isItemGroup(item)) {
1742
+ const inner = item.items.filter(matches);
1743
+ if (inner.length > 0) kept.push({ ...item, items: inner });
1744
+ } else if (matches(item)) {
1745
+ kept.push(item);
1746
+ }
1747
+ }
1748
+ return kept;
1749
+ });
1750
+
1751
+ const registry = staticCollection();
1752
+ const itemsByKey = new Map<Key, unknown>();
1753
+
1754
+ const choose = (keys: SelectionValue): void => {
1755
+ if (keys === "all") return;
1756
+ const held = new Map<Key, V>(values().map((value) => [keyOf(value), value]));
1757
+ const itemFor = (key: Key): V | undefined => held.get(key) ?? (itemsByKey.get(key) as V);
1758
+
1759
+ if (isMultiple()) {
1760
+ const next: V[] = values().filter((value) => keys.has(keyOf(value)));
1761
+ for (const key of keys) {
1762
+ const item = itemFor(key);
1763
+ if (!held.has(key) && item !== undefined) next.push(item);
1764
+ }
1765
+ setRaw(next);
1766
+ // Chosen, so the query has done its job and the whole list comes back.
1767
+ writeInput("");
1768
+ return;
1769
+ }
1770
+
1771
+ const key: Key | undefined = keys.values().next().value;
1772
+ const item = key === undefined ? undefined : itemFor(key);
1773
+ if (key === undefined || item === undefined) return;
1774
+ if (!held.has(key)) setRaw(item);
1775
+ setOpen(false);
1776
+ };
1777
+
1778
+ const list = listState<StaticEntry>({
1779
+ items: registry.entries,
1780
+ ...staticAccessors,
1781
+ selectionMode: () => (isMultiple() ? "multiple" : "single"),
1782
+ disallowEmptySelection: () => !isMultiple(),
1783
+ allowDuplicateSelectionEvents: true,
1784
+ selectedKeys: () => values().map(keyOf),
1785
+ onSelectionChange: choose,
1786
+ });
1787
+
1788
+ const [pending, setPending] = createSignal<FocusStrategy | null>(null);
1789
+
1790
+ const delegate = new ListKeyboardDelegate({
1791
+ collection: list.collection,
1792
+ ref: listRef,
1793
+ disabledKeys: list.disabledKeys,
1794
+ });
1795
+
1796
+ // The arrows drive the LIST while the caret stays in the input, so the
1797
+ // collection's key handling is bound to the input rather than to the list.
1798
+ const { collectionProps } = selectableCollection({
1799
+ ref: inputRef,
1800
+ selectionManager: list.selectionManager,
1801
+ keyboardDelegate: delegate,
1802
+ shouldUseVirtualFocus: true,
1803
+ disallowTypeAhead: true,
1804
+ disallowEmptySelection: true,
1805
+ shouldFocusWrap: true,
1806
+ });
1807
+
1808
+ /** Back to rest: nothing typed, and the field showing what the value reads as. */
1809
+ const settleInput = (): void => {
1810
+ setIsQuery(false);
1811
+ writeInput(null);
1812
+ };
1813
+
1814
+ function setOpen(next: boolean): void {
1815
+ if (next === untrack(isOpen)) return;
1816
+ if (next && (isDisabled() || isReadOnly())) return;
1817
+ setOpenState(next);
1818
+ }
1819
+
1820
+ const openWith = (strategy: FocusStrategy | null): void => {
1821
+ setPending(strategy);
1822
+ setOpen(true);
1823
+ };
1824
+
1825
+ const focusInput = (): void => {
1826
+ inputRef()?.focus();
1827
+ };
1828
+
1829
+ if (!isServer) {
1830
+ // The list is only the focused collection while it is open, and neither
1831
+ // the highlight nor a half-typed query survives a close.
1832
+ let wasOpen = untrack(isOpen);
1833
+ createEffect(isOpen, (open) => {
1834
+ const manager = untrack(list.selectionManager);
1835
+ manager.setFocused(open);
1836
+ if (!open) {
1837
+ manager.setFocusedKey(null);
1838
+ setPending(null);
1839
+ if (wasOpen) settleInput();
1840
+ }
1841
+ wasOpen = open;
1842
+ });
1843
+
1844
+ // An end of the list is highlighted once there is a list: the items render
1845
+ // after the popup opens, so the key that opened it cannot do this itself.
1846
+ createEffect(
1847
+ () => {
1848
+ const strategy = pending();
1849
+ if (!isOpen() || strategy === null || list.collection().size === 0) return null;
1850
+ return strategy;
1851
+ },
1852
+ (strategy) => {
1853
+ if (strategy === null) return;
1854
+ setPending(null);
1855
+ untrack(() => {
1856
+ const key = strategy === "last" ? delegate.getLastKey() : delegate.getFirstKey();
1857
+ list.selectionManager().setFocusedKey(key);
1858
+ });
1859
+ },
1860
+ );
1861
+
1862
+ // A value set from outside is not a query, so the field goes back to
1863
+ // following it.
1864
+ let shownFor = untrack(() => values().map(keyOf).join("\u0000"));
1865
+ createEffect(
1866
+ () => values().map(keyOf).join("\u0000"),
1867
+ (now) => {
1868
+ if (now === shownFor) return;
1869
+ shownFor = now;
1870
+ if (untrack(() => !isMultiple() && !isOpen())) settleInput();
1871
+ },
1872
+ );
1873
+ }
1874
+
1875
+ const removeAt = (index: number): void => {
1876
+ if (isDisabled() || isReadOnly()) return;
1877
+ setRaw(values().filter((_, at) => at !== index));
1878
+ };
1879
+
1880
+ const clear = (): void => {
1881
+ if (isDisabled() || isReadOnly()) return;
1882
+ if (values().length > 0) setRaw(isMultiple() ? [] : null);
1883
+ setIsQuery(false);
1884
+ writeInput(isMultiple() ? "" : null);
1885
+ setOpen(false);
1886
+ focusInput();
1887
+ };
1888
+
1889
+ const onInput = (event: Event): void => {
1890
+ const input = event.target as HTMLInputElement;
1891
+ const text = input.value;
1892
+ setIsQuery(true);
1893
+ writeInput(text);
1894
+ // The highlight was for a list that no longer exists.
1895
+ list.selectionManager().setFocusedKey(null);
1896
+ if (props.autoHighlight?.() === true) setPending("first");
1897
+ // Emptying the field by hand empties the value: a field showing nothing
1898
+ // and holding something is how a form submits what nobody can see.
1899
+ if (text === "" && !isMultiple() && hasOuterInput() && values().length > 0) setRaw(null);
1900
+ setOpen(true);
1901
+ // The field has already changed itself; a controlled owner that declined
1902
+ // re-renders nothing, so the DOM has to be put back by hand.
1903
+ if (input.value !== inputValue()) input.value = inputValue();
1904
+ };
1905
+
1906
+ const onKeyDown = (event: KeyboardEvent, chips: ChipsValue | null): void => {
1907
+ if (isDisabled() || isReadOnly()) return;
1908
+ const input = event.currentTarget as HTMLInputElement;
1909
+ const manager = list.selectionManager();
1910
+
1911
+ if (chips !== null && chips.count() > 0) {
1912
+ const towardsChips = locale().direction === "rtl" ? "ArrowRight" : "ArrowLeft";
1913
+ if (event.key === "Backspace" && input.value === "") {
1914
+ event.preventDefault();
1915
+ removeAt(chips.count() - 1);
1916
+ return;
1917
+ }
1918
+ if (event.key === towardsChips && input.selectionStart === 0 && input.selectionEnd === 0) {
1919
+ event.preventDefault();
1920
+ chips.focus(chips.count() - 1);
1921
+ return;
1922
+ }
1923
+ }
1924
+
1925
+ switch (event.key) {
1926
+ case "ArrowDown":
1927
+ case "ArrowUp": {
1928
+ if (isOpen()) break;
1929
+ event.preventDefault();
1930
+ openWith(event.key === "ArrowDown" ? "first" : "last");
1931
+ return;
1932
+ }
1933
+ case "Enter": {
1934
+ // Only swallowed while something is highlighted: a combobox inside a
1935
+ // form must still submit on Enter otherwise.
1936
+ if (!isOpen() || manager.focusedKey === null) return;
1937
+ event.preventDefault();
1938
+ manager.select(manager.focusedKey);
1939
+ return;
1940
+ }
1941
+ case "Tab": {
1942
+ setOpen(false);
1943
+ return;
1944
+ }
1945
+ case "Escape": {
1946
+ if (isOpen()) {
1947
+ // The list's Escape, not the dialog's the combobox may be in.
1948
+ event.preventDefault();
1949
+ event.stopPropagation();
1950
+ setOpen(false);
1951
+ return;
1952
+ }
1953
+ if (inputValue() === "" && values().length === 0) return;
1954
+ event.preventDefault();
1955
+ if (!isMultiple() && values().length > 0) setRaw(null);
1956
+ setIsQuery(false);
1957
+ writeInput(isMultiple() ? "" : null);
1958
+ return;
1959
+ }
1960
+ default:
1961
+ break;
1962
+ }
1963
+
1964
+ if (isOpen()) (collectionProps.onKeyDown as (event: KeyboardEvent) => void)(event);
1965
+ };
1966
+
1967
+ const owns = (element: Element): boolean =>
1968
+ [inputRef(), triggerRef(), clearRef(), chipsRef()].some(
1969
+ (part) => part !== null && part.contains(element),
1970
+ );
1971
+
1972
+ const onBlur = (event: FocusEvent): void => {
1973
+ const related = event.relatedTarget as Element | null;
1974
+ // Focus moving to the toggle or into the popup is still focus on the
1975
+ // combobox.
1976
+ if (related !== null && (owns(related) || popupRef()?.contains(related) === true)) return;
1977
+ if (isOpen()) setOpen(false);
1978
+ else if (hasOuterInput()) settleInput();
1979
+ };
1980
+
1981
+ return {
1982
+ isOpen,
1983
+ setOpen,
1984
+ openWith,
1985
+ isMultiple,
1986
+ isDisabled,
1987
+ isReadOnly,
1988
+ values,
1989
+ inputValue,
1990
+ query,
1991
+ filteredItems,
1992
+ matches,
1993
+ labelOf,
1994
+ ownLabelOf,
1995
+ stringValueOf,
1996
+ keyOf,
1997
+ list,
1998
+ registry,
1999
+ baseId,
2000
+ listId,
2001
+ isEmpty: () => list.collection().size === 0,
2002
+ hasOuterInput,
2003
+ hasChips: () => chipBoxes() > 0,
2004
+ name: () => props.name?.(),
2005
+ form: () => props.form?.(),
2006
+ clear,
2007
+ removeAt,
2008
+ focusInput,
2009
+ highlight: (key) => list.selectionManager().setFocusedKey(key),
2010
+ anchor: () => chipsRef() ?? (hasOuterInput() ? inputRef() : triggerRef()),
2011
+ owns,
2012
+ listRef,
2013
+ inputRef,
2014
+ triggerRef,
2015
+ clearRef,
2016
+ chipsRef,
2017
+ popupRef,
2018
+ listName: () => ({ label: named()?.label(), labelledBy: named()?.labelledBy() }),
2019
+ attachInput: (input) => {
2020
+ setNamed({ label: input.label, labelledBy: input.labelledBy });
2021
+ setInputDisabled(() => input.isDisabled);
2022
+ if (input.isInside) return;
2023
+ setOuterInputs((count) => count + 1);
2024
+ onCleanup(() => setOuterInputs((count) => count - 1));
2025
+ },
2026
+ attachChips: () => {
2027
+ setChipBoxes((count) => count + 1);
2028
+ onCleanup(() => setChipBoxes((count) => count - 1));
2029
+ },
2030
+ attachItem: (key, item) => {
2031
+ itemsByKey.set(key, item);
2032
+ onCleanup(() => {
2033
+ if (itemsByKey.get(key) === item) itemsByKey.delete(key);
2034
+ });
2035
+ },
2036
+ rememberLabel: (key, text) => {
2037
+ if (text === "" || rendered.get(key) === text) return;
2038
+ rendered.set(key, text);
2039
+ setRenderedVersion((version) => version + 1);
2040
+ },
2041
+ inputProps: (chips) => ({
2042
+ role: "combobox",
2043
+ type: "text",
2044
+ value: inputValue,
2045
+ readOnly: isReadOnly,
2046
+ "aria-haspopup": "listbox",
2047
+ "aria-expanded": isOpen,
2048
+ "aria-controls": () => (isOpen() ? listId() : undefined),
2049
+ "aria-autocomplete": "list",
2050
+ // Virtual focus: the input keeps DOM focus and NAMES the highlighted
2051
+ // option, so the caret never moves and the highlight still travels.
2052
+ "aria-activedescendant": () => {
2053
+ if (!isOpen()) return undefined;
2054
+ const key = list.selectionManager().focusedKey;
2055
+ return key === null ? undefined : optionIdFor(baseId(), key);
2056
+ },
2057
+ // The combobox has its own suggestions; the browser's would cover them,
2058
+ // and iOS autocorrect would rewrite the query as it is typed.
2059
+ autocomplete: "off",
2060
+ autocorrect: "off",
2061
+ spellcheck: "false",
2062
+ onInput,
2063
+ onKeyDown: (event: KeyboardEvent) => onKeyDown(event, chips),
2064
+ onClick: () => {
2065
+ if (props.openOnInputClick?.() !== false) setOpen(true);
2066
+ },
2067
+ onBlur,
2068
+ }),
2069
+ };
2070
+ }
2071
+
2072
+ function ComboboxRootProvider(props: { value: ComboboxRootValue; children?: Child }) {
2073
+ return provide(
2074
+ ComboboxRootContext,
2075
+ () => props.value,
2076
+ () => props.children as unknown,
2077
+ );
2078
+ }
2079
+
2080
+ /** The fields that put the value in a form: a combobox's own input holds a query. */
2081
+ function ComboboxFormValue() {
2082
+ const root = useComboboxRoot();
2083
+ return (
2084
+ <Show when={root.name() !== undefined}>
2085
+ <For each={root.values()}>
2086
+ {(value: unknown) => (
2087
+ <input
2088
+ type="hidden"
2089
+ name={root.name()}
2090
+ form={root.form()}
2091
+ value={root.stringValueOf(value)}
2092
+ disabled={root.isDisabled()}
2093
+ />
2094
+ )}
2095
+ </For>
2096
+ </Show>
2097
+ );
2098
+ }
2099
+
2100
+ /**
2101
+ * ```tsx
2102
+ * <ComboboxRoot items={frameworks} onValueChange={(value) => pick(value)}>
2103
+ * <ComboboxInput aria-label="Framework" />
2104
+ * <ComboboxPopup>
2105
+ * <ComboboxEmpty>No frameworks found.</ComboboxEmpty>
2106
+ * <ComboboxList>
2107
+ * {(item) => <ComboboxItem value={item}>{item}</ComboboxItem>}
2108
+ * </ComboboxList>
2109
+ * </ComboboxPopup>
2110
+ * </ComboboxRoot>
2111
+ * ```
2112
+ *
2113
+ * Renders no element of its own: the parts are placed by whoever writes them.
2114
+ */
2115
+ export function ComboboxRoot<V>(props: ComboboxRootProps<V>) {
2116
+ const root = createComboboxRoot(cells(props));
2117
+ return (
2118
+ <ComboboxRootProvider value={root}>
2119
+ {props.children}
2120
+ <ComboboxFormValue />
2121
+ </ComboboxRootProvider>
2122
+ );
2123
+ }
2124
+
2125
+ const INPUT_PROPS = new Set([
2126
+ "onKeyDown",
2127
+ "onKeyUp",
2128
+ "onChange",
2129
+ "aria-invalid",
2130
+ "aria-required",
2131
+ "inputMode",
2132
+ "enterKeyHint",
2133
+ "autoFocus",
2134
+ "maxLength",
2135
+ "required",
2136
+ ]);
2137
+
2138
+ export interface ComboboxInputProps extends StyleProps {
2139
+ placeholder?: string;
2140
+ disabled?: boolean;
2141
+ required?: boolean;
2142
+ "aria-label"?: string;
2143
+ "aria-labelledby"?: string;
2144
+ "aria-describedby"?: string;
2145
+ "aria-invalid"?: boolean | "true" | "false";
2146
+ ref?: RefTarget<HTMLInputElement>;
2147
+ onKeyDown?: (event: KeyboardEvent) => void;
2148
+ }
2149
+
2150
+ /**
2151
+ * The text field. Outside the popup it is the combobox; inside one it is the
2152
+ * search over a list a button opened, and inside {@link ComboboxChips} it also
2153
+ * walks the chips beside it.
2154
+ */
2155
+ export function ComboboxInput(props: ComboboxInputProps) {
2156
+ const root = useComboboxRoot();
2157
+ const chips = getContext(ComboboxChipsContext) ?? null;
2158
+ const isInside = getContext(ComboboxPopupContext);
2159
+ const isDisabled = (): boolean => props.disabled === true;
2160
+
2161
+ root.attachInput({
2162
+ isInside,
2163
+ isDisabled,
2164
+ label: () => props["aria-label"],
2165
+ labelledBy: () => props["aria-labelledby"],
2166
+ });
2167
+
2168
+ const { focusProps, isFocusVisible } = focusRing();
2169
+
2170
+ const elementProps = mergeProps(
2171
+ root.inputProps(chips),
2172
+ focusProps,
2173
+ filterDOMProps(fromProps(cells(props)), {
2174
+ global: true,
2175
+ labelable: true,
2176
+ propNames: INPUT_PROPS,
2177
+ }),
2178
+ styleProps(cells(props)),
2179
+ {
2180
+ placeholder: () => props.placeholder,
2181
+ disabled: root.isDisabled,
2182
+ // With several values the field only ever holds a query, empty once
2183
+ // something is chosen, so it is required only while nothing is.
2184
+ required: () => props.required === true && (!root.isMultiple() || root.values().length === 0),
2185
+ "data-focus-visible": isFocusVisible,
2186
+ "data-open": root.isOpen,
2187
+ "data-state": () => (root.isOpen() ? "open" : "closed"),
2188
+ "data-disabled": root.isDisabled,
2189
+ "data-testid": () => props["data-testid"],
2190
+ },
2191
+ );
2192
+
2193
+ return <input {...elementProps} ref={mergeRefs(root.inputRef.set, props.ref)} />;
2194
+ }
2195
+
2196
+ /** Nothing reads it. `provide` is what creates the scope a slot is installed in. */
2197
+ const SlotScope = createContext<boolean>(false);
2198
+
2199
+ /**
2200
+ * Hands the toggle's props to the button inside it.
2201
+ *
2202
+ * Beside an input it is a shortcut to the same list, so it is out of the Tab
2203
+ * order and a press on it leaves focus in the field. With no input outside the
2204
+ * popup it IS the control, and takes the keyboard like any button that opens
2205
+ * something.
2206
+ */
2207
+ export function ComboboxTrigger(props: Incoming<{ children?: Child }>) {
2208
+ const root = useComboboxRoot();
2209
+
2210
+ const toggle = (event: PressEvent): void => {
2211
+ if (root.isOpen()) {
2212
+ root.setOpen(false);
2213
+ return;
2214
+ }
2215
+ if (root.hasOuterInput()) root.focusInput();
2216
+ root.openWith(
2217
+ event.pointerType === "keyboard" || event.pointerType === "virtual" ? "first" : null,
2218
+ );
2219
+ };
2220
+
2221
+ return provide(
2222
+ SlotScope,
2223
+ () => true,
2224
+ () => {
2225
+ provideTriggerSlot({
2226
+ props: {
2227
+ "aria-haspopup": "listbox",
2228
+ "aria-expanded": root.isOpen,
2229
+ "aria-controls": () => (root.isOpen() ? root.listId() : undefined),
2230
+ "data-state": () => (root.isOpen() ? "open" : "closed"),
2231
+ "data-popup-open": () => root.isOpen() || undefined,
2232
+ excludeFromTabOrder: root.hasOuterInput,
2233
+ preventFocusOnPress: root.hasOuterInput,
2234
+ isDisabled: () => root.isDisabled() || root.isReadOnly(),
2235
+ onPressStart: (event: PressEvent) => {
2236
+ if (event.pointerType !== "touch") toggle(event);
2237
+ },
2238
+ onPress: (event: PressEvent) => {
2239
+ if (event.pointerType === "touch") toggle(event);
2240
+ },
2241
+ onKeyDown: (event: KeyboardEvent) => {
2242
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
2243
+ event.preventDefault();
2244
+ root.openWith(event.key === "ArrowDown" ? "first" : "last");
2245
+ },
2246
+ },
2247
+ ref: root.triggerRef.set,
2248
+ });
2249
+ return props.children;
2250
+ },
2251
+ );
2252
+ }
2253
+
2254
+ function ComboboxClearSlot(props: { children?: Child }) {
2255
+ const root = useComboboxRoot();
2256
+ return provide(
2257
+ SlotScope,
2258
+ () => true,
2259
+ () => {
2260
+ provideTriggerSlot({
2261
+ props: {
2262
+ excludeFromTabOrder: true,
2263
+ preventFocusOnPress: true,
2264
+ isDisabled: () => root.isDisabled() || root.isReadOnly(),
2265
+ onPress: () => root.clear(),
2266
+ },
2267
+ ref: root.clearRef.set,
2268
+ });
2269
+ return props.children;
2270
+ },
2271
+ );
2272
+ }
2273
+
2274
+ /**
2275
+ * Hands the clearing press to the button inside it, and renders that button
2276
+ * only while there is something to clear.
2277
+ */
2278
+ export function ComboboxClear(props: { children?: Child }) {
2279
+ const root = useComboboxRoot();
2280
+ return (
2281
+ <Show when={root.values().length > 0 || root.inputValue() !== ""}>
2282
+ <ComboboxClearSlot>{props.children}</ComboboxClearSlot>
2283
+ </Show>
2284
+ );
2285
+ }
2286
+
2287
+ export interface ComboboxValueProps {
2288
+ /** Called with the value, or with every value when there are several. */
2289
+ children?: Child | ((value: never) => Child);
2290
+ /** What to show while nothing is chosen. */
2291
+ placeholder?: string;
2292
+ }
2293
+
2294
+ /**
2295
+ * What is chosen, as text or through a callback.
2296
+ *
2297
+ * With `multiple` the callback runs ONCE and is handed a list that changes in
2298
+ * place, so a `<For>` over it adds and removes chips without rebuilding the
2299
+ * input written beside them, which would take the caret with it.
2300
+ */
2301
+ export function ComboboxValue(props: ComboboxValueProps) {
2302
+ const root = useComboboxRoot();
2303
+ const render = renderCallback(props.children);
2304
+
2305
+ if (render === null) {
2306
+ const text = (): string => {
2307
+ const chosen = root.values();
2308
+ if (chosen.length === 0) return props.placeholder ?? "";
2309
+ return chosen.map(root.labelOf).join(", ");
2310
+ };
2311
+ return <>{props.children === undefined ? text() : (props.children as () => Child)()}</>;
2312
+ }
2313
+
2314
+ if (root.isMultiple()) {
2315
+ const chosen = createProjection<unknown[]>((draft) => {
2316
+ const next = root.values();
2317
+ draft.length = 0;
2318
+ draft.push(...next);
2319
+ }, []);
2320
+ return <>{render(chosen, 0)}</>;
2321
+ }
2322
+
2323
+ const one = (): Child => render(root.values()[0] ?? null, 0);
2324
+ return <>{one()}</>;
2325
+ }
2326
+
2327
+ export type ComboboxAnchor =
2328
+ | Element
2329
+ | { current: Element | null }
2330
+ | (() => Element | null | undefined)
2331
+ | null;
2332
+
2333
+ function anchorElement(anchor: ComboboxAnchor | undefined): Element | null {
2334
+ if (anchor === null || anchor === undefined) return null;
2335
+ if (typeof anchor === "function") return anchor() ?? null;
2336
+ if (anchor instanceof Element) return anchor;
2337
+ return anchor.current;
2338
+ }
2339
+
2340
+ export interface ComboboxPopupProps extends StyleProps {
2341
+ children?: Child;
2342
+ /** The panel the list is drawn in, which `class` and `style` land on. */
2343
+ ref?: RefTarget<HTMLDivElement>;
2344
+ /** @default "bottom" */
2345
+ side?: Side;
2346
+ /** @default "start" */
2347
+ align?: Align;
2348
+ /** @default 6 */
2349
+ sideOffset?: number;
2350
+ /** @default 0 */
2351
+ alignOffset?: number;
2352
+ /** What to place against. @default the chips box, the input, or the trigger */
2353
+ anchor?: ComboboxAnchor;
2354
+ role?: string;
2355
+ "aria-label"?: string;
2356
+ }
2357
+
2358
+ /**
2359
+ * The popup, portalled and placed against the input.
2360
+ *
2361
+ * Two elements: the outer one is positioned and nothing else, and the inner
2362
+ * one is the caller's to style. Animating the positioned element would move
2363
+ * the thing being measured.
2364
+ */
2365
+ export function ComboboxPopup(props: ComboboxPopupProps) {
2366
+ const root = useComboboxRoot();
2367
+ const locale = useLocale();
2368
+ const positionerRef = makeRef<HTMLDivElement>();
2369
+ const popupRef = root.popupRef;
2370
+ const close = (): void => root.setOpen(false);
2371
+
2372
+ const placement = (): Placement => placementFor(props.side ?? "bottom", props.align ?? "start");
2373
+
2374
+ const position = overlayPosition({
2375
+ targetRef: () => anchorElement(props.anchor) ?? root.anchor(),
2376
+ overlayRef: positionerRef,
2377
+ placement,
2378
+ offset: () => props.sideOffset ?? 6,
2379
+ crossOffset: () => props.alignOffset ?? 0,
2380
+ isOpen: root.isOpen,
2381
+ onClose: close,
2382
+ direction: () => locale().direction,
2383
+ });
2384
+
2385
+ const { overlayProps } = dismissal(
2386
+ {
2387
+ isOpen: root.isOpen,
2388
+ onClose: close,
2389
+ isDismissable: true,
2390
+ // The input, the toggle and the chips are outside the popup and are not
2391
+ // outside the combobox.
2392
+ shouldCloseOnInteractOutside: (element) => !root.owns(element),
2393
+ },
2394
+ positionerRef,
2395
+ );
2396
+
2397
+ const gate = presence({ isOpen: root.isOpen, ref: popupRef });
2398
+ const target = usePortalTarget();
2399
+
2400
+ const popupDirection = declaredDirection();
2401
+ const popupProps = mergeProps(
2402
+ filterDOMProps(fromProps(cells(props)), { global: true, labelable: true }),
2403
+ // Portalled out from under the element that carries `dir`.
2404
+ { dir: () => props.dir ?? popupDirection() },
2405
+ styleProps(cells(props)),
2406
+ {
2407
+ role: () => props.role ?? "presentation",
2408
+ "data-open": () => !gate.isExiting(),
2409
+ "data-closed": gate.isExiting,
2410
+ "data-state": () => (gate.isExiting() ? "closed" : "open"),
2411
+ "data-side": position.placement,
2412
+ "data-align": () => alignOf(placement()),
2413
+ "data-placement": position.placement,
2414
+ "data-empty": root.isEmpty,
2415
+ "data-testid": () => props["data-testid"],
2416
+ },
2417
+ );
2418
+
2419
+ return (
2420
+ <Show when={gate.isPresent()}>
2421
+ <Portal mount={portalContainer(target)}>
2422
+ <ComboboxPopupBody
2423
+ positionerProps={mergeProps(overlayProps, position.overlayProps)}
2424
+ positionerRef={positionerRef}
2425
+ popupProps={popupProps}
2426
+ popupRef={popupRef}
2427
+ forwardedRef={props.ref}
2428
+ >
2429
+ {props.children}
2430
+ </ComboboxPopupBody>
2431
+ </Portal>
2432
+ </Show>
2433
+ );
2434
+ }
2435
+
2436
+ interface ComboboxPopupBodyProps {
2437
+ positionerProps: DOMProps;
2438
+ positionerRef: ReturnType<typeof makeRef<HTMLDivElement>>;
2439
+ popupProps: DOMProps;
2440
+ popupRef: ReturnType<typeof makeRef<HTMLDivElement>>;
2441
+ forwardedRef?: RefTarget<HTMLDivElement>;
2442
+ children?: Child;
2443
+ }
2444
+
2445
+ /**
2446
+ * Inside the `<Show>`, so a focus scope is created WITH the content it holds
2447
+ * and disposed with it, which is what gives focus back to the trigger.
2448
+ *
2449
+ * Only when there is no input outside: a list under a field the user is typing
2450
+ * in must not take the caret, and a scope would.
2451
+ */
2452
+ function ComboboxPopupBody(props: ComboboxPopupBodyProps) {
2453
+ const root = useComboboxRoot();
2454
+ const scope = untrack(root.hasOuterInput)
2455
+ ? null
2456
+ : focusScope({ contain: true, restoreFocus: true, autoFocus: true });
2457
+ const positionerRef = props.positionerRef;
2458
+ const setPopup = mergeRefs(props.popupRef.set, props.forwardedRef);
2459
+
2460
+ return (
2461
+ <>
2462
+ <span hidden ref={scope?.startRef} />
2463
+ <ComboboxPopupScope>
2464
+ <div {...props.positionerProps} ref={positionerRef.set}>
2465
+ <div {...props.popupProps} ref={setPopup}>
2466
+ {props.children}
2467
+ </div>
2468
+ </div>
2469
+ </ComboboxPopupScope>
2470
+ <span hidden ref={scope?.endRef} />
2471
+ </>
2472
+ );
2473
+ }
2474
+
2475
+ function ComboboxPopupScope(props: { children?: Child }) {
2476
+ return provide(
2477
+ ComboboxPopupContext,
2478
+ () => true,
2479
+ () => props.children as unknown,
2480
+ );
2481
+ }
2482
+
2483
+ export interface ComboboxListProps extends StyleProps {
2484
+ /** A callback building an item from each of `items`, or the items themselves. */
2485
+ children?: Child | ((item: never, index: number) => Child);
2486
+ "aria-label"?: string;
2487
+ "aria-labelledby"?: string;
2488
+ }
2489
+
2490
+ /** The listbox. Its options are whatever its children render. */
2491
+ export function ComboboxList(props: ComboboxListProps) {
2492
+ const root = useComboboxRoot();
2493
+ const { children: _children, ...own } = props;
2494
+
2495
+ const { listBoxProps, baseId } = listBox(
2496
+ {
2497
+ ref: root.listRef,
2498
+ baseId: root.baseId,
2499
+ shouldUseVirtualFocus: true,
2500
+ shouldSelectOnPressUp: true,
2501
+ disallowEmptySelection: () => !root.isMultiple(),
2502
+ linkBehavior: "selection",
2503
+ },
2504
+ root.list,
2505
+ );
2506
+
2507
+ const elementProps = mergeProps(
2508
+ listBoxProps,
2509
+ filterDOMProps(fromProps(cells(own)), { global: true }),
2510
+ styleProps(cells(props)),
2511
+ {
2512
+ id: root.listId,
2513
+ "aria-label": () =>
2514
+ props["aria-label"] ??
2515
+ root.listName().label ??
2516
+ (root.listName().labelledBy === undefined && props["aria-labelledby"] === undefined
2517
+ ? "Suggestions"
2518
+ : undefined),
2519
+ "aria-labelledby": () => props["aria-labelledby"] ?? root.listName().labelledBy,
2520
+ "data-empty": root.isEmpty,
2521
+ "data-testid": () => props["data-testid"],
2522
+ },
2523
+ );
2524
+
2525
+ const value: ListBoxContextValue = {
2526
+ state: root.list,
2527
+ baseId,
2528
+ shouldSelectOnPressUp: () => true,
2529
+ shouldUseVirtualFocus: () => true,
2530
+ staticItems: root.registry,
2531
+ };
2532
+
2533
+ const render = renderCallback(props.children);
2534
+
2535
+ if (render === null) {
2536
+ return (
2537
+ <ListBoxProvider value={value}>
2538
+ <ul {...elementProps} ref={root.listRef.set}>
2539
+ {props.children}
2540
+ </ul>
2541
+ </ListBoxProvider>
2542
+ );
2543
+ }
2544
+
2545
+ return (
2546
+ <ListBoxProvider value={value}>
2547
+ <ul {...elementProps} ref={root.listRef.set}>
2548
+ <For each={root.filteredItems()}>
2549
+ {(item: unknown, index: Accessor<number>) => render(item, index())}
2550
+ </For>
2551
+ </ul>
2552
+ </ListBoxProvider>
2553
+ );
2554
+ }
2555
+
2556
+ export interface ComboboxItemValue {
2557
+ isSelected: Accessor<boolean>;
2558
+ isHighlighted: Accessor<boolean>;
2559
+ isDisabled: Accessor<boolean>;
2560
+ }
2561
+
2562
+ const ComboboxItemContext = createContext<ComboboxItemValue | null>(null);
2563
+
2564
+ /** The enclosing {@link ComboboxItem}'s state, for a tick or anything else inside it. */
2565
+ export function useComboboxItem(): ComboboxItemValue {
2566
+ const value = getContext(ComboboxItemContext);
2567
+ if (value === null || value === undefined) {
2568
+ throw new Error("This must be rendered inside a ComboboxItem.");
2569
+ }
2570
+ return value;
2571
+ }
2572
+
2573
+ function ComboboxItemProvider(props: { value: ComboboxItemValue; children?: Child }) {
2574
+ return provide(
2575
+ ComboboxItemContext,
2576
+ () => props.value,
2577
+ () => props.children as unknown,
2578
+ );
2579
+ }
2580
+
2581
+ export interface ComboboxItemProps extends StyleProps {
2582
+ /** The item this option stands for, handed back by `onValueChange`. */
2583
+ value: unknown;
2584
+ disabled?: boolean;
2585
+ /** What the filter and the field read. @default the item's label, or this option's text */
2586
+ textValue?: string;
2587
+ children?: Child;
2588
+ "aria-label"?: string;
2589
+ ref?: RefTarget<HTMLLIElement>;
2590
+ }
2591
+
2592
+ /** One option. It joins the list by rendering and leaves it by going away. */
2593
+ export function ComboboxItem(props: ComboboxItemProps) {
2594
+ const root = useComboboxRoot();
2595
+ // Read once: an option does not turn into a different one.
2596
+ const item = untrack(cells(props).value);
2597
+ const key = root.keyOf(item);
2598
+ root.attachItem(key, item);
2599
+
2600
+ const manager = () => root.list.selectionManager();
2601
+ const isDisabled = (): boolean => props.disabled === true;
2602
+ const state: ComboboxItemValue = {
2603
+ isSelected: () => manager().isSelected(key),
2604
+ isHighlighted: () => root.isOpen() && manager().focusedKey === key,
2605
+ isDisabled,
2606
+ };
2607
+
2608
+ onSettled(() => {
2609
+ untrack(() => {
2610
+ root.rememberLabel(
2611
+ key,
2612
+ props.textValue ??
2613
+ root.ownLabelOf(item) ??
2614
+ root.registry.elementOf(key)?.textContent?.trim() ??
2615
+ "",
2616
+ );
2617
+ });
2618
+ });
2619
+
2620
+ const { value: _value, ...rest } = props;
2621
+
2622
+ return (
2623
+ <ComboboxItemProvider value={state}>
2624
+ <Option
2625
+ {...rest}
2626
+ value={key}
2627
+ textValue={props.textValue ?? root.ownLabelOf(item)}
2628
+ isDisabled={isDisabled()}
2629
+ isHidden={!root.matches(item)}
2630
+ data-highlighted={state.isHighlighted() ? "" : undefined}
2631
+ data-state={state.isSelected() ? "checked" : "unchecked"}
2632
+ // A pointer over an option highlights it, so the keyboard carries on
2633
+ // from where the pointer was.
2634
+ onPointerMove={() => {
2635
+ if (!isDisabled() && manager().focusedKey !== key) root.highlight(key);
2636
+ }}
2637
+ >
2638
+ {props.children}
2639
+ </Option>
2640
+ </ComboboxItemProvider>
2641
+ );
2642
+ }
2643
+
2644
+ interface GroupValue {
2645
+ /** The group's own items, for a {@link ComboboxCollection} inside it. */
2646
+ items: Accessor<readonly unknown[]>;
2647
+ headingId: Accessor<string>;
2648
+ readonly name: (has: boolean) => void;
2649
+ }
2650
+
2651
+ const ComboboxGroupContext = createContext<GroupValue | null>(null);
2652
+
2653
+ function ComboboxGroupProvider(props: { value: GroupValue; section: Key; children?: Child }) {
2654
+ return provideStaticSection(props.section, () =>
2655
+ provide(
2656
+ ComboboxGroupContext,
2657
+ () => props.value,
2658
+ () => props.children as unknown,
2659
+ ),
2660
+ ) as never;
2661
+ }
2662
+
2663
+ export interface ComboboxGroupProps extends StyleProps {
2664
+ /** The items a {@link ComboboxCollection} inside renders. */
2665
+ items?: readonly unknown[];
2666
+ children?: Child;
2667
+ "aria-label"?: string;
2668
+ }
2669
+
2670
+ /**
2671
+ * A run of options, named by the {@link ComboboxGroupLabel} inside it.
2672
+ *
2673
+ * Two elements, because the options have to be the group's own children in the
2674
+ * accessibility tree and a `<li>` cannot hold another `<li>`: the outer one is
2675
+ * presentational and takes the caller's class, the inner one is the group.
2676
+ */
2677
+ export function ComboboxGroup(props: ComboboxGroupProps) {
2678
+ const root = useComboboxRoot();
2679
+ const section = staticItem(root.registry, { type: "section", textValue: "" });
2680
+ const headingId = id();
2681
+ const [isNamed, setNamed] = createSignal(false, { ownedWrite: true });
2682
+
2683
+ const group: GroupValue = {
2684
+ items: () => props.items ?? [],
2685
+ headingId,
2686
+ name: setNamed,
2687
+ };
2688
+
2689
+ const elementProps = mergeProps(
2690
+ filterDOMProps(fromProps(cells(props)), { global: true }),
2691
+ styleProps(cells(props)),
2692
+ {
2693
+ role: "presentation",
2694
+ // A group the query has emptied still holds its label, and a design
2695
+ // system hides the whole thing off this.
2696
+ "data-empty": () =>
2697
+ (root.list.collection().getItem(section.key)?.childNodes.length ?? 0) === 0,
2698
+ "data-testid": () => props["data-testid"],
2699
+ },
2700
+ );
2701
+
2702
+ return (
2703
+ <ComboboxGroupProvider value={group} section={section.key}>
2704
+ <li {...elementProps} ref={section.ref}>
2705
+ <ul
2706
+ role="group"
2707
+ aria-label={props["aria-label"]}
2708
+ aria-labelledby={isNamed() ? headingId() : undefined}
2709
+ >
2710
+ {props.children}
2711
+ </ul>
2712
+ </li>
2713
+ </ComboboxGroupProvider>
2714
+ );
2715
+ }
2716
+
2717
+ export interface ComboboxGroupLabelProps extends StyleProps {
2718
+ children?: Child;
2719
+ }
2720
+
2721
+ /**
2722
+ * The heading of the group it is written in.
2723
+ *
2724
+ * Rendering it is what makes the group point here, and leaving undoes that, so
2725
+ * a group never names an element that is not there.
2726
+ */
2727
+ export function ComboboxGroupLabel(props: ComboboxGroupLabelProps) {
2728
+ const group = getContext(ComboboxGroupContext) ?? null;
2729
+ group?.name(true);
2730
+ onCleanup(() => group?.name(false));
2731
+
2732
+ const elementProps = mergeProps(
2733
+ filterDOMProps(fromProps(cells(props)), { global: true }),
2734
+ styleProps(cells(props)),
2735
+ {
2736
+ // Inside the group and not one of its options.
2737
+ role: "presentation",
2738
+ id: () => group?.headingId(),
2739
+ "data-testid": () => props["data-testid"],
2740
+ },
2741
+ );
2742
+
2743
+ return <li {...elementProps}>{props.children}</li>;
2744
+ }
2745
+
2746
+ export interface ComboboxCollectionProps {
2747
+ /** How one of the enclosing group's items renders. */
2748
+ children: (item: never, index: number) => Child;
2749
+ }
2750
+
2751
+ /** The enclosing {@link ComboboxGroup}'s items, less what the query rules out. */
2752
+ export function ComboboxCollection(props: ComboboxCollectionProps) {
2753
+ const root = useComboboxRoot();
2754
+ const group = getContext(ComboboxGroupContext) ?? null;
2755
+ const render = renderCallback(props.children);
2756
+ if (render === null) {
2757
+ throw new Error("A ComboboxCollection takes a callback that renders one item.");
2758
+ }
2759
+
2760
+ return (
2761
+ <For each={(group?.items() ?? []).filter(root.matches)}>
2762
+ {(item: unknown, index: Accessor<number>) => render(item, index())}
2763
+ </For>
2764
+ );
2765
+ }
2766
+
2767
+ export interface ComboboxEmptyProps extends StyleProps {
2768
+ children?: Child;
2769
+ }
2770
+
2771
+ /**
2772
+ * What the popup says when nothing matches.
2773
+ *
2774
+ * The element is always there and only its content comes and goes: a live
2775
+ * region announces a change to what it holds, and one that arrives already
2776
+ * full announces nothing.
2777
+ */
2778
+ export function ComboboxEmpty(props: ComboboxEmptyProps) {
2779
+ const root = useComboboxRoot();
2780
+
2781
+ const elementProps = mergeProps(
2782
+ filterDOMProps(fromProps(cells(props)), { global: true }),
2783
+ styleProps(cells(props)),
2784
+ {
2785
+ role: "status",
2786
+ "aria-live": "polite",
2787
+ "aria-atomic": "true",
2788
+ "data-testid": () => props["data-testid"],
2789
+ },
2790
+ );
2791
+
2792
+ return (
2793
+ <div {...elementProps}>
2794
+ <Show when={root.isEmpty()}>{props.children}</Show>
2795
+ </div>
2796
+ );
2797
+ }
2798
+
2799
+ function ComboboxChipsProvider(props: { value: ChipsValue; children?: Child }) {
2800
+ return provide(
2801
+ ComboboxChipsContext,
2802
+ () => props.value,
2803
+ () => props.children as unknown,
2804
+ );
2805
+ }
2806
+
2807
+ export interface ComboboxChipsProps extends StyleProps {
2808
+ children?: Child;
2809
+ "aria-label"?: string;
2810
+ "aria-labelledby"?: string;
2811
+ ref?: RefTarget<HTMLDivElement>;
2812
+ }
2813
+
2814
+ /**
2815
+ * The box a multiple combobox's chips and input sit in, and what its popup is
2816
+ * placed against.
2817
+ *
2818
+ * A `<div>` that looks like a field: the chips inside carry remove buttons,
2819
+ * and a button inside an input is markup nothing can render.
2820
+ */
2821
+ export function ComboboxChips(props: ComboboxChipsProps) {
2822
+ const root = useComboboxRoot();
2823
+ const registry = staticCollection();
2824
+ root.attachChips();
2825
+
2826
+ const chips: ChipsValue = {
2827
+ registry,
2828
+ count: () => registry.keys().length,
2829
+ focus: (index) => {
2830
+ const key = registry.keys()[index];
2831
+ const element = key === undefined ? null : registry.elementOf(key);
2832
+ if (element instanceof HTMLElement) element.focus();
2833
+ },
2834
+ };
2835
+
2836
+ const elementProps = mergeProps(
2837
+ filterDOMProps(fromProps(cells(props)), { global: true, labelable: true }),
2838
+ styleProps(cells(props)),
2839
+ {
2840
+ // A toolbar only while there are chips to move between: an input alone
2841
+ // in a toolbar is a toolbar of one.
2842
+ role: () => (chips.count() > 0 ? "toolbar" : undefined),
2843
+ "data-disabled": root.isDisabled,
2844
+ "data-testid": () => props["data-testid"],
2845
+ onMouseDown: (event: MouseEvent) => {
2846
+ // The box is the field, so a press on its own padding is a press on
2847
+ // the input.
2848
+ if (event.target !== event.currentTarget) return;
2849
+ event.preventDefault();
2850
+ root.focusInput();
2851
+ },
2852
+ },
2853
+ );
2854
+
2855
+ return (
2856
+ <ComboboxChipsProvider value={chips}>
2857
+ <div {...elementProps} ref={mergeRefs(root.chipsRef.set, props.ref)}>
2858
+ {props.children}
2859
+ </div>
2860
+ </ComboboxChipsProvider>
2861
+ );
2862
+ }
2863
+
2864
+ export interface ComboboxChipValue {
2865
+ remove: () => void;
2866
+ /** What the chip's value reads as, for naming the button that removes it. */
2867
+ label: Accessor<string>;
2868
+ }
2869
+
2870
+ const ComboboxChipContext = createContext<ComboboxChipValue | null>(null);
2871
+
2872
+ /** The enclosing {@link ComboboxChip}. */
2873
+ export function useComboboxChip(): ComboboxChipValue {
2874
+ const value = getContext(ComboboxChipContext);
2875
+ if (value === null || value === undefined) {
2876
+ throw new Error("This must be rendered inside a ComboboxChip.");
2877
+ }
2878
+ return value;
2879
+ }
2880
+
2881
+ function ComboboxChipProvider(props: { value: ComboboxChipValue; children?: Child }) {
2882
+ return provide(
2883
+ ComboboxChipContext,
2884
+ () => props.value,
2885
+ () => props.children as unknown,
2886
+ );
2887
+ }
2888
+
2889
+ export interface ComboboxChipProps extends StyleProps {
2890
+ children?: Child;
2891
+ "aria-label"?: string;
2892
+ ref?: RefTarget<HTMLDivElement>;
2893
+ }
2894
+
2895
+ /**
2896
+ * One chosen value. Which one is its position among the chips, so it needs
2897
+ * telling nothing.
2898
+ *
2899
+ * Reached with the arrows from the input rather than with Tab: a field holding
2900
+ * eight values would otherwise be eight stops before the next field.
2901
+ */
2902
+ export function ComboboxChip(props: ComboboxChipProps) {
2903
+ const root = useComboboxRoot();
2904
+ const locale = useLocale();
2905
+ const chips = getContext(ComboboxChipsContext);
2906
+ if (chips === null || chips === undefined) {
2907
+ throw new Error("A ComboboxChip must be rendered inside a ComboboxChips.");
2908
+ }
2909
+
2910
+ const chip = staticItem(chips.registry, { textValue: "" });
2911
+ const [isFocused, setFocused] = createSignal(false);
2912
+ const index = (): number => chips.registry.keys().indexOf(chip.key);
2913
+
2914
+ const remove = (): void => {
2915
+ const at = index();
2916
+ if (at >= 0) root.removeAt(at);
2917
+ };
2918
+ const label = (): string => {
2919
+ const value = root.values()[index()];
2920
+ return value === undefined ? "" : root.labelOf(value);
2921
+ };
2922
+
2923
+ const onKeyDown = (event: KeyboardEvent): void => {
2924
+ if (event.target !== event.currentTarget) return;
2925
+ const at = index();
2926
+ const isRtl = locale().direction === "rtl";
2927
+ const back = isRtl ? "ArrowRight" : "ArrowLeft";
2928
+ const forward = isRtl ? "ArrowLeft" : "ArrowRight";
2929
+
2930
+ if (event.key === back) {
2931
+ event.preventDefault();
2932
+ chips.focus(Math.max(0, at - 1));
2933
+ } else if (event.key === forward) {
2934
+ event.preventDefault();
2935
+ if (at + 1 < chips.count()) chips.focus(at + 1);
2936
+ else root.focusInput();
2937
+ } else if (event.key === "Backspace" || event.key === "Delete") {
2938
+ event.preventDefault();
2939
+ // Focus moves BEFORE the chip goes: once it is removed there is nothing
2940
+ // focused to move from, and the keyboard is back at the top of the page.
2941
+ if (at + 1 < chips.count()) chips.focus(at + 1);
2942
+ else if (at > 0) chips.focus(at - 1);
2943
+ else root.focusInput();
2944
+ remove();
2945
+ }
2946
+ };
2947
+
2948
+ const elementProps = mergeProps(
2949
+ filterDOMProps(fromProps(cells(props)), { global: true, labelable: true }),
2950
+ styleProps(cells(props)),
2951
+ {
2952
+ tabIndex: -1,
2953
+ "data-highlighted": isFocused,
2954
+ "data-disabled": root.isDisabled,
2955
+ "data-testid": () => props["data-testid"],
2956
+ onKeyDown,
2957
+ onFocus: (event: FocusEvent) => {
2958
+ if (event.target === event.currentTarget) setFocused(true);
2959
+ },
2960
+ onBlur: () => setFocused(false),
2961
+ },
2962
+ );
2963
+
2964
+ // The provider is OUTSIDE the element, as it is for every part here: handed
2965
+ // a label and a button as two children it would build the button first, and
2966
+ // a hydrating page would claim the server's label as the button.
2967
+ return (
2968
+ <ComboboxChipProvider value={{ remove, label }}>
2969
+ <div {...elementProps} ref={mergeRefs(chip.ref, props.ref)}>
2970
+ {props.children}
2971
+ </div>
2972
+ </ComboboxChipProvider>
2973
+ );
2974
+ }
2975
+
2976
+ /**
2977
+ * Hands the removing press to the button inside it.
2978
+ *
2979
+ * Out of the Tab order, like the chip it is in: Backspace on the chip does the
2980
+ * same thing from the keyboard.
2981
+ */
2982
+ export function ComboboxChipRemove(props: Incoming<{ children?: Child }>) {
2983
+ const root = useComboboxRoot();
2984
+ const chip = useComboboxChip();
2985
+
2986
+ return provide(
2987
+ SlotScope,
2988
+ () => true,
2989
+ () => {
2990
+ provideTriggerSlot({
2991
+ props: {
2992
+ excludeFromTabOrder: true,
2993
+ isDisabled: () => root.isDisabled() || root.isReadOnly(),
2994
+ onPress: () => {
2995
+ chip.remove();
2996
+ root.focusInput();
2997
+ },
2998
+ },
2999
+ });
3000
+ return props.children;
3001
+ },
3002
+ );
3003
+ }