@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
package/src/select.tsx ADDED
@@ -0,0 +1,1745 @@
1
+ /**
2
+ * A select: a button that shows the current choice and opens a listbox.
3
+ *
4
+ * Not a `<select>`. The native one cannot be styled past a point and cannot
5
+ * hold anything but text, which is why every design system reimplements it,
6
+ * and why every reimplementation has to put back what the platform was doing:
7
+ *
8
+ * - **The name.** The button is named by the label AND by the current value,
9
+ * in that order, so a screen reader announces "Fruit, Banana, button" rather
10
+ * than just "Banana".
11
+ * - **Form participation.** A visually hidden native `<select>` carries the
12
+ * value into `FormData`, gets autofilled by the browser, and gives mobile
13
+ * browsers the form navigation bar their users expect. It is hidden by
14
+ * CLIPPING rather than by `display: none`, because Safari will not autofill
15
+ * a control it considers invisible.
16
+ * - **Typing on the closed button.** A native select jumps to the matching
17
+ * option without opening, and so does this one.
18
+ *
19
+ * The listbox is a listbox, not a menu: the options are values to choose
20
+ * between, and `aria-selected` is what says which one is current.
21
+ */
22
+
23
+ import {
24
+ cells,
25
+ type Accessor,
26
+ type Child,
27
+ For,
28
+ Show,
29
+ createContext,
30
+ createEffect,
31
+ getContext,
32
+ getOwner,
33
+ type Incoming,
34
+ install,
35
+ createSignal,
36
+ onCleanup,
37
+ onSettled,
38
+ provide,
39
+ } from "@barqjs/core";
40
+ import { Portal } from "@barqjs/web";
41
+ import { resizeObserver } from "@barqjs/primitives/observers";
42
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
43
+ import { button, type ButtonOptions } from "./button.tsx";
44
+ import type {
45
+ Collection,
46
+ FocusStrategy,
47
+ ItemAccessors,
48
+ Key,
49
+ ListStateOptions,
50
+ Node,
51
+ SelectionMode,
52
+ SelectionValue,
53
+ } from "./collections.ts";
54
+ import { listState, type ListState } from "./collections.ts";
55
+ import { PREVENT_FOCUS_ATTRIBUTE } from "./dom.ts";
56
+ import { Popover, popoverStateProps } from "./dialog.tsx";
57
+ import { focusRing } from "./focus.ts";
58
+ import { collator, useLocale } from "./i18n.ts";
59
+ import { hover } from "./interactions/hover.ts";
60
+ import type { ElementRef } from "./interactions/press.ts";
61
+ import { field, type FieldOptions } from "./label.ts";
62
+ import {
63
+ formValidation,
64
+ fieldValidation,
65
+ type FormValidationState,
66
+ type ValidateFunction,
67
+ type ValidationBehavior,
68
+ } from "./validation.ts";
69
+ import {
70
+ listBox,
71
+ ListBoxProvider,
72
+ Option,
73
+ provideItemNode,
74
+ provideItemRender,
75
+ type ListBoxContextValue,
76
+ } from "./listbox.tsx";
77
+ import { visuallyHidden } from "./live.ts";
78
+ import { menuTrigger } from "./menu.tsx";
79
+ import { overlayTriggerState, type OverlayTriggerState, type Placement } from "./overlays.ts";
80
+ import { ListKeyboardDelegate, typeSelect, type KeyboardDelegate } from "./selection.ts";
81
+ import {
82
+ staticAccessors,
83
+ staticCollection,
84
+ type StaticCollection,
85
+ type StaticEntry,
86
+ } from "./static-collection.ts";
87
+ import { formReset } from "./toggle.ts";
88
+ import {
89
+ access,
90
+ callback,
91
+ type DOMProps,
92
+ filterDOMProps,
93
+ fromProps,
94
+ id,
95
+ type MaybeAccessor,
96
+ mergeProps,
97
+ type StyleProps,
98
+ styleProps,
99
+ } from "./utils.ts";
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // State
103
+ // ---------------------------------------------------------------------------
104
+
105
+ export interface SelectStateOptions<T> extends Omit<ListStateOptions<T>, "onSelectionChange"> {
106
+ selectedKey?: MaybeAccessor<Key | null | undefined>;
107
+ defaultSelectedKey?: MaybeAccessor<Key | null | undefined>;
108
+ isOpen?: MaybeAccessor<boolean | undefined>;
109
+ defaultOpen?: MaybeAccessor<boolean | undefined>;
110
+ /** Close when a value is chosen. @default true for single selection */
111
+ shouldCloseOnSelect?: MaybeAccessor<boolean | undefined>;
112
+ /** Let the popup open with nothing in it. @default false */
113
+ allowsEmptyCollection?: MaybeAccessor<boolean | undefined>;
114
+ onOpenChange?: (isOpen: boolean) => void;
115
+ onSelectionChange?: (key: Key | null) => void;
116
+ /** Every selected key, for a multiple-selection select. */
117
+ onSelectionChangeAll?: (keys: SelectionValue) => void;
118
+ }
119
+
120
+ export interface SelectState<T> extends ListState<T>, Omit<OverlayTriggerState, "open" | "toggle"> {
121
+ selectedKey: Accessor<Key | null>;
122
+ setSelectedKey(key: Key | null): void;
123
+ selectedItem: Accessor<Node<T> | null>;
124
+ selectedItems: Accessor<Node<T>[]>;
125
+ /** What the form control submits. */
126
+ value: Accessor<Key | Key[] | null>;
127
+ defaultValue: Accessor<Key | Key[] | null>;
128
+ setValue(value: Key | Key[] | null): void;
129
+ isFocused: Accessor<boolean>;
130
+ setFocused(isFocused: boolean): void;
131
+ focusStrategy: Accessor<FocusStrategy | null>;
132
+ open(focusStrategy?: FocusStrategy | null): void;
133
+ toggle(focusStrategy?: FocusStrategy | null): void;
134
+ }
135
+
136
+ /**
137
+ * The collection, the selection and the popup, kept in step.
138
+ *
139
+ * A select with nothing in it does not open. An empty popup is a dead end the
140
+ * user has to escape from, and it tells them nothing that a disabled button
141
+ * does not.
142
+ */
143
+ export function selectState<T>(options: SelectStateOptions<T>): SelectState<T> {
144
+ const overlay = overlayTriggerState(options);
145
+ const [strategy, setStrategy] = createSignal<FocusStrategy | null>(null);
146
+ const [isFocused, setIsFocused] = createSignal(false);
147
+
148
+ const mode = (): SelectionMode => access(options.selectionMode) ?? "single";
149
+ const closesOnSelect = (): boolean => access(options.shouldCloseOnSelect) ?? mode() === "single";
150
+
151
+ const list = listState<T>({
152
+ ...options,
153
+ selectionMode: mode,
154
+ disallowEmptySelection: () => mode() === "single",
155
+ allowDuplicateSelectionEvents: true,
156
+ selectedKeys: () => {
157
+ const key = access(options.selectedKey);
158
+ if (key === undefined) return access(options.selectedKeys);
159
+ return key === null ? [] : [key];
160
+ },
161
+ defaultSelectedKeys: () => {
162
+ const key = access(options.defaultSelectedKey);
163
+ if (key === undefined) return access(options.defaultSelectedKeys);
164
+ return key === null ? [] : [key];
165
+ },
166
+ onSelectionChange: (keys: SelectionValue) => {
167
+ if (keys !== "all") {
168
+ const first = keys.values().next().value ?? null;
169
+ options.onSelectionChange?.(mode() === "single" ? first : null);
170
+ }
171
+ options.onSelectionChangeAll?.(keys);
172
+ if (closesOnSelect()) overlay.close();
173
+ },
174
+ });
175
+
176
+ const selectedKey = (): Key | null => list.selectionManager().firstSelectedKey;
177
+
178
+ const selectedItems = (): Node<T>[] => {
179
+ const collection = list.collection();
180
+ const keys = list.selectionManager().selectedKeys;
181
+ const items: Node<T>[] = [];
182
+ for (const key of keys) {
183
+ const item = collection.getItem(key);
184
+ if (item !== null) items.push(item);
185
+ }
186
+ return items;
187
+ };
188
+
189
+ const setValue = (value: Key | Key[] | null): void => {
190
+ const keys = value === null ? [] : Array.isArray(value) ? value : [value];
191
+ list.selectionManager().setSelectedKeys(new Set(keys));
192
+ };
193
+
194
+ const value = (): Key | Key[] | null =>
195
+ mode() === "single" ? selectedKey() : [...list.selectionManager().selectedKeys];
196
+
197
+ // Read once: what a form reset goes back to is where it STARTED, not
198
+ // wherever the caller's default happens to point by then.
199
+ const initial = value();
200
+
201
+ const hasItems = (): boolean =>
202
+ list.collection().size !== 0 || access(options.allowsEmptyCollection) === true;
203
+
204
+ return {
205
+ ...list,
206
+ isOpen: overlay.isOpen,
207
+ setOpen: overlay.setOpen,
208
+ close: overlay.close,
209
+ selectedKey,
210
+ setSelectedKey: (key) => setValue(key),
211
+ selectedItem: () => selectedItems()[0] ?? null,
212
+ selectedItems,
213
+ value,
214
+ defaultValue: () => initial,
215
+ setValue,
216
+ isFocused,
217
+ setFocused: (next) => setIsFocused(next),
218
+ focusStrategy: strategy,
219
+ open(focusStrategy: FocusStrategy | null = null) {
220
+ if (!hasItems()) return;
221
+ setStrategy(focusStrategy);
222
+ overlay.open();
223
+ },
224
+ toggle(focusStrategy: FocusStrategy | null = null) {
225
+ if (!hasItems()) return;
226
+ setStrategy(focusStrategy);
227
+ overlay.toggle();
228
+ },
229
+ };
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Hooks
234
+ // ---------------------------------------------------------------------------
235
+
236
+ export interface SelectOptions extends FieldOptions {
237
+ ref: ElementRef;
238
+ isDisabled?: MaybeAccessor<boolean | undefined>;
239
+ isRequired?: MaybeAccessor<boolean | undefined>;
240
+ name?: MaybeAccessor<string | undefined>;
241
+ form?: MaybeAccessor<string | undefined>;
242
+ autoComplete?: MaybeAccessor<string | undefined>;
243
+ keyboardDelegate?: KeyboardDelegate;
244
+ /** What the page thinks of the choice, checked as it changes. */
245
+ validate?: ValidateFunction<Key | Key[] | null>;
246
+ /** @default "aria" */
247
+ validationBehavior?: MaybeAccessor<ValidationBehavior | undefined>;
248
+ }
249
+
250
+ export interface SelectResult {
251
+ labelProps: DOMProps;
252
+ triggerProps: DOMProps;
253
+ /** For the element showing what is currently chosen. */
254
+ valueProps: DOMProps;
255
+ listBoxProps: DOMProps;
256
+ descriptionProps: DOMProps;
257
+ errorMessageProps: DOMProps;
258
+ /** What is wrong with the choice, and whether the user is being told. */
259
+ validation: FormValidationState;
260
+ errors: Accessor<string[]>;
261
+ isInvalid: Accessor<boolean>;
262
+ /** The behaviour in force: the select's own, or the enclosing form's. */
263
+ validationBehavior: Accessor<ValidationBehavior | undefined>;
264
+ }
265
+
266
+ export function select(options: SelectOptions, state: SelectState<unknown>): SelectResult {
267
+ const valueId = id();
268
+ const triggerId = id();
269
+
270
+ const search = collator({ usage: "search", sensitivity: "base" });
271
+ const delegate =
272
+ options.keyboardDelegate ??
273
+ new ListKeyboardDelegate({
274
+ collection: state.collection,
275
+ ref: options.ref,
276
+ disabledKeys: state.disabledKeys,
277
+ collator: search,
278
+ });
279
+
280
+ // A select's trigger IS a menu trigger: it opens on pointer down, closes on
281
+ // the press that follows over an option, and ArrowDown/ArrowUp open it with
282
+ // an end focused. `SelectState` already has the shape that needs.
283
+ const { menuTriggerProps, menuProps } = menuTrigger(
284
+ { type: "listbox", isDisabled: options.isDisabled },
285
+ state,
286
+ );
287
+
288
+ const {
289
+ state: validation,
290
+ behavior,
291
+ isInvalid,
292
+ errors,
293
+ errorMessage,
294
+ } = fieldValidation<Key | Key[] | null>({
295
+ value: state.value,
296
+ validate: options.validate,
297
+ validationBehavior: options.validationBehavior,
298
+ isInvalid: options.isInvalid,
299
+ errorMessage: options.errorMessage,
300
+ name: options.name,
301
+ });
302
+
303
+ const { labelProps, fieldProps, descriptionProps, errorMessageProps } = field({
304
+ ...options,
305
+ isInvalid,
306
+ errorMessage,
307
+ // A `<button>` is not a labelable element, so the label is a `<span>` that
308
+ // points at it rather than a `<label>` that wraps it.
309
+ labelElementType: "span",
310
+ });
311
+
312
+ // Typing on the CLOSED button moves the selection, as a native select does.
313
+ const { typeSelectProps } = singleTypeSelect(delegate, state);
314
+
315
+ // With only an `aria-label`, the label lives on the trigger itself, and the
316
+ // value's id in `aria-labelledby` would replace it: the trigger joins the
317
+ // list so it keeps its own name.
318
+ const labelledBy = (): string | undefined => {
319
+ const given = access(fieldProps["aria-labelledby"] as MaybeAccessor<string | undefined>);
320
+ if (given !== undefined) return given;
321
+ return access(fieldProps["aria-label"] as MaybeAccessor<string | undefined>) === undefined
322
+ ? undefined
323
+ : triggerId();
324
+ };
325
+
326
+ /**
327
+ * Left and right step through the values WITHOUT opening.
328
+ *
329
+ * A native select does this, and it is the only way to change one from the
330
+ * keyboard without looking at the list.
331
+ */
332
+ const onKeyDown = (event: KeyboardEvent): void => {
333
+ if (access(options.isDisabled) === true) return;
334
+ if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
335
+ if (state.selectionManager().selectionMode === "multiple") return;
336
+
337
+ event.preventDefault();
338
+ const current = state.selectedKey();
339
+ const next =
340
+ current === null
341
+ ? (delegate.getFirstKey?.() ?? null)
342
+ : event.key === "ArrowLeft"
343
+ ? (delegate.getKeyAbove?.(current) ?? null)
344
+ : (delegate.getKeyBelow?.(current) ?? null);
345
+ if (next !== null) state.setSelectedKey(next);
346
+ };
347
+
348
+ return {
349
+ descriptionProps,
350
+ errorMessageProps,
351
+ validation,
352
+ errors,
353
+ isInvalid,
354
+ validationBehavior: behavior,
355
+ valueProps: { id: valueId },
356
+ labelProps: mergeProps(labelProps, {
357
+ // Clicking the label focuses the button, as it would a native control.
358
+ onClick: () => {
359
+ if (access(options.isDisabled) === true) return;
360
+ (access(options.ref) as HTMLElement | null)?.focus();
361
+ },
362
+ }),
363
+ triggerProps: mergeProps(
364
+ filterDOMProps(options, { labelable: true }),
365
+ menuTriggerProps,
366
+ fieldProps,
367
+ typeSelectProps,
368
+ {
369
+ id: triggerId,
370
+ onKeyDown,
371
+ "aria-invalid": () => isInvalid() || undefined,
372
+ "aria-required": () => access(options.isRequired) === true || undefined,
373
+ // The label FIRST and the value second: "Fruit, Banana", not "Banana".
374
+ "aria-labelledby": () => [labelledBy(), valueId()].filter(Boolean).join(" "),
375
+ onFocus: () => state.setFocused(true),
376
+ onBlur: () => {
377
+ // Focus inside the open popup is still focus on the select.
378
+ if (state.isOpen()) return;
379
+ state.setFocused(false);
380
+ validation.commitValidation();
381
+ },
382
+ },
383
+ ),
384
+ listBoxProps: {
385
+ id: menuProps.id,
386
+ "aria-labelledby": () => [labelledBy(), valueId()].filter(Boolean).join(" "),
387
+ autoFocus: () => state.focusStrategy() ?? true,
388
+ // A select's popup closes on choosing, so choosing on pointer DOWN would
389
+ // consume the press that opened it.
390
+ shouldSelectOnPressUp: true,
391
+ disallowEmptySelection: true,
392
+ linkBehavior: "selection",
393
+ },
394
+ };
395
+ }
396
+
397
+ /**
398
+ * Typing on the closed trigger, which picks the match as a native select does.
399
+ *
400
+ * Not in multiple selection, where picking the match would replace every
401
+ * other choice with it.
402
+ */
403
+ function singleTypeSelect(
404
+ delegate: KeyboardDelegate,
405
+ state: SelectState<unknown>,
406
+ ): { typeSelectProps: DOMProps } {
407
+ const { typeSelectProps } = typeSelect({
408
+ keyboardDelegate: delegate,
409
+ selectionManager: state.selectionManager,
410
+ onTypeSelect: (key) => state.setSelectedKey(key),
411
+ });
412
+ const isSingle = (): boolean => state.selectionManager().selectionMode !== "multiple";
413
+ const onKeyDown = typeSelectProps.onKeyDown as (event: KeyboardEvent) => void;
414
+ const onKeyDownCapture = typeSelectProps.onKeyDownCapture as (event: KeyboardEvent) => void;
415
+ return {
416
+ typeSelectProps: {
417
+ onKeyDown: (event: KeyboardEvent) => {
418
+ if (isSingle()) onKeyDown(event);
419
+ },
420
+ onKeyDownCapture: (event: KeyboardEvent) => {
421
+ if (isSingle()) onKeyDownCapture(event);
422
+ },
423
+ },
424
+ };
425
+ }
426
+
427
+ /**
428
+ * Whether a select's hidden control belongs in the page: with a `name`, with
429
+ * `form`, or inside a form, where a required select with no name still has to
430
+ * hold back a native submit and only a control in the form can.
431
+ *
432
+ * The form is looked for once the trigger is attached; at the moment its ref
433
+ * resolves it has no ancestors yet.
434
+ */
435
+ function hiddenControlPresence(
436
+ triggerRef: Accessor<HTMLElement | null>,
437
+ name: Accessor<string | undefined>,
438
+ form: Accessor<string | undefined>,
439
+ ): { isNeeded: Accessor<boolean>; placed: () => void } {
440
+ const [isInsideForm, setInsideForm] = createSignal(false);
441
+ return {
442
+ isNeeded: () => name() !== undefined || form() !== undefined || isInsideForm(),
443
+ placed: () => {
444
+ setInsideForm((triggerRef()?.closest("form") ?? null) !== null);
445
+ },
446
+ };
447
+ }
448
+
449
+ export interface HiddenSelectOptions {
450
+ selectRef: ElementRef<HTMLSelectElement>;
451
+ /**
452
+ * The visible button, which is where focus goes when the browser refuses a
453
+ * submit. The `<select>` this validates is clipped out of sight, so focusing
454
+ * it would move focus somewhere the user cannot see.
455
+ */
456
+ triggerRef: ElementRef;
457
+ name?: MaybeAccessor<string | undefined>;
458
+ form?: MaybeAccessor<string | undefined>;
459
+ autoComplete?: MaybeAccessor<string | undefined>;
460
+ isDisabled?: MaybeAccessor<boolean | undefined>;
461
+ isRequired?: MaybeAccessor<boolean | undefined>;
462
+ /** @default "aria" */
463
+ validationBehavior?: MaybeAccessor<ValidationBehavior | undefined>;
464
+ /** The select's validation state, so the browser and the page agree. */
465
+ validation?: FormValidationState;
466
+ }
467
+
468
+ export interface HiddenSelectResult {
469
+ containerProps: DOMProps;
470
+ selectProps: DOMProps;
471
+ }
472
+
473
+ /**
474
+ * A real `<select>`, clipped out of sight, so the form works.
475
+ *
476
+ * Hidden by clipping rather than by `display: none` or `hidden`: Safari will
477
+ * not autofill a control it considers invisible, and Firefox needs a `<label>`
478
+ * to identify one. `aria-hidden` on the container keeps it out of the
479
+ * accessibility tree, where the real button already stands for it, and
480
+ * `tabIndex={-1}` keeps it out of the Tab order.
481
+ */
482
+ export function hiddenSelect(
483
+ options: HiddenSelectOptions,
484
+ state: SelectState<unknown>,
485
+ ): HiddenSelectResult {
486
+ const { visuallyHiddenProps } = visuallyHidden();
487
+
488
+ formReset(
489
+ options.selectRef as unknown as ElementRef<HTMLInputElement>,
490
+ state.defaultValue,
491
+ (value) => state.setValue(value),
492
+ );
493
+
494
+ // The NATIVE half of validation, which only this element can carry: the
495
+ // `<select>` is the thing in the form, so it is the thing
496
+ // `setCustomValidity` has to be written onto and the thing the browser
497
+ // refuses the submit over. Focus goes to the visible button instead of to
498
+ // it, because a submit that focuses a clipped element looks like nothing
499
+ // happened.
500
+ if (options.validation !== undefined) {
501
+ formValidation(
502
+ {
503
+ validationBehavior: options.validationBehavior,
504
+ focus: () => (access(options.triggerRef) as HTMLElement | null)?.focus(),
505
+ },
506
+ options.validation,
507
+ options.selectRef,
508
+ );
509
+ }
510
+
511
+ // A `<select>` cannot hold a value its options do not offer, and the options
512
+ // are inserted after the element. Written again once they exist, and again
513
+ // whenever the collection changes.
514
+ createEffect(
515
+ () =>
516
+ [
517
+ access(options.selectRef) as HTMLSelectElement | null,
518
+ state.collection(),
519
+ state.value(),
520
+ ] as const,
521
+ ([element, , value]) => {
522
+ if (element === null) return;
523
+ const wanted =
524
+ value === null ? "" : Array.isArray(value) ? String(value[0] ?? "") : String(value);
525
+ if (element.multiple) {
526
+ const keys = new Set((Array.isArray(value) ? value : []).map(String));
527
+ for (const option of element.options) option.selected = keys.has(option.value);
528
+ return;
529
+ }
530
+ if (element.value !== wanted) element.value = wanted;
531
+ },
532
+ );
533
+
534
+ const onChange = (event: Event): void => {
535
+ const element = event.currentTarget as HTMLSelectElement;
536
+ if (element.multiple) {
537
+ state.setValue([...element.selectedOptions].map((option) => option.value));
538
+ } else {
539
+ state.setValue(element.value === "" ? null : element.value);
540
+ }
541
+ };
542
+
543
+ return {
544
+ containerProps: {
545
+ ...visuallyHiddenProps,
546
+ style: { ...(visuallyHiddenProps.style as object), position: "fixed", top: 0, left: 0 },
547
+ "aria-hidden": true,
548
+ [PREVENT_FOCUS_ATTRIBUTE]: true,
549
+ },
550
+ selectProps: {
551
+ tabIndex: -1,
552
+ autocomplete: () => access(options.autoComplete),
553
+ disabled: () => access(options.isDisabled) === true,
554
+ // Only a native select blocks the submit; under "aria" the page decides.
555
+ required: () =>
556
+ access(options.validationBehavior) === "native" && access(options.isRequired) === true,
557
+ multiple: () => state.selectionManager().selectionMode === "multiple",
558
+ name: () => access(options.name),
559
+ form: () => access(options.form),
560
+ value: () => {
561
+ const value = state.value();
562
+ if (value === null) return "";
563
+ return Array.isArray(value) ? value.map(String) : String(value);
564
+ },
565
+ onChange,
566
+ onInput: onChange,
567
+ },
568
+ };
569
+ }
570
+
571
+ // ---------------------------------------------------------------------------
572
+ // Components
573
+ // ---------------------------------------------------------------------------
574
+
575
+ function itemsOf<T>(collection: Collection<T>): Node<T>[] {
576
+ const items: Node<T>[] = [];
577
+ for (const key of collection.getKeys()) {
578
+ const node = collection.getItem(key);
579
+ if (node !== null && node.type === "item") items.push(node);
580
+ }
581
+ return items;
582
+ }
583
+
584
+ interface SelectContextValue {
585
+ state: SelectState<unknown>;
586
+ valueProps: DOMProps;
587
+ placeholder: Accessor<string | undefined>;
588
+ /** Present when the select is written as parts rather than built from `items`. */
589
+ parts?: SelectParts | undefined;
590
+ }
591
+
592
+ const SelectContext = createContext<SelectContextValue | null>(null);
593
+
594
+ export function useSelect(): SelectContextValue {
595
+ const value = getContext(SelectContext);
596
+ if (value === null || value === undefined) {
597
+ throw new Error("This must be rendered inside a Select.");
598
+ }
599
+ return value;
600
+ }
601
+
602
+ export interface SelectValueComponentProps extends StyleProps {
603
+ /** Shown in place of the chosen option's own content, once something is chosen. */
604
+ children?: Child;
605
+ /** Shown when nothing is chosen. @default the select's own `placeholder` */
606
+ placeholder?: string;
607
+ }
608
+
609
+ /** Marks the part of an option that the trigger shows when it is chosen. */
610
+ const ITEM_TEXT_ATTRIBUTE = "data-barq-item-text";
611
+
612
+ /**
613
+ * What is currently chosen, or the placeholder.
614
+ *
615
+ * The element it renders is what `aria-labelledby` on the trigger points at,
616
+ * so a select whose value is an icon still announces something.
617
+ *
618
+ * An option written as a child may hold more than text, and what it holds is
619
+ * shown here as it is drawn there: a COPY of its {@link SelectItemText}, since
620
+ * one node cannot be in the list and in the trigger at once.
621
+ */
622
+ export function SelectValue(props: SelectValueComponentProps) {
623
+ const picker = useSelect();
624
+ const placeholder = (): string => props.placeholder ?? picker.placeholder() ?? "";
625
+
626
+ const elementProps = mergeProps(
627
+ picker.valueProps,
628
+ filterDOMProps(fromProps(cells(props)), { global: true }),
629
+ styleProps(cells(props)),
630
+ {
631
+ "data-placeholder": () => picker.state.selectedItem() === null,
632
+ "data-testid": () => props["data-testid"],
633
+ },
634
+ );
635
+
636
+ const chosen = (): Child => {
637
+ const selected = picker.state.selectedItem();
638
+ if (selected === null) return placeholder();
639
+ const drawn = picker.parts?.registry
640
+ .elementOf(selected.key)
641
+ ?.querySelector(`[${ITEM_TEXT_ATTRIBUTE}]`);
642
+ if (drawn === null || drawn === undefined || drawn.children.length === 0) {
643
+ return selected.textValue;
644
+ }
645
+ return [...drawn.childNodes].map((node) => node.cloneNode(true));
646
+ };
647
+
648
+ if (props.children === undefined) {
649
+ return (
650
+ <span {...elementProps} ref={picker.parts?.valueRef.set}>
651
+ {chosen}
652
+ </span>
653
+ );
654
+ }
655
+
656
+ return (
657
+ <span {...elementProps} ref={picker.parts?.valueRef.set}>
658
+ <Show when={picker.state.selectedItem() !== null} fallback={<>{placeholder()}</>}>
659
+ {props.children}
660
+ </Show>
661
+ </span>
662
+ );
663
+ }
664
+
665
+ export interface SelectComponentProps<T> extends StyleProps, ItemAccessors<T> {
666
+ /** The values to choose between, in order. */
667
+ items: Iterable<T>;
668
+ /** How one value renders. Return an `<Option>`. */
669
+ children: (item: T) => Child;
670
+ label?: Child;
671
+ description?: Child;
672
+ errorMessage?: Child;
673
+ /** Shown when nothing is chosen. */
674
+ placeholder?: string;
675
+ selectedKey?: Key | null;
676
+ defaultSelectedKey?: Key | null;
677
+ /** @default "single" */
678
+ selectionMode?: "single" | "multiple";
679
+ /** Every chosen key, for a multiple select. */
680
+ selectedKeys?: Iterable<Key>;
681
+ defaultSelectedKeys?: Iterable<Key>;
682
+ disabledKeys?: Iterable<Key>;
683
+ isOpen?: boolean;
684
+ defaultOpen?: boolean;
685
+ isDisabled?: boolean;
686
+ isRequired?: boolean;
687
+ isInvalid?: boolean;
688
+ /** What the page thinks of the choice, checked as it changes. */
689
+ validate?: ValidateFunction<Key | Key[] | null>;
690
+ /** @default "aria" */
691
+ validationBehavior?: ValidationBehavior;
692
+ /**
693
+ * Submitted with the form. Without it, the hidden control is rendered only
694
+ * inside a form or with `form`, where it still carries `isRequired`.
695
+ */
696
+ name?: string;
697
+ form?: string;
698
+ autoComplete?: string;
699
+ /** @default "bottom start" */
700
+ placement?: Placement;
701
+ /**
702
+ * The class for the LIST, inside the popover.
703
+ *
704
+ * `class` styles the trigger, which is the element a caller can see. The list
705
+ * is built inside a popover this component owns, so without this it could
706
+ * only be reached by a global rule — and a design system has to be able to
707
+ * draw the box the options sit in.
708
+ */
709
+ listClass?: string;
710
+ /**
711
+ * The `data-slot` for that same list.
712
+ *
713
+ * `select-list` is what it says by default, and a design system naming the
714
+ * element after its own vocabulary — shadcn calls it the select CONTENT —
715
+ * could otherwise only reach it through a global rule that every select on
716
+ * the page would share.
717
+ */
718
+ listSlot?: string;
719
+ "aria-label"?: string;
720
+ "aria-labelledby"?: string;
721
+ ref?: RefTarget<HTMLButtonElement>;
722
+ onSelectionChange?: (key: Key | null) => void;
723
+ /** Every chosen key, for a multiple select. */
724
+ onSelectionChangeAll?: (keys: SelectionValue) => void;
725
+ onOpenChange?: (isOpen: boolean) => void;
726
+ }
727
+
728
+ /**
729
+ * ```tsx
730
+ * <Select label="Fruit" items={fruits()} placeholder="Pick one"
731
+ * onSelectionChange={(key) => chosen.set(key)}>
732
+ * {(fruit) => <Option>{fruit.name}</Option>}
733
+ * </Select>
734
+ * ```
735
+ */
736
+ export function Select<T>(props: SelectComponentProps<T>) {
737
+ const triggerRef = makeRef<HTMLButtonElement>();
738
+ const listRef = makeRef<HTMLUListElement>();
739
+ const selectRef = makeRef<HTMLSelectElement>();
740
+ const options = fromProps(cells(props) as unknown as Incoming<Record<string, unknown>>);
741
+
742
+ const state = selectState<T>({
743
+ ...(options as SelectStateOptions<T>),
744
+ onSelectionChange: (key) => props.onSelectionChange?.(key),
745
+ });
746
+
747
+ const {
748
+ labelProps,
749
+ triggerProps,
750
+ valueProps,
751
+ listBoxProps: listBoxOptions,
752
+ descriptionProps,
753
+ errorMessageProps,
754
+ errors,
755
+ isInvalid,
756
+ validation,
757
+ validationBehavior,
758
+ } = select(
759
+ {
760
+ ...(options as unknown as SelectOptions),
761
+ ref: triggerRef,
762
+ validate: callback(cells(props).validate),
763
+ validationBehavior: () => props.validationBehavior,
764
+ },
765
+ state,
766
+ );
767
+
768
+ const { buttonProps, isPressed } = button(
769
+ { ...(options as ButtonOptions), ...triggerProps },
770
+ triggerRef,
771
+ );
772
+ const { hoverProps, isHovered } = hover({ isDisabled: () => props.isDisabled });
773
+ const { focusProps, isFocusVisible } = focusRing();
774
+
775
+ const buttonElementProps = mergeProps(
776
+ buttonProps,
777
+ // `id` only: every handler in `triggerProps` is already a `button` option,
778
+ // and binding them here as well would run each one twice — two toggles
779
+ // for one ArrowDown, which is no toggle at all.
780
+ { id: triggerProps.id },
781
+ hoverProps,
782
+ focusProps,
783
+ filterDOMProps(options, { global: true }),
784
+ styleProps(cells(props)),
785
+ {
786
+ "data-pressed": isPressed,
787
+ "data-hovered": isHovered,
788
+ "data-focus-visible": isFocusVisible,
789
+ "data-open": state.isOpen,
790
+ "data-state": () => (state.isOpen() ? "open" : "closed"),
791
+ "data-disabled": () => props.isDisabled === true,
792
+ "data-placeholder": () => state.selectedItem() === null,
793
+ "data-invalid": isInvalid,
794
+ "data-testid": () => props["data-testid"],
795
+ },
796
+ );
797
+
798
+ const { containerProps, selectProps } = hiddenSelect(
799
+ {
800
+ selectRef,
801
+ triggerRef,
802
+ name: () => props.name,
803
+ form: () => props.form,
804
+ autoComplete: () => props.autoComplete,
805
+ isDisabled: () => props.isDisabled,
806
+ isRequired: () => props.isRequired,
807
+ validationBehavior,
808
+ validation,
809
+ },
810
+ state,
811
+ );
812
+
813
+ const formControl = hiddenControlPresence(
814
+ triggerRef,
815
+ () => props.name,
816
+ () => props.form,
817
+ );
818
+ onSettled(formControl.placed);
819
+
820
+ const renderOption = props.children;
821
+
822
+ const owner = getOwner();
823
+ if (owner !== null) {
824
+ install(owner, SelectContext, () => ({
825
+ state: state as unknown as SelectState<unknown>,
826
+ valueProps,
827
+ placeholder: () => props.placeholder,
828
+ }));
829
+ }
830
+
831
+ return (
832
+ <>
833
+ <span {...labelProps}>{props.label}</span>
834
+ <button {...buttonElementProps} ref={mergeRefs(triggerRef.set, props.ref)}>
835
+ <SelectValue />
836
+ </button>
837
+ <Show when={formControl.isNeeded()}>
838
+ <div {...containerProps}>
839
+ <label>
840
+ {/* Text only: an element can be in one place, and it belongs in
841
+ the visible label that names the trigger. */}
842
+ {() => (typeof props.label === "string" ? props.label : null)}
843
+ <select {...selectProps} ref={selectRef.set}>
844
+ <option value="" label="&nbsp;" />
845
+ {/* Every item, whichever section holds it: the top level of a
846
+ sectioned collection is its sections. */}
847
+ <For each={() => itemsOf(state.collection())}>
848
+ {(node: Node<T>) => <option value={String(node.key)}>{node.textValue}</option>}
849
+ </For>
850
+ </select>
851
+ </label>
852
+ </div>
853
+ </Show>
854
+ <Popover
855
+ triggerRef={triggerRef}
856
+ isOpen={state.isOpen()}
857
+ onOpenChange={state.setOpen}
858
+ placement={props.placement ?? "bottom start"}
859
+ >
860
+ <SelectList
861
+ options={listBoxOptions}
862
+ ariaLabel={props["aria-label"]}
863
+ listClass={props.listClass}
864
+ listSlot={props.listSlot}
865
+ state={state}
866
+ listRef={listRef}
867
+ render={renderOption as unknown as (item: unknown) => Child}
868
+ />
869
+ </Popover>
870
+ <span {...descriptionProps}>{props.description}</span>
871
+ <span {...errorMessageProps}>
872
+ {() => {
873
+ const given = props.errorMessage;
874
+ if (given !== undefined && given !== null && given !== "") return given;
875
+ const found = errors();
876
+ return found.length === 0 ? null : found.join(" ");
877
+ }}
878
+ </span>
879
+ </>
880
+ );
881
+ }
882
+
883
+ interface SelectListProps {
884
+ options: DOMProps;
885
+ ariaLabel?: string;
886
+ listClass?: string;
887
+ listSlot?: string;
888
+ state: SelectState<unknown>;
889
+ listRef: ReturnType<typeof makeRef<HTMLUListElement>>;
890
+ render: (item: unknown) => Child;
891
+ }
892
+
893
+ /**
894
+ * The listbox inside the popover.
895
+ *
896
+ * Its own component so it is a Block, and the `listBox` hook is called HERE
897
+ * rather than in `Select`: the autofocus is read once, at construction, so
898
+ * reading it before the popover opened would always find the strategy unset
899
+ * and land focus on the list instead of on an option.
900
+ */
901
+ function SelectList(props: SelectListProps) {
902
+ const state = props.state;
903
+ const listRef = props.listRef;
904
+ const render = props.render;
905
+ const options = props.options;
906
+
907
+ const { listBoxProps, baseId } = listBox(
908
+ {
909
+ ...(options as unknown as Record<string, MaybeAccessor<never>>),
910
+ ref: listRef,
911
+ "aria-label": cells(props).ariaLabel,
912
+ },
913
+ state,
914
+ );
915
+
916
+ const elementProps = mergeProps(listBoxProps, popoverStateProps(), {
917
+ id: options.id,
918
+ "aria-labelledby": options["aria-labelledby"],
919
+ class: cells(props).listClass,
920
+ "data-slot": () => props.listSlot ?? "select-list",
921
+ });
922
+
923
+ provideItemRender(render);
924
+
925
+ return (
926
+ <ListBoxProvider
927
+ value={{
928
+ state: state as unknown as ListState<unknown>,
929
+ baseId,
930
+ shouldSelectOnPressUp: () => true,
931
+ shouldUseVirtualFocus: () => undefined,
932
+ }}
933
+ >
934
+ <ul {...elementProps} ref={listRef.set}>
935
+ <For each={() => [...state.collection()]}>
936
+ {(node: Node<unknown>) => {
937
+ provideItemNode(node);
938
+ return render(node.value);
939
+ }}
940
+ </For>
941
+ </ul>
942
+ </ListBoxProvider>
943
+ );
944
+ }
945
+
946
+ // ---------------------------------------------------------------------------
947
+ // Written as parts
948
+ // ---------------------------------------------------------------------------
949
+
950
+ /**
951
+ * The same select, written out: a root that holds the state, a trigger, and a
952
+ * content whose `<Option>` children are the collection.
953
+ *
954
+ * ```tsx
955
+ * <SelectRoot defaultSelectedKey="apple" name="fruit">
956
+ * <SelectTrigger><SelectValue placeholder="Pick one" /></SelectTrigger>
957
+ * <SelectContent>
958
+ * <SelectViewport>
959
+ * <Option value="apple"><SelectItemText>Apple</SelectItemText></Option>
960
+ * <Option value="banana"><SelectItemText>Banana</SelectItemText></Option>
961
+ * </SelectViewport>
962
+ * </SelectContent>
963
+ * </SelectRoot>
964
+ * ```
965
+ *
966
+ * Three decisions differ from {@link Select}, and each follows from the
967
+ * options being written rather than given:
968
+ *
969
+ * - **The options exist before the list opens.** A written option registers
970
+ * when it renders, and a closed list renders nothing, so the trigger would
971
+ * have no text for its value and a typed letter nothing to match. While the
972
+ * list is closed its content is therefore built into an element that is
973
+ * never put in the document: the options register from there, nothing is
974
+ * exposed to a screen reader or a selector, and the copy is dropped once the
975
+ * real list has taken its place.
976
+ * - **The trigger is a combobox.** It is named by its label alone, and what is
977
+ * chosen is its value rather than part of its name, which is the select-only
978
+ * combobox pattern and what a `<label for>` expects of the control it names.
979
+ * - **The form control follows the form.** The hidden `<select>` is rendered
980
+ * whenever there is a `name` or a form around the trigger, so `isRequired`
981
+ * holds a submit back with or without a name.
982
+ */
983
+
984
+ interface SelectParts {
985
+ registry: StaticCollection;
986
+ triggerRef: ReturnType<typeof makeRef<HTMLButtonElement>>;
987
+ valueRef: ReturnType<typeof makeRef<HTMLSpanElement>>;
988
+ /** Options for {@link button}. */
989
+ triggerProps: DOMProps;
990
+ /** What the trigger's element carries beyond what `button` writes. */
991
+ comboboxProps: DOMProps;
992
+ /** Options for the content's {@link listBox}. */
993
+ listBoxProps: DOMProps;
994
+ baseId: Accessor<string>;
995
+ isDisabled: Accessor<boolean>;
996
+ isInvalid: Accessor<boolean>;
997
+ dir: Accessor<"ltr" | "rtl" | undefined>;
998
+ /** The trigger is in the document, so what is around it can be read. */
999
+ placed: () => void;
1000
+ }
1001
+
1002
+ function useSelectParts(part: string): SelectContextValue & { parts: SelectParts } {
1003
+ const picker = useSelect();
1004
+ if (picker.parts === undefined) {
1005
+ throw new Error(`A ${part} must be rendered inside a SelectRoot.`);
1006
+ }
1007
+ return picker as SelectContextValue & { parts: SelectParts };
1008
+ }
1009
+
1010
+ export interface SelectTriggerOptions {
1011
+ ref: ElementRef;
1012
+ isDisabled?: MaybeAccessor<boolean | undefined>;
1013
+ isRequired?: MaybeAccessor<boolean | undefined>;
1014
+ keyboardDelegate?: KeyboardDelegate;
1015
+ }
1016
+
1017
+ export interface SelectTriggerResult {
1018
+ /** Options for {@link button}, not props for an element. */
1019
+ triggerProps: DOMProps;
1020
+ /** What the element carries on top of what `button` writes. */
1021
+ comboboxProps: DOMProps;
1022
+ /** Options for the {@link listBox} the trigger opens. */
1023
+ listBoxProps: DOMProps;
1024
+ }
1025
+
1026
+ /**
1027
+ * A select's trigger as a select-only combobox.
1028
+ *
1029
+ * {@link select} names its button by the label AND the value, which suits a
1030
+ * `<span>` label it wires up itself. This one leaves the name to whatever
1031
+ * labels the element: a `<label for>` or an `aria-label` names a combobox, and
1032
+ * an `aria-labelledby` written here would override both.
1033
+ *
1034
+ * Space, Enter and the vertical arrows open the list, and a typed letter
1035
+ * changes the value without opening, as a native select does.
1036
+ */
1037
+ export function selectTrigger(
1038
+ options: SelectTriggerOptions,
1039
+ state: SelectState<unknown>,
1040
+ ): SelectTriggerResult {
1041
+ const search = collator({ usage: "search", sensitivity: "base" });
1042
+ const delegate =
1043
+ options.keyboardDelegate ??
1044
+ new ListKeyboardDelegate({
1045
+ collection: state.collection,
1046
+ ref: options.ref,
1047
+ disabledKeys: state.disabledKeys,
1048
+ collator: search,
1049
+ });
1050
+
1051
+ const { menuTriggerProps, menuProps } = menuTrigger(
1052
+ { type: "listbox", isDisabled: options.isDisabled },
1053
+ state,
1054
+ );
1055
+
1056
+ const { typeSelectProps } = singleTypeSelect(delegate, state);
1057
+
1058
+ return {
1059
+ triggerProps: mergeProps(
1060
+ menuTriggerProps,
1061
+ { onKeyDown: typeSelectProps.onKeyDown },
1062
+ {
1063
+ "aria-required": () => access(options.isRequired) === true || undefined,
1064
+ onFocus: () => state.setFocused(true),
1065
+ onBlur: () => {
1066
+ // Focus inside the open popup is still focus on the select.
1067
+ if (!state.isOpen()) state.setFocused(false);
1068
+ },
1069
+ },
1070
+ ),
1071
+ comboboxProps: {
1072
+ id: menuTriggerProps.id,
1073
+ role: "combobox",
1074
+ "aria-autocomplete": "none",
1075
+ onKeyDownCapture: typeSelectProps.onKeyDownCapture,
1076
+ },
1077
+ listBoxProps: {
1078
+ id: menuProps.id,
1079
+ "aria-labelledby": menuTriggerProps.id,
1080
+ autoFocus: () => state.focusStrategy() ?? true,
1081
+ // A select's popup closes on choosing, so choosing on pointer DOWN would
1082
+ // consume the press that opened it.
1083
+ shouldSelectOnPressUp: true,
1084
+ disallowEmptySelection: true,
1085
+ linkBehavior: "selection",
1086
+ },
1087
+ };
1088
+ }
1089
+
1090
+ export interface SelectRootComponentProps {
1091
+ /** A `<SelectTrigger>` and a `<SelectContent>`, and anything around them. */
1092
+ children?: Child;
1093
+ selectedKey?: Key | null;
1094
+ defaultSelectedKey?: Key | null;
1095
+ isOpen?: boolean;
1096
+ defaultOpen?: boolean;
1097
+ isDisabled?: boolean;
1098
+ isRequired?: boolean;
1099
+ /** Submitted with the form. */
1100
+ name?: string;
1101
+ form?: string;
1102
+ autoComplete?: string;
1103
+ /** The reading direction of the trigger and the list, when it is not the page's. */
1104
+ dir?: "ltr" | "rtl";
1105
+ onSelectionChange?: (key: Key | null) => void;
1106
+ onOpenChange?: (isOpen: boolean) => void;
1107
+ }
1108
+
1109
+ /** The state of a select written as parts. Renders no element of its own. */
1110
+ export function SelectRoot(props: SelectRootComponentProps) {
1111
+ const triggerRef = makeRef<HTMLButtonElement>();
1112
+ const valueRef = makeRef<HTMLSpanElement>();
1113
+ const selectRef = makeRef<HTMLSelectElement>();
1114
+ const registry = staticCollection();
1115
+ const baseId = id();
1116
+ const isDisabled = (): boolean => props.isDisabled === true;
1117
+
1118
+ const state = selectState<StaticEntry>({
1119
+ items: registry.entries,
1120
+ ...staticAccessors,
1121
+ selectedKey: () => props.selectedKey,
1122
+ defaultSelectedKey: () => props.defaultSelectedKey,
1123
+ isOpen: () => props.isOpen,
1124
+ defaultOpen: () => props.defaultOpen,
1125
+ onOpenChange: (isOpen) => props.onOpenChange?.(isOpen),
1126
+ onSelectionChange: (key) => props.onSelectionChange?.(key),
1127
+ }) as unknown as SelectState<unknown>;
1128
+
1129
+ const { triggerProps, comboboxProps, listBoxProps } = selectTrigger(
1130
+ { ref: triggerRef, isDisabled, isRequired: () => props.isRequired },
1131
+ state,
1132
+ );
1133
+
1134
+ // The browser's own verdict on the hidden control, shown on the trigger: a
1135
+ // required select with nothing chosen refuses the submit, and the refusal
1136
+ // has to land on something the user can see.
1137
+ const { state: validation, isInvalid } = fieldValidation<Key | Key[] | null>({
1138
+ value: state.value,
1139
+ validationBehavior: "native",
1140
+ name: () => props.name,
1141
+ });
1142
+
1143
+ // The hidden control's options, written onto it rather than rendered into
1144
+ // it. They exist on the client only, where the written options register, so
1145
+ // a list rendered here would be one the server's markup does not have and a
1146
+ // hydrating page would report every row of it. Before `hiddenSelect`, whose
1147
+ // own effect writes the value and needs the option it names to be there.
1148
+ createEffect(
1149
+ () => [selectRef(), state.collection()] as const,
1150
+ ([element, collection]) => {
1151
+ if (element === null) return;
1152
+ while (element.options.length > 1) element.remove(1);
1153
+ // By key rather than by walking the top level, which holds the GROUPS: a
1154
+ // native `<select>` wants every option, whichever group it was written in.
1155
+ for (const node of itemsOf(collection)) {
1156
+ const option = element.ownerDocument.createElement("option");
1157
+ option.value = String(node.key);
1158
+ option.textContent = node.textValue;
1159
+ element.append(option);
1160
+ }
1161
+ },
1162
+ );
1163
+
1164
+ const { containerProps, selectProps } = hiddenSelect(
1165
+ {
1166
+ selectRef,
1167
+ triggerRef,
1168
+ name: () => props.name,
1169
+ form: () => props.form,
1170
+ autoComplete: () => props.autoComplete,
1171
+ isDisabled,
1172
+ isRequired: () => props.isRequired,
1173
+ validationBehavior: "native",
1174
+ validation,
1175
+ },
1176
+ state,
1177
+ );
1178
+
1179
+ const formControl = hiddenControlPresence(
1180
+ triggerRef,
1181
+ () => props.name,
1182
+ () => props.form,
1183
+ );
1184
+
1185
+ const value: SelectContextValue = {
1186
+ state,
1187
+ valueProps: {},
1188
+ placeholder: () => undefined,
1189
+ parts: {
1190
+ registry,
1191
+ triggerRef,
1192
+ valueRef,
1193
+ triggerProps,
1194
+ comboboxProps,
1195
+ listBoxProps,
1196
+ baseId,
1197
+ isDisabled,
1198
+ isInvalid,
1199
+ dir: () => props.dir,
1200
+ placed: formControl.placed,
1201
+ },
1202
+ };
1203
+
1204
+ return (
1205
+ <>
1206
+ {
1207
+ provide(
1208
+ SelectContext,
1209
+ () => value,
1210
+ () => props.children as unknown,
1211
+ ) as Child
1212
+ }
1213
+ <Show when={formControl.isNeeded()}>
1214
+ <div {...containerProps}>
1215
+ <select {...selectProps} ref={selectRef.set}>
1216
+ <option value="" label="&nbsp;" />
1217
+ </select>
1218
+ </div>
1219
+ </Show>
1220
+ </>
1221
+ );
1222
+ }
1223
+
1224
+ export interface SelectTriggerComponentProps extends StyleProps {
1225
+ /** A `<SelectValue>`, and whatever sits beside it. */
1226
+ children?: Child;
1227
+ id?: string;
1228
+ isDisabled?: boolean;
1229
+ "aria-label"?: string;
1230
+ "aria-labelledby"?: string;
1231
+ "aria-describedby"?: string;
1232
+ "aria-invalid"?: boolean | "true" | "false";
1233
+ ref?: RefTarget<HTMLButtonElement>;
1234
+ }
1235
+
1236
+ /** The control that shows the value and opens the list. */
1237
+ export function SelectTrigger(props: SelectTriggerComponentProps) {
1238
+ const picker = useSelectParts("SelectTrigger");
1239
+ const { parts, state } = picker;
1240
+ const isDisabled = (): boolean => parts.isDisabled() || props.isDisabled === true;
1241
+ const isInvalid = (): boolean => {
1242
+ const given = props["aria-invalid"];
1243
+ return given === undefined ? parts.isInvalid() : given === true || given === "true";
1244
+ };
1245
+
1246
+ const options = fromProps(cells(props));
1247
+ const { buttonProps, isPressed } = button(
1248
+ {
1249
+ ...(parts.triggerProps as ButtonOptions),
1250
+ isDisabled,
1251
+ "aria-label": () => props["aria-label"],
1252
+ "aria-labelledby": () => props["aria-labelledby"],
1253
+ "aria-describedby": () => props["aria-describedby"],
1254
+ "aria-invalid": isInvalid,
1255
+ },
1256
+ parts.triggerRef,
1257
+ );
1258
+ const { hoverProps, isHovered } = hover({ isDisabled });
1259
+ const { focusProps, isFocusVisible } = focusRing();
1260
+
1261
+ onSettled(parts.placed);
1262
+
1263
+ const elementProps = mergeProps(
1264
+ buttonProps,
1265
+ parts.comboboxProps,
1266
+ hoverProps,
1267
+ focusProps,
1268
+ filterDOMProps(options, { global: true }),
1269
+ styleProps(cells(props)),
1270
+ {
1271
+ // A caller's `id` is what a `<label for>` points at, and it wins.
1272
+ id: () => props.id ?? access(parts.comboboxProps.id as MaybeAccessor<string>),
1273
+ dir: () => parts.dir(),
1274
+ "data-state": () => (state.isOpen() ? "open" : "closed"),
1275
+ "data-open": state.isOpen,
1276
+ "data-pressed": isPressed,
1277
+ "data-hovered": isHovered,
1278
+ "data-focus-visible": isFocusVisible,
1279
+ "data-disabled": isDisabled,
1280
+ "data-placeholder": () => state.selectedItem() === null,
1281
+ "data-invalid": isInvalid,
1282
+ "data-testid": () => props["data-testid"],
1283
+ },
1284
+ );
1285
+
1286
+ return (
1287
+ <button {...elementProps} ref={mergeRefs(parts.triggerRef.set, props.ref)}>
1288
+ {props.children}
1289
+ </button>
1290
+ );
1291
+ }
1292
+
1293
+ /** A box in client coordinates. */
1294
+ interface Box {
1295
+ top: number;
1296
+ left: number;
1297
+ width: number;
1298
+ height: number;
1299
+ }
1300
+
1301
+ export interface ItemAlignmentBoxes {
1302
+ trigger: Box;
1303
+ /** The trigger's value element, whose text the option's is laid over. */
1304
+ value: Box | null;
1305
+ /** The list's own box, wherever it currently is. */
1306
+ content: Box;
1307
+ /** The chosen option, in the same coordinates as `content`. */
1308
+ item: Box;
1309
+ /** The part of the option that holds its text. */
1310
+ itemText: Box | null;
1311
+ /** The viewport the list has to stay inside. */
1312
+ boundary: { width: number; height: number };
1313
+ /** How far from the viewport's edges it must stay. @default 12 */
1314
+ padding?: number;
1315
+ /** @default "ltr" */
1316
+ direction?: "ltr" | "rtl";
1317
+ }
1318
+
1319
+ /**
1320
+ * Where a list goes so that its chosen option lies over the trigger.
1321
+ *
1322
+ * The answer is in the terms {@link Popover} takes for a `"bottom start"`
1323
+ * placement: `offset` from the trigger's bottom edge and `crossOffset` from
1324
+ * its inline-start edge. `null` means the list would leave the viewport, and
1325
+ * the caller places it as an ordinary popover instead.
1326
+ *
1327
+ * Vertically the option is CENTRED on the trigger, so the two need not be the
1328
+ * same height. Horizontally the option's text starts where the value's does,
1329
+ * which is what makes the list read as the trigger unfolding.
1330
+ */
1331
+ export function itemAlignedPosition(
1332
+ boxes: ItemAlignmentBoxes,
1333
+ ): { offset: number; crossOffset: number } | null {
1334
+ const { trigger, content, item, boundary } = boxes;
1335
+ const padding = boxes.padding ?? 12;
1336
+ const value = boxes.value ?? trigger;
1337
+ const text = boxes.itemText ?? item;
1338
+
1339
+ const itemCentre = item.top - content.top + item.height / 2;
1340
+ const top = trigger.top + trigger.height / 2 - itemCentre;
1341
+ if (top < padding || top + content.height > boundary.height - padding) return null;
1342
+
1343
+ const left =
1344
+ boxes.direction === "rtl"
1345
+ ? value.left + value.width - (text.left + text.width - content.left)
1346
+ : value.left - (text.left - content.left);
1347
+ if (left < padding || left + content.width > boundary.width - padding) return null;
1348
+
1349
+ const start =
1350
+ boxes.direction === "rtl" ? trigger.left + trigger.width - content.width : trigger.left;
1351
+ return { offset: top - (trigger.top + trigger.height), crossOffset: left - start };
1352
+ }
1353
+
1354
+ interface SelectContentValue {
1355
+ /**
1356
+ * Built off the page so the options register, with nothing to place, scroll
1357
+ * or focus.
1358
+ */
1359
+ isRegistering: boolean;
1360
+ viewportRef: ReturnType<typeof makeRef<HTMLUListElement>>;
1361
+ canScrollUp: Accessor<boolean>;
1362
+ canScrollDown: Accessor<boolean>;
1363
+ /** Re-read how far the viewport can scroll. */
1364
+ measure: () => void;
1365
+ /** The real list is in place, or has gone. */
1366
+ mounted: (isMounted: boolean) => void;
1367
+ ariaLabel: Accessor<string | undefined>;
1368
+ ariaLabelledBy: Accessor<string | undefined>;
1369
+ }
1370
+
1371
+ const SelectContentContext = createContext<SelectContentValue | null>(null);
1372
+
1373
+ function useSelectContent(part: string): SelectContentValue {
1374
+ const value = getContext(SelectContentContext);
1375
+ if (value === null || value === undefined) {
1376
+ throw new Error(`A ${part} must be rendered inside a SelectContent.`);
1377
+ }
1378
+ return value;
1379
+ }
1380
+
1381
+ function SelectContentProvider(props: { value: SelectContentValue; children?: Child }) {
1382
+ return provide(
1383
+ SelectContentContext,
1384
+ () => props.value,
1385
+ () => props.children as unknown,
1386
+ );
1387
+ }
1388
+
1389
+ export type SelectPosition = "item-aligned" | "popper";
1390
+
1391
+ export interface SelectContentComponentProps extends StyleProps {
1392
+ /** A `<SelectViewport>`, and the scroll buttons either side of it. */
1393
+ children?: Child;
1394
+ /** The box the list is drawn in, which `class` and `style` land on. */
1395
+ ref?: RefTarget<HTMLDivElement>;
1396
+ /**
1397
+ * `"item-aligned"` lays the list over the trigger with the chosen option on
1398
+ * top of it, where that fits; `"popper"` hangs it off the trigger's edge.
1399
+ *
1400
+ * @default "popper"
1401
+ */
1402
+ position?: SelectPosition;
1403
+ /** Where a popper list goes, and an item-aligned one that does not fit. @default "bottom start" */
1404
+ placement?: Placement;
1405
+ /** @default 8 */
1406
+ offset?: number;
1407
+ crossOffset?: number;
1408
+ "aria-label"?: string;
1409
+ "aria-labelledby"?: string;
1410
+ }
1411
+
1412
+ function clientBox(element: Element): Box {
1413
+ const rect = element.getBoundingClientRect();
1414
+ return { top: rect.top, left: rect.left, width: rect.width, height: rect.height };
1415
+ }
1416
+
1417
+ /** The box of an element that has one: a `display: contents` wrapper does not. */
1418
+ function laidOutBox(element: Element | null): Box | null {
1419
+ if (element === null) return null;
1420
+ const box = clientBox(element);
1421
+ return box.width === 0 && box.height === 0 ? null : box;
1422
+ }
1423
+
1424
+ /**
1425
+ * The popover the list opens in, and the box a design system draws.
1426
+ *
1427
+ * The listbox itself is the {@link SelectViewport} inside, so the scroll
1428
+ * buttons beside it are not children of a `role="listbox"`.
1429
+ */
1430
+ export function SelectContent(props: SelectContentComponentProps) {
1431
+ const { parts, state } = useSelectParts("SelectContent");
1432
+ const locale = useLocale();
1433
+ const viewportRef = makeRef<HTMLUListElement>();
1434
+ const contentRef = makeRef<HTMLDivElement>();
1435
+
1436
+ // Nothing is in the holder's document, so nothing in it is exposed, matched
1437
+ // by a selector or reachable by focus. A server has no document to make it
1438
+ // from and builds no portal either, so the same markup is written with or
1439
+ // without one and the client claims it unchanged.
1440
+ const holder = typeof document === "undefined" ? undefined : document.createElement("div");
1441
+
1442
+ const [isMounted, setMounted] = createSignal(false, { ownedWrite: true });
1443
+ const [edges, setEdges] = createSignal({ up: false, down: false });
1444
+ const [aligned, setAligned] = createSignal<{ offset: number; crossOffset: number } | null>(null);
1445
+
1446
+ const measure = (): void => {
1447
+ const viewport = viewportRef();
1448
+ if (viewport === null) return;
1449
+ const up = viewport.scrollTop > 0;
1450
+ const down = Math.ceil(viewport.scrollTop) < viewport.scrollHeight - viewport.clientHeight;
1451
+ const current = edges();
1452
+ if (current.up !== up || current.down !== down) setEdges({ up, down });
1453
+ };
1454
+
1455
+ const align = (): void => {
1456
+ if (props.position !== "item-aligned") return;
1457
+ const trigger = parts.triggerRef();
1458
+ const content = contentRef();
1459
+ const key = state.selectedKey();
1460
+ const item = key === null ? null : parts.registry.elementOf(key);
1461
+ if (trigger === null || content === null || item === null) return;
1462
+
1463
+ const view = trigger.ownerDocument.defaultView;
1464
+ setAligned(
1465
+ itemAlignedPosition({
1466
+ trigger: clientBox(trigger),
1467
+ value: laidOutBox(parts.valueRef()),
1468
+ content: clientBox(content),
1469
+ item: clientBox(item),
1470
+ itemText: laidOutBox(item.querySelector(`[${ITEM_TEXT_ATTRIBUTE}]`)),
1471
+ boundary: { width: view?.innerWidth ?? 0, height: view?.innerHeight ?? 0 },
1472
+ direction: parts.dir() ?? locale().direction,
1473
+ }),
1474
+ );
1475
+ };
1476
+
1477
+ const registering: SelectContentValue = {
1478
+ isRegistering: true,
1479
+ viewportRef,
1480
+ canScrollUp: () => false,
1481
+ canScrollDown: () => false,
1482
+ measure: () => {},
1483
+ mounted: () => {},
1484
+ ariaLabel: () => undefined,
1485
+ ariaLabelledBy: () => undefined,
1486
+ };
1487
+
1488
+ const showing: SelectContentValue = {
1489
+ isRegistering: false,
1490
+ viewportRef,
1491
+ canScrollUp: () => edges().up,
1492
+ canScrollDown: () => edges().down,
1493
+ measure,
1494
+ mounted: (isIn) => {
1495
+ setMounted(isIn);
1496
+ if (!isIn) {
1497
+ setAligned(null);
1498
+ return;
1499
+ }
1500
+ align();
1501
+ measure();
1502
+ },
1503
+ ariaLabel: () => props["aria-label"],
1504
+ ariaLabelledBy: () => props["aria-labelledby"],
1505
+ };
1506
+
1507
+ const options = fromProps(cells(props));
1508
+ const elementProps = mergeProps(
1509
+ filterDOMProps(options, { global: true, labelable: true }),
1510
+ styleProps(cells(props)),
1511
+ {
1512
+ role: "presentation",
1513
+ dir: () => parts.dir(),
1514
+ "data-position": () => props.position ?? "popper",
1515
+ // Said of what was ASKED for, so a design system can drop its entrance
1516
+ // animation before the first frame: the list is measured as it is drawn,
1517
+ // and a scale on it would be measured too.
1518
+ "data-align-trigger": () => String(props.position === "item-aligned"),
1519
+ "data-testid": () => props["data-testid"],
1520
+ },
1521
+ );
1522
+
1523
+ return (
1524
+ <>
1525
+ {/* The options stay registered across the swap: this copy is built before
1526
+ the real list leaves and dropped only after the real one is in, and a
1527
+ key registered twice keeps whichever copy is still there. */}
1528
+ <Show when={!state.isOpen() || !isMounted()}>
1529
+ <Portal mount={holder}>
1530
+ <SelectContentProvider value={registering}>{props.children}</SelectContentProvider>
1531
+ </Portal>
1532
+ </Show>
1533
+ <Popover
1534
+ triggerRef={parts.triggerRef}
1535
+ isOpen={state.isOpen()}
1536
+ onOpenChange={state.setOpen}
1537
+ placement={aligned() === null ? (props.placement ?? "bottom start") : "bottom start"}
1538
+ offset={aligned()?.offset ?? props.offset ?? 8}
1539
+ crossOffset={aligned()?.crossOffset ?? props.crossOffset}
1540
+ shouldFlip={aligned() === null}
1541
+ >
1542
+ <SelectContentBox
1543
+ elementProps={elementProps}
1544
+ contentRef={contentRef}
1545
+ forwardedRef={props.ref}
1546
+ value={showing}
1547
+ >
1548
+ {props.children}
1549
+ </SelectContentBox>
1550
+ </Popover>
1551
+ </>
1552
+ );
1553
+ }
1554
+
1555
+ interface SelectContentBoxProps {
1556
+ elementProps: DOMProps;
1557
+ contentRef: ReturnType<typeof makeRef<HTMLDivElement>>;
1558
+ forwardedRef?: RefTarget<HTMLDivElement>;
1559
+ value: SelectContentValue;
1560
+ children?: Child;
1561
+ }
1562
+
1563
+ /** Inside the popover, which is the only place its side and state can be read. */
1564
+ function SelectContentBox(props: SelectContentBoxProps) {
1565
+ return (
1566
+ <div
1567
+ {...props.elementProps}
1568
+ {...popoverStateProps()}
1569
+ ref={mergeRefs(props.contentRef.set, props.forwardedRef)}
1570
+ >
1571
+ <SelectContentProvider value={props.value}>{props.children}</SelectContentProvider>
1572
+ </div>
1573
+ );
1574
+ }
1575
+
1576
+ export interface SelectViewportComponentProps extends StyleProps {
1577
+ /** The `<Option>`s, and the groups and separators between them. */
1578
+ children?: Child;
1579
+ }
1580
+
1581
+ /** The listbox: the scroller the options are in. */
1582
+ export function SelectViewport(props: SelectViewportComponentProps) {
1583
+ const { parts, state } = useSelectParts("SelectViewport");
1584
+ const content = useSelectContent("SelectViewport");
1585
+
1586
+ const lent: ListBoxContextValue = {
1587
+ state,
1588
+ baseId: parts.baseId,
1589
+ shouldSelectOnPressUp: () => true,
1590
+ shouldUseVirtualFocus: () => undefined,
1591
+ staticItems: parts.registry,
1592
+ };
1593
+
1594
+ if (content.isRegistering) {
1595
+ return (
1596
+ <ListBoxProvider value={lent}>
1597
+ <ul>{props.children}</ul>
1598
+ </ListBoxProvider>
1599
+ );
1600
+ }
1601
+
1602
+ const listRef = content.viewportRef;
1603
+ const options = parts.listBoxProps;
1604
+
1605
+ // Called here rather than in the root: the autofocus is read once, at
1606
+ // construction, and the strategy the opening key set exists only once the
1607
+ // list is being built.
1608
+ const { listBoxProps } = listBox(
1609
+ {
1610
+ ...(options as unknown as Record<string, MaybeAccessor<never>>),
1611
+ ref: listRef,
1612
+ baseId: parts.baseId,
1613
+ "aria-label": content.ariaLabel,
1614
+ },
1615
+ state,
1616
+ );
1617
+
1618
+ const elementProps = mergeProps(
1619
+ listBoxProps,
1620
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1621
+ styleProps(cells(props)),
1622
+ {
1623
+ id: options.id,
1624
+ "aria-labelledby": () =>
1625
+ content.ariaLabelledBy() ??
1626
+ (content.ariaLabel() === undefined
1627
+ ? access(options["aria-labelledby"] as MaybeAccessor<string>)
1628
+ : undefined),
1629
+ onScroll: content.measure,
1630
+ "data-testid": () => props["data-testid"],
1631
+ },
1632
+ );
1633
+
1634
+ resizeObserver(listRef, content.measure);
1635
+ onSettled(() => {
1636
+ content.mounted(true);
1637
+ });
1638
+ onCleanup(() => {
1639
+ content.mounted(false);
1640
+ });
1641
+
1642
+ return (
1643
+ <ListBoxProvider value={lent}>
1644
+ <ul {...elementProps} ref={listRef.set}>
1645
+ {props.children}
1646
+ </ul>
1647
+ </ListBoxProvider>
1648
+ );
1649
+ }
1650
+
1651
+ export interface SelectItemTextComponentProps extends StyleProps {
1652
+ children?: Child;
1653
+ }
1654
+
1655
+ /**
1656
+ * The part of an option the trigger shows when the option is chosen.
1657
+ *
1658
+ * Everything else in the row, a tick or a shortcut, stays in the row.
1659
+ */
1660
+ export function SelectItemText(props: SelectItemTextComponentProps) {
1661
+ const elementProps = mergeProps(
1662
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1663
+ styleProps(cells(props)),
1664
+ { [ITEM_TEXT_ATTRIBUTE]: "", "data-testid": () => props["data-testid"] },
1665
+ );
1666
+ return <span {...elementProps}>{props.children}</span>;
1667
+ }
1668
+
1669
+ export interface SelectScrollButtonComponentProps extends StyleProps {
1670
+ direction: "up" | "down";
1671
+ children?: Child;
1672
+ }
1673
+
1674
+ /** How often a held scroll button moves the list, in milliseconds. */
1675
+ const SCROLL_INTERVAL = 50;
1676
+
1677
+ /**
1678
+ * An arrow at one end of the list, there only while the list can scroll that
1679
+ * way.
1680
+ *
1681
+ * It scrolls for as long as the pointer is over it, a row at a time, and it is
1682
+ * hidden from assistive technology: the keyboard already scrolls the list by
1683
+ * moving through it, so the arrow is a pointer's convenience and nothing a
1684
+ * screen reader user needs to find.
1685
+ */
1686
+ export function SelectScrollButton(props: SelectScrollButtonComponentProps) {
1687
+ useSelectParts("SelectScrollButton");
1688
+ const content = useSelectContent("SelectScrollButton");
1689
+ if (content.isRegistering) return null;
1690
+
1691
+ const isUp = props.direction === "up";
1692
+ let timer: ReturnType<typeof setInterval> | undefined;
1693
+
1694
+ const stop = (): void => {
1695
+ clearInterval(timer);
1696
+ timer = undefined;
1697
+ };
1698
+
1699
+ const step = (): void => {
1700
+ const viewport = content.viewportRef();
1701
+ if (viewport === null) return;
1702
+ const row = viewport.querySelector<HTMLElement>('[role="option"]')?.offsetHeight ?? 0;
1703
+ const distance = row > 0 ? row : 32;
1704
+ viewport.scrollTop += isUp ? -distance : distance;
1705
+ content.measure();
1706
+ };
1707
+
1708
+ const start = (): void => {
1709
+ if (timer === undefined) timer = setInterval(step, SCROLL_INTERVAL);
1710
+ };
1711
+
1712
+ onCleanup(stop);
1713
+
1714
+ const elementProps = mergeProps(
1715
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1716
+ styleProps(cells(props)),
1717
+ {
1718
+ "aria-hidden": "true",
1719
+ onPointerDown: start,
1720
+ onPointerMove: start,
1721
+ onPointerLeave: stop,
1722
+ "data-testid": () => props["data-testid"],
1723
+ },
1724
+ );
1725
+
1726
+ return (
1727
+ <Show when={isUp ? content.canScrollUp() : content.canScrollDown()}>
1728
+ <ScrollButton elementProps={elementProps} onLeave={stop}>
1729
+ {props.children}
1730
+ </ScrollButton>
1731
+ </Show>
1732
+ );
1733
+ }
1734
+
1735
+ /**
1736
+ * Its own component so that leaving the document stops the timer: the button
1737
+ * goes the moment the list reaches its end, with the pointer still over it and
1738
+ * no `pointerleave` to say so.
1739
+ */
1740
+ function ScrollButton(props: { elementProps: DOMProps; onLeave: () => void; children?: Child }) {
1741
+ onCleanup(() => props.onLeave());
1742
+ return <div {...props.elementProps}>{props.children}</div>;
1743
+ }
1744
+
1745
+ export { Option };