@octanejs/aria 0.0.46 → 0.0.48

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 (201) hide show
  1. package/README.md +7 -6
  2. package/UPSTREAM.md +58 -69
  3. package/package.json +11 -11
  4. package/src/calendar/useCalendarGrid.tsx +64 -62
  5. package/src/collections/Document.ts +3 -0
  6. package/src/color/useColorArea.tsx +95 -69
  7. package/src/color/useColorWheel.tsx +38 -37
  8. package/src/combobox/{useComboBox.ts → useComboBox.tsx} +243 -258
  9. package/src/components/ComboBox.ts +35 -2
  10. package/src/components/Dialog.ts +12 -1
  11. package/src/components/DropZone.tsx +3 -2
  12. package/src/components/FileTrigger.tsx +1 -0
  13. package/src/components/GridList.ts +11 -2
  14. package/src/components/ListBox.ts +1 -1
  15. package/src/components/Menu.ts +1 -0
  16. package/src/components/Meter.ts +3 -1
  17. package/src/components/Popover.ts +20 -8
  18. package/src/components/PreviewTrigger.tsx +101 -0
  19. package/src/components/ProgressBar.ts +10 -2
  20. package/src/components/Select.ts +1 -1
  21. package/src/components/Table.ts +26 -15
  22. package/src/components/TokenField.tsx +395 -0
  23. package/src/components/Tooltip.ts +4 -6
  24. package/src/components/Tree.ts +14 -7
  25. package/src/components/Virtualizer.tsx +30 -14
  26. package/src/components/index.ts +22 -0
  27. package/src/components/utils.ts +1 -1
  28. package/src/datepicker/useDateField.tsx +2 -11
  29. package/src/datepicker/useDatePickerGroup.tsx +44 -33
  30. package/src/datepicker/useDateSegment.tsx +31 -30
  31. package/src/dialog/useDialog.ts +8 -1
  32. package/src/dnd/DragManager.tsx +5 -1
  33. package/src/dnd/useDrag.tsx +2 -1
  34. package/src/focus/FocusScope.ts +2 -2
  35. package/src/grid/useGrid.ts +3 -0
  36. package/src/grid/{useGridCell.ts → useGridCell.tsx} +128 -66
  37. package/src/grid/utils.ts +1 -0
  38. package/src/gridlist/{useGridListItem.ts → useGridListItem.tsx} +154 -112
  39. package/src/index.ts +22 -0
  40. package/src/interactions/createEventHandler.ts +11 -8
  41. package/src/interactions/createKeyboardShortcutHandler.tsx +218 -0
  42. package/src/interactions/textSelection.ts +3 -3
  43. package/src/interactions/useContextMenu.tsx +125 -0
  44. package/src/interactions/useFocusVisible.ts +4 -4
  45. package/src/interactions/useKeyboard.ts +50 -2
  46. package/src/interactions/useLongPress.ts +33 -22
  47. package/src/interactions/useMove.ts +6 -6
  48. package/src/interactions/usePress.ts +8 -0
  49. package/src/interactions/utils.ts +10 -10
  50. package/src/intl/combobox/fi-FI.json +2 -2
  51. package/src/intl/previewtrigger/ar-AE.json +3 -0
  52. package/src/intl/previewtrigger/bg-BG.json +3 -0
  53. package/src/intl/previewtrigger/cs-CZ.json +3 -0
  54. package/src/intl/previewtrigger/da-DK.json +3 -0
  55. package/src/intl/previewtrigger/de-DE.json +3 -0
  56. package/src/intl/previewtrigger/el-GR.json +3 -0
  57. package/src/intl/previewtrigger/en-US.json +3 -0
  58. package/src/intl/previewtrigger/es-ES.json +3 -0
  59. package/src/intl/previewtrigger/et-EE.json +3 -0
  60. package/src/intl/previewtrigger/fi-FI.json +3 -0
  61. package/src/intl/previewtrigger/fr-FR.json +3 -0
  62. package/src/intl/previewtrigger/he-IL.json +3 -0
  63. package/src/intl/previewtrigger/hr-HR.json +3 -0
  64. package/src/intl/previewtrigger/hu-HU.json +3 -0
  65. package/src/intl/previewtrigger/index.ts +73 -0
  66. package/src/intl/previewtrigger/it-IT.json +3 -0
  67. package/src/intl/previewtrigger/ja-JP.json +3 -0
  68. package/src/intl/previewtrigger/ko-KR.json +3 -0
  69. package/src/intl/previewtrigger/lt-LT.json +3 -0
  70. package/src/intl/previewtrigger/lv-LV.json +3 -0
  71. package/src/intl/previewtrigger/nb-NO.json +3 -0
  72. package/src/intl/previewtrigger/nl-NL.json +3 -0
  73. package/src/intl/previewtrigger/pl-PL.json +3 -0
  74. package/src/intl/previewtrigger/pt-BR.json +3 -0
  75. package/src/intl/previewtrigger/pt-PT.json +3 -0
  76. package/src/intl/previewtrigger/ro-RO.json +3 -0
  77. package/src/intl/previewtrigger/ru-RU.json +3 -0
  78. package/src/intl/previewtrigger/sk-SK.json +3 -0
  79. package/src/intl/previewtrigger/sl-SI.json +3 -0
  80. package/src/intl/previewtrigger/sr-SP.json +3 -0
  81. package/src/intl/previewtrigger/sv-SE.json +3 -0
  82. package/src/intl/previewtrigger/tr-TR.json +3 -0
  83. package/src/intl/previewtrigger/uk-UA.json +3 -0
  84. package/src/intl/previewtrigger/zh-CN.json +3 -0
  85. package/src/intl/previewtrigger/zh-TW.json +3 -0
  86. package/src/intl/table/ar-AE.json +3 -3
  87. package/src/intl/table/bg-BG.json +3 -3
  88. package/src/intl/table/cs-CZ.json +3 -3
  89. package/src/intl/table/da-DK.json +3 -3
  90. package/src/intl/table/de-DE.json +3 -3
  91. package/src/intl/table/el-GR.json +3 -3
  92. package/src/intl/table/es-ES.json +3 -3
  93. package/src/intl/table/et-EE.json +3 -3
  94. package/src/intl/table/fi-FI.json +3 -3
  95. package/src/intl/table/fr-FR.json +3 -3
  96. package/src/intl/table/he-IL.json +3 -3
  97. package/src/intl/table/hr-HR.json +3 -3
  98. package/src/intl/table/hu-HU.json +3 -3
  99. package/src/intl/table/it-IT.json +3 -3
  100. package/src/intl/table/ja-JP.json +3 -3
  101. package/src/intl/table/ko-KR.json +3 -3
  102. package/src/intl/table/lt-LT.json +3 -3
  103. package/src/intl/table/lv-LV.json +3 -3
  104. package/src/intl/table/nb-NO.json +3 -3
  105. package/src/intl/table/nl-NL.json +3 -3
  106. package/src/intl/table/pl-PL.json +3 -3
  107. package/src/intl/table/pt-BR.json +3 -3
  108. package/src/intl/table/pt-PT.json +3 -3
  109. package/src/intl/table/ro-RO.json +3 -3
  110. package/src/intl/table/ru-RU.json +3 -3
  111. package/src/intl/table/sk-SK.json +3 -3
  112. package/src/intl/table/sl-SI.json +3 -3
  113. package/src/intl/table/sr-SP.json +3 -3
  114. package/src/intl/table/sv-SE.json +3 -3
  115. package/src/intl/table/tr-TR.json +3 -3
  116. package/src/intl/table/uk-UA.json +3 -3
  117. package/src/intl/table/zh-CN.json +4 -4
  118. package/src/intl/table/zh-TW.json +3 -3
  119. package/src/intl/tree/es-ES.json +1 -1
  120. package/src/link/useLink.ts +2 -0
  121. package/src/menu/useMenuItem.ts +33 -36
  122. package/src/menu/useMenuTrigger.tsx +222 -0
  123. package/src/menu/{useSubmenuTrigger.ts → useSubmenuTrigger.tsx} +116 -151
  124. package/src/numberfield/{useNumberField.ts → useNumberField.tsx} +188 -238
  125. package/src/overlays/Overlay.ts +5 -1
  126. package/src/overlays/ariaHideOutside.ts +6 -8
  127. package/src/overlays/useCloseOnScroll.ts +7 -5
  128. package/src/overlays/{useOverlay.ts → useOverlay.tsx} +76 -83
  129. package/src/overlays/usePopover.ts +10 -5
  130. package/src/overlays/usePreventScroll.ts +4 -4
  131. package/src/progress/useProgressBar.ts +2 -1
  132. package/src/radio/{useRadioGroup.ts → useRadioGroup.tsx} +87 -79
  133. package/src/searchfield/useSearchField.tsx +152 -0
  134. package/src/select/useSelect.ts +20 -20
  135. package/src/selection/useSelectableCollection.tsx +755 -0
  136. package/src/selection/useSelectableItem.ts +48 -11
  137. package/src/slider/{useSliderThumb.ts → useSliderThumb.tsx} +120 -158
  138. package/src/spinbutton/useSpinButton.tsx +335 -0
  139. package/src/stately/combobox/useComboBoxState.ts +1 -1
  140. package/src/stately/grid/useGridState.ts +9 -10
  141. package/src/stately/index.ts +11 -0
  142. package/src/stately/menu/useMenuTriggerState.ts +1 -1
  143. package/src/stately/menu/useSubmenuTriggerState.ts +2 -0
  144. package/src/stately/overlays/useOverlayTriggerState.ts +12 -1
  145. package/src/stately/radio/useRadioGroupState.ts +5 -1
  146. package/src/stately/table/TableUtils.ts +15 -1
  147. package/src/stately/table/useTableState.ts +7 -0
  148. package/src/stately/tokenfield/TokenFieldValue.tsx +440 -0
  149. package/src/stately/tokenfield/useTokenFieldState.tsx +57 -0
  150. package/src/stately/tooltip/useTooltipTriggerState.ts +16 -7
  151. package/src/stately/virtualizer/Layout.tsx +2 -0
  152. package/src/stately/virtualizer/ScrollAnchor.tsx +338 -0
  153. package/src/stately/virtualizer/Virtualizer.tsx +52 -1
  154. package/src/stately/virtualizer/types.tsx +2 -0
  155. package/src/table/useTableCell.ts +12 -0
  156. package/src/table/useTableColumnHeader.ts +8 -1
  157. package/src/table/useTableColumnResize.tsx +359 -0
  158. package/src/tag/useTag.ts +22 -15
  159. package/src/textfield/useTextField.ts +2 -0
  160. package/src/tokenfield/useToken.tsx +64 -0
  161. package/src/tokenfield/useTokenField.tsx +849 -0
  162. package/src/tooltip/usePreviewTrigger.tsx +266 -0
  163. package/src/tooltip/useSafeArea.tsx +171 -0
  164. package/src/upstream-exports/react-aria/mergeRefs.tsx +3 -0
  165. package/src/upstream-exports/react-aria/usePreviewTrigger.tsx +18 -0
  166. package/src/upstream-exports/react-aria/useTokenField.tsx +22 -0
  167. package/src/upstream-exports/react-stately/private/collections/getChildNodes.tsx +8 -0
  168. package/src/upstream-exports/react-stately/private/collections/getItemCount.tsx +2 -0
  169. package/src/upstream-exports/react-stately/private/grid/GridCollection.tsx +7 -0
  170. package/src/upstream-exports/react-stately/private/grid/useGridState.tsx +6 -0
  171. package/src/upstream-exports/react-stately/private/utils/number.tsx +2 -0
  172. package/src/upstream-exports/react-stately/useComboBoxState.tsx +23 -0
  173. package/src/upstream-exports/react-stately/useListState.tsx +15 -0
  174. package/src/upstream-exports/react-stately/useMenuTriggerState.tsx +26 -0
  175. package/src/upstream-exports/react-stately/useMultipleSelectionState.tsx +21 -0
  176. package/src/upstream-exports/react-stately/useNumberFieldState.tsx +20 -0
  177. package/src/upstream-exports/react-stately/useOverlayTriggerState.tsx +20 -0
  178. package/src/upstream-exports/react-stately/useRadioGroupState.tsx +16 -0
  179. package/src/upstream-exports/react-stately/useSearchFieldState.tsx +19 -0
  180. package/src/upstream-exports/react-stately/useSliderState.tsx +20 -0
  181. package/src/upstream-exports/react-stately/useTableState.tsx +45 -0
  182. package/src/upstream-exports/react-stately/useTokenFieldState.tsx +25 -0
  183. package/src/upstream-exports/react-stately/useTooltipTriggerState.tsx +20 -0
  184. package/src/upstream-exports/react-stately/useTreeState.tsx +14 -0
  185. package/src/utils/domHelpers.ts +74 -17
  186. package/src/utils/isVirtualEvent.ts +2 -1
  187. package/src/utils/openLink.ts +8 -3
  188. package/src/utils/platform.ts +7 -3
  189. package/src/utils/scrollIntoView.ts +4 -4
  190. package/src/utils/shadowdom/DOMFunctions.ts +42 -2
  191. package/src/utils/useId.ts +11 -2
  192. package/src/utils/useLoadMoreSentinel.ts +8 -3
  193. package/src/utils/useViewportSize.ts +3 -3
  194. package/src/virtualizer/ScrollView.tsx +13 -4
  195. package/src/virtualizer/VirtualizerItem.tsx +4 -1
  196. package/src/virtualizer/useVirtualizerItem.tsx +43 -3
  197. package/src/menu/useMenuTrigger.ts +0 -189
  198. package/src/searchfield/useSearchField.ts +0 -156
  199. package/src/selection/useSelectableCollection.ts +0 -750
  200. package/src/spinbutton/useSpinButton.ts +0 -380
  201. package/src/table/useTableColumnResize.ts +0 -374
@@ -0,0 +1,755 @@
1
+ /** @jsxImportSource octane */
2
+ import type { BaseEvent } from '../interactions/createEventHandler';
3
+ type KeyboardEvent = BaseEvent<globalThis.KeyboardEvent>;
4
+ type DOMAttributes = Record<string, any>;
5
+ // Ported from adobe/react-spectrum@5ecb3333001313e83898cd07644227897e3bae1f (packages/react-aria/src/selection/useSelectableCollection.ts).
6
+ /*
7
+ * Copyright 2020 Adobe. All rights reserved.
8
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
9
+ * you may not use this file except in compliance with the License. You may obtain a copy
10
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software distributed under
13
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
14
+ * OF ANY KIND, either express or implied. See the License for the specific language
15
+ * governing permissions and limitations under the License.
16
+ */
17
+
18
+ import { CLEAR_FOCUS_EVENT, FOCUS_EVENT } from '../utils/constants';
19
+
20
+ import { dispatchVirtualFocus, moveVirtualFocus } from '../focus/virtualFocus';
21
+ import {
22
+ FocusableElement,
23
+ FocusStrategy,
24
+ Key,
25
+ KeyboardDelegate,
26
+ RefObject,
27
+ } from '@react-types/shared';
28
+ import { flushSync, withSlot } from 'octane';
29
+ import { FocusEvent, useEffect, useRef } from '../compat/react';
30
+ import { focusSafely } from '../interactions/focusSafely';
31
+ import { focusWithoutScrolling } from '../utils/focusWithoutScrolling';
32
+ import {
33
+ getActiveElement,
34
+ getEventTarget,
35
+ isFocusWithin,
36
+ nodeContains,
37
+ } from '../utils/shadowdom/DOMFunctions';
38
+ import { getFocusableTreeWalker } from '../focus/FocusScope';
39
+ import { getInteractionModality } from '../interactions/useFocusVisible';
40
+ import { getItemElement, isNonContiguousSelectionModifier, useCollectionId } from './utils';
41
+ import { isCtrlKeyPressed } from '../utils/keyboard';
42
+ import { isMac } from '../utils/platform';
43
+ import { isTabbable } from '../utils/isFocusable';
44
+ import { mergeProps } from '../utils/mergeProps';
45
+ import { MultipleSelectionManager } from '../upstream-exports/react-stately/useMultipleSelectionState';
46
+ import { scrollIntoView, scrollIntoViewport } from '../utils/scrollIntoView';
47
+ import { useEvent } from '../utils/useEvent';
48
+ import { useKeyboard } from '../interactions/useKeyboard';
49
+ import { useLocale } from '../i18n/I18nProvider';
50
+ import { useRouter } from '../utils/openLink';
51
+ import { useTypeSelect } from './useTypeSelect';
52
+ import { useUpdateLayoutEffect } from '../utils/useUpdateLayoutEffect';
53
+
54
+ export interface AriaSelectableCollectionOptions {
55
+ /**
56
+ * An interface for reading and updating multiple selection state.
57
+ */
58
+ selectionManager: MultipleSelectionManager;
59
+ /**
60
+ * A delegate object that implements behavior for keyboard focus movement.
61
+ */
62
+ keyboardDelegate: KeyboardDelegate;
63
+ /**
64
+ * The ref attached to the element representing the collection.
65
+ */
66
+ ref: RefObject<HTMLElement | null>;
67
+ /**
68
+ * Whether the collection or one of its items should be automatically focused upon render.
69
+ *
70
+ * @default false
71
+ */
72
+ autoFocus?: boolean | FocusStrategy;
73
+ /**
74
+ * Whether focus should wrap around when the end/start is reached.
75
+ *
76
+ * @default false
77
+ */
78
+ shouldFocusWrap?: boolean;
79
+ /**
80
+ * Whether the collection allows empty selection.
81
+ *
82
+ * @default false
83
+ */
84
+ disallowEmptySelection?: boolean;
85
+ /**
86
+ * Whether the collection allows the user to select all items via keyboard shortcut.
87
+ *
88
+ * @default false
89
+ */
90
+ disallowSelectAll?: boolean;
91
+ /**
92
+ * Whether pressing the Escape should clear selection in the collection or not.
93
+ *
94
+ * @default 'clearSelection'
95
+ */
96
+ escapeKeyBehavior?: 'clearSelection' | 'none';
97
+ /**
98
+ * Whether selection should occur automatically on focus.
99
+ *
100
+ * @default false
101
+ */
102
+ selectOnFocus?: boolean;
103
+ /**
104
+ * Whether typeahead is disabled.
105
+ *
106
+ * @default false
107
+ */
108
+ disallowTypeAhead?: boolean;
109
+ /**
110
+ * Whether the collection items should use virtual focus instead of being focused directly.
111
+ */
112
+ shouldUseVirtualFocus?: boolean;
113
+ /**
114
+ * Whether navigation through tab key is enabled.
115
+ */
116
+ allowsTabNavigation?: boolean;
117
+ /**
118
+ * Whether the collection items are contained in a virtual scroller.
119
+ */
120
+ isVirtualized?: boolean;
121
+ /**
122
+ * The ref attached to the scrollable body. Used to provide automatic scrolling on item focus for
123
+ * non-virtualized collections. If not provided, defaults to the collection ref.
124
+ */
125
+ scrollRef?: RefObject<HTMLElement | null>;
126
+ /**
127
+ * The behavior of links in the collection.
128
+ * - 'action': link behaves like onAction.
129
+ * - 'selection': link follows selection interactions (e.g. if URL drives selection).
130
+ * - 'override': links override all other interactions (link items are not selectable).
131
+ *
132
+ * @default 'action'
133
+ */
134
+ linkBehavior?: 'action' | 'selection' | 'override';
135
+ /**
136
+ * Which item in the collection to focus when tabbing into the collection. Overrides default
137
+ * roving tab index like behavior.
138
+ *
139
+ * @private
140
+ */
141
+ UNSTABLE_focusOnEntry?: 'first' | 'last';
142
+ }
143
+
144
+ export interface SelectableCollectionAria {
145
+ /** Props for the collection element. */
146
+ collectionProps: DOMAttributes;
147
+ }
148
+
149
+ /**
150
+ * Handles interactions with selectable collections.
151
+ */
152
+ export function useSelectableCollection(
153
+ options: AriaSelectableCollectionOptions,
154
+ _slot?: symbol,
155
+ ): SelectableCollectionAria {
156
+ if (_slot !== undefined) {
157
+ return withSlot(_slot, useSelectableCollection, options);
158
+ }
159
+
160
+ let {
161
+ selectionManager: manager,
162
+ keyboardDelegate: delegate,
163
+ ref,
164
+ autoFocus = false,
165
+ shouldFocusWrap = false,
166
+ disallowEmptySelection = false,
167
+ disallowSelectAll = false,
168
+ escapeKeyBehavior = 'clearSelection',
169
+ selectOnFocus = manager.selectionBehavior === 'replace',
170
+ disallowTypeAhead = false,
171
+ shouldUseVirtualFocus,
172
+ allowsTabNavigation = false,
173
+ // If no scrollRef is provided, assume the collection ref is the scrollable region
174
+ scrollRef = ref,
175
+ linkBehavior = 'action',
176
+ UNSTABLE_focusOnEntry,
177
+ } = options;
178
+ let { direction } = useLocale();
179
+ let router = useRouter();
180
+
181
+ const navigateToKey = (
182
+ e: KeyboardEvent,
183
+ key: Key | undefined,
184
+ childFocus?: FocusStrategy,
185
+ ): boolean | void => {
186
+ if (key != null) {
187
+ if (
188
+ manager.isLink(key) &&
189
+ linkBehavior === 'selection' &&
190
+ selectOnFocus &&
191
+ !isNonContiguousSelectionModifier(e)
192
+ ) {
193
+ // Set focused key and re-render synchronously to bring item into view if needed.
194
+ flushSync(() => {
195
+ manager.setFocusedKey(key, childFocus);
196
+ });
197
+
198
+ let item = getItemElement(ref, key);
199
+ let itemProps = manager.getItemProps(key);
200
+ if (item) {
201
+ router.open(item, e, itemProps.href, itemProps.routerOptions);
202
+ return;
203
+ }
204
+
205
+ return false;
206
+ }
207
+
208
+ manager.setFocusedKey(key, childFocus);
209
+
210
+ if (manager.isLink(key) && linkBehavior === 'override') {
211
+ return false;
212
+ }
213
+
214
+ if (e.shiftKey && manager.selectionMode === 'multiple') {
215
+ manager.extendSelection(key);
216
+ return;
217
+ } else if (selectOnFocus && !isNonContiguousSelectionModifier(e)) {
218
+ manager.replaceSelection(key);
219
+ return;
220
+ }
221
+ }
222
+ return false;
223
+ };
224
+
225
+ let arrowDown = (e: KeyboardEvent) => {
226
+ if (delegate.getKeyBelow) {
227
+ let nextKey =
228
+ manager.focusedKey != null
229
+ ? delegate.getKeyBelow?.(manager.focusedKey)
230
+ : delegate.getFirstKey?.();
231
+ if (nextKey == null && shouldFocusWrap) {
232
+ nextKey = delegate.getFirstKey?.(manager.focusedKey);
233
+ }
234
+ if (nextKey != null) {
235
+ navigateToKey(e, nextKey);
236
+ return;
237
+ }
238
+ }
239
+ return false;
240
+ };
241
+
242
+ let arrowUp = (e: KeyboardEvent) => {
243
+ if (delegate.getKeyAbove) {
244
+ let nextKey =
245
+ manager.focusedKey != null
246
+ ? delegate.getKeyAbove?.(manager.focusedKey)
247
+ : delegate.getLastKey?.();
248
+ if (nextKey == null && shouldFocusWrap) {
249
+ nextKey = delegate.getLastKey?.(manager.focusedKey);
250
+ }
251
+ if (nextKey != null) {
252
+ navigateToKey(e, nextKey);
253
+ return;
254
+ }
255
+ }
256
+ return false;
257
+ };
258
+
259
+ let home = (e: KeyboardEvent) => {
260
+ if (delegate.getFirstKey) {
261
+ if (manager.focusedKey === null && e.shiftKey) {
262
+ return false;
263
+ }
264
+ // TODO: should Home and End also be reversed in column reverse aka Home goes to top? Or should Home always to to the "first" (bottom)
265
+ let firstKey: Key | null = delegate.getFirstKey(manager.focusedKey, isCtrlKeyPressed(e));
266
+ manager.setFocusedKey(firstKey);
267
+ if (firstKey != null) {
268
+ if (isCtrlKeyPressed(e) && e.shiftKey && manager.selectionMode === 'multiple') {
269
+ manager.extendSelection(firstKey);
270
+ return;
271
+ } else if (selectOnFocus) {
272
+ manager.replaceSelection(firstKey);
273
+ return;
274
+ }
275
+ }
276
+ }
277
+ return false;
278
+ };
279
+
280
+ let arrowLeft = (e: KeyboardEvent) => {
281
+ if (delegate.getKeyLeftOf) {
282
+ let nextKey: Key | undefined | null =
283
+ manager.focusedKey != null
284
+ ? delegate.getKeyLeftOf?.(manager.focusedKey)
285
+ : delegate.getFirstKey?.();
286
+ if (nextKey == null && shouldFocusWrap) {
287
+ nextKey =
288
+ direction === 'rtl'
289
+ ? delegate.getFirstKey?.(manager.focusedKey)
290
+ : delegate.getLastKey?.(manager.focusedKey);
291
+ }
292
+ if (nextKey != null) {
293
+ navigateToKey(e, nextKey, direction === 'rtl' ? 'first' : 'last');
294
+ return;
295
+ }
296
+ }
297
+ return false;
298
+ };
299
+
300
+ let arrowRight = (e: KeyboardEvent) => {
301
+ if (delegate.getKeyRightOf) {
302
+ let nextKey: Key | undefined | null =
303
+ manager.focusedKey != null
304
+ ? delegate.getKeyRightOf?.(manager.focusedKey)
305
+ : delegate.getFirstKey?.();
306
+ if (nextKey == null && shouldFocusWrap) {
307
+ nextKey =
308
+ direction === 'rtl'
309
+ ? delegate.getLastKey?.(manager.focusedKey)
310
+ : delegate.getFirstKey?.(manager.focusedKey);
311
+ }
312
+ if (nextKey != null) {
313
+ navigateToKey(e, nextKey, direction === 'rtl' ? 'last' : 'first');
314
+ return;
315
+ }
316
+ }
317
+ return false;
318
+ };
319
+
320
+ let end = (e: KeyboardEvent) => {
321
+ if (delegate.getLastKey) {
322
+ if (manager.focusedKey === null && e.shiftKey) {
323
+ return false;
324
+ }
325
+ let lastKey = delegate.getLastKey(manager.focusedKey, isCtrlKeyPressed(e));
326
+ manager.setFocusedKey(lastKey);
327
+ if (lastKey != null) {
328
+ if (isCtrlKeyPressed(e) && e.shiftKey && manager.selectionMode === 'multiple') {
329
+ manager.extendSelection(lastKey);
330
+ return;
331
+ } else if (selectOnFocus) {
332
+ manager.replaceSelection(lastKey);
333
+ return;
334
+ }
335
+ }
336
+ }
337
+ return false;
338
+ };
339
+
340
+ let pageDown = (e: KeyboardEvent) => {
341
+ if (delegate.getKeyPageBelow && manager.focusedKey != null) {
342
+ let nextKey = delegate.getKeyPageBelow(manager.focusedKey);
343
+ if (nextKey != null) {
344
+ return navigateToKey(e, nextKey);
345
+ }
346
+ }
347
+ return false;
348
+ };
349
+
350
+ let pageUp = (e: KeyboardEvent) => {
351
+ if (delegate.getKeyPageAbove && manager.focusedKey != null) {
352
+ let nextKey = delegate.getKeyPageAbove(manager.focusedKey);
353
+ if (nextKey != null) {
354
+ return navigateToKey(e, nextKey);
355
+ }
356
+ }
357
+ return false;
358
+ };
359
+
360
+ let aHandler = () => {
361
+ if (manager.selectionMode === 'multiple' && disallowSelectAll !== true) {
362
+ manager.selectAll();
363
+ return;
364
+ }
365
+ return false;
366
+ };
367
+
368
+ let escape = () => {
369
+ if (
370
+ escapeKeyBehavior === 'clearSelection' &&
371
+ !disallowEmptySelection &&
372
+ manager.selectedKeys.size !== 0
373
+ ) {
374
+ manager.clearSelection();
375
+ return;
376
+ }
377
+ return false;
378
+ };
379
+
380
+ let tab = () => {
381
+ if (!allowsTabNavigation && ref.current) {
382
+ // There may be elements that are "tabbable" inside a collection (e.g. in a grid cell).
383
+ // However, collections should be treated as a single tab stop, with arrow key navigation internally.
384
+ // We don't control the rendering of these, so we can't override the tabIndex to prevent tabbing.
385
+ // Instead, we handle the Tab key, and move focus manually to the first/last tabbable element
386
+ // in the collection, so that the browser default behavior will apply starting from that element
387
+ // rather than the currently focused one.
388
+
389
+ let walker = getFocusableTreeWalker(ref.current, { tabbable: true });
390
+ let next: FocusableElement | undefined = undefined;
391
+ let last: FocusableElement;
392
+ do {
393
+ last = walker.lastChild() as FocusableElement;
394
+ if (last) {
395
+ next = last;
396
+ }
397
+ } while (last);
398
+
399
+ // If the active element is NOT tabbable but is contained by an element that IS tabbable (aka the cell), the browser will actually move focus to
400
+ // the containing element. We need to special case this so that tab will move focus out of the grid instead of looping between
401
+ // focusing the containing cell and back to the non-tabbable child element
402
+ let activeElement = getActiveElement();
403
+ if (next && (!isFocusWithin(next) || (activeElement && !isTabbable(activeElement)))) {
404
+ focusWithoutScrolling(next);
405
+ }
406
+ }
407
+ return { shouldContinuePropagation: true, shouldPreventDefault: false };
408
+ };
409
+
410
+ let shiftTab = () => {
411
+ if (!allowsTabNavigation && ref.current) {
412
+ ref.current.focus();
413
+ }
414
+ return { shouldContinuePropagation: true, shouldPreventDefault: false };
415
+ };
416
+
417
+ let withShiftSel = (
418
+ key: string,
419
+ callback: import('../interactions/createKeyboardShortcutHandler').KeyboardShortcutAction,
420
+ ) => {
421
+ return {
422
+ [isMac() ? key + '+Shift+Alt' : key + '+Shift+Control']: callback,
423
+ [key + '+Shift']: callback,
424
+ [isMac() ? key + '+Alt' : key + '+Control']: callback,
425
+ [key]: callback,
426
+ };
427
+ };
428
+ // oxlint-disable react/react-compiler
429
+ let { keyboardProps: repeatKeyboardProps } = useKeyboard({
430
+ shortcuts: {
431
+ ...withShiftSel('ArrowDown', arrowDown),
432
+ ...withShiftSel('ArrowUp', arrowUp),
433
+ ...withShiftSel('ArrowLeft', arrowLeft),
434
+ ...withShiftSel('ArrowRight', arrowRight),
435
+ ...withShiftSel('PageDown', pageDown),
436
+ ...withShiftSel('PageUp', pageUp),
437
+ },
438
+ allowRepeats: true,
439
+ });
440
+ // oxlint-disable react/react-compiler
441
+ let { keyboardProps } = useKeyboard({
442
+ shortcuts: {
443
+ ...withShiftSel('Home', home),
444
+ ...withShiftSel('End', end),
445
+ 'Mod+A': aHandler,
446
+ Escape: escape,
447
+ Tab: tab,
448
+ 'Tab+Shift': shiftTab,
449
+ },
450
+ });
451
+ // oxlint-enable react/react-compiler
452
+
453
+ // Store the scroll position so we can restore it later.
454
+ /// TODO: should this happen all the time??
455
+ let scrollPos = useRef({ top: 0, left: 0 });
456
+ useEvent(scrollRef, 'scroll', () => {
457
+ scrollPos.current = {
458
+ top: scrollRef.current?.scrollTop ?? 0,
459
+ left: scrollRef.current?.scrollLeft ?? 0,
460
+ };
461
+ });
462
+
463
+ let onFocus = (e: FocusEvent) => {
464
+ if (manager.isFocused) {
465
+ // If a focus event bubbled through a portal, reset focus state.
466
+ if (!nodeContains(e.currentTarget as Element, getEventTarget(e) as Element)) {
467
+ manager.setFocused(false);
468
+ }
469
+ return;
470
+ }
471
+
472
+ // Focus events can bubble through portals. Ignore these events.
473
+ if (!nodeContains(e.currentTarget as Element, getEventTarget(e) as Element)) {
474
+ return;
475
+ }
476
+
477
+ let modality = getInteractionModality();
478
+ manager.setFocused(true);
479
+ let navigateToKey = (key: Key | undefined | null) => {
480
+ if (key != null) {
481
+ manager.setFocusedKey(key);
482
+ if (selectOnFocus && !manager.isSelected(key)) {
483
+ manager.replaceSelection(key);
484
+ }
485
+ }
486
+ };
487
+
488
+ // we need the "virtual" modality case checks here because shift tabbing from the prompt field's attachment card back into the
489
+ // thread is a virtual focus event (the tab handler in onKeyDown focuses the ref of the attachmentList aka TagGroup via a focus() call, hence the virtual modality)
490
+ if (UNSTABLE_focusOnEntry && (modality === 'keyboard' || modality === 'virtual')) {
491
+ // always go to the first item in the Thread when tabbing forwards/backwards into the collection
492
+ // since it is probably more important to the user to see the new prompt reply rather than go to the last focused key
493
+ navigateToKey(
494
+ UNSTABLE_focusOnEntry === 'first' ? delegate.getFirstKey?.() : delegate.getLastKey?.(),
495
+ );
496
+ } else if (manager.focusedKey == null) {
497
+ // If the user hasn't yet interacted with the collection, there will be no focusedKey set.
498
+ // Attempt to detect whether the user is tabbing forward or backward into the collection
499
+ // and either focus the first or last item accordingly.
500
+ let relatedTarget = e.relatedTarget as Element;
501
+ if (
502
+ relatedTarget &&
503
+ e.currentTarget.compareDocumentPosition(relatedTarget) & Node.DOCUMENT_POSITION_FOLLOWING
504
+ ) {
505
+ navigateToKey(manager.lastSelectedKey ?? delegate.getLastKey?.());
506
+ } else {
507
+ navigateToKey(manager.firstSelectedKey ?? delegate.getFirstKey?.());
508
+ }
509
+ } else if (scrollRef.current) {
510
+ // Restore the scroll position to what it was before.
511
+ scrollRef.current.scrollTop = scrollPos.current.top;
512
+ scrollRef.current.scrollLeft = scrollPos.current.left;
513
+ }
514
+
515
+ if (manager.focusedKey != null && scrollRef.current) {
516
+ // Refocus and scroll the focused item into view if it exists within the scrollable region.
517
+ let element = getItemElement(ref, manager.focusedKey);
518
+ if (element instanceof HTMLElement) {
519
+ // This prevents a flash of focus on the first/last element in the collection, or the collection itself.
520
+ if (!isFocusWithin(element) && !shouldUseVirtualFocus) {
521
+ focusWithoutScrolling(element);
522
+ }
523
+
524
+ if (modality === 'keyboard' || (UNSTABLE_focusOnEntry && modality === 'virtual')) {
525
+ scrollIntoViewport(element, { containingElement: ref.current });
526
+ }
527
+ }
528
+ }
529
+ };
530
+
531
+ let onBlur = (e: globalThis.FocusEvent) => {
532
+ // Don't set blurred and then focused again if moving focus within the collection.
533
+ if (!nodeContains(e.currentTarget as Element, e.relatedTarget as HTMLElement)) {
534
+ manager.setFocused(false);
535
+ }
536
+ };
537
+
538
+ // Ref to track whether the first item in the collection should be automatically focused. Specifically used for autocomplete when user types
539
+ // to focus the first key AFTER the collection updates.
540
+ // TODO: potentially expand the usage of this
541
+ let shouldVirtualFocusFirst = useRef(false);
542
+ // Add event listeners for custom virtual events. These handle updating the focused key in response to various keyboard events
543
+ // at the autocomplete level
544
+ // TODO: fix type later
545
+ useEvent(
546
+ ref,
547
+ FOCUS_EVENT,
548
+ !shouldUseVirtualFocus
549
+ ? undefined
550
+ : (e: any) => {
551
+ let { detail } = e;
552
+ e.stopPropagation();
553
+ manager.setFocused(true);
554
+ // If the user is typing forwards, autofocus the first option in the list.
555
+ if (detail?.focusStrategy === 'first') {
556
+ shouldVirtualFocusFirst.current = true;
557
+ }
558
+ },
559
+ );
560
+
561
+ // update active descendant
562
+ let firstKey = delegate.getFirstKey?.() ?? null;
563
+ useUpdateLayoutEffect(() => {
564
+ if (shouldVirtualFocusFirst.current) {
565
+ // If no focusable items exist in the list, make sure to clear any activedescendant that may still exist and move focus back to
566
+ // the original active element (e.g. the autocomplete input)
567
+ if (firstKey == null) {
568
+ let previousActiveElement = getActiveElement();
569
+ moveVirtualFocus(ref.current);
570
+ dispatchVirtualFocus(previousActiveElement!, null);
571
+
572
+ // If there wasn't a focusable key but the collection had items, then that means we aren't in an intermediate load state and all keys are disabled.
573
+ // Reset shouldVirtualFocusFirst so that we don't erronously autofocus an item when the collection is filtered again.
574
+ if (manager.collection.size > 0) {
575
+ shouldVirtualFocusFirst.current = false;
576
+ }
577
+ } else {
578
+ manager.setFocusedKey(firstKey);
579
+ // Only set shouldVirtualFocusFirst to false if we've successfully set the first key as the focused key
580
+ // If there wasn't a key to focus, we might be in a temporary loading state so we'll want to still focus the first key
581
+ // after the collection updates after load
582
+ shouldVirtualFocusFirst.current = false;
583
+ }
584
+ }
585
+ }, [firstKey, manager.collection.size]);
586
+
587
+ // reset focus first flag
588
+ useUpdateLayoutEffect(() => {
589
+ // If user causes the focused key to change in any other way, clear shouldVirtualFocusFirst so we don't
590
+ // accidentally move focus from under them. Skip this if the collection was empty because we might be in a load
591
+ // state and will still want to focus the first item after load
592
+ if (manager.collection.size > 0) {
593
+ shouldVirtualFocusFirst.current = false;
594
+ }
595
+ }, [manager.focusedKey]);
596
+
597
+ useEvent(
598
+ ref,
599
+ CLEAR_FOCUS_EVENT,
600
+ !shouldUseVirtualFocus
601
+ ? undefined
602
+ : (e: any) => {
603
+ e.stopPropagation();
604
+ manager.setFocused(false);
605
+ if (e.detail?.clearFocusKey) {
606
+ manager.setFocusedKey(null);
607
+ }
608
+ },
609
+ );
610
+
611
+ const autoFocusRef = useRef(autoFocus);
612
+ const didAutoFocusRef = useRef(false);
613
+ useEffect(() => {
614
+ if (autoFocusRef.current) {
615
+ let focusedKey: Key | null = null;
616
+
617
+ // Check focus strategy to determine which item to focus
618
+ if (autoFocus === 'first') {
619
+ focusedKey = delegate.getFirstKey?.() ?? null;
620
+ }
621
+ if (autoFocus === 'last') {
622
+ focusedKey = delegate.getLastKey?.() ?? null;
623
+ }
624
+
625
+ // If there are any selected keys, make the first one the new focus target
626
+ let selectedKeys = manager.selectedKeys;
627
+ if (selectedKeys.size) {
628
+ for (let key of selectedKeys) {
629
+ if (manager.canSelectItem(key)) {
630
+ focusedKey = key;
631
+ break;
632
+ }
633
+ }
634
+ }
635
+
636
+ manager.setFocused(true);
637
+ manager.setFocusedKey(focusedKey);
638
+
639
+ // If no default focus key is selected, focus the collection itself.
640
+ if (focusedKey == null && !shouldUseVirtualFocus && ref.current) {
641
+ focusSafely(ref.current);
642
+ }
643
+
644
+ // Wait until the collection has items to autofocus.
645
+ if (manager.collection.size > 0) {
646
+ autoFocusRef.current = false;
647
+ didAutoFocusRef.current = true;
648
+ }
649
+ }
650
+ });
651
+
652
+ // Scroll the focused element into view when the focusedKey changes.
653
+ let lastFocusedKey = useRef<typeof manager.focusedKey>(manager.focusedKey);
654
+ let raf = useRef<number | null>(null);
655
+ useEffect(() => {
656
+ if (
657
+ manager.isFocused &&
658
+ manager.focusedKey != null &&
659
+ (manager.focusedKey !== lastFocusedKey.current || didAutoFocusRef.current) &&
660
+ scrollRef.current &&
661
+ ref.current
662
+ ) {
663
+ let modality = getInteractionModality();
664
+ let element = getItemElement(ref, manager.focusedKey);
665
+ if (!(element instanceof HTMLElement)) {
666
+ // If item element wasn't found, return early (don't update autoFocusRef and lastFocusedKey).
667
+ // The collection may initially be empty (e.g. virtualizer), so wait until the element exists.
668
+ return;
669
+ }
670
+
671
+ if (modality === 'keyboard' || didAutoFocusRef.current) {
672
+ if (raf.current) {
673
+ cancelAnimationFrame(raf.current);
674
+ }
675
+
676
+ raf.current = requestAnimationFrame(() => {
677
+ if (scrollRef.current) {
678
+ scrollIntoView(scrollRef.current, element);
679
+ // Avoid scroll in iOS VO, since it may cause overlay to close (i.e. RAC submenu)
680
+ if (modality !== 'virtual') {
681
+ scrollIntoViewport(element, { containingElement: ref.current });
682
+ }
683
+ }
684
+ });
685
+ }
686
+ }
687
+
688
+ // If the focused key becomes null (e.g. the last item is deleted), focus the whole collection.
689
+ if (
690
+ !shouldUseVirtualFocus &&
691
+ manager.isFocused &&
692
+ manager.focusedKey == null &&
693
+ lastFocusedKey.current != null &&
694
+ ref.current
695
+ ) {
696
+ focusSafely(ref.current);
697
+ }
698
+
699
+ lastFocusedKey.current = manager.focusedKey;
700
+ didAutoFocusRef.current = false;
701
+ });
702
+
703
+ useEffect(() => {
704
+ return () => {
705
+ if (raf.current) {
706
+ cancelAnimationFrame(raf.current);
707
+ }
708
+ };
709
+ }, []);
710
+
711
+ // Intercept FocusScope restoration since virtualized collections can reuse DOM nodes.
712
+ useEvent(ref, 'react-aria-focus-scope-restore', (e) => {
713
+ e.preventDefault();
714
+ manager.setFocused(true);
715
+ });
716
+
717
+ let handlers = {
718
+ ...mergeProps(keyboardProps, repeatKeyboardProps),
719
+ onFocus,
720
+ onBlur,
721
+ onMouseDown(e: MouseEvent) {
722
+ // Ignore events that bubbled through portals.
723
+ if (scrollRef.current === (getEventTarget(e) as Element)) {
724
+ // Prevent focus going to the collection when clicking on the scrollbar.
725
+ e.preventDefault();
726
+ }
727
+ },
728
+ };
729
+
730
+ let { typeSelectProps } = useTypeSelect({
731
+ keyboardDelegate: delegate,
732
+ selectionManager: manager,
733
+ });
734
+
735
+ if (!disallowTypeAhead) {
736
+ // oxlint-disable-next-line react/react-compiler
737
+ handlers = mergeProps(typeSelectProps, handlers);
738
+ }
739
+
740
+ // If nothing is focused within the collection, make the collection itself tabbable.
741
+ // This will be marshalled to either the first or last item depending on where focus came from.
742
+ let tabIndex: number | undefined = undefined;
743
+ if (!shouldUseVirtualFocus) {
744
+ tabIndex = manager.focusedKey == null ? 0 : -1;
745
+ }
746
+
747
+ let collectionId = useCollectionId(manager.collection);
748
+ return {
749
+ // oxlint-disable-next-line react/react-compiler
750
+ collectionProps: mergeProps(handlers, {
751
+ tabIndex,
752
+ 'data-collection': collectionId,
753
+ }),
754
+ };
755
+ }