-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathuseSelectableItem.ts
More file actions
418 lines (388 loc) · 15.8 KB
/
useSelectableItem.ts
File metadata and controls
418 lines (388 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {chain, isCtrlKeyPressed, mergeProps, openLink, useId, useRouter} from '@react-aria/utils';
import {DOMAttributes, DOMProps, FocusableElement, Key, LongPressEvent, PointerType, PressEvent, RefObject} from '@react-types/shared';
import {focusSafely, PressHookProps, useLongPress, usePress} from '@react-aria/interactions';
import {getCollectionId, isNonContiguousSelectionModifier} from './utils';
import {moveVirtualFocus} from '@react-aria/focus';
import {MultipleSelectionManager} from '@react-stately/selection';
import {useEffect, useRef} from 'react';
export interface SelectableItemOptions extends DOMProps {
/**
* An interface for reading and updating multiple selection state.
*/
selectionManager: MultipleSelectionManager,
/**
* A unique key for the item.
*/
key: Key,
/**
* Ref to the item.
*/
ref: RefObject<FocusableElement | null>,
/**
* By default, selection occurs on pointer down. This can be strange if selecting an
* item causes the UI to disappear immediately (e.g. menus).
*/
shouldSelectOnPressUp?: boolean,
/**
* Whether selection requires the pointer/mouse down and up events to occur on the same target or triggers selection on
* the target of the pointer/mouse up event.
*/
allowsDifferentPressOrigin?: boolean,
/**
* Whether the option is contained in a virtual scroller.
*/
isVirtualized?: boolean,
/**
* Function to focus the item.
*/
focus?: () => void,
/**
* Whether the option should use virtual focus instead of being focused directly.
*/
shouldUseVirtualFocus?: boolean,
/** Whether the item is disabled. */
isDisabled?: boolean,
/**
* Handler that is called when a user performs an action on the item. The exact user event depends on
* the collection's `selectionBehavior` prop and the interaction modality.
*/
onAction?: () => void,
/**
* The behavior of links in the collection.
* - 'action': link behaves like onAction.
* - 'selection': link follows selection interactions (e.g. if URL drives selection).
* - 'override': links override all other interactions (link items are not selectable).
* - 'none': links are disabled for both selection and actions (e.g. handled elsewhere).
* @default 'action'
*/
linkBehavior?: 'action' | 'selection' | 'override' | 'none'
}
export interface SelectableItemStates {
/** Whether the item is currently in a pressed state. */
isPressed: boolean,
/** Whether the item is currently selected. */
isSelected: boolean,
/** Whether the item is currently focused. */
isFocused: boolean,
/**
* Whether the item is non-interactive, i.e. both selection and actions are disabled and the item may
* not be focused. Dependent on `disabledKeys` and `disabledBehavior`.
*/
isDisabled: boolean,
/**
* Whether the item may be selected, dependent on `selectionMode`, `disabledKeys`, and `disabledBehavior`.
*/
allowsSelection: boolean,
/**
* Whether the item has an action, dependent on `onAction`, `disabledKeys`,
* and `disabledBehavior`. It may also change depending on the current selection state
* of the list (e.g. when selection is primary). This can be used to enable or disable hover
* styles or other visual indications of interactivity.
*/
hasAction: boolean
}
export interface SelectableItemAria extends SelectableItemStates {
/**
* Props to be spread on the item root node.
*/
itemProps: DOMAttributes
}
/**
* Handles interactions with an item in a selectable collection.
*/
export function useSelectableItem(options: SelectableItemOptions): SelectableItemAria {
let {
id,
selectionManager: manager,
key,
ref,
shouldSelectOnPressUp,
shouldUseVirtualFocus,
focus,
isDisabled,
onAction,
allowsDifferentPressOrigin,
linkBehavior = 'action'
} = options;
let router = useRouter();
id = useId(id);
let onSelect = (e: PressEvent | LongPressEvent | PointerEvent) => {
if (e.pointerType === 'keyboard' && isNonContiguousSelectionModifier(e)) {
manager.toggleSelection(key);
} else {
if (manager.selectionMode === 'none') {
return;
}
if (manager.isLink(key)) {
if (linkBehavior === 'selection' && ref.current) {
let itemProps = manager.getItemProps(key);
router.open(ref.current, e, itemProps.href, itemProps.routerOptions);
// Always set selected keys back to what they were so that select and combobox close.
manager.setSelectedKeys(manager.selectedKeys);
return;
} else if (linkBehavior === 'override' || linkBehavior === 'none') {
return;
}
}
if (manager.selectionMode === 'single') {
if (manager.isSelected(key) && !manager.disallowEmptySelection) {
manager.toggleSelection(key);
} else {
manager.replaceSelection(key);
}
} else if (e && e.shiftKey) {
manager.extendSelection(key);
} else if (manager.selectionBehavior === 'toggle' || (e && (isCtrlKeyPressed(e) || e.pointerType === 'touch' || e.pointerType === 'virtual'))) {
// if touch or virtual (VO) then we just want to toggle, otherwise it's impossible to multi select because they don't have modifier keys
manager.toggleSelection(key);
} else {
manager.replaceSelection(key);
}
}
};
// Focus the associated DOM node when this item becomes the focusedKey
// TODO: can't make this useLayoutEffect bacause it breaks menus inside dialogs
// However, if this is a useEffect, it runs twice and dispatches two blur events and immediately sets
// aria-activeDescendant in useAutocomplete... I've worked around this for now
useEffect(() => {
let isFocused = key === manager.focusedKey;
if (isFocused && manager.isFocused) {
if (!shouldUseVirtualFocus) {
if (focus) {
focus();
} else if (document.activeElement !== ref.current && ref.current) {
focusSafely(ref.current);
}
} else {
moveVirtualFocus(ref.current);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ref, key, manager.focusedKey, manager.childFocusStrategy, manager.isFocused, shouldUseVirtualFocus]);
isDisabled = isDisabled || manager.isDisabled(key);
// Set tabIndex to 0 if the element is focused, or -1 otherwise so that only the last focused
// item is tabbable. If using virtual focus, don't set a tabIndex at all so that VoiceOver
// on iOS 14 doesn't try to move real DOM focus to the item anyway.
let itemProps: SelectableItemAria['itemProps'] = {};
if (!shouldUseVirtualFocus && !isDisabled) {
itemProps = {
tabIndex: key === manager.focusedKey ? 0 : -1,
onFocus(e) {
if (e.target === ref.current) {
manager.setFocusedKey(key);
}
}
};
} else if (isDisabled) {
itemProps.onMouseDown = (e) => {
// Prevent focus going to the body when clicking on a disabled item.
e.preventDefault();
};
}
// With checkbox selection, onAction (i.e. navigation) becomes primary, and occurs on a single click of the row.
// Clicking the checkbox enters selection mode, after which clicking anywhere on any row toggles selection for that row.
// With highlight selection, onAction is secondary, and occurs on double click. Single click selects the row.
// With touch, onAction occurs on single tap, and long press enters selection mode.
let isLinkOverride = manager.isLink(key) && linkBehavior === 'override';
let isActionOverride = onAction && options['UNSTABLE_itemBehavior'] === 'action';
let hasLinkAction = manager.isLink(key) && linkBehavior !== 'selection' && linkBehavior !== 'none';
let allowsSelection = !isDisabled && manager.canSelectItem(key) && !isLinkOverride && !isActionOverride;
let allowsActions = (onAction || hasLinkAction) && !isDisabled;
let hasPrimaryAction = allowsActions && (
manager.selectionBehavior === 'replace'
? !allowsSelection
: !allowsSelection || manager.isEmpty
);
let hasSecondaryAction = allowsActions && allowsSelection && manager.selectionBehavior === 'replace';
let hasAction = hasPrimaryAction || hasSecondaryAction;
let modality = useRef<PointerType | null>(null);
let longPressEnabled = hasAction && allowsSelection;
let longPressEnabledOnPressStart = useRef(false);
let hadPrimaryActionOnPressStart = useRef(false);
let collectionItemProps = manager.getItemProps(key);
let performAction = (e) => {
if (onAction) {
onAction();
ref.current?.dispatchEvent(new CustomEvent('react-aria-item-action', {bubbles: true}));
}
if (hasLinkAction && ref.current) {
router.open(ref.current, e, collectionItemProps.href, collectionItemProps.routerOptions);
}
};
// By default, selection occurs on pointer down. This can be strange if selecting an
// item causes the UI to disappear immediately (e.g. menus).
// If shouldSelectOnPressUp is true, we use onPressUp instead of onPressStart.
// onPress requires a pointer down event on the same element as pointer up. For menus,
// we want to be able to have the pointer down on the trigger that opens the menu and
// the pointer up on the menu item rather than requiring a separate press.
// For keyboard events, selection still occurs on key down.
let itemPressProps: PressHookProps = {ref};
if (shouldSelectOnPressUp) {
itemPressProps.onPressStart = (e) => {
modality.current = e.pointerType;
longPressEnabledOnPressStart.current = longPressEnabled;
if (e.pointerType === 'keyboard' && (!hasAction || isSelectionKey())) {
onSelect(e);
}
};
// If allowsDifferentPressOrigin and interacting with mouse, make selection happen on pressUp (e.g. open menu on press down, selection on menu item happens on press up.)
// Otherwise, have selection happen onPress (prevents listview row selection when clicking on interactable elements in the row)
if (!allowsDifferentPressOrigin) {
itemPressProps.onPress = (e) => {
if (hasPrimaryAction || (hasSecondaryAction && e.pointerType !== 'mouse')) {
if (e.pointerType === 'keyboard' && !isActionKey()) {
return;
}
performAction(e);
} else if (e.pointerType !== 'keyboard' && allowsSelection) {
onSelect(e);
}
};
} else {
itemPressProps.onPressUp = hasPrimaryAction ? undefined : (e) => {
if (e.pointerType === 'mouse' && allowsSelection) {
onSelect(e);
}
};
itemPressProps.onPress = hasPrimaryAction ? performAction : (e) => {
if (e.pointerType !== 'keyboard' && e.pointerType !== 'mouse' && allowsSelection) {
onSelect(e);
}
};
}
} else {
itemPressProps.onPressStart = (e) => {
modality.current = e.pointerType;
longPressEnabledOnPressStart.current = longPressEnabled;
hadPrimaryActionOnPressStart.current = hasPrimaryAction;
// Select on mouse down unless there is a primary action which will occur on mouse up.
// For keyboard, select on key down. If there is an action, the Space key selects on key down,
// and the Enter key performs onAction on key up.
if (
allowsSelection && (
(e.pointerType === 'mouse' && !hasPrimaryAction) ||
(e.pointerType === 'keyboard' && (!allowsActions || isSelectionKey()))
)
) {
onSelect(e);
}
};
itemPressProps.onPress = (e) => {
// Selection occurs on touch up. Primary actions always occur on pointer up.
// Both primary and secondary actions occur on Enter key up. The only exception
// is secondary actions, which occur on double click with a mouse.
if (
e.pointerType === 'touch' ||
e.pointerType === 'pen' ||
e.pointerType === 'virtual' ||
(e.pointerType === 'keyboard' && hasAction && isActionKey()) ||
(e.pointerType === 'mouse' && hadPrimaryActionOnPressStart.current)
) {
if (hasAction) {
performAction(e);
} else if (allowsSelection) {
onSelect(e);
}
}
};
}
itemProps['data-collection'] = getCollectionId(manager.collection);
itemProps['data-key'] = key;
itemPressProps.preventFocusOnPress = shouldUseVirtualFocus;
// When using virtual focus, make sure the focused key gets updated on press.
if (shouldUseVirtualFocus) {
itemPressProps = mergeProps(itemPressProps, {
onPressStart(e) {
if (e.pointerType !== 'touch') {
manager.setFocused(true);
manager.setFocusedKey(key);
}
},
onPress(e) {
if (e.pointerType === 'touch') {
manager.setFocused(true);
manager.setFocusedKey(key);
}
}
});
}
if (collectionItemProps) {
for (let key of ['onPressStart', 'onPressEnd', 'onPressChange', 'onPress', 'onPressUp', 'onClick']) {
if (collectionItemProps[key]) {
itemPressProps[key] = chain(itemPressProps[key], collectionItemProps[key]);
}
}
}
let {pressProps, isPressed} = usePress(itemPressProps);
// Double clicking with a mouse with selectionBehavior = 'replace' performs an action.
let onDoubleClick = hasSecondaryAction ? (e) => {
if (modality.current === 'mouse') {
e.stopPropagation();
e.preventDefault();
performAction(e);
}
} : undefined;
// Long pressing an item with touch when selectionBehavior = 'replace' switches the selection behavior
// to 'toggle'. This changes the single tap behavior from performing an action (i.e. navigating) to
// selecting, and may toggle the appearance of a UI affordance like checkboxes on each item.
let {longPressProps} = useLongPress({
isDisabled: !longPressEnabled,
onLongPress(e) {
if (e.pointerType === 'touch') {
onSelect(e);
manager.setSelectionBehavior('toggle');
}
}
});
// Prevent native drag and drop on long press if we also select on long press.
// Once the user is in selection mode, they can long press again to drag.
// Use a capturing listener to ensure this runs before useDrag, regardless of
// the order the props get merged.
let onDragStartCapture = e => {
if (modality.current === 'touch' && longPressEnabledOnPressStart.current) {
e.preventDefault();
}
};
// Prevent default on link clicks so that we control exactly
// when they open (to match selection behavior).
let onClick = linkBehavior !== 'none' && manager.isLink(key) ? e => {
if (!(openLink as any).isOpening) {
e.preventDefault();
}
} : undefined;
return {
itemProps: mergeProps(
itemProps,
allowsSelection || hasPrimaryAction || (shouldUseVirtualFocus && !isDisabled) ? pressProps : {},
longPressEnabled ? longPressProps : {},
{onDoubleClick, onDragStartCapture, onClick, id},
// Prevent DOM focus from moving on mouse down when using virtual focus
shouldUseVirtualFocus ? {onMouseDown: e => e.preventDefault()} : undefined
),
isPressed,
isSelected: manager.isSelected(key),
isFocused: manager.isFocused && manager.focusedKey === key,
isDisabled,
allowsSelection,
hasAction
};
}
function isActionKey() {
let event = window.event as KeyboardEvent;
return event?.key === 'Enter';
}
function isSelectionKey() {
let event = window.event as KeyboardEvent;
return event?.key === ' ' || event?.code === 'Space';
}