@react-aria/selection 3.0.0-alpha.1 → 3.0.0-nightly-641446f65-240905

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 (53) hide show
  1. package/README.md +1 -1
  2. package/dist/DOMLayoutDelegate.main.js +53 -0
  3. package/dist/DOMLayoutDelegate.main.js.map +1 -0
  4. package/dist/DOMLayoutDelegate.mjs +48 -0
  5. package/dist/DOMLayoutDelegate.module.js +48 -0
  6. package/dist/DOMLayoutDelegate.module.js.map +1 -0
  7. package/dist/ListKeyboardDelegate.main.js +189 -0
  8. package/dist/ListKeyboardDelegate.main.js.map +1 -0
  9. package/dist/ListKeyboardDelegate.mjs +184 -0
  10. package/dist/ListKeyboardDelegate.module.js +184 -0
  11. package/dist/ListKeyboardDelegate.module.js.map +1 -0
  12. package/dist/import.mjs +27 -0
  13. package/dist/main.js +16 -608
  14. package/dist/main.js.map +1 -0
  15. package/dist/module.js +9 -563
  16. package/dist/module.js.map +1 -0
  17. package/dist/types.d.ts +218 -30
  18. package/dist/types.d.ts.map +1 -1
  19. package/dist/useSelectableCollection.main.js +318 -0
  20. package/dist/useSelectableCollection.main.js.map +1 -0
  21. package/dist/useSelectableCollection.mjs +313 -0
  22. package/dist/useSelectableCollection.module.js +313 -0
  23. package/dist/useSelectableCollection.module.js.map +1 -0
  24. package/dist/useSelectableItem.main.js +213 -0
  25. package/dist/useSelectableItem.main.js.map +1 -0
  26. package/dist/useSelectableItem.mjs +208 -0
  27. package/dist/useSelectableItem.module.js +208 -0
  28. package/dist/useSelectableItem.module.js.map +1 -0
  29. package/dist/useSelectableList.main.js +63 -0
  30. package/dist/useSelectableList.main.js.map +1 -0
  31. package/dist/useSelectableList.mjs +58 -0
  32. package/dist/useSelectableList.module.js +58 -0
  33. package/dist/useSelectableList.module.js.map +1 -0
  34. package/dist/useTypeSelect.main.js +73 -0
  35. package/dist/useTypeSelect.main.js.map +1 -0
  36. package/dist/useTypeSelect.mjs +68 -0
  37. package/dist/useTypeSelect.module.js +68 -0
  38. package/dist/useTypeSelect.module.js.map +1 -0
  39. package/dist/utils.main.js +32 -0
  40. package/dist/utils.main.js.map +1 -0
  41. package/dist/utils.mjs +26 -0
  42. package/dist/utils.module.js +26 -0
  43. package/dist/utils.module.js.map +1 -0
  44. package/package.json +20 -13
  45. package/src/DOMLayoutDelegate.ts +57 -0
  46. package/src/ListKeyboardDelegate.ts +288 -0
  47. package/src/index.ts +23 -0
  48. package/src/useSelectableCollection.ts +490 -0
  49. package/src/useSelectableItem.ts +374 -0
  50. package/src/useSelectableList.ts +85 -0
  51. package/src/useTypeSelect.ts +114 -0
  52. package/src/utils.ts +33 -0
  53. package/LICENSE +0 -201
@@ -0,0 +1,490 @@
1
+ /*
2
+ * Copyright 2020 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import {DOMAttributes, FocusableElement, FocusStrategy, Key, KeyboardDelegate, RefObject} from '@react-types/shared';
14
+ import {flushSync} from 'react-dom';
15
+ import {FocusEvent, KeyboardEvent, useEffect, useRef} from 'react';
16
+ import {focusSafely, getFocusableTreeWalker} from '@react-aria/focus';
17
+ import {focusWithoutScrolling, mergeProps, scrollIntoView, scrollIntoViewport, useEvent, useRouter} from '@react-aria/utils';
18
+ import {getInteractionModality} from '@react-aria/interactions';
19
+ import {isCtrlKeyPressed, isNonContiguousSelectionModifier} from './utils';
20
+ import {MultipleSelectionManager} from '@react-stately/selection';
21
+ import {useLocale} from '@react-aria/i18n';
22
+ import {useTypeSelect} from './useTypeSelect';
23
+
24
+ export interface AriaSelectableCollectionOptions {
25
+ /**
26
+ * An interface for reading and updating multiple selection state.
27
+ */
28
+ selectionManager: MultipleSelectionManager,
29
+ /**
30
+ * A delegate object that implements behavior for keyboard focus movement.
31
+ */
32
+ keyboardDelegate: KeyboardDelegate,
33
+ /**
34
+ * The ref attached to the element representing the collection.
35
+ */
36
+ ref: RefObject<HTMLElement | null>,
37
+ /**
38
+ * Whether the collection or one of its items should be automatically focused upon render.
39
+ * @default false
40
+ */
41
+ autoFocus?: boolean | FocusStrategy,
42
+ /**
43
+ * Whether focus should wrap around when the end/start is reached.
44
+ * @default false
45
+ */
46
+ shouldFocusWrap?: boolean,
47
+ /**
48
+ * Whether the collection allows empty selection.
49
+ * @default false
50
+ */
51
+ disallowEmptySelection?: boolean,
52
+ /**
53
+ * Whether the collection allows the user to select all items via keyboard shortcut.
54
+ * @default false
55
+ */
56
+ disallowSelectAll?: boolean,
57
+ /**
58
+ * Whether selection should occur automatically on focus.
59
+ * @default false
60
+ */
61
+ selectOnFocus?: boolean,
62
+ /**
63
+ * Whether typeahead is disabled.
64
+ * @default false
65
+ */
66
+ disallowTypeAhead?: boolean,
67
+ /**
68
+ * Whether the collection items should use virtual focus instead of being focused directly.
69
+ */
70
+ shouldUseVirtualFocus?: boolean,
71
+ /**
72
+ * Whether navigation through tab key is enabled.
73
+ */
74
+ allowsTabNavigation?: boolean,
75
+ /**
76
+ * Whether the collection items are contained in a virtual scroller.
77
+ */
78
+ isVirtualized?: boolean,
79
+ /**
80
+ * The ref attached to the scrollable body. Used to provide automatic scrolling on item focus for non-virtualized collections.
81
+ * If not provided, defaults to the collection ref.
82
+ */
83
+ scrollRef?: RefObject<HTMLElement | null>,
84
+ /**
85
+ * The behavior of links in the collection.
86
+ * - 'action': link behaves like onAction.
87
+ * - 'selection': link follows selection interactions (e.g. if URL drives selection).
88
+ * - 'override': links override all other interactions (link items are not selectable).
89
+ * @default 'action'
90
+ */
91
+ linkBehavior?: 'action' | 'selection' | 'override'
92
+ }
93
+
94
+ export interface SelectableCollectionAria {
95
+ /** Props for the collection element. */
96
+ collectionProps: DOMAttributes
97
+ }
98
+
99
+ /**
100
+ * Handles interactions with selectable collections.
101
+ */
102
+ export function useSelectableCollection(options: AriaSelectableCollectionOptions): SelectableCollectionAria {
103
+ let {
104
+ selectionManager: manager,
105
+ keyboardDelegate: delegate,
106
+ ref,
107
+ autoFocus = false,
108
+ shouldFocusWrap = false,
109
+ disallowEmptySelection = false,
110
+ disallowSelectAll = false,
111
+ selectOnFocus = manager.selectionBehavior === 'replace',
112
+ disallowTypeAhead = false,
113
+ shouldUseVirtualFocus,
114
+ allowsTabNavigation = false,
115
+ isVirtualized,
116
+ // If no scrollRef is provided, assume the collection ref is the scrollable region
117
+ scrollRef = ref,
118
+ linkBehavior = 'action'
119
+ } = options;
120
+ let {direction} = useLocale();
121
+ let router = useRouter();
122
+
123
+ let onKeyDown = (e: KeyboardEvent) => {
124
+ // Prevent option + tab from doing anything since it doesn't move focus to the cells, only buttons/checkboxes
125
+ if (e.altKey && e.key === 'Tab') {
126
+ e.preventDefault();
127
+ }
128
+
129
+ // Keyboard events bubble through portals. Don't handle keyboard events
130
+ // for elements outside the collection (e.g. menus).
131
+ if (!ref.current.contains(e.target as Element)) {
132
+ return;
133
+ }
134
+
135
+ const navigateToKey = (key: Key | undefined, childFocus?: FocusStrategy) => {
136
+ if (key != null) {
137
+ if (manager.isLink(key) && linkBehavior === 'selection' && selectOnFocus && !isNonContiguousSelectionModifier(e)) {
138
+ // Set focused key and re-render synchronously to bring item into view if needed.
139
+ flushSync(() => {
140
+ manager.setFocusedKey(key, childFocus);
141
+ });
142
+
143
+ let item = scrollRef.current.querySelector(`[data-key="${CSS.escape(key.toString())}"]`);
144
+ let itemProps = manager.getItemProps(key);
145
+ router.open(item, e, itemProps.href, itemProps.routerOptions);
146
+
147
+ return;
148
+ }
149
+
150
+ manager.setFocusedKey(key, childFocus);
151
+
152
+ if (manager.isLink(key) && linkBehavior === 'override') {
153
+ return;
154
+ }
155
+
156
+ if (e.shiftKey && manager.selectionMode === 'multiple') {
157
+ manager.extendSelection(key);
158
+ } else if (selectOnFocus && !isNonContiguousSelectionModifier(e)) {
159
+ manager.replaceSelection(key);
160
+ }
161
+ }
162
+ };
163
+
164
+ switch (e.key) {
165
+ case 'ArrowDown': {
166
+ if (delegate.getKeyBelow) {
167
+ let nextKey = manager.focusedKey != null
168
+ ? delegate.getKeyBelow?.(manager.focusedKey)
169
+ : delegate.getFirstKey?.();
170
+ if (nextKey == null && shouldFocusWrap) {
171
+ nextKey = delegate.getFirstKey?.(manager.focusedKey);
172
+ }
173
+ if (nextKey != null) {
174
+ e.preventDefault();
175
+ navigateToKey(nextKey);
176
+ }
177
+ }
178
+ break;
179
+ }
180
+ case 'ArrowUp': {
181
+ if (delegate.getKeyAbove) {
182
+ let nextKey = manager.focusedKey != null
183
+ ? delegate.getKeyAbove?.(manager.focusedKey)
184
+ : delegate.getLastKey?.();
185
+ if (nextKey == null && shouldFocusWrap) {
186
+ nextKey = delegate.getLastKey?.(manager.focusedKey);
187
+ }
188
+ if (nextKey != null) {
189
+ e.preventDefault();
190
+ navigateToKey(nextKey);
191
+ }
192
+ }
193
+ break;
194
+ }
195
+ case 'ArrowLeft': {
196
+ if (delegate.getKeyLeftOf) {
197
+ let nextKey = delegate.getKeyLeftOf?.(manager.focusedKey);
198
+ if (nextKey == null && shouldFocusWrap) {
199
+ nextKey = direction === 'rtl' ? delegate.getFirstKey?.(manager.focusedKey) : delegate.getLastKey?.(manager.focusedKey);
200
+ }
201
+ if (nextKey != null) {
202
+ e.preventDefault();
203
+ navigateToKey(nextKey, direction === 'rtl' ? 'first' : 'last');
204
+ }
205
+ }
206
+ break;
207
+ }
208
+ case 'ArrowRight': {
209
+ if (delegate.getKeyRightOf) {
210
+ let nextKey = delegate.getKeyRightOf?.(manager.focusedKey);
211
+ if (nextKey == null && shouldFocusWrap) {
212
+ nextKey = direction === 'rtl' ? delegate.getLastKey?.(manager.focusedKey) : delegate.getFirstKey?.(manager.focusedKey);
213
+ }
214
+ if (nextKey != null) {
215
+ e.preventDefault();
216
+ navigateToKey(nextKey, direction === 'rtl' ? 'last' : 'first');
217
+ }
218
+ }
219
+ break;
220
+ }
221
+ case 'Home':
222
+ if (delegate.getFirstKey) {
223
+ e.preventDefault();
224
+ let firstKey = delegate.getFirstKey(manager.focusedKey, isCtrlKeyPressed(e));
225
+ manager.setFocusedKey(firstKey);
226
+ if (isCtrlKeyPressed(e) && e.shiftKey && manager.selectionMode === 'multiple') {
227
+ manager.extendSelection(firstKey);
228
+ } else if (selectOnFocus) {
229
+ manager.replaceSelection(firstKey);
230
+ }
231
+ }
232
+ break;
233
+ case 'End':
234
+ if (delegate.getLastKey) {
235
+ e.preventDefault();
236
+ let lastKey = delegate.getLastKey(manager.focusedKey, isCtrlKeyPressed(e));
237
+ manager.setFocusedKey(lastKey);
238
+ if (isCtrlKeyPressed(e) && e.shiftKey && manager.selectionMode === 'multiple') {
239
+ manager.extendSelection(lastKey);
240
+ } else if (selectOnFocus) {
241
+ manager.replaceSelection(lastKey);
242
+ }
243
+ }
244
+ break;
245
+ case 'PageDown':
246
+ if (delegate.getKeyPageBelow) {
247
+ let nextKey = delegate.getKeyPageBelow(manager.focusedKey);
248
+ if (nextKey != null) {
249
+ e.preventDefault();
250
+ navigateToKey(nextKey);
251
+ }
252
+ }
253
+ break;
254
+ case 'PageUp':
255
+ if (delegate.getKeyPageAbove) {
256
+ let nextKey = delegate.getKeyPageAbove(manager.focusedKey);
257
+ if (nextKey != null) {
258
+ e.preventDefault();
259
+ navigateToKey(nextKey);
260
+ }
261
+ }
262
+ break;
263
+ case 'a':
264
+ if (isCtrlKeyPressed(e) && manager.selectionMode === 'multiple' && disallowSelectAll !== true) {
265
+ e.preventDefault();
266
+ manager.selectAll();
267
+ }
268
+ break;
269
+ case 'Escape':
270
+ if (!disallowEmptySelection && manager.selectedKeys.size !== 0) {
271
+ e.stopPropagation();
272
+ e.preventDefault();
273
+ manager.clearSelection();
274
+ }
275
+ break;
276
+ case 'Tab': {
277
+ if (!allowsTabNavigation) {
278
+ // There may be elements that are "tabbable" inside a collection (e.g. in a grid cell).
279
+ // However, collections should be treated as a single tab stop, with arrow key navigation internally.
280
+ // We don't control the rendering of these, so we can't override the tabIndex to prevent tabbing.
281
+ // Instead, we handle the Tab key, and move focus manually to the first/last tabbable element
282
+ // in the collection, so that the browser default behavior will apply starting from that element
283
+ // rather than the currently focused one.
284
+ if (e.shiftKey) {
285
+ ref.current.focus();
286
+ } else {
287
+ let walker = getFocusableTreeWalker(ref.current, {tabbable: true});
288
+ let next: FocusableElement;
289
+ let last: FocusableElement;
290
+ do {
291
+ last = walker.lastChild() as FocusableElement;
292
+ if (last) {
293
+ next = last;
294
+ }
295
+ } while (last);
296
+
297
+ if (next && !next.contains(document.activeElement)) {
298
+ focusWithoutScrolling(next);
299
+ }
300
+ }
301
+ break;
302
+ }
303
+ }
304
+ }
305
+ };
306
+
307
+ // Store the scroll position so we can restore it later.
308
+ /// TODO: should this happen all the time??
309
+ let scrollPos = useRef({top: 0, left: 0});
310
+ useEvent(scrollRef, 'scroll', isVirtualized ? null : () => {
311
+ scrollPos.current = {
312
+ top: scrollRef.current.scrollTop,
313
+ left: scrollRef.current.scrollLeft
314
+ };
315
+ });
316
+
317
+ let onFocus = (e: FocusEvent) => {
318
+ if (manager.isFocused) {
319
+ // If a focus event bubbled through a portal, reset focus state.
320
+ if (!e.currentTarget.contains(e.target)) {
321
+ manager.setFocused(false);
322
+ }
323
+
324
+ return;
325
+ }
326
+
327
+ // Focus events can bubble through portals. Ignore these events.
328
+ if (!e.currentTarget.contains(e.target)) {
329
+ return;
330
+ }
331
+
332
+ manager.setFocused(true);
333
+
334
+ if (manager.focusedKey == null) {
335
+ let navigateToFirstKey = (key: Key | undefined) => {
336
+ if (key != null) {
337
+ manager.setFocusedKey(key);
338
+ if (selectOnFocus) {
339
+ manager.replaceSelection(key);
340
+ }
341
+ }
342
+ };
343
+ // If the user hasn't yet interacted with the collection, there will be no focusedKey set.
344
+ // Attempt to detect whether the user is tabbing forward or backward into the collection
345
+ // and either focus the first or last item accordingly.
346
+ let relatedTarget = e.relatedTarget as Element;
347
+ if (relatedTarget && (e.currentTarget.compareDocumentPosition(relatedTarget) & Node.DOCUMENT_POSITION_FOLLOWING)) {
348
+ navigateToFirstKey(manager.lastSelectedKey ?? delegate.getLastKey());
349
+ } else {
350
+ navigateToFirstKey(manager.firstSelectedKey ?? delegate.getFirstKey());
351
+ }
352
+ } else if (!isVirtualized) {
353
+ // Restore the scroll position to what it was before.
354
+ scrollRef.current.scrollTop = scrollPos.current.top;
355
+ scrollRef.current.scrollLeft = scrollPos.current.left;
356
+ }
357
+
358
+ if (manager.focusedKey != null) {
359
+ // Refocus and scroll the focused item into view if it exists within the scrollable region.
360
+ let element = scrollRef.current.querySelector(`[data-key="${CSS.escape(manager.focusedKey.toString())}"]`) as HTMLElement;
361
+ if (element) {
362
+ // This prevents a flash of focus on the first/last element in the collection, or the collection itself.
363
+ if (!element.contains(document.activeElement)) {
364
+ focusWithoutScrolling(element);
365
+ }
366
+
367
+ let modality = getInteractionModality();
368
+ if (modality === 'keyboard') {
369
+ scrollIntoViewport(element, {containingElement: ref.current});
370
+ }
371
+ }
372
+ }
373
+ };
374
+
375
+ let onBlur = (e) => {
376
+ // Don't set blurred and then focused again if moving focus within the collection.
377
+ if (!e.currentTarget.contains(e.relatedTarget as HTMLElement)) {
378
+ manager.setFocused(false);
379
+ }
380
+ };
381
+
382
+ const autoFocusRef = useRef(autoFocus);
383
+ useEffect(() => {
384
+ if (autoFocusRef.current) {
385
+ let focusedKey = null;
386
+
387
+ // Check focus strategy to determine which item to focus
388
+ if (autoFocus === 'first') {
389
+ focusedKey = delegate.getFirstKey();
390
+ } if (autoFocus === 'last') {
391
+ focusedKey = delegate.getLastKey();
392
+ }
393
+
394
+ // If there are any selected keys, make the first one the new focus target
395
+ let selectedKeys = manager.selectedKeys;
396
+ if (selectedKeys.size) {
397
+ for (let key of selectedKeys) {
398
+ if (manager.canSelectItem(key)) {
399
+ focusedKey = key;
400
+ break;
401
+ }
402
+ }
403
+ }
404
+
405
+ manager.setFocused(true);
406
+ manager.setFocusedKey(focusedKey);
407
+
408
+ // If no default focus key is selected, focus the collection itself.
409
+ if (focusedKey == null && !shouldUseVirtualFocus) {
410
+ focusSafely(ref.current);
411
+ }
412
+ }
413
+ // eslint-disable-next-line react-hooks/exhaustive-deps
414
+ }, []);
415
+
416
+ // Scroll the focused element into view when the focusedKey changes.
417
+ let lastFocusedKey = useRef(manager.focusedKey);
418
+ useEffect(() => {
419
+ if (manager.isFocused && manager.focusedKey != null && (manager.focusedKey !== lastFocusedKey.current || autoFocusRef.current) && scrollRef?.current) {
420
+ let modality = getInteractionModality();
421
+ let element = ref.current.querySelector(`[data-key="${CSS.escape(manager.focusedKey.toString())}"]`) as HTMLElement;
422
+ if (!element) {
423
+ // If item element wasn't found, return early (don't update autoFocusRef and lastFocusedKey).
424
+ // The collection may initially be empty (e.g. virtualizer), so wait until the element exists.
425
+ return;
426
+ }
427
+
428
+ if (modality === 'keyboard' || autoFocusRef.current) {
429
+ scrollIntoView(scrollRef.current, element);
430
+
431
+ // Avoid scroll in iOS VO, since it may cause overlay to close (i.e. RAC submenu)
432
+ if (modality !== 'virtual') {
433
+ scrollIntoViewport(element, {containingElement: ref.current});
434
+ }
435
+ }
436
+ }
437
+
438
+ // If the focused key becomes null (e.g. the last item is deleted), focus the whole collection.
439
+ if (!shouldUseVirtualFocus && manager.isFocused && manager.focusedKey == null && lastFocusedKey.current != null) {
440
+ focusSafely(ref.current);
441
+ }
442
+
443
+ lastFocusedKey.current = manager.focusedKey;
444
+ autoFocusRef.current = false;
445
+ });
446
+
447
+ // Intercept FocusScope restoration since virtualized collections can reuse DOM nodes.
448
+ useEvent(ref, 'react-aria-focus-scope-restore', e => {
449
+ e.preventDefault();
450
+ manager.setFocused(true);
451
+ });
452
+
453
+ let handlers = {
454
+ onKeyDown,
455
+ onFocus,
456
+ onBlur,
457
+ onMouseDown(e) {
458
+ // Ignore events that bubbled through portals.
459
+ if (scrollRef.current === e.target) {
460
+ // Prevent focus going to the collection when clicking on the scrollbar.
461
+ e.preventDefault();
462
+ }
463
+ }
464
+ };
465
+
466
+ let {typeSelectProps} = useTypeSelect({
467
+ keyboardDelegate: delegate,
468
+ selectionManager: manager
469
+ });
470
+
471
+ if (!disallowTypeAhead) {
472
+ handlers = mergeProps(typeSelectProps, handlers);
473
+ }
474
+
475
+ // If nothing is focused within the collection, make the collection itself tabbable.
476
+ // This will be marshalled to either the first or last item depending on where focus came from.
477
+ // If using virtual focus, don't set a tabIndex at all so that VoiceOver on iOS 14 doesn't try
478
+ // to move real DOM focus to the element anyway.
479
+ let tabIndex: number;
480
+ if (!shouldUseVirtualFocus) {
481
+ tabIndex = manager.focusedKey == null ? 0 : -1;
482
+ }
483
+
484
+ return {
485
+ collectionProps: {
486
+ ...handlers,
487
+ tabIndex
488
+ }
489
+ };
490
+ }