@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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -2
  3. package/package.json +347 -4
  4. package/src/breadcrumbs.tsx +296 -0
  5. package/src/button.tsx +342 -0
  6. package/src/calendar.tsx +1389 -0
  7. package/src/checkbox.tsx +570 -0
  8. package/src/collections.ts +976 -0
  9. package/src/color.ts +562 -0
  10. package/src/colorpicker.tsx +1478 -0
  11. package/src/combobox.tsx +2481 -0
  12. package/src/command.tsx +1184 -0
  13. package/src/date.ts +652 -0
  14. package/src/datefield.tsx +951 -0
  15. package/src/datepicker.tsx +556 -0
  16. package/src/dialog.tsx +890 -0
  17. package/src/disclosure.tsx +659 -0
  18. package/src/dom.ts +706 -0
  19. package/src/drawer.ts +674 -0
  20. package/src/focus.ts +1370 -0
  21. package/src/form.tsx +94 -0
  22. package/src/gridlist.tsx +563 -0
  23. package/src/i18n.ts +823 -0
  24. package/src/index.ts +1270 -0
  25. package/src/interactions/description.ts +73 -0
  26. package/src/interactions/flags.ts +35 -0
  27. package/src/interactions/focus-events.ts +218 -0
  28. package/src/interactions/focusable.ts +86 -0
  29. package/src/interactions/hover.ts +213 -0
  30. package/src/interactions/interact-outside.ts +123 -0
  31. package/src/interactions/keyboard.ts +105 -0
  32. package/src/interactions/listeners.ts +78 -0
  33. package/src/interactions/long-press.ts +160 -0
  34. package/src/interactions/modality.ts +416 -0
  35. package/src/interactions/move.ts +257 -0
  36. package/src/interactions/open-link.ts +193 -0
  37. package/src/interactions/press.ts +898 -0
  38. package/src/interactions/prevent-focus.ts +102 -0
  39. package/src/interactions/scroll-wheel.ts +43 -0
  40. package/src/interactions/text-selection.ts +77 -0
  41. package/src/interactions.ts +81 -0
  42. package/src/label.ts +128 -0
  43. package/src/link.tsx +381 -0
  44. package/src/listbox.tsx +721 -0
  45. package/src/live.ts +204 -0
  46. package/src/menu.tsx +2290 -0
  47. package/src/menubar.tsx +575 -0
  48. package/src/navigation.ts +735 -0
  49. package/src/numberfield.tsx +838 -0
  50. package/src/otp.ts +430 -0
  51. package/src/overlays.ts +1247 -0
  52. package/src/platform.ts +74 -0
  53. package/src/presence.ts +164 -0
  54. package/src/questionnaire.tsx +1712 -0
  55. package/src/radio.tsx +567 -0
  56. package/src/register-dom.ts +12 -0
  57. package/src/scroller.ts +1165 -0
  58. package/src/select.tsx +1665 -0
  59. package/src/selection.ts +1415 -0
  60. package/src/slider.tsx +1042 -0
  61. package/src/splitter.ts +1152 -0
  62. package/src/static-collection.ts +211 -0
  63. package/src/switch.tsx +186 -0
  64. package/src/table.tsx +0 -0
  65. package/src/tabs.tsx +1018 -0
  66. package/src/tag.tsx +452 -0
  67. package/src/textfield.tsx +417 -0
  68. package/src/toast.ts +658 -0
  69. package/src/toggle-input.tsx +48 -0
  70. package/src/toggle.ts +321 -0
  71. package/src/togglegroup.ts +365 -0
  72. package/src/toolbar.tsx +179 -0
  73. package/src/tooltip.tsx +657 -0
  74. package/src/utils.ts +758 -0
  75. package/src/validation.ts +447 -0
  76. package/src/virtualizer.tsx +674 -0
package/src/form.tsx ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * A form, and the validation that belongs to the whole of it rather than to
3
+ * one field.
4
+ *
5
+ * Three things a `<form>` cannot do on its own:
6
+ *
7
+ * - **Hand a submission's errors back to the fields they belong to.** A server
8
+ * answering "that address is already taken" knows the field name and nothing
9
+ * else; `<Form validationErrors={…}>` puts each message where its field can
10
+ * find it, and the field clears it the moment the user edits the value.
11
+ * - **Choose one validation behaviour for everything inside.** Setting
12
+ * `validationBehavior` per field is how a form ends up half native and half
13
+ * ARIA, which means half of it blocks submission and half does not.
14
+ * - **Give a submit handler the values.** `onSubmit` here is called with a
15
+ * `FormData`, and the default is prevented, because a form that both calls a
16
+ * handler AND navigates does both.
17
+ */
18
+
19
+ import { type Child, type Incoming } from "@barqjs/core";
20
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
21
+ import {
22
+ provideValidationBehavior,
23
+ provideValidationErrors,
24
+ type ValidationBehavior,
25
+ type ValidationErrors,
26
+ } from "./validation.ts";
27
+ import { filterDOMProps, fromProps, mergeProps, type StyleProps, styleProps } from "./utils.ts";
28
+
29
+ export interface FormComponentProps extends StyleProps {
30
+ children?: Child;
31
+ /** Errors a submission came back with, by field name. */
32
+ validationErrors?: ValidationErrors;
33
+ /** @default "aria" */
34
+ validationBehavior?: ValidationBehavior;
35
+ action?: string;
36
+ method?: "get" | "post" | "dialog";
37
+ encType?: string;
38
+ target?: string;
39
+ autoComplete?: "on" | "off";
40
+ /** Turn off the browser's own validation UI. */
41
+ noValidate?: boolean;
42
+ "aria-label"?: string;
43
+ "aria-labelledby"?: string;
44
+ ref?: RefTarget<HTMLFormElement>;
45
+ onSubmit?: (data: FormData, event: SubmitEvent) => void;
46
+ onReset?: (event: Event) => void;
47
+ }
48
+
49
+ /**
50
+ * ```tsx
51
+ * <Form validationErrors={errors()} onSubmit={(data) => save(data)}>
52
+ * <TextField label="Email" name="email" type="email" isRequired />
53
+ * <Button type="submit">Save</Button>
54
+ * </Form>
55
+ * ```
56
+ */
57
+ export function Form(props: Incoming<FormComponentProps>) {
58
+ const domRef = makeRef<HTMLFormElement>();
59
+
60
+ provideValidationErrors(() => props.validationErrors?.() ?? {});
61
+ provideValidationBehavior(() => props.validationBehavior?.());
62
+
63
+ const onSubmit = (event: SubmitEvent): void => {
64
+ const handler = props.onSubmit?.();
65
+ if (handler === undefined) return;
66
+ // Both calling a handler and navigating is doing the thing twice.
67
+ event.preventDefault();
68
+ handler(new FormData(event.currentTarget as HTMLFormElement), event);
69
+ };
70
+
71
+ const elementProps = mergeProps(
72
+ filterDOMProps(fromProps(props), { global: true }),
73
+ styleProps(props),
74
+ {
75
+ action: () => props.action?.(),
76
+ method: () => props.method?.(),
77
+ enctype: () => props.encType?.(),
78
+ target: () => props.target?.(),
79
+ autocomplete: () => props.autoComplete?.(),
80
+ novalidate: () => props.noValidate?.() === true || undefined,
81
+ "aria-label": () => props["aria-label"]?.(),
82
+ "aria-labelledby": () => props["aria-labelledby"]?.(),
83
+ "data-testid": () => props["data-testid"]?.(),
84
+ onSubmit,
85
+ onReset: (event: Event) => props.onReset?.()?.(event),
86
+ },
87
+ );
88
+
89
+ return (
90
+ <form {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
91
+ {props.children}
92
+ </form>
93
+ );
94
+ }
@@ -0,0 +1,563 @@
1
+ /**
2
+ * A grid list: rows that hold their own controls.
3
+ *
4
+ * A listbox's options are values; a grid list's rows are things you act on,
5
+ * and each one may contain a checkbox, a menu button, a link. That is why it
6
+ * is `role="grid"` and not `role="listbox"`: an option may not contain
7
+ * interactive content, and a screen reader in browse mode will not let you
8
+ * reach it if it does.
9
+ *
10
+ * The navigation is two-dimensional even though there is one column:
11
+ *
12
+ * - **Up and down move between ROWS**, and they belong to the list however
13
+ * deep in a row the focus is. A menu button inside a row must not swallow
14
+ * Down, so the row takes those keys in the CAPTURE phase and re-dispatches
15
+ * them from its parent, where the collection's own handler is.
16
+ * - **Left and right move WITHIN a row**, between its focusable children,
17
+ * flipped in a right-to-left layout. Past the last child, focus returns to
18
+ * the row, which is what makes the row itself a place to stand.
19
+ *
20
+ * `keyboardNavigationBehavior: "tab"` swaps that second rule for the Tab key,
21
+ * which is what a form of editable rows wants: Left and Right then belong to
22
+ * the caret in whatever field the user is in.
23
+ */
24
+
25
+ import {
26
+ type Accessor,
27
+ type Child,
28
+ For,
29
+ createContext,
30
+ getContext,
31
+ getOwner,
32
+ type Incoming,
33
+ install,
34
+ provide,
35
+ } from "@barqjs/core";
36
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
37
+ import type {
38
+ ItemAccessors,
39
+ Key,
40
+ LayoutDelegate,
41
+ ListStateOptions,
42
+ Node,
43
+ SelectionMode,
44
+ } from "./collections.ts";
45
+ import { listState, type ListState } from "./collections.ts";
46
+ import {
47
+ contentStyle,
48
+ measureRow,
49
+ rowStyle,
50
+ useVirtualizer,
51
+ type LayoutInfo,
52
+ } from "./virtualizer.tsx";
53
+ import { activeElement, contains, ownerDocument, targetElement } from "./dom.ts";
54
+ import { focusableWalker, focusRing } from "./focus.ts";
55
+ import { useLocale } from "./i18n.ts";
56
+ import { focusSafely } from "./interactions/focusable.ts";
57
+ import { hover } from "./interactions/hover.ts";
58
+ import type { ElementRef } from "./interactions/press.ts";
59
+ import {
60
+ selectableItem,
61
+ selectableList,
62
+ type KeyboardDelegate,
63
+ type LinkBehavior,
64
+ } from "./selection.ts";
65
+ import {
66
+ access,
67
+ type DOMProps,
68
+ filterDOMProps,
69
+ fromProps,
70
+ id,
71
+ type MaybeAccessor,
72
+ mergeProps,
73
+ type StyleProps,
74
+ styleProps,
75
+ } from "./utils.ts";
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // The list
79
+ // ---------------------------------------------------------------------------
80
+
81
+ export type KeyboardNavigationBehavior = "arrow" | "tab";
82
+
83
+ export interface GridListOptions {
84
+ ref: ElementRef;
85
+ shouldFocusWrap?: MaybeAccessor<boolean | undefined>;
86
+ autoFocus?: MaybeAccessor<boolean | "first" | "last" | undefined>;
87
+ disallowTypeAhead?: MaybeAccessor<boolean | undefined>;
88
+ disallowEmptySelection?: MaybeAccessor<boolean | undefined>;
89
+ isVirtualized?: MaybeAccessor<boolean | undefined>;
90
+ /** @default "arrow" */
91
+ keyboardNavigationBehavior?: MaybeAccessor<KeyboardNavigationBehavior | undefined>;
92
+ /** @default "action" */
93
+ linkBehavior?: MaybeAccessor<LinkBehavior | undefined>;
94
+ escapeKeyBehavior?: MaybeAccessor<"clearSelection" | "none" | undefined>;
95
+ keyboardDelegate?: KeyboardDelegate;
96
+ /** Where the rows are, when the DOM cannot answer because they are not in it. */
97
+ layoutDelegate?: LayoutDelegate;
98
+ "aria-label"?: MaybeAccessor<string | undefined>;
99
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
100
+ onAction?: (key: Key) => void;
101
+ }
102
+
103
+ export interface GridListResult {
104
+ gridProps: DOMProps;
105
+ /** The base every row id is derived from. */
106
+ baseId: Accessor<string>;
107
+ }
108
+
109
+ export function gridList(options: GridListOptions, state: ListState<unknown>): GridListResult {
110
+ const baseId = id();
111
+
112
+ const { listProps } = selectableList({
113
+ ...options,
114
+ selectionManager: state.selectionManager,
115
+ collection: state.collection,
116
+ disabledKeys: state.disabledKeys,
117
+ selectOnFocus: () => state.selectionManager().selectionBehavior === "replace",
118
+ linkBehavior: () => access(options.linkBehavior) ?? "action",
119
+ });
120
+
121
+ const isEmpty = (): boolean => state.collection().size === 0;
122
+
123
+ return {
124
+ baseId,
125
+ gridProps: mergeProps(filterDOMProps(options, { labelable: true }), listProps, {
126
+ role: "grid",
127
+ id: baseId,
128
+ "aria-multiselectable": () =>
129
+ state.selectionManager().selectionMode === "multiple" ? true : undefined,
130
+ // An empty grid still has to be reachable, or a keyboard user cannot
131
+ // land on it to be told it is empty.
132
+ tabIndex: () => (isEmpty() ? 0 : access(listProps.tabIndex as MaybeAccessor<number>)),
133
+ "aria-rowcount": () =>
134
+ access(options.isVirtualized) === true ? state.collection().size : undefined,
135
+ "aria-colcount": () => (access(options.isVirtualized) === true ? 1 : undefined),
136
+ }),
137
+ };
138
+ }
139
+
140
+ /** The id a row renders under, derived from the key so anything can name it. */
141
+ export function rowIdFor(baseId: string, key: Key): string {
142
+ return `${baseId}-row-${String(key)}`;
143
+ }
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // A row
147
+ // ---------------------------------------------------------------------------
148
+
149
+ export interface GridListItemOptions {
150
+ key: Key;
151
+ ref: ElementRef;
152
+ baseId: MaybeAccessor<string>;
153
+ "aria-label"?: MaybeAccessor<string | undefined>;
154
+ isDisabled?: MaybeAccessor<boolean | undefined>;
155
+ isVirtualized?: MaybeAccessor<boolean | undefined>;
156
+ shouldSelectOnPressUp?: MaybeAccessor<boolean | undefined>;
157
+ /** @default "arrow" */
158
+ keyboardNavigationBehavior?: MaybeAccessor<KeyboardNavigationBehavior | undefined>;
159
+ linkBehavior?: MaybeAccessor<LinkBehavior | undefined>;
160
+ onAction?: (key: Key) => void;
161
+ /** See `selectableItem`. @default `onAction !== undefined` */
162
+ hasAction?: MaybeAccessor<boolean | undefined>;
163
+ }
164
+
165
+ export interface GridListItemResult {
166
+ rowProps: DOMProps;
167
+ /** For the single cell inside the row. */
168
+ gridCellProps: DOMProps;
169
+ isSelected: Accessor<boolean>;
170
+ isFocused: Accessor<boolean>;
171
+ isPressed: Accessor<boolean>;
172
+ isDisabled: Accessor<boolean>;
173
+ allowsSelection: Accessor<boolean>;
174
+ hasAction: Accessor<boolean>;
175
+ }
176
+
177
+ export function gridListItem(
178
+ options: GridListItemOptions,
179
+ state: ListState<unknown>,
180
+ ): GridListItemResult {
181
+ const locale = useLocale();
182
+ const node = (): Node<unknown> | null => state.collection().getItem(options.key);
183
+ const rowId = (): string => rowIdFor(access(options.baseId), options.key);
184
+ const behavior = (): KeyboardNavigationBehavior =>
185
+ access(options.keyboardNavigationBehavior) ?? "arrow";
186
+
187
+ const item = selectableItem({
188
+ key: options.key,
189
+ ref: options.ref,
190
+ id: rowId,
191
+ selectionManager: state.selectionManager,
192
+ isDisabled: options.isDisabled,
193
+ shouldSelectOnPressUp: options.shouldSelectOnPressUp,
194
+ linkBehavior: options.linkBehavior,
195
+ hasAction: () =>
196
+ access(options.hasAction) ??
197
+ (options.onAction !== undefined || node()?.props?.onAction !== undefined),
198
+ onAction: () => {
199
+ const own = node()?.props?.onAction;
200
+ if (typeof own === "function") (own as () => void)();
201
+ options.onAction?.(options.key);
202
+ },
203
+ });
204
+
205
+ const row = (): HTMLElement | null => (access(options.ref) as HTMLElement | null) ?? null;
206
+
207
+ /** A walker over the row's own focusable children, standing where focus is. */
208
+ const walkerAt = (element: HTMLElement, from: Element): ReturnType<typeof focusableWalker> => {
209
+ const walker = focusableWalker(element);
210
+ walker.currentNode = from;
211
+ return walker;
212
+ };
213
+
214
+ const lastFocusable = (element: HTMLElement): Element | null => {
215
+ const walker = focusableWalker(element);
216
+ walker.currentNode = element;
217
+ return walker.last() as Element | null;
218
+ };
219
+
220
+ /**
221
+ * Captured, not bubbled.
222
+ *
223
+ * A control inside the row would otherwise see these first: a menu button
224
+ * takes Down to open, a text field takes Left to move the caret. The row has
225
+ * to decide before they do.
226
+ */
227
+ const onKeyDownCapture = (event: KeyboardEvent): void => {
228
+ const element = row();
229
+ if (element === null) return;
230
+ const target = targetElement(event);
231
+ if (target === null || !contains(element, target)) return;
232
+ const active = activeElement(ownerDocument(element));
233
+ if (active === null) return;
234
+
235
+ const rtl = locale().direction === "rtl";
236
+ const inwards = rtl ? "ArrowLeft" : "ArrowRight";
237
+ const outwards = rtl ? "ArrowRight" : "ArrowLeft";
238
+
239
+ if (event.key === inwards || event.key === outwards) {
240
+ if (behavior() !== "arrow") return;
241
+ event.preventDefault();
242
+ event.stopPropagation();
243
+
244
+ const walker = walkerAt(element, active);
245
+ const next = (
246
+ event.key === inwards ? walker.nextNode() : walker.previousNode()
247
+ ) as HTMLElement | null;
248
+
249
+ if (next !== null) {
250
+ focusSafely(next);
251
+ return;
252
+ }
253
+
254
+ // Off the end of the row. Forwards lands back on the ROW, which is where
255
+ // the up and down keys work from; backwards past the first control wraps
256
+ // to the last, so the cycle is row, first, …, last, row.
257
+ if (event.key === inwards) {
258
+ focusSafely(element);
259
+ return;
260
+ }
261
+ const last = lastFocusable(element) as HTMLElement | null;
262
+ if (last !== null) focusSafely(last);
263
+ return;
264
+ }
265
+
266
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
267
+ if (event.altKey) return;
268
+ // The collection's handler is on the LIST, and the row is about to stop
269
+ // this event before a child sees it — so it is re-dispatched from the
270
+ // row's parent, where the list still hears it.
271
+ event.preventDefault();
272
+ event.stopPropagation();
273
+ element.parentElement?.dispatchEvent(
274
+ new KeyboardEvent(event.type, {
275
+ key: event.key,
276
+ code: event.code,
277
+ altKey: event.altKey,
278
+ ctrlKey: event.ctrlKey,
279
+ metaKey: event.metaKey,
280
+ shiftKey: event.shiftKey,
281
+ bubbles: true,
282
+ cancelable: true,
283
+ }),
284
+ );
285
+ }
286
+ };
287
+
288
+ /**
289
+ * Tab within the row, when that is the navigation mode.
290
+ *
291
+ * Stopping propagation is all it takes: the collection's Tab handling is
292
+ * what would otherwise take focus out of the list, and the browser's own
293
+ * Tab then moves to the next control in the row.
294
+ */
295
+ const onKeyDown = (event: KeyboardEvent): void => {
296
+ if (event.key !== "Tab" || behavior() !== "tab") return;
297
+ const element = row();
298
+ if (element === null) return;
299
+ const active = activeElement(ownerDocument(element));
300
+ if (active === null) return;
301
+
302
+ const walker = focusableWalker(element, { tabbable: true });
303
+ walker.currentNode = active;
304
+ const next = event.shiftKey ? walker.previousNode() : walker.nextNode();
305
+ if (next !== null) event.stopPropagation();
306
+ };
307
+
308
+ const onFocus = (event: FocusEvent): void => {
309
+ // `selectableItem` only claims focus that lands on the row itself; a
310
+ // control inside it is still the row being focused as far as the
311
+ // collection is concerned.
312
+ if (targetElement(event) === row()) return;
313
+ state.selectionManager().setFocusedKey(options.key);
314
+ };
315
+
316
+ return {
317
+ isSelected: item.isSelected,
318
+ isFocused: item.isFocused,
319
+ isPressed: item.isPressed,
320
+ isDisabled: item.isDisabled,
321
+ allowsSelection: item.allowsSelection,
322
+ hasAction: item.hasAction,
323
+ gridCellProps: { role: "gridcell", "aria-colindex": 1 },
324
+ rowProps: mergeProps(item.itemProps, {
325
+ role: "row",
326
+ id: rowId,
327
+ onKeyDownCapture,
328
+ onKeyDown,
329
+ onFocus,
330
+ "aria-label": () =>
331
+ access(options["aria-label"]) ?? node()?.["aria-label"] ?? node()?.textValue ?? undefined,
332
+ // Only where selection is possible: on a list that only performs
333
+ // actions the attribute would say every row is unselected rather than
334
+ // that selection is not the point.
335
+ "aria-selected": () =>
336
+ state.selectionManager().canSelectItem(options.key) ? item.isSelected() : undefined,
337
+ "aria-disabled": () => item.isDisabled() || undefined,
338
+ "aria-rowindex": () =>
339
+ access(options.isVirtualized) === true ? (node()?.index ?? 0) + 1 : undefined,
340
+ }),
341
+ };
342
+ }
343
+
344
+ // ---------------------------------------------------------------------------
345
+ // Components
346
+ // ---------------------------------------------------------------------------
347
+
348
+ interface GridListContextValue {
349
+ state: ListState<unknown>;
350
+ baseId: Accessor<string>;
351
+ keyboardNavigationBehavior: Accessor<KeyboardNavigationBehavior>;
352
+ onAction: Accessor<((key: Key) => void) | undefined>;
353
+ }
354
+
355
+ const GridListContext = createContext<GridListContextValue | null>(null);
356
+ const RowNodeContext = createContext<Node<unknown> | null>(null);
357
+
358
+ export function useGridList(): GridListContextValue {
359
+ const value = getContext(GridListContext);
360
+ if (value === null || value === undefined) {
361
+ throw new Error("A GridListItem must be rendered inside a GridList.");
362
+ }
363
+ return value;
364
+ }
365
+
366
+ /** The collection node the row being built is for. */
367
+ export function useRowNode(): Node<unknown> {
368
+ const node = getContext(RowNodeContext);
369
+ if (node === null || node === undefined) {
370
+ throw new Error("A GridListItem must be rendered inside a GridList's item callback.");
371
+ }
372
+ return node;
373
+ }
374
+
375
+ /** Make `<GridListItem>` usable inside something that is not a `<GridList>`. */
376
+ export function GridListProvider(
377
+ props: Incoming<{ value: GridListContextValue; children?: Child }>,
378
+ ) {
379
+ return provide(
380
+ GridListContext,
381
+ () => props.value(),
382
+ () => props.children as unknown,
383
+ );
384
+ }
385
+
386
+ /** The collection node the row being built is for. */
387
+ export function provideRowNode(node: Node<unknown>): void {
388
+ const owner = getOwner();
389
+ if (owner !== null) install(owner, RowNodeContext, () => node);
390
+ }
391
+
392
+ export interface GridListComponentProps<T> extends StyleProps, ItemAccessors<T> {
393
+ /** The rows, in order. */
394
+ items: Iterable<T>;
395
+ /** How one row renders. Return a `<GridListItem>`. */
396
+ children: (item: T) => Child;
397
+ /** @default "none" */
398
+ selectionMode?: SelectionMode;
399
+ selectionBehavior?: "toggle" | "replace";
400
+ selectedKeys?: "all" | Iterable<Key>;
401
+ defaultSelectedKeys?: "all" | Iterable<Key>;
402
+ disabledKeys?: Iterable<Key>;
403
+ disallowEmptySelection?: boolean;
404
+ shouldFocusWrap?: boolean;
405
+ autoFocus?: boolean | "first" | "last";
406
+ /** @default "arrow" */
407
+ keyboardNavigationBehavior?: KeyboardNavigationBehavior;
408
+ "aria-label"?: string;
409
+ "aria-labelledby"?: string;
410
+ ref?: RefTarget<HTMLDivElement>;
411
+ onSelectionChange?: (keys: "all" | Set<Key>) => void;
412
+ onAction?: (key: Key) => void;
413
+ }
414
+
415
+ /**
416
+ * ```tsx
417
+ * <GridList aria-label="Files" items={files()} selectionMode="multiple">
418
+ * {(file) => (
419
+ * <GridListItem>
420
+ * {file.name}
421
+ * <Button onPress={() => remove(file.id)}>Delete</Button>
422
+ * </GridListItem>
423
+ * )}
424
+ * </GridList>
425
+ * ```
426
+ */
427
+ export function GridList<T>(props: Incoming<GridListComponentProps<T>>) {
428
+ const domRef = makeRef<HTMLDivElement>();
429
+ const options = fromProps(props as unknown as Incoming<Record<string, unknown>>);
430
+
431
+ const state = listState<T>({
432
+ ...(options as ListStateOptions<T>),
433
+ onSelectionChange: (keys) => props.onSelectionChange?.()?.(keys),
434
+ });
435
+
436
+ // Inside a `<Virtualizer>` the list renders a WINDOW of its collection, and
437
+ // the layout — not the DOM — answers what is above, below and a page away.
438
+ const virtual = useVirtualizer();
439
+ virtual?.attach(state.collection, domRef, () => state.selectionManager().focusedKey);
440
+
441
+ const { gridProps, baseId } = gridList(
442
+ {
443
+ ...(options as unknown as GridListOptions),
444
+ ref: domRef,
445
+ isVirtualized: () => virtual !== null,
446
+ layoutDelegate: virtual?.layout,
447
+ },
448
+ state,
449
+ );
450
+
451
+ const value: GridListContextValue = {
452
+ state: state,
453
+ baseId,
454
+ keyboardNavigationBehavior: () => props.keyboardNavigationBehavior?.() ?? "arrow",
455
+ onAction: () => props.onAction?.(),
456
+ };
457
+
458
+ const elementProps = mergeProps(
459
+ gridProps,
460
+ filterDOMProps(fromProps(props), { global: true }),
461
+ styleProps(props),
462
+ {
463
+ "data-empty": () => state.collection().size === 0,
464
+ "data-virtualized": () => virtual !== null,
465
+ "data-testid": () => props["data-testid"]?.(),
466
+ style: () => (virtual === null ? props.style?.() : contentStyle(virtual.contentSize())),
467
+ },
468
+ );
469
+
470
+ const render = props.children;
471
+
472
+ /** The whole collection, or the window of it the virtualiser says is on screen. */
473
+ const rows = (): Node<T>[] => {
474
+ if (virtual === null) return [...state.collection()];
475
+ const collection = state.collection();
476
+ return virtual
477
+ .visible()
478
+ .map((info: LayoutInfo) => collection.getItem(info.key))
479
+ .filter((node: Node<T> | null): node is Node<T> => node !== null);
480
+ };
481
+
482
+ return (
483
+ <GridListProvider value={value}>
484
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
485
+ <For each={rows}>
486
+ {(node: Node<T>) => {
487
+ provideRowNode(node);
488
+ return render(node.value as T);
489
+ }}
490
+ </For>
491
+ </div>
492
+ </GridListProvider>
493
+ );
494
+ }
495
+
496
+ export interface GridListItemComponentProps extends StyleProps {
497
+ children?: Child;
498
+ "aria-label"?: string;
499
+ ref?: RefTarget<HTMLDivElement>;
500
+ }
501
+
502
+ /**
503
+ * One row, holding one cell.
504
+ *
505
+ * The cell is what the row's content goes in: a row may not contain content
506
+ * directly, and a screen reader reports "row 2 of 7" from the pair.
507
+ */
508
+ export function GridListItem(props: Incoming<GridListItemComponentProps>) {
509
+ const domRef = makeRef<HTMLDivElement>();
510
+ const virtual = useVirtualizer();
511
+ const list = useGridList();
512
+ const node = useRowNode();
513
+
514
+ measureRow(virtual, node.key, domRef);
515
+
516
+ const { rowProps, gridCellProps, isSelected, isFocused, isPressed, isDisabled } = gridListItem(
517
+ {
518
+ key: node.key,
519
+ ref: domRef,
520
+ baseId: list.baseId,
521
+ isVirtualized: () => virtual !== null,
522
+ "aria-label": () => props["aria-label"]?.(),
523
+ isDisabled: () => node.props?.isDisabled === true,
524
+ keyboardNavigationBehavior: list.keyboardNavigationBehavior,
525
+ hasAction: () => list.onAction() !== undefined || node.props?.onAction !== undefined,
526
+ onAction: (key) => list.onAction()?.(key),
527
+ },
528
+ list.state,
529
+ );
530
+
531
+ const { hoverProps, isHovered } = hover({ isDisabled });
532
+ const { focusProps, isFocusVisible } = focusRing();
533
+
534
+ const elementProps = mergeProps(
535
+ rowProps,
536
+ hoverProps,
537
+ focusProps,
538
+ filterDOMProps(fromProps(props), { global: true }),
539
+ styleProps(props),
540
+ {
541
+ "data-selected": isSelected,
542
+ "data-focused": isFocused,
543
+ "data-focus-visible": isFocusVisible,
544
+ "data-pressed": isPressed,
545
+ "data-hovered": isHovered,
546
+ "data-disabled": isDisabled,
547
+ "data-testid": () => props["data-testid"]?.(),
548
+ // Positioned by the LAYOUT: the rows above it are not rendered, so
549
+ // document flow has nothing to place it against.
550
+ style: () => {
551
+ if (virtual === null) return props.style?.();
552
+ const info = virtual.layout.getLayoutInfo(node.key);
553
+ return info === null ? props.style?.() : rowStyle(info);
554
+ },
555
+ },
556
+ );
557
+
558
+ return (
559
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
560
+ <div {...gridCellProps}>{props.children}</div>
561
+ </div>
562
+ );
563
+ }