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