@react-aria/gridlist 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.
@@ -0,0 +1,154 @@
1
+ /*
2
+ * Copyright 2022 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 {
14
+ AriaLabelingProps,
15
+ CollectionBase,
16
+ DisabledBehavior,
17
+ DOMAttributes,
18
+ DOMProps,
19
+ Key,
20
+ KeyboardDelegate,
21
+ LayoutDelegate,
22
+ MultipleSelection,
23
+ RefObject
24
+ } from '@react-types/shared';
25
+ import {filterDOMProps, mergeProps, useId} from '@react-aria/utils';
26
+ import {listMap} from './utils';
27
+ import {ListState} from '@react-stately/list';
28
+ import {useGridSelectionAnnouncement, useHighlightSelectionDescription} from '@react-aria/grid';
29
+ import {useHasTabbableChild} from '@react-aria/focus';
30
+ import {useSelectableList} from '@react-aria/selection';
31
+
32
+ export interface GridListProps<T> extends CollectionBase<T>, MultipleSelection {
33
+ /**
34
+ * Handler that is called when a user performs an action on an item. The exact user event depends on
35
+ * the collection's `selectionBehavior` prop and the interaction modality.
36
+ */
37
+ onAction?: (key: Key) => void,
38
+ /** Whether `disabledKeys` applies to all interactions, or only selection. */
39
+ disabledBehavior?: DisabledBehavior
40
+ }
41
+
42
+ export interface AriaGridListProps<T> extends GridListProps<T>, DOMProps, AriaLabelingProps {
43
+ /**
44
+ * Whether keyboard navigation to focusable elements within grid list items is
45
+ * via the left/right arrow keys or the tab key.
46
+ * @default 'arrow'
47
+ */
48
+ keyboardNavigationBehavior?: 'arrow' | 'tab'
49
+ }
50
+
51
+ export interface AriaGridListOptions<T> extends Omit<AriaGridListProps<T>, 'children'> {
52
+ /** Whether the list uses virtual scrolling. */
53
+ isVirtualized?: boolean,
54
+ /**
55
+ * An optional keyboard delegate implementation for type to select,
56
+ * to override the default.
57
+ */
58
+ keyboardDelegate?: KeyboardDelegate,
59
+ /**
60
+ * A delegate object that provides layout information for items in the collection.
61
+ * By default this uses the DOM, but this can be overridden to implement things like
62
+ * virtualized scrolling.
63
+ */
64
+ layoutDelegate?: LayoutDelegate,
65
+ /**
66
+ * Whether focus should wrap around when the end/start is reached.
67
+ * @default false
68
+ */
69
+ shouldFocusWrap?: boolean,
70
+ /**
71
+ * The behavior of links in the collection.
72
+ * - 'action': link behaves like onAction.
73
+ * - 'selection': link follows selection interactions (e.g. if URL drives selection).
74
+ * - 'override': links override all other interactions (link items are not selectable).
75
+ * @default 'action'
76
+ */
77
+ linkBehavior?: 'action' | 'selection' | 'override'
78
+ }
79
+
80
+ export interface GridListAria {
81
+ /** Props for the grid element. */
82
+ gridProps: DOMAttributes
83
+ }
84
+
85
+ /**
86
+ * Provides the behavior and accessibility implementation for a list component with interactive children.
87
+ * A grid list displays data in a single column and enables a user to navigate its contents via directional navigation keys.
88
+ * @param props - Props for the list.
89
+ * @param state - State for the list, as returned by `useListState`.
90
+ * @param ref - The ref attached to the list element.
91
+ */
92
+ export function useGridList<T>(props: AriaGridListOptions<T>, state: ListState<T>, ref: RefObject<HTMLElement | null>): GridListAria {
93
+ let {
94
+ isVirtualized,
95
+ keyboardDelegate,
96
+ layoutDelegate,
97
+ onAction,
98
+ linkBehavior = 'action',
99
+ keyboardNavigationBehavior = 'arrow'
100
+ } = props;
101
+
102
+ if (!props['aria-label'] && !props['aria-labelledby']) {
103
+ console.warn('An aria-label or aria-labelledby prop is required for accessibility.');
104
+ }
105
+
106
+ let {listProps} = useSelectableList({
107
+ selectionManager: state.selectionManager,
108
+ collection: state.collection,
109
+ disabledKeys: state.disabledKeys,
110
+ ref,
111
+ keyboardDelegate,
112
+ layoutDelegate,
113
+ isVirtualized,
114
+ selectOnFocus: state.selectionManager.selectionBehavior === 'replace',
115
+ shouldFocusWrap: props.shouldFocusWrap,
116
+ linkBehavior
117
+ });
118
+
119
+ let id = useId(props.id);
120
+ listMap.set(state, {id, onAction, linkBehavior, keyboardNavigationBehavior});
121
+
122
+ let descriptionProps = useHighlightSelectionDescription({
123
+ selectionManager: state.selectionManager,
124
+ hasItemActions: !!onAction
125
+ });
126
+
127
+ let hasTabbableChild = useHasTabbableChild(ref, {
128
+ isDisabled: state.collection.size !== 0
129
+ });
130
+
131
+ let domProps = filterDOMProps(props, {labelable: true});
132
+ let gridProps: DOMAttributes = mergeProps(
133
+ domProps,
134
+ {
135
+ role: 'grid',
136
+ id,
137
+ 'aria-multiselectable': state.selectionManager.selectionMode === 'multiple' ? 'true' : undefined
138
+ },
139
+ // If collection is empty, make sure the grid is tabbable unless there is a child tabbable element.
140
+ state.collection.size === 0 ? {tabIndex: hasTabbableChild ? -1 : 0} : listProps,
141
+ descriptionProps
142
+ );
143
+
144
+ if (isVirtualized) {
145
+ gridProps['aria-rowcount'] = state.collection.size;
146
+ gridProps['aria-colcount'] = 1;
147
+ }
148
+
149
+ useGridSelectionAnnouncement({}, state);
150
+
151
+ return {
152
+ gridProps
153
+ };
154
+ }
@@ -0,0 +1,299 @@
1
+ /*
2
+ * Copyright 2022 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 {chain, getScrollParent, mergeProps, scrollIntoViewport, useSlotId, useSyntheticLinkProps} from '@react-aria/utils';
14
+ import {DOMAttributes, FocusableElement, RefObject, Node as RSNode} from '@react-types/shared';
15
+ import {focusSafely, getFocusableTreeWalker} from '@react-aria/focus';
16
+ import {getLastItem} from '@react-stately/collections';
17
+ import {getRowId, listMap} from './utils';
18
+ import {HTMLAttributes, KeyboardEvent as ReactKeyboardEvent, useRef} from 'react';
19
+ import {isFocusVisible} from '@react-aria/interactions';
20
+ import type {ListState} from '@react-stately/list';
21
+ import {SelectableItemStates, useSelectableItem} from '@react-aria/selection';
22
+ import type {TreeState} from '@react-stately/tree';
23
+ import {useLocale} from '@react-aria/i18n';
24
+
25
+ export interface AriaGridListItemOptions {
26
+ /** An object representing the list item. Contains all the relevant information that makes up the list row. */
27
+ node: RSNode<unknown>,
28
+ /** Whether the list row is contained in a virtual scroller. */
29
+ isVirtualized?: boolean,
30
+ /** Whether selection should occur on press up instead of press down. */
31
+ shouldSelectOnPressUp?: boolean
32
+ }
33
+
34
+ export interface GridListItemAria extends SelectableItemStates {
35
+ /** Props for the list row element. */
36
+ rowProps: DOMAttributes,
37
+ /** Props for the grid cell element within the list row. */
38
+ gridCellProps: DOMAttributes,
39
+ /** Props for the list item description element, if any. */
40
+ descriptionProps: DOMAttributes
41
+ }
42
+
43
+ const EXPANSION_KEYS = {
44
+ 'expand': {
45
+ ltr: 'ArrowRight',
46
+ rtl: 'ArrowLeft'
47
+ },
48
+ 'collapse': {
49
+ ltr: 'ArrowLeft',
50
+ rtl: 'ArrowRight'
51
+ }
52
+ };
53
+
54
+ /**
55
+ * Provides the behavior and accessibility implementation for a row in a grid list.
56
+ * @param props - Props for the row.
57
+ * @param state - State of the parent list, as returned by `useListState`.
58
+ * @param ref - The ref attached to the row element.
59
+ */
60
+ export function useGridListItem<T>(props: AriaGridListItemOptions, state: ListState<T> | TreeState<T>, ref: RefObject<FocusableElement | null>): GridListItemAria {
61
+ // Copied from useGridCell + some modifications to make it not so grid specific
62
+ let {
63
+ node,
64
+ isVirtualized,
65
+ shouldSelectOnPressUp
66
+ } = props;
67
+
68
+ // let stringFormatter = useLocalizedStringFormatter(intlMessages, '@react-aria/gridlist');
69
+ let {direction} = useLocale();
70
+ let {onAction, linkBehavior, keyboardNavigationBehavior} = listMap.get(state);
71
+ let descriptionId = useSlotId();
72
+
73
+ // We need to track the key of the item at the time it was last focused so that we force
74
+ // focus to go to the item when the DOM node is reused for a different item in a virtualizer.
75
+ let keyWhenFocused = useRef(null);
76
+ let focus = () => {
77
+ // Don't shift focus to the row if the active element is a element within the row already
78
+ // (e.g. clicking on a row button)
79
+ if (
80
+ (keyWhenFocused.current != null && node.key !== keyWhenFocused.current) ||
81
+ !ref.current?.contains(document.activeElement)
82
+ ) {
83
+ focusSafely(ref.current);
84
+ }
85
+ };
86
+
87
+ let treeGridRowProps: HTMLAttributes<HTMLElement> = {};
88
+ let hasChildRows;
89
+ let hasLink = state.selectionManager.isLink(node.key);
90
+ if (node != null && 'expandedKeys' in state) {
91
+ // TODO: ideally node.hasChildNodes would be a way to tell if a row has child nodes, but the row's contents make it so that value is always
92
+ // true...
93
+ hasChildRows = [...state.collection.getChildren(node.key)].length > 1;
94
+ if (onAction == null && !hasLink && state.selectionManager.selectionMode === 'none' && hasChildRows) {
95
+ onAction = () => state.toggleKey(node.key);
96
+ }
97
+
98
+ let isExpanded = hasChildRows ? state.expandedKeys.has(node.key) : undefined;
99
+ treeGridRowProps = {
100
+ 'aria-expanded': isExpanded,
101
+ 'aria-level': node.level + 1,
102
+ 'aria-posinset': node?.index + 1,
103
+ 'aria-setsize': node.level > 0 ?
104
+ (getLastItem(state.collection.getChildren(node?.parentKey))).index + 1 :
105
+ [...state.collection].filter(row => row.level === 0).at(-1).index + 1
106
+ };
107
+ }
108
+
109
+ let {itemProps, ...itemStates} = useSelectableItem({
110
+ selectionManager: state.selectionManager,
111
+ key: node.key,
112
+ ref,
113
+ isVirtualized,
114
+ shouldSelectOnPressUp,
115
+ onAction: onAction || node.props?.onAction ? chain(node.props?.onAction, onAction ? () => onAction(node.key) : undefined) : undefined,
116
+ focus,
117
+ linkBehavior
118
+ });
119
+
120
+ let onKeyDown = (e: ReactKeyboardEvent) => {
121
+ if (!e.currentTarget.contains(e.target as Element)) {
122
+ return;
123
+ }
124
+
125
+ let walker = getFocusableTreeWalker(ref.current);
126
+ walker.currentNode = document.activeElement;
127
+
128
+ if ('expandedKeys' in state && document.activeElement === ref.current) {
129
+ if ((e.key === EXPANSION_KEYS['expand'][direction]) && state.selectionManager.focusedKey === node.key && hasChildRows && !state.expandedKeys.has(node.key)) {
130
+ state.toggleKey(node.key);
131
+ e.stopPropagation();
132
+ return;
133
+ } else if ((e.key === EXPANSION_KEYS['collapse'][direction]) && state.selectionManager.focusedKey === node.key && hasChildRows && state.expandedKeys.has(node.key)) {
134
+ state.toggleKey(node.key);
135
+ e.stopPropagation();
136
+ return;
137
+ }
138
+ }
139
+
140
+ switch (e.key) {
141
+ case 'ArrowLeft': {
142
+ if (keyboardNavigationBehavior === 'arrow') {
143
+ // Find the next focusable element within the row.
144
+ let focusable = direction === 'rtl'
145
+ ? walker.nextNode() as FocusableElement
146
+ : walker.previousNode() as FocusableElement;
147
+
148
+ if (focusable) {
149
+ e.preventDefault();
150
+ e.stopPropagation();
151
+ focusSafely(focusable);
152
+ scrollIntoViewport(focusable, {containingElement: getScrollParent(ref.current)});
153
+ } else {
154
+ // If there is no next focusable child, then return focus back to the row
155
+ e.preventDefault();
156
+ e.stopPropagation();
157
+ if (direction === 'rtl') {
158
+ focusSafely(ref.current);
159
+ scrollIntoViewport(ref.current, {containingElement: getScrollParent(ref.current)});
160
+ } else {
161
+ walker.currentNode = ref.current;
162
+ let lastElement = last(walker);
163
+ if (lastElement) {
164
+ focusSafely(lastElement);
165
+ scrollIntoViewport(lastElement, {containingElement: getScrollParent(ref.current)});
166
+ }
167
+ }
168
+ }
169
+ }
170
+ break;
171
+ }
172
+ case 'ArrowRight': {
173
+ if (keyboardNavigationBehavior === 'arrow') {
174
+ let focusable = direction === 'rtl'
175
+ ? walker.previousNode() as FocusableElement
176
+ : walker.nextNode() as FocusableElement;
177
+
178
+ if (focusable) {
179
+ e.preventDefault();
180
+ e.stopPropagation();
181
+ focusSafely(focusable);
182
+ scrollIntoViewport(focusable, {containingElement: getScrollParent(ref.current)});
183
+ } else {
184
+ e.preventDefault();
185
+ e.stopPropagation();
186
+ if (direction === 'ltr') {
187
+ focusSafely(ref.current);
188
+ scrollIntoViewport(ref.current, {containingElement: getScrollParent(ref.current)});
189
+ } else {
190
+ walker.currentNode = ref.current;
191
+ let lastElement = last(walker);
192
+ if (lastElement) {
193
+ focusSafely(lastElement);
194
+ scrollIntoViewport(lastElement, {containingElement: getScrollParent(ref.current)});
195
+ }
196
+ }
197
+ }
198
+ }
199
+ break;
200
+ }
201
+ case 'ArrowUp':
202
+ case 'ArrowDown':
203
+ // Prevent this event from reaching row children, e.g. menu buttons. We want arrow keys to navigate
204
+ // to the row above/below instead. We need to re-dispatch the event from a higher parent so it still
205
+ // bubbles and gets handled by useSelectableCollection.
206
+ if (!e.altKey && ref.current.contains(e.target as Element)) {
207
+ e.stopPropagation();
208
+ e.preventDefault();
209
+ ref.current.parentElement.dispatchEvent(
210
+ new KeyboardEvent(e.nativeEvent.type, e.nativeEvent)
211
+ );
212
+ }
213
+ break;
214
+ case 'Tab': {
215
+ if (keyboardNavigationBehavior === 'tab') {
216
+ // If there is another focusable element within this item, stop propagation so the tab key
217
+ // is handled by the browser and not by useSelectableCollection (which would take us out of the list).
218
+ let walker = getFocusableTreeWalker(ref.current, {tabbable: true});
219
+ walker.currentNode = document.activeElement;
220
+ let next = e.shiftKey ? walker.previousNode() : walker.nextNode();
221
+ if (next) {
222
+ e.stopPropagation();
223
+ }
224
+ }
225
+ }
226
+ }
227
+ };
228
+
229
+ let onFocus = (e) => {
230
+ keyWhenFocused.current = node.key;
231
+ if (e.target !== ref.current) {
232
+ // useSelectableItem only handles setting the focused key when
233
+ // the focused element is the row itself. We also want to
234
+ // set the focused key when a child element receives focus.
235
+ // If focus is currently visible (e.g. the user is navigating with the keyboard),
236
+ // then skip this. We want to restore focus to the previously focused row
237
+ // in that case since the list should act like a single tab stop.
238
+ if (!isFocusVisible()) {
239
+ state.selectionManager.setFocusedKey(node.key);
240
+ }
241
+ return;
242
+ }
243
+ };
244
+
245
+ let syntheticLinkProps = useSyntheticLinkProps(node.props);
246
+ let linkProps = itemStates.hasAction ? syntheticLinkProps : {};
247
+ // TODO: re-add when we get translations and fix this for iOS VO
248
+ // let rowAnnouncement;
249
+ // if (onAction) {
250
+ // rowAnnouncement = stringFormatter.format('hasActionAnnouncement');
251
+ // } else if (hasLink) {
252
+ // rowAnnouncement = stringFormatter.format('hasLinkAnnouncement', {
253
+ // link: node.props.href
254
+ // });
255
+ // }
256
+
257
+ let rowProps: DOMAttributes = mergeProps(itemProps, linkProps, {
258
+ role: 'row',
259
+ onKeyDownCapture: onKeyDown,
260
+ onFocus,
261
+ // 'aria-label': [(node.textValue || undefined), rowAnnouncement].filter(Boolean).join(', '),
262
+ 'aria-label': node.textValue || undefined,
263
+ 'aria-selected': state.selectionManager.canSelectItem(node.key) ? state.selectionManager.isSelected(node.key) : undefined,
264
+ 'aria-disabled': state.selectionManager.isDisabled(node.key) || undefined,
265
+ 'aria-labelledby': descriptionId && node.textValue ? `${getRowId(state, node.key)} ${descriptionId}` : undefined,
266
+ id: getRowId(state, node.key)
267
+ });
268
+
269
+ if (isVirtualized) {
270
+ rowProps['aria-rowindex'] = node.index + 1;
271
+ }
272
+
273
+ let gridCellProps = {
274
+ role: 'gridcell',
275
+ 'aria-colindex': 1
276
+ };
277
+
278
+ // TODO: should isExpanded and hasChildRows be a item state that gets returned by the hook?
279
+ return {
280
+ rowProps: {...mergeProps(rowProps, treeGridRowProps)},
281
+ gridCellProps,
282
+ descriptionProps: {
283
+ id: descriptionId
284
+ },
285
+ ...itemStates
286
+ };
287
+ }
288
+
289
+ function last(walker: TreeWalker) {
290
+ let next: FocusableElement;
291
+ let last: FocusableElement;
292
+ do {
293
+ last = walker.lastChild() as FocusableElement;
294
+ if (last) {
295
+ next = last;
296
+ }
297
+ } while (last);
298
+ return next;
299
+ }
@@ -0,0 +1,32 @@
1
+ /*
2
+ * Copyright 2022 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 {AriaGridSelectionCheckboxProps, GridSelectionCheckboxAria, useGridSelectionCheckbox} from '@react-aria/grid';
14
+ import {getRowId} from './utils';
15
+ import type {ListState} from '@react-stately/list';
16
+
17
+ /**
18
+ * Provides the behavior and accessibility implementation for a selection checkbox in a grid list.
19
+ * @param props - Props for the selection checkbox.
20
+ * @param state - State of the list, as returned by `useListState`.
21
+ */
22
+ export function useGridListSelectionCheckbox<T>(props: AriaGridSelectionCheckboxProps, state: ListState<T>): GridSelectionCheckboxAria {
23
+ let {key} = props;
24
+ const {checkboxProps} = useGridSelectionCheckbox(props, state as any);
25
+
26
+ return {
27
+ checkboxProps: {
28
+ ...checkboxProps,
29
+ 'aria-labelledby': `${checkboxProps.id} ${getRowId(state, key)}`
30
+ }
31
+ };
32
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,42 @@
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 {Key} from '@react-types/shared';
14
+ import type {ListState} from '@react-stately/list';
15
+
16
+ interface ListMapShared {
17
+ id: string,
18
+ onAction: (key: Key) => void,
19
+ linkBehavior?: 'action' | 'selection' | 'override',
20
+ keyboardNavigationBehavior: 'arrow' | 'tab'
21
+ }
22
+
23
+ // Used to share:
24
+ // id of the list and onAction between useList, useListItem, and useListSelectionCheckbox
25
+ export const listMap = new WeakMap<ListState<unknown>, ListMapShared>();
26
+
27
+ export function getRowId<T>(state: ListState<T>, key: Key) {
28
+ let {id} = listMap.get(state);
29
+ if (!id) {
30
+ throw new Error('Unknown list');
31
+ }
32
+
33
+ return `${id}-${normalizeKey(key)}`;
34
+ }
35
+
36
+ export function normalizeKey(key: Key): string {
37
+ if (typeof key === 'string') {
38
+ return key.replace(/\s*/g, '');
39
+ }
40
+
41
+ return '' + key;
42
+ }