@barqjs/aria 0.2.0-next.0 → 0.2.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +24 -13
  2. package/package.json +127 -37
  3. package/src/autocomplete.tsx +581 -0
  4. package/src/breadcrumbs.tsx +21 -20
  5. package/src/button.tsx +151 -25
  6. package/src/calendar.tsx +1019 -92
  7. package/src/checkbox.tsx +214 -52
  8. package/src/collections.ts +88 -5
  9. package/src/color.ts +1580 -23
  10. package/src/colorpicker.tsx +698 -153
  11. package/src/colorswatchpicker.tsx +240 -0
  12. package/src/combobox.tsx +635 -113
  13. package/src/command.tsx +78 -59
  14. package/src/date.ts +31 -9
  15. package/src/datefield.tsx +1451 -336
  16. package/src/datepicker.tsx +465 -114
  17. package/src/dialog.tsx +302 -115
  18. package/src/disclosure.tsx +81 -29
  19. package/src/dnd/clipboard.ts +125 -0
  20. package/src/dnd/collection.ts +1265 -0
  21. package/src/dnd/data.ts +409 -0
  22. package/src/dnd/drag-drop.ts +801 -0
  23. package/src/dnd/index.ts +133 -0
  24. package/src/dnd/manager.ts +639 -0
  25. package/src/dnd/strings.ts +1279 -0
  26. package/src/dnd/targets.ts +726 -0
  27. package/src/dnd/types.ts +212 -0
  28. package/src/dom.ts +3 -6
  29. package/src/drag-and-drop.tsx +669 -0
  30. package/src/dropzone.tsx +208 -0
  31. package/src/file-trigger.tsx +103 -0
  32. package/src/form.tsx +18 -18
  33. package/src/gridlist.tsx +912 -121
  34. package/src/group.tsx +146 -0
  35. package/src/index.ts +402 -0
  36. package/src/interactions/focus-events.ts +13 -5
  37. package/src/interactions/keyboard.ts +195 -2
  38. package/src/interactions/modality.ts +18 -6
  39. package/src/interactions/open-link.ts +46 -13
  40. package/src/interactions/press.ts +35 -18
  41. package/src/label.ts +18 -6
  42. package/src/link.tsx +146 -50
  43. package/src/listbox.tsx +615 -89
  44. package/src/live.ts +4 -0
  45. package/src/menu.tsx +182 -89
  46. package/src/menubar.tsx +21 -17
  47. package/src/navigation-tree.tsx +357 -0
  48. package/src/numberfield.tsx +164 -60
  49. package/src/overlay-arrow.tsx +157 -0
  50. package/src/overlays.ts +364 -62
  51. package/src/platform.ts +2 -1
  52. package/src/preview-trigger.tsx +582 -0
  53. package/src/progress-bar-context.ts +15 -0
  54. package/src/questionnaire.tsx +109 -104
  55. package/src/radio.tsx +101 -27
  56. package/src/select.tsx +225 -145
  57. package/src/selection-indicator.tsx +74 -0
  58. package/src/selection.ts +73 -16
  59. package/src/shared-element-transition.tsx +316 -0
  60. package/src/sheet.tsx +1461 -0
  61. package/src/slider.tsx +139 -44
  62. package/src/switch.tsx +47 -21
  63. package/src/table.tsx +0 -0
  64. package/src/tabs.tsx +198 -89
  65. package/src/tag.tsx +217 -32
  66. package/src/textarea.tsx +186 -0
  67. package/src/textfield.tsx +103 -37
  68. package/src/toast-components.tsx +589 -0
  69. package/src/toggle-button-group.tsx +175 -0
  70. package/src/toggle-input.tsx +38 -0
  71. package/src/toggle.ts +68 -5
  72. package/src/tokenfield.tsx +1673 -0
  73. package/src/toolbar.tsx +15 -10
  74. package/src/tooltip.tsx +46 -29
  75. package/src/tree.tsx +2075 -0
  76. package/src/utils.ts +30 -1
  77. package/src/validation.ts +79 -22
  78. package/src/virtualizer.tsx +186 -23
package/src/gridlist.tsx CHANGED
@@ -18,28 +18,41 @@
18
18
  * the row, which is what makes the row itself a place to stand.
19
19
  *
20
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.
21
+ * which is what a form of editable rows wants: every key typed into a control
22
+ * in a row is the control's, and only Tab goes on to the list. A grid
23
+ * `layout` always navigates this way, since Left and Right move between rows.
23
24
  */
24
25
 
25
26
  import {
27
+ cells,
26
28
  type Accessor,
27
29
  type Child,
28
30
  For,
29
31
  createContext,
32
+ createEffect,
33
+ createMemo,
34
+ createSignal,
30
35
  getContext,
31
36
  getOwner,
32
37
  type Incoming,
33
38
  install,
39
+ onCleanup,
34
40
  provide,
41
+ Show,
35
42
  } from "@barqjs/core";
43
+ import { isServer } from "@barqjs/web";
36
44
  import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
45
+ import { Checkbox } from "./checkbox.tsx";
37
46
  import type {
47
+ Collection,
48
+ DisabledBehavior,
38
49
  ItemAccessors,
39
50
  Key,
40
51
  LayoutDelegate,
41
52
  ListStateOptions,
42
53
  Node,
54
+ SelectionBehavior,
55
+ SelectionManager,
43
56
  SelectionMode,
44
57
  } from "./collections.ts";
45
58
  import { listState, type ListState } from "./collections.ts";
@@ -49,21 +62,49 @@ import {
49
62
  rowStyle,
50
63
  useVirtualizer,
51
64
  type LayoutInfo,
65
+ type VirtualizerValue,
52
66
  } from "./virtualizer.tsx";
53
- import { activeElement, contains, ownerDocument, targetElement } from "./dom.ts";
67
+ import {
68
+ activeElement,
69
+ contains,
70
+ ownerDocument,
71
+ scrollIntoViewport,
72
+ scrollParents,
73
+ targetElement,
74
+ } from "./dom.ts";
75
+ import {
76
+ type CollectionDragAndDrop,
77
+ collectionDragAndDrop,
78
+ type DragAndDropHooks,
79
+ draggableItemSlotProps,
80
+ type DropIndicatorProps,
81
+ provideDragButton,
82
+ provideDropIndicator,
83
+ useDragAndDropContext,
84
+ dropIndicatorStyle,
85
+ } from "./drag-and-drop.tsx";
86
+ import { afterDropIndicatorTargets, type ItemDropTarget } from "./dnd/index.ts";
54
87
  import { focusableWalker, focusRing } from "./focus.ts";
55
- import { useLocale } from "./i18n.ts";
88
+ import { collator, StringDictionary, stringFormatter, useLocale } from "./i18n.ts";
89
+ import { focused } from "./interactions/focus-events.ts";
56
90
  import { focusSafely } from "./interactions/focusable.ts";
57
- import { hover } from "./interactions/hover.ts";
58
- import type { ElementRef } from "./interactions/press.ts";
91
+ import { hover, type HoverEvent } from "./interactions/hover.ts";
92
+ import { isFocusVisible as focusIsVisible } from "./interactions/modality.ts";
93
+ import type { ElementRef, PressEvent } from "./interactions/press.ts";
94
+ import { idFragment } from "./listbox.tsx";
95
+ import { visuallyHidden } from "./live.ts";
96
+ import { SelectionIndicatorProvider } from "./selection-indicator.tsx";
59
97
  import {
98
+ ListKeyboardDelegate,
60
99
  selectableItem,
61
100
  selectableList,
62
101
  type KeyboardDelegate,
63
102
  type LinkBehavior,
64
103
  } from "./selection.ts";
104
+ import { SharedElementTransition } from "./shared-element-transition.tsx";
65
105
  import {
66
106
  access,
107
+ callback,
67
108
  type DOMProps,
68
109
  filterDOMProps,
69
110
  fromProps,
@@ -82,22 +123,38 @@ export type KeyboardNavigationBehavior = "arrow" | "tab";
82
123
 
83
124
  export interface GridListOptions {
84
125
  ref: ElementRef;
126
+ /** The grid's id, which every row id is derived from. */
127
+ id?: MaybeAccessor<string | undefined>;
85
128
  shouldFocusWrap?: MaybeAccessor<boolean | undefined>;
86
129
  autoFocus?: MaybeAccessor<boolean | "first" | "last" | undefined>;
87
130
  disallowTypeAhead?: MaybeAccessor<boolean | undefined>;
88
131
  disallowEmptySelection?: MaybeAccessor<boolean | undefined>;
89
132
  isVirtualized?: MaybeAccessor<boolean | undefined>;
90
- /** @default "arrow" */
133
+ /** @default "arrow", and always "tab" in a grid layout */
91
134
  keyboardNavigationBehavior?: MaybeAccessor<KeyboardNavigationBehavior | undefined>;
135
+ /** Whether the rows are a stack or a grid the arrows move across. @default "stack" */
136
+ layout?: MaybeAccessor<"stack" | "grid" | undefined>;
137
+ /** @default "vertical" */
138
+ orientation?: MaybeAccessor<"horizontal" | "vertical" | undefined>;
92
139
  /** @default "action" */
93
140
  linkBehavior?: MaybeAccessor<LinkBehavior | undefined>;
94
141
  escapeKeyBehavior?: MaybeAccessor<"clearSelection" | "none" | undefined>;
142
+ /** Select on pointer up rather than down. */
143
+ shouldSelectOnPressUp?: MaybeAccessor<boolean | undefined>;
144
+ /**
145
+ * Whether an empty grid's empty state holds a Tab stop of its own, so the
146
+ * grid need not be one.
147
+ */
148
+ emptyStateIsTabbable?: MaybeAccessor<boolean | undefined>;
95
149
  keyboardDelegate?: KeyboardDelegate;
96
150
  /** Where the rows are, when the DOM cannot answer because they are not in it. */
97
151
  layoutDelegate?: LayoutDelegate;
98
152
  "aria-label"?: MaybeAccessor<string | undefined>;
99
153
  "aria-labelledby"?: MaybeAccessor<string | undefined>;
154
+ /** Called when a row is acted on, with its key. */
100
155
  onAction?: (key: Key) => void;
156
+ /** Whether `onAction` does anything. @default `onAction !== undefined` */
157
+ hasAction?: MaybeAccessor<boolean | undefined>;
101
158
  }
102
159
 
103
160
  export interface GridListResult {
@@ -106,19 +163,65 @@ export interface GridListResult {
106
163
  baseId: Accessor<string>;
107
164
  }
108
165
 
166
+ /** What a grid list tells its rows. */
167
+ interface GridListData {
168
+ baseId: Accessor<string>;
169
+ hasAction: Accessor<boolean>;
170
+ onAction: (key: Key) => void;
171
+ linkBehavior: Accessor<LinkBehavior>;
172
+ keyboardNavigationBehavior: Accessor<KeyboardNavigationBehavior>;
173
+ shouldSelectOnPressUp: Accessor<boolean | undefined>;
174
+ }
175
+
176
+ /** Keyed by the state, as the rows are handed it, whoever renders them. */
177
+ const gridData = new WeakMap<ListState<unknown>, GridListData>();
178
+
109
179
  export function gridList(options: GridListOptions, state: ListState<unknown>): GridListResult {
110
- const baseId = id();
180
+ const baseId = id(options.id);
181
+ const locale = useLocale();
182
+ const isEmpty = (): boolean => state.collection().size === 0;
183
+ const linkBehavior = (): LinkBehavior => access(options.linkBehavior) ?? "action";
184
+
185
+ const search = collator({ usage: "search", sensitivity: "base" });
186
+ const keyboardDelegate =
187
+ options.keyboardDelegate ??
188
+ new ListKeyboardDelegate({
189
+ collection: state.collection,
190
+ ref: options.ref,
191
+ disabledKeys: state.disabledKeys,
192
+ disabledBehavior: () => state.selectionManager().disabledBehavior,
193
+ collator: search,
194
+ layout: access(options.layout) === "grid" ? "grid" : "stack",
195
+ orientation: options.orientation,
196
+ direction: () => locale().direction,
197
+ layoutDelegate: options.layoutDelegate,
198
+ });
111
199
 
112
200
  const { listProps } = selectableList({
113
201
  ...options,
202
+ keyboardDelegate,
114
203
  selectionManager: state.selectionManager,
115
204
  collection: state.collection,
116
205
  disabledKeys: state.disabledKeys,
117
206
  selectOnFocus: () => state.selectionManager().selectionBehavior === "replace",
118
- linkBehavior: () => access(options.linkBehavior) ?? "action",
207
+ // Empty, there is nothing to move between or select, and Tab must be free
208
+ // to reach whatever the empty state holds.
209
+ allowsTabNavigation: isEmpty,
210
+ disallowSelectAll: isEmpty,
211
+ linkBehavior,
119
212
  });
120
213
 
121
- const isEmpty = (): boolean => state.collection().size === 0;
214
+ gridData.set(state, {
215
+ baseId,
216
+ hasAction: () => access(options.hasAction) ?? options.onAction !== undefined,
217
+ onAction: (key) => options.onAction?.(key),
218
+ linkBehavior,
219
+ keyboardNavigationBehavior: () =>
220
+ access(options.layout) === "grid"
221
+ ? "tab"
222
+ : (access(options.keyboardNavigationBehavior) ?? "arrow"),
223
+ shouldSelectOnPressUp: () => access(options.shouldSelectOnPressUp),
224
+ });
122
225
 
123
226
  return {
124
227
  baseId,
@@ -128,38 +231,123 @@ export function gridList(options: GridListOptions, state: ListState<unknown>): G
128
231
  "aria-multiselectable": () =>
129
232
  state.selectionManager().selectionMode === "multiple" ? true : undefined,
130
233
  // 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>)),
234
+ // land on it to be told it is empty, unless its empty state has a stop.
235
+ tabIndex: () => {
236
+ if (!isEmpty()) return access(listProps.tabIndex as MaybeAccessor<number>);
237
+ return access(options.emptyStateIsTabbable) === true ? -1 : 0;
238
+ },
133
239
  "aria-rowcount": () =>
134
- access(options.isVirtualized) === true ? state.collection().size : undefined,
240
+ access(options.isVirtualized) === true ? rowCount(state.collection()) : undefined,
135
241
  "aria-colcount": () => (access(options.isVirtualized) === true ? 1 : undefined),
136
242
  }),
137
243
  };
138
244
  }
139
245
 
140
- /** The id a row renders under, derived from the key so anything can name it. */
246
+ /** How many rows a collection holds: its items, without the sections around them. */
247
+ function rowCount(collection: Collection<unknown>): number {
248
+ let count = 0;
249
+ for (const key of collection.getKeys()) {
250
+ if (collection.getItem(key)?.type === "item") count++;
251
+ }
252
+ return count;
253
+ }
254
+
255
+ /** Counting from 1, as `aria-rowindex` does, with sections left out. */
256
+ function rowIndexOf(collection: Collection<unknown>, key: Key): number {
257
+ let index = 0;
258
+ for (const each of collection.getKeys()) {
259
+ if (collection.getItem(each)?.type !== "item") continue;
260
+ index++;
261
+ if (each === key) return index;
262
+ }
263
+ return 0;
264
+ }
265
+
266
+ /**
267
+ * The id a row renders under, derived from the key so anything can name it.
268
+ * The key is escaped: one holding a space would be two ids to
269
+ * `aria-labelledby`.
270
+ */
141
271
  export function rowIdFor(baseId: string, key: Key): string {
142
- return `${baseId}-row-${String(key)}`;
272
+ return `${baseId}-row-${idFragment(key)}`;
143
273
  }
144
274
 
145
275
  // ---------------------------------------------------------------------------
146
276
  // A row
147
277
  // ---------------------------------------------------------------------------
148
278
 
279
+ const strings = new StringDictionary<"select">({
280
+ "ar-AE": { select: "تحديد" },
281
+ "bg-BG": { select: "Изберете" },
282
+ "cs-CZ": { select: "Vybrat" },
283
+ "da-DK": { select: "Vælg" },
284
+ "de-DE": { select: "Auswählen" },
285
+ "el-GR": { select: "Επιλογή" },
286
+ "en-US": { select: "Select" },
287
+ "es-ES": { select: "Seleccionar" },
288
+ "et-EE": { select: "Vali" },
289
+ "fi-FI": { select: "Valitse" },
290
+ "fr-FR": { select: "Sélectionner" },
291
+ "he-IL": { select: "בחר" },
292
+ "hr-HR": { select: "Odaberite" },
293
+ "hu-HU": { select: "Kijelölés" },
294
+ "it-IT": { select: "Seleziona" },
295
+ "ja-JP": { select: "選択" },
296
+ "ko-KR": { select: "선택" },
297
+ "lt-LT": { select: "Pasirinkti" },
298
+ "lv-LV": { select: "Atlasīt" },
299
+ "nb-NO": { select: "Velg" },
300
+ "nl-NL": { select: "Selecteren" },
301
+ "pl-PL": { select: "Zaznacz" },
302
+ "pt-BR": { select: "Selecionar" },
303
+ "pt-PT": { select: "Selecionar" },
304
+ "ro-RO": { select: "Selectare" },
305
+ "ru-RU": { select: "Выбрать" },
306
+ "sk-SK": { select: "Vybrať" },
307
+ "sl-SI": { select: "Izberite" },
308
+ "sr-SP": { select: "Izaberite" },
309
+ "sv-SE": { select: "Markera" },
310
+ "tr-TR": { select: "Seç" },
311
+ "uk-UA": { select: "Вибрати" },
312
+ "zh-CN": { select: "选择" },
313
+ "zh-TW": { select: "選取" },
314
+ });
315
+
316
+ export type GridListFocusMode = "row" | "child";
317
+
149
318
  export interface GridListItemOptions {
150
319
  key: Key;
151
320
  ref: ElementRef;
152
- baseId: MaybeAccessor<string>;
321
+ /** @default the grid's own, from `gridList` */
322
+ baseId?: MaybeAccessor<string>;
153
323
  "aria-label"?: MaybeAccessor<string | undefined>;
154
324
  isDisabled?: MaybeAccessor<boolean | undefined>;
155
325
  isVirtualized?: MaybeAccessor<boolean | undefined>;
326
+ /** @default what the grid was given */
156
327
  shouldSelectOnPressUp?: MaybeAccessor<boolean | undefined>;
157
- /** @default "arrow" */
328
+ /** @default what the grid was given */
158
329
  keyboardNavigationBehavior?: MaybeAccessor<KeyboardNavigationBehavior | undefined>;
330
+ /** @default what the grid was given */
159
331
  linkBehavior?: MaybeAccessor<LinkBehavior | undefined>;
160
- onAction?: (key: Key) => void;
161
- /** See `selectableItem`. @default `onAction !== undefined` */
332
+ /**
333
+ * Whether focus arriving on the row moves on to its first tabbable control.
334
+ * @default "row"
335
+ */
336
+ focusMode?: MaybeAccessor<GridListFocusMode | undefined>;
337
+ /**
338
+ * Whether the arrow keys still move between rows while focus is on a
339
+ * control inside the row, under `"tab"` navigation.
340
+ */
341
+ allowsArrowNavigation?: MaybeAccessor<boolean | undefined>;
342
+ /** The row's own action, run before the grid's `onAction`. */
343
+ onAction?: () => void;
344
+ /** Whether `onAction` does anything. @default `onAction !== undefined` */
162
345
  hasAction?: MaybeAccessor<boolean | undefined>;
346
+ onPressStart?: (event: PressEvent) => void;
347
+ onPressEnd?: (event: PressEvent) => void;
348
+ onPressUp?: (event: PressEvent) => void;
349
+ onPress?: (event: PressEvent) => void;
350
+ onPressChange?: (isPressed: boolean) => void;
163
351
  }
164
352
 
165
353
  export interface GridListItemResult {
@@ -179,52 +367,66 @@ export function gridListItem(
179
367
  state: ListState<unknown>,
180
368
  ): GridListItemResult {
181
369
  const locale = useLocale();
182
- const node = (): Node<unknown> | null => state.collection().getItem(options.key);
183
- const rowId = (): string => rowIdFor(access(options.baseId), options.key);
370
+ const data = gridData.get(state);
371
+ const key = options.key;
372
+ const manager = (): SelectionManager => state.selectionManager();
373
+ const node = (): Node<unknown> | null => state.collection().getItem(key);
374
+ const baseId = (): string => access(options.baseId) ?? data?.baseId() ?? "";
375
+ const rowId = (): string => rowIdFor(baseId(), key);
184
376
  const behavior = (): KeyboardNavigationBehavior =>
185
- access(options.keyboardNavigationBehavior) ?? "arrow";
377
+ access(options.keyboardNavigationBehavior) ?? data?.keyboardNavigationBehavior() ?? "arrow";
378
+ const focusMode = (): GridListFocusMode => access(options.focusMode) ?? "row";
379
+ const allowsArrows = (): boolean => access(options.allowsArrowNavigation) === true;
380
+ const ownAction = (): unknown => node()?.props?.onAction;
186
381
 
187
382
  const item = selectableItem({
188
- key: options.key,
383
+ key,
189
384
  ref: options.ref,
190
385
  id: rowId,
191
386
  selectionManager: state.selectionManager,
192
387
  isDisabled: options.isDisabled,
193
- shouldSelectOnPressUp: options.shouldSelectOnPressUp,
194
- linkBehavior: options.linkBehavior,
388
+ shouldSelectOnPressUp: () =>
389
+ access(options.shouldSelectOnPressUp) === true || data?.shouldSelectOnPressUp() === true,
390
+ linkBehavior: () => access(options.linkBehavior) ?? data?.linkBehavior() ?? "action",
195
391
  hasAction: () =>
196
- access(options.hasAction) ??
197
- (options.onAction !== undefined || node()?.props?.onAction !== undefined),
392
+ (access(options.hasAction) ?? options.onAction !== undefined) ||
393
+ typeof ownAction() === "function" ||
394
+ data?.hasAction() === true,
198
395
  onAction: () => {
199
- const own = node()?.props?.onAction;
396
+ options.onAction?.();
397
+ const own = ownAction();
200
398
  if (typeof own === "function") (own as () => void)();
201
- options.onAction?.(options.key);
399
+ if (data?.hasAction() === true) data.onAction(key);
202
400
  },
401
+ onPressStart: options.onPressStart,
402
+ onPressEnd: options.onPressEnd,
403
+ onPressUp: options.onPressUp,
404
+ onPress: options.onPress,
405
+ onPressChange: options.onPressChange,
203
406
  });
204
407
 
205
408
  const row = (): HTMLElement | null => (access(options.ref) as HTMLElement | null) ?? null;
206
409
 
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 => {
410
+ const lastFocusable = (element: HTMLElement): HTMLElement | null => {
215
411
  const walker = focusableWalker(element);
216
412
  walker.currentNode = element;
217
- return walker.last() as Element | null;
413
+ return walker.last() as HTMLElement | null;
218
414
  };
219
415
 
416
+ // Set when the arrow keys walk off the end of the row back onto it, which
417
+ // is the one way onto a child-focused row that must not move on again.
418
+ let standOnRow = false;
419
+
220
420
  /**
221
421
  * Captured, not bubbled.
222
422
  *
223
423
  * A control inside the row would otherwise see these first: a menu button
224
424
  * takes Down to open, a text field takes Left to move the caret. The row has
225
- * to decide before they do.
425
+ * to decide before they do. Under tab navigation the control keeps them,
426
+ * unless the row allows arrow navigation from its controls.
226
427
  */
227
428
  const onKeyDownCapture = (event: KeyboardEvent): void => {
429
+ if (behavior() !== "arrow" && !allowsArrows()) return;
228
430
  const element = row();
229
431
  if (element === null) return;
230
432
  const target = targetElement(event);
@@ -241,7 +443,8 @@ export function gridListItem(
241
443
  event.preventDefault();
242
444
  event.stopPropagation();
243
445
 
244
- const walker = walkerAt(element, active);
446
+ const walker = focusableWalker(element);
447
+ walker.currentNode = active;
245
448
  const next = (
246
449
  event.key === inwards ? walker.nextNode() : walker.previousNode()
247
450
  ) as HTMLElement | null;
@@ -255,10 +458,11 @@ export function gridListItem(
255
458
  // the up and down keys work from; backwards past the first control wraps
256
459
  // to the last, so the cycle is row, first, …, last, row.
257
460
  if (event.key === inwards) {
461
+ standOnRow = true;
258
462
  focusSafely(element);
259
463
  return;
260
464
  }
261
- const last = lastFocusable(element) as HTMLElement | null;
465
+ const last = lastFocusable(element);
262
466
  if (last !== null) focusSafely(last);
263
467
  return;
264
468
  }
@@ -286,31 +490,91 @@ export function gridListItem(
286
490
  };
287
491
 
288
492
  /**
289
- * Tab within the row, when that is the navigation mode.
493
+ * Under tab navigation a key typed into a control in the row is the
494
+ * control's: it must not move rows, select, or start a typeahead. Tab still
495
+ * goes up, so the list can let focus out, unless there is another control
496
+ * in the row for the browser's own Tab to reach.
290
497
  *
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.
498
+ * Answers whether it stopped the event, so the row's own press does not see
499
+ * it either: Space in a field would otherwise select the row.
294
500
  */
295
- const onKeyDown = (event: KeyboardEvent): void => {
296
- if (event.key !== "Tab" || behavior() !== "tab") return;
501
+ const onKeyDown = (event: KeyboardEvent): boolean => {
502
+ if (behavior() !== "tab") return false;
297
503
  const element = row();
298
- if (element === null) return;
504
+ if (element === null || !contains(element, targetElement(event))) return false;
299
505
  const active = activeElement(ownerDocument(element));
300
- if (active === null) return;
506
+ if (active === null) return false;
301
507
 
508
+ if (targetElement(event) !== element && event.key !== "Tab") {
509
+ event.stopPropagation();
510
+ return true;
511
+ }
512
+
513
+ if (event.key === "Tab") {
514
+ const walker = focusableWalker(element, { tabbable: true });
515
+ walker.currentNode = active;
516
+ const next = event.shiftKey ? walker.previousNode() : walker.nextNode();
517
+ if (next !== null) {
518
+ event.stopPropagation();
519
+ return true;
520
+ }
521
+ }
522
+ return false;
523
+ };
524
+
525
+ const focusFirstChild = (element: HTMLElement): void => {
302
526
  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();
527
+ const first = walker.nextNode() as HTMLElement | null;
528
+ if (first === null) return;
529
+ focusSafely(first);
530
+ scrollIntoViewport(first, { containingElement: scrollParents(element)[0] ?? null });
306
531
  };
307
532
 
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);
533
+ const onFocusIn = (event: FocusEvent): void => {
534
+ const element = row();
535
+ if (element === null) return;
536
+ if (targetElement(event) !== element) {
537
+ // `selectableItem` only claims focus that lands on the row itself. A
538
+ // control inside it focused by pointer makes the row the one the arrows
539
+ // work from; from the keyboard the focused row already is.
540
+ if (!focusIsVisible()) manager().setFocusedKey(key);
541
+ return;
542
+ }
543
+ const stay = standOnRow;
544
+ standOnRow = false;
545
+ if (focusMode() !== "child" || stay) return;
546
+ // A frame later, once the focus has finished arriving at the list.
547
+ requestAnimationFrame(() => {
548
+ if (activeElement(ownerDocument(element)) === element) focusFirstChild(element);
549
+ });
550
+ };
551
+
552
+ const rowProps = mergeProps(item.itemProps, {
553
+ role: "row",
554
+ id: rowId,
555
+ onKeyDownCapture,
556
+ onFocusIn,
557
+ "aria-label": () =>
558
+ access(options["aria-label"]) ??
559
+ (node()?.["aria-label"] || undefined) ??
560
+ (node()?.textValue || undefined),
561
+ // Only where selection is possible: on a list that only performs
562
+ // actions the attribute would say every row is unselected rather than
563
+ // that selection is not the point.
564
+ "aria-selected": () => (manager().canSelectItem(key) ? item.isSelected() : undefined),
565
+ "aria-disabled": () => item.isDisabled() || undefined,
566
+ "aria-rowindex": () =>
567
+ access(options.isVirtualized) === true ? rowIndexOf(state.collection(), key) : undefined,
568
+ // Focus that the row hands on to a control must not be taken back.
569
+ tabIndex: () => {
570
+ if (focusMode() === "child" && allowsArrows() && behavior() === "tab") return -1;
571
+ return access(item.itemProps.tabIndex as MaybeAccessor<number | undefined>);
572
+ },
573
+ });
574
+
575
+ const pressKeyDown = rowProps.onKeyDown as ((event: KeyboardEvent) => void) | undefined;
576
+ rowProps.onKeyDown = (event: KeyboardEvent): void => {
577
+ if (!onKeyDown(event)) pressKeyDown?.(event);
314
578
  };
315
579
 
316
580
  return {
@@ -321,23 +585,45 @@ export function gridListItem(
321
585
  allowsSelection: item.allowsSelection,
322
586
  hasAction: item.hasAction,
323
587
  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
- }),
588
+ rowProps,
589
+ };
590
+ }
591
+
592
+ export interface GridListSelectionCheckboxOptions {
593
+ key: Key;
594
+ }
595
+
596
+ export interface GridListSelectionCheckboxResult {
597
+ checkboxProps: {
598
+ id: Accessor<string>;
599
+ "aria-label": Accessor<string>;
600
+ "aria-labelledby": Accessor<string>;
601
+ isSelected: Accessor<boolean>;
602
+ isDisabled: Accessor<boolean>;
603
+ onChange: () => void;
604
+ };
605
+ }
606
+
607
+ /**
608
+ * A checkbox that selects one row, named "Select" followed by the row's name.
609
+ * It toggles whatever the selection behaviour, as a checkbox does.
610
+ */
611
+ export function gridListSelectionCheckbox(
612
+ options: GridListSelectionCheckboxOptions,
613
+ state: ListState<unknown>,
614
+ ): GridListSelectionCheckboxResult {
615
+ const message = stringFormatter(strings);
616
+ const checkboxId = id();
617
+ const baseId = gridData.get(state)?.baseId;
618
+ return {
619
+ checkboxProps: {
620
+ id: checkboxId,
621
+ "aria-label": () => message().format("select"),
622
+ "aria-labelledby": () => `${checkboxId()} ${rowIdFor(baseId?.() ?? "", options.key)}`,
623
+ isSelected: () => state.selectionManager().isSelected(options.key),
624
+ isDisabled: () => !state.selectionManager().canSelectItem(options.key),
625
+ onChange: () => state.selectionManager().toggleSelection(options.key),
626
+ },
341
627
  };
342
628
  }
343
629
 
@@ -348,8 +634,10 @@ export function gridListItem(
348
634
  interface GridListContextValue {
349
635
  state: ListState<unknown>;
350
636
  baseId: Accessor<string>;
351
- keyboardNavigationBehavior: Accessor<KeyboardNavigationBehavior>;
352
- onAction: Accessor<((key: Key) => void) | undefined>;
637
+ /** The list's item callback, which a section renders its rows with. */
638
+ render?: ((item: unknown) => Child) | undefined;
639
+ /** The list's drag and drop, when it was given `dragAndDropHooks`. */
640
+ dragAndDrop?: CollectionDragAndDrop | undefined;
353
641
  }
354
642
 
355
643
  const GridListContext = createContext<GridListContextValue | null>(null);
@@ -373,12 +661,10 @@ export function useRowNode(): Node<unknown> {
373
661
  }
374
662
 
375
663
  /** Make `<GridListItem>` usable inside something that is not a `<GridList>`. */
376
- export function GridListProvider(
377
- props: Incoming<{ value: GridListContextValue; children?: Child }>,
378
- ) {
664
+ export function GridListProvider(props: { value: GridListContextValue; children?: Child }) {
379
665
  return provide(
380
666
  GridListContext,
381
- () => props.value(),
667
+ () => props.value,
382
668
  () => props.children as unknown,
383
669
  );
384
670
  }
@@ -389,27 +675,57 @@ export function provideRowNode(node: Node<unknown>): void {
389
675
  if (owner !== null) install(owner, RowNodeContext, () => node);
390
676
  }
391
677
 
678
+ /** What a grid list hands to its empty state. Every field follows the list. */
679
+ export interface GridListRenderState {
680
+ isEmpty: Accessor<boolean>;
681
+ isFocused: Accessor<boolean>;
682
+ isFocusVisible: Accessor<boolean>;
683
+ isDropTarget: Accessor<boolean>;
684
+ layout: Accessor<"stack" | "grid">;
685
+ orientation: Accessor<"horizontal" | "vertical">;
686
+ state: ListState<unknown>;
687
+ }
688
+
392
689
  export interface GridListComponentProps<T> extends StyleProps, ItemAccessors<T> {
393
- /** The rows, in order. */
690
+ /** The rows, in order. An item with children is a section of rows. */
394
691
  items: Iterable<T>;
395
- /** How one row renders. Return a `<GridListItem>`. */
692
+ /** How one row renders. Return a `<GridListItem>`, or a `<GridListSection>`. */
396
693
  children: (item: T) => Child;
397
694
  /** @default "none" */
398
695
  selectionMode?: SelectionMode;
399
- selectionBehavior?: "toggle" | "replace";
696
+ /** @default "toggle" */
697
+ selectionBehavior?: SelectionBehavior;
400
698
  selectedKeys?: "all" | Iterable<Key>;
401
699
  defaultSelectedKeys?: "all" | Iterable<Key>;
402
700
  disabledKeys?: Iterable<Key>;
701
+ /** Whether `disabledKeys` stops everything, or only selection. @default "all" */
702
+ disabledBehavior?: DisabledBehavior;
403
703
  disallowEmptySelection?: boolean;
704
+ disallowTypeAhead?: boolean;
404
705
  shouldFocusWrap?: boolean;
405
706
  autoFocus?: boolean | "first" | "last";
406
- /** @default "arrow" */
707
+ /** @default "arrow", and always "tab" in a grid layout */
407
708
  keyboardNavigationBehavior?: KeyboardNavigationBehavior;
709
+ /** Whether the rows are a stack or a grid the arrows move across. @default "stack" */
710
+ layout?: "stack" | "grid";
711
+ /** @default "vertical" */
712
+ orientation?: "horizontal" | "vertical";
713
+ /** @default "clearSelection" */
714
+ escapeKeyBehavior?: "clearSelection" | "none";
715
+ /** Select on pointer up rather than down. */
716
+ shouldSelectOnPressUp?: boolean;
717
+ /** What to show when there are no rows. */
718
+ renderEmptyState?: (grid: GridListRenderState) => Child;
408
719
  "aria-label"?: string;
409
720
  "aria-labelledby"?: string;
410
721
  ref?: RefTarget<HTMLDivElement>;
411
722
  onSelectionChange?: (keys: "all" | Set<Key>) => void;
412
723
  onAction?: (key: Key) => void;
724
+ /**
725
+ * Drag and drop, from `dragAndDrop()`. A draggable row needs a
726
+ * `<DragButton>` for keyboard and screen reader users to drag it with.
727
+ */
728
+ dragAndDropHooks?: DragAndDropHooks;
413
729
  }
414
730
 
415
731
  /**
@@ -424,51 +740,91 @@ export interface GridListComponentProps<T> extends StyleProps, ItemAccessors<T>
424
740
  * </GridList>
425
741
  * ```
426
742
  */
427
- export function GridList<T>(props: Incoming<GridListComponentProps<T>>) {
743
+ export function GridList<T>(props: GridListComponentProps<T>) {
428
744
  const domRef = makeRef<HTMLDivElement>();
429
- const options = fromProps(props as unknown as Incoming<Record<string, unknown>>);
745
+ const options = fromProps(cells(props) as unknown as Incoming<Record<string, unknown>>);
430
746
 
431
747
  const state = listState<T>({
432
748
  ...(options as ListStateOptions<T>),
433
- onSelectionChange: (keys) => props.onSelectionChange?.()?.(keys),
749
+ onSelectionChange: (keys) => props.onSelectionChange?.(keys),
434
750
  });
751
+ const anyState = state as unknown as ListState<unknown>;
435
752
 
436
753
  // Inside a `<Virtualizer>` the list renders a WINDOW of its collection, and
437
754
  // the layout — not the DOM — answers what is above, below and a page away.
438
755
  const virtual = useVirtualizer();
439
- virtual?.attach(state.collection, domRef, () => state.selectionManager().focusedKey);
756
+ const dropping: { held?: CollectionDragAndDrop } = {};
757
+ virtual?.attach(
758
+ state.collection,
759
+ domRef,
760
+ () => state.selectionManager().focusedKey,
761
+ () => dropping.held?.persistedKeys() ?? [],
762
+ );
763
+
764
+ const isEmpty = (): boolean => state.collection().size === 0;
765
+ // Whether the empty state holds a Tab stop, so the grid need not be one.
766
+ const [emptyStateIsTabbable, setEmptyStateIsTabbable] = createSignal(false);
767
+ if (!isServer) {
768
+ createEffect(
769
+ () => [isEmpty(), domRef()] as const,
770
+ ([empty, element]) => {
771
+ setEmptyStateIsTabbable(
772
+ empty &&
773
+ element !== null &&
774
+ focusableWalker(element, { tabbable: true }).nextNode() !== null,
775
+ );
776
+ },
777
+ );
778
+ }
440
779
 
441
780
  const { gridProps, baseId } = gridList(
442
781
  {
443
782
  ...(options as unknown as GridListOptions),
444
783
  ref: domRef,
784
+ onAction: (key) => props.onAction?.(key),
785
+ hasAction: () => props.onAction !== undefined,
786
+ emptyStateIsTabbable,
445
787
  isVirtualized: () => virtual !== null,
446
788
  layoutDelegate: virtual?.layout,
447
789
  },
448
- state,
790
+ anyState,
449
791
  );
450
792
 
793
+ const dragAndDrop = gridListDragAndDrop(props.dragAndDropHooks, anyState, domRef, virtual);
794
+ dropping.held = dragAndDrop;
795
+ const render = props.children as unknown as (item: unknown) => Child;
796
+
451
797
  const value: GridListContextValue = {
452
- state: state,
798
+ state: anyState,
453
799
  baseId,
454
- keyboardNavigationBehavior: () => props.keyboardNavigationBehavior?.() ?? "arrow",
455
- onAction: () => props.onAction?.(),
800
+ render,
801
+ dragAndDrop,
456
802
  };
457
803
 
804
+ const { focusProps, isFocused, isFocusVisible } = focusRing();
805
+ const layout = (): "stack" | "grid" => props.layout ?? "stack";
806
+ const orientation = (): "horizontal" | "vertical" => props.orientation ?? "vertical";
807
+ const isDropTarget = (): boolean => dragAndDrop?.isRootDropTarget() === true;
808
+
458
809
  const elementProps = mergeProps(
459
810
  gridProps,
460
- filterDOMProps(fromProps(props), { global: true }),
461
- styleProps(props),
811
+ focusProps,
812
+ dragAndDrop?.collectionProps,
813
+ filterDOMProps(fromProps(cells(props)), { global: true }),
814
+ styleProps(cells(props)),
462
815
  {
463
- "data-empty": () => state.collection().size === 0,
816
+ "data-empty": isEmpty,
817
+ "data-focused": isFocused,
818
+ "data-focus-visible": isFocusVisible,
819
+ "data-layout": layout,
820
+ "data-orientation": orientation,
464
821
  "data-virtualized": () => virtual !== null,
465
- "data-testid": () => props["data-testid"]?.(),
466
- style: () => (virtual === null ? props.style?.() : contentStyle(virtual.contentSize())),
822
+ "data-testid": () => props["data-testid"],
823
+ "data-drop-target": isDropTarget,
824
+ style: () => (virtual === null ? props.style : contentStyle(virtual.contentSize())),
467
825
  },
468
826
  );
469
827
 
470
- const render = props.children;
471
-
472
828
  /** The whole collection, or the window of it the virtualiser says is on screen. */
473
829
  const rows = (): Node<T>[] => {
474
830
  if (virtual === null) return [...state.collection()];
@@ -479,85 +835,520 @@ export function GridList<T>(props: Incoming<GridListComponentProps<T>>) {
479
835
  .filter((node: Node<T> | null): node is Node<T> => node !== null);
480
836
  };
481
837
 
838
+ const renderState: GridListRenderState = {
839
+ isEmpty,
840
+ isFocused,
841
+ isFocusVisible,
842
+ isDropTarget,
843
+ layout,
844
+ orientation,
845
+ state: anyState,
846
+ };
847
+ const renderEmpty = callback(cells(props).renderEmptyState);
848
+ const emptyState = (): Child => {
849
+ if (!isEmpty() || renderEmpty === undefined) return null;
850
+ return (
851
+ <div role="row" aria-rowindex={1} style={{ display: "contents" }}>
852
+ <div role="gridcell" style={{ display: "contents" }}>
853
+ {renderEmpty(renderState)}
854
+ </div>
855
+ </div>
856
+ );
857
+ };
858
+
482
859
  return (
483
860
  <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>
861
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref)}>
862
+ {dragAndDrop?.dropState === undefined ? null : <GridListRootDropIndicator />}
863
+ <SharedElementTransition>
864
+ <For each={rows}>
865
+ {(node: Node<T>) => {
866
+ provideRowNode(node);
867
+ return render(node.value);
868
+ }}
869
+ </For>
870
+ </SharedElementTransition>
871
+ {emptyState}
491
872
  </div>
873
+ {dragAndDrop?.preview}
492
874
  </GridListProvider>
493
875
  );
494
876
  }
495
877
 
878
+ function gridListDragAndDrop(
879
+ hooks: DragAndDropHooks | undefined,
880
+ state: ListState<unknown>,
881
+ domRef: Accessor<HTMLDivElement | null>,
882
+ virtual: VirtualizerValue | null,
883
+ ): CollectionDragAndDrop | undefined {
884
+ if (hooks === undefined) return undefined;
885
+ const layoutDelegate = virtual?.layout;
886
+ const locale = useLocale();
887
+ const direction = (): "ltr" | "rtl" => locale().direction;
888
+ const collection = state.collection as Accessor<Collection<unknown>>;
889
+
890
+ const dragAndDrop = collectionDragAndDrop({
891
+ virtual,
892
+ hooks,
893
+ collection,
894
+ selectionManager: state.selectionManager,
895
+ ref: domRef,
896
+ // A position next to a disabled row is still a place to drop.
897
+ keyboardDelegate: new ListKeyboardDelegate({
898
+ collection,
899
+ ref: domRef,
900
+ disabledBehavior: () => "selection",
901
+ direction,
902
+ layoutDelegate,
903
+ }),
904
+ direction,
905
+ });
906
+
907
+ if (dragAndDrop.dropState !== undefined) {
908
+ provideDropIndicator({ render: (props) => <GridListDropIndicator of={props} /> });
909
+ }
910
+ return dragAndDrop;
911
+ }
912
+
913
+ /**
914
+ * A drop indicator in a grid list: a row, so the grid's structure holds, with
915
+ * the focusable target a visually hidden button inside its cell.
916
+ */
917
+ function GridListDropIndicator(indicator: { of: Incoming<DropIndicatorProps> }) {
918
+ const props = indicator.of;
919
+ const { dragAndDropHooks, dropState } = useDragAndDropContext();
920
+ if (dragAndDropHooks?.dropIndicator === undefined || dropState === undefined) {
921
+ throw new Error("A DropIndicator must be rendered inside a droppable GridList.");
922
+ }
923
+
924
+ const buttonRef = makeRef<HTMLDivElement>();
925
+ const virtual = useVirtualizer();
926
+ const placed = (): Record<string, string> | undefined => {
927
+ const target = props.target();
928
+ return target.type === "item" ? dropIndicatorStyle(virtual, target) : undefined;
929
+ };
930
+ const { visuallyHiddenProps } = visuallyHidden();
931
+ const { dropIndicatorProps, isDropTarget, isHidden } = dragAndDropHooks.dropIndicator(
932
+ { target: props.target() },
933
+ dropState,
934
+ buttonRef,
935
+ );
936
+
937
+ return (
938
+ <Show when={!isHidden()}>
939
+ <div
940
+ {...styleProps(props)}
941
+ {...(virtual === null ? {} : { style: placed })}
942
+ role="row"
943
+ data-slot={props["data-slot"]?.() ?? "drop-indicator"}
944
+ data-drop-target={isDropTarget()}
945
+ >
946
+ <div role="gridcell">
947
+ <div {...visuallyHiddenProps} role="button" {...dropIndicatorProps} ref={buttonRef.set} />
948
+ {props.children?.()}
949
+ </div>
950
+ </div>
951
+ </Show>
952
+ );
953
+ }
954
+
955
+ /** The target for a drop on the whole list, there for keyboard and screen reader drags. */
956
+ function GridListRootDropIndicator() {
957
+ const { dragAndDropHooks, dropState } = useDragAndDropContext();
958
+ if (dragAndDropHooks?.dropIndicator === undefined || dropState === undefined) return null;
959
+
960
+ const buttonRef = makeRef<HTMLDivElement>();
961
+ const { visuallyHiddenProps } = visuallyHidden();
962
+ const { dropIndicatorProps, isDropTarget } = dragAndDropHooks.dropIndicator(
963
+ { target: { type: "root" } },
964
+ dropState,
965
+ buttonRef,
966
+ );
967
+ const ariaHidden = dropIndicatorProps["aria-hidden"] as Accessor<string | undefined>;
968
+
969
+ return (
970
+ <Show when={isDropTarget() || ariaHidden() === undefined}>
971
+ <div
972
+ role="row"
973
+ aria-hidden={ariaHidden() === "true" ? true : undefined}
974
+ style={{ position: "absolute" }}
975
+ >
976
+ <div role="gridcell">
977
+ <div {...visuallyHiddenProps} role="button" {...dropIndicatorProps} ref={buttonRef.set} />
978
+ </div>
979
+ </div>
980
+ </Show>
981
+ );
982
+ }
983
+
496
984
  export interface GridListItemComponentProps extends StyleProps {
497
985
  children?: Child;
498
986
  "aria-label"?: string;
499
987
  ref?: RefTarget<HTMLDivElement>;
988
+ /** @default "row" */
989
+ focusMode?: GridListFocusMode;
990
+ /** Let the arrow keys move between rows from a control in the row under `"tab"` navigation. */
991
+ allowsArrowNavigation?: boolean;
992
+ /** Performed on this row, before the list's own `onAction`. */
993
+ onAction?: () => void;
994
+ onPress?: (event: PressEvent) => void;
995
+ onPressStart?: (event: PressEvent) => void;
996
+ onPressEnd?: (event: PressEvent) => void;
997
+ onPressUp?: (event: PressEvent) => void;
998
+ onPressChange?: (isPressed: boolean) => void;
999
+ onHoverStart?: (event: HoverEvent) => void;
1000
+ onHoverEnd?: (event: HoverEvent) => void;
1001
+ onHoverChange?: (isHovered: boolean) => void;
1002
+ onFocusChange?: (isFocused: boolean) => void;
1003
+ }
1004
+
1005
+ interface GridListRowValue {
1006
+ key: Key;
1007
+ state: ListState<unknown>;
500
1008
  }
501
1009
 
1010
+ const GridListRowContext = createContext<GridListRowValue | null>(null);
1011
+
502
1012
  /**
503
1013
  * One row, holding one cell.
504
1014
  *
505
1015
  * The cell is what the row's content goes in: a row may not contain content
506
1016
  * directly, and a screen reader reports "row 2 of 7" from the pair.
507
1017
  */
508
- export function GridListItem(props: Incoming<GridListItemComponentProps>) {
1018
+ export function GridListItem(props: GridListItemComponentProps) {
509
1019
  const domRef = makeRef<HTMLDivElement>();
510
1020
  const virtual = useVirtualizer();
511
1021
  const list = useGridList();
512
1022
  const node = useRowNode();
1023
+ const options = fromProps(cells(props));
1024
+ const dnd = rowDragAndDrop(list, node.key);
513
1025
 
514
1026
  measureRow(virtual, node.key, domRef);
515
1027
 
516
- const { rowProps, gridCellProps, isSelected, isFocused, isPressed, isDisabled } = gridListItem(
1028
+ const {
1029
+ rowProps,
1030
+ gridCellProps,
1031
+ isSelected,
1032
+ isFocused,
1033
+ isPressed,
1034
+ isDisabled,
1035
+ allowsSelection,
1036
+ hasAction,
1037
+ } = gridListItem(
517
1038
  {
518
1039
  key: node.key,
519
1040
  ref: domRef,
520
1041
  baseId: list.baseId,
521
1042
  isVirtualized: () => virtual !== null,
522
- "aria-label": () => props["aria-label"]?.(),
1043
+ "aria-label": () => props["aria-label"],
523
1044
  isDisabled: () => node.props?.isDisabled === true,
524
- keyboardNavigationBehavior: list.keyboardNavigationBehavior,
525
- hasAction: () => list.onAction() !== undefined || node.props?.onAction !== undefined,
526
- onAction: (key) => list.onAction()?.(key),
1045
+ focusMode: () => props.focusMode,
1046
+ allowsArrowNavigation: () => props.allowsArrowNavigation,
1047
+ onAction: () => props.onAction?.(),
1048
+ hasAction: () => props.onAction !== undefined,
1049
+ // Selecting on release lets a press that becomes a drag leave the
1050
+ // selection alone, unless only the drag button starts a drag.
1051
+ shouldSelectOnPressUp: () =>
1052
+ dnd?.collection.dragState !== undefined &&
1053
+ dnd.collection.hooks?.pointerDragSource !== "handle",
1054
+ onPress: options.onPress,
1055
+ onPressStart: options.onPressStart,
1056
+ onPressEnd: options.onPressEnd,
1057
+ onPressUp: options.onPressUp,
1058
+ onPressChange: options.onPressChange,
527
1059
  },
528
1060
  list.state,
529
1061
  );
530
1062
 
531
- const { hoverProps, isHovered } = hover({ isDisabled });
1063
+ const isDraggable = (): boolean =>
1064
+ dnd?.collection.dragState !== undefined && !list.state.selectionManager().isDisabled(node.key);
1065
+ const { hoverProps, isHovered } = hover({
1066
+ isDisabled: () => !allowsSelection() && !hasAction() && !isDraggable(),
1067
+ onHoverStart: options.onHoverStart,
1068
+ onHoverEnd: options.onHoverEnd,
1069
+ onHoverChange: options.onHoverChange,
1070
+ });
1071
+ const { focusProps: focusEventProps } = focused({ onFocusChange: options.onFocusChange });
532
1072
  const { focusProps, isFocusVisible } = focusRing();
1073
+ const { focusProps: withinProps, isFocusVisible: isFocusVisibleWithin } = focusRing({
1074
+ within: true,
1075
+ });
1076
+ const selectionMode = (): SelectionMode => list.state.selectionManager().selectionMode;
533
1077
 
534
1078
  const elementProps = mergeProps(
535
1079
  rowProps,
536
1080
  hoverProps,
1081
+ focusEventProps,
537
1082
  focusProps,
538
- filterDOMProps(fromProps(props), { global: true }),
539
- styleProps(props),
1083
+ withinProps,
1084
+ // The id is the one the key gives it, which a selection checkbox names.
1085
+ filterDOMProps(options, { global: true, id: false }),
1086
+ styleProps(cells(props)),
540
1087
  {
541
1088
  "data-selected": isSelected,
542
1089
  "data-focused": isFocused,
543
1090
  "data-focus-visible": isFocusVisible,
1091
+ "data-focus-visible-within": isFocusVisibleWithin,
544
1092
  "data-pressed": isPressed,
545
1093
  "data-hovered": isHovered,
546
1094
  "data-disabled": isDisabled,
547
- "data-testid": () => props["data-testid"]?.(),
1095
+ "data-selection-mode": () => (selectionMode() === "none" ? undefined : selectionMode()),
1096
+ "data-testid": () => props["data-testid"],
548
1097
  // Positioned by the LAYOUT: the rows above it are not rendered, so
549
1098
  // document flow has nothing to place it against.
550
1099
  style: () => {
551
- if (virtual === null) return props.style?.();
1100
+ if (virtual === null) return props.style;
552
1101
  const info = virtual.layout.getLayoutInfo(node.key);
553
- return info === null ? props.style?.() : rowStyle(info);
1102
+ return info === null ? props.style : rowStyle(info);
554
1103
  },
555
1104
  },
1105
+ dnd?.itemProps,
1106
+ );
1107
+
1108
+ const rowValue: GridListRowValue = { key: node.key, state: list.state };
1109
+
1110
+ const row = (
1111
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref)}>
1112
+ <div {...gridCellProps}>
1113
+ <SelectionIndicatorProvider isSelected={isSelected()}>
1114
+ {provide(
1115
+ GridListRowContext,
1116
+ () => rowValue,
1117
+ () => props.children as unknown,
1118
+ )}
1119
+ </SelectionIndicatorProvider>
1120
+ </div>
1121
+ </div>
1122
+ );
1123
+ if (dnd === null) return row;
1124
+
1125
+ const { visuallyHiddenProps } = visuallyHidden();
1126
+ const on = dnd.on;
1127
+
1128
+ return (
1129
+ <>
1130
+ <Show when={dnd.collection.shouldRenderIndicator(dnd.before)}>
1131
+ {dnd.collection.renderDropIndicator(dnd.before)}
1132
+ </Show>
1133
+ {on === null ? null : (
1134
+ <Show when={!on.indicator.isHidden()}>
1135
+ <div role="row" style={{ position: "absolute" }}>
1136
+ <div role="gridcell">
1137
+ <div
1138
+ role="button"
1139
+ {...visuallyHiddenProps}
1140
+ {...on.indicator.dropIndicatorProps}
1141
+ ref={on.ref.set}
1142
+ />
1143
+ </div>
1144
+ </div>
1145
+ </Show>
1146
+ )}
1147
+ {row}
1148
+ <For each={dnd.after()}>
1149
+ {(target: ItemDropTarget) => (
1150
+ <Show when={dnd.collection.shouldRenderIndicator(target)}>
1151
+ {dnd.collection.renderDropIndicator(target)}
1152
+ </Show>
1153
+ )}
1154
+ </For>
1155
+ </>
556
1156
  );
1157
+ }
1158
+
1159
+ export interface GridListSelectionCheckboxProps extends StyleProps {
1160
+ /** What is drawn inside the checkbox. */
1161
+ children?: Child;
1162
+ }
557
1163
 
1164
+ /**
1165
+ * A checkbox that selects its row, named "Select" followed by the row's name.
1166
+ *
1167
+ * A press on it is the checkbox's, not the row's, so under `"replace"`
1168
+ * selection it adds to the selection rather than replacing it.
1169
+ */
1170
+ export function GridListSelectionCheckbox(props: GridListSelectionCheckboxProps) {
1171
+ const row = getContext(GridListRowContext);
1172
+ if (row === null || row === undefined) {
1173
+ throw new Error("A GridListSelectionCheckbox must be rendered inside a GridListItem.");
1174
+ }
1175
+ const { checkboxProps: box } = gridListSelectionCheckbox({ key: row.key }, row.state);
558
1176
  return (
559
- <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
560
- <div {...gridCellProps}>{props.children}</div>
1177
+ <Checkbox
1178
+ id={box.id()}
1179
+ aria-label={box["aria-label"]()}
1180
+ aria-labelledby={box["aria-labelledby"]()}
1181
+ isSelected={box.isSelected()}
1182
+ isDisabled={box.isDisabled()}
1183
+ onChange={() => box.onChange()}
1184
+ class={props.class}
1185
+ style={props.style}
1186
+ >
1187
+ {props.children}
1188
+ </Checkbox>
1189
+ );
1190
+ }
1191
+
1192
+ // ---------------------------------------------------------------------------
1193
+ // Sections
1194
+ // ---------------------------------------------------------------------------
1195
+
1196
+ interface GridListSectionValue {
1197
+ headingId: Accessor<string>;
1198
+ registerHeader(): () => void;
1199
+ }
1200
+
1201
+ const GridListSectionContext = createContext<GridListSectionValue | null>(null);
1202
+
1203
+ export interface GridListSectionProps extends StyleProps {
1204
+ /** A `<GridListHeader>`. The section's rows are rendered after it. */
1205
+ children?: Child;
1206
+ "aria-label"?: string;
1207
+ ref?: RefTarget<HTMLDivElement>;
1208
+ }
1209
+
1210
+ /**
1211
+ * A group of rows, named by its `<GridListHeader>` or its `aria-label`.
1212
+ *
1213
+ * Rendered from the list's item callback for an item with children, like any
1214
+ * other row; its rows are built by the same callback. The keyboard moves
1215
+ * across sections as though they were one list and never stops on a header.
1216
+ */
1217
+ export function GridListSection(props: GridListSectionProps) {
1218
+ const list = useGridList();
1219
+ const node = useRowNode();
1220
+ const render = list.render;
1221
+ if (render === undefined) {
1222
+ throw new Error("A GridListSection must be rendered inside a GridList's item callback.");
1223
+ }
1224
+ const headingId = id();
1225
+ // Written by a header from its own component body, when it mounts.
1226
+ const [headers, setHeaders] = createSignal(0, { ownedWrite: true });
1227
+ const section: GridListSectionValue = {
1228
+ headingId,
1229
+ registerHeader: () => {
1230
+ setHeaders((count) => count + 1);
1231
+ return () => setHeaders((count) => count - 1);
1232
+ },
1233
+ };
1234
+ const children = createMemo(() => list.state.collection().getItem(node.key)?.childNodes ?? []);
1235
+
1236
+ const elementProps = mergeProps(
1237
+ filterDOMProps(fromProps(cells(props)), { global: true, id: false }),
1238
+ styleProps(cells(props)),
1239
+ {
1240
+ role: "rowgroup",
1241
+ "aria-label": () => props["aria-label"],
1242
+ "aria-labelledby": () =>
1243
+ props["aria-label"] === undefined && headers() > 0 ? headingId() : undefined,
1244
+ },
1245
+ );
1246
+
1247
+ return (
1248
+ <div {...elementProps} ref={mergeRefs(props.ref)}>
1249
+ {provide(
1250
+ GridListSectionContext,
1251
+ () => section,
1252
+ () => (
1253
+ <>
1254
+ {props.children}
1255
+ <For each={children}>
1256
+ {(child: Node<unknown>) => {
1257
+ provideRowNode(child);
1258
+ return render(child.value);
1259
+ }}
1260
+ </For>
1261
+ </>
1262
+ ),
1263
+ )}
1264
+ </div>
1265
+ );
1266
+ }
1267
+
1268
+ export interface GridListHeaderProps extends StyleProps {
1269
+ children?: Child;
1270
+ ref?: RefTarget<HTMLDivElement>;
1271
+ }
1272
+
1273
+ /** The header row of a {@link GridListSection}. Not focusable: it names the group. */
1274
+ export function GridListHeader(props: GridListHeaderProps) {
1275
+ const section = getContext(GridListSectionContext);
1276
+ if (section === null || section === undefined) {
1277
+ throw new Error("A GridListHeader must be rendered inside a GridListSection.");
1278
+ }
1279
+ onCleanup(section.registerHeader());
1280
+ const elementProps = mergeProps(
1281
+ filterDOMProps(fromProps(cells(props)), { global: true, id: false }),
1282
+ styleProps(cells(props)),
1283
+ { role: "row" },
1284
+ );
1285
+ return (
1286
+ <div {...elementProps} ref={mergeRefs(props.ref)}>
1287
+ <div role="rowheader" id={section.headingId()}>
1288
+ {props.children}
1289
+ </div>
561
1290
  </div>
562
1291
  );
563
1292
  }
1293
+
1294
+ interface RowDragAndDrop {
1295
+ collection: CollectionDragAndDrop;
1296
+ itemProps: DOMProps;
1297
+ before: ItemDropTarget;
1298
+ after: Accessor<ItemDropTarget[]>;
1299
+ /** The target for a drop ON the row, focusable apart from the row's own controls. */
1300
+ on: {
1301
+ indicator: ReturnType<NonNullable<DragAndDropHooks["dropIndicator"]>>;
1302
+ ref: ReturnType<typeof makeRef<HTMLDivElement>>;
1303
+ } | null;
1304
+ }
1305
+
1306
+ /**
1307
+ * A row's part in its list's drag and drop. A row holds controls, so Enter on
1308
+ * it is not free to start a drag: a `<DragButton>` inside it does that.
1309
+ */
1310
+ function rowDragAndDrop(list: GridListContextValue, key: Key): RowDragAndDrop | null {
1311
+ const collection = list.dragAndDrop;
1312
+ if (collection === undefined) return null;
1313
+ const { hooks, dragState, dropState } = collection;
1314
+
1315
+ const draggable =
1316
+ dragState === undefined || hooks?.draggableItem === undefined
1317
+ ? null
1318
+ : hooks.draggableItem({ key, hasDragButton: true }, dragState);
1319
+ const dragButtonRef = makeRef<Element>();
1320
+ const slot = draggableItemSlotProps(draggable, hooks, dragButtonRef, dragButtonRef.set);
1321
+ if (draggable !== null) provideDragButton(slot.dragButton);
1322
+
1323
+ let on: RowDragAndDrop["on"] = null;
1324
+ if (dropState !== undefined && hooks?.dropIndicator !== undefined) {
1325
+ const ref = makeRef<HTMLDivElement>();
1326
+ on = {
1327
+ ref,
1328
+ indicator: hooks.dropIndicator(
1329
+ { target: { type: "item", key, dropPosition: "on" } },
1330
+ dropState,
1331
+ ref,
1332
+ ),
1333
+ };
1334
+ }
1335
+ const onTarget = on;
1336
+
1337
+ const after = createMemo(() => {
1338
+ const items = list.state.collection();
1339
+ const node = items.getItem(key);
1340
+ return node === null ? [] : afterDropIndicatorTargets(items, node);
1341
+ });
1342
+
1343
+ return {
1344
+ collection,
1345
+ on,
1346
+ before: { type: "item", key, dropPosition: "before" },
1347
+ after,
1348
+ itemProps: mergeProps(slot.itemProps, {
1349
+ "data-allows-dragging": () => dragState !== undefined,
1350
+ "data-dragging": () => dragState?.isDragging(key) === true,
1351
+ "data-drop-target": () => onTarget?.indicator.isDropTarget() === true,
1352
+ }),
1353
+ };
1354
+ }