forked from microsoft/react-native-macos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPressable.js
More file actions
497 lines (438 loc) · 12.7 KB
/
Pressable.js
File metadata and controls
497 lines (438 loc) · 12.7 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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
*/
import type {ViewStyleProp} from '../../StyleSheet/StyleSheet';
import type {
GestureResponderEvent,
LayoutChangeEvent,
MouseEvent,
} from '../../Types/CoreEventTypes';
// [macOS
import type {
BlurEvent,
DragEvent,
FocusEvent,
HandledKeyEvent,
KeyEvent,
} from '../../Types/CoreEventTypes';
// macOS]
import type {DraggedTypesType} from '../View/DraggedType'; // [macOS]
import type {ViewProps} from '../View/ViewPropTypes';
import {PressabilityDebugView} from '../../Pressability/PressabilityDebug';
import usePressability from '../../Pressability/usePressability';
import {type RectOrSize} from '../../StyleSheet/Rect';
import useMergeRefs from '../../Utilities/useMergeRefs';
import View from '../View/View';
import useAndroidRippleForView, {
type PressableAndroidRippleConfig,
} from './useAndroidRippleForView';
import * as React from 'react';
import {memo, useMemo, useRef, useState} from 'react';
export type {PressableAndroidRippleConfig};
export type PressableStateCallbackType = $ReadOnly<{
pressed: boolean,
}>;
type PressableBaseProps = $ReadOnly<{
/**
* Whether a press gesture can be interrupted by a parent gesture such as a
* scroll event. Defaults to true.
*/
cancelable?: ?boolean,
/**
* Either children or a render prop that receives a boolean reflecting whether
* the component is currently pressed.
*/
children?: React.Node | ((state: PressableStateCallbackType) => React.Node),
/**
* Duration to wait after hover in before calling `onHoverIn`.
*/
delayHoverIn?: ?number,
/**
* Duration to wait after hover out before calling `onHoverOut`.
*/
delayHoverOut?: ?number,
/**
* Duration (in milliseconds) from `onPressIn` before `onLongPress` is called.
*/
delayLongPress?: ?number,
/**
* Whether the press behavior is disabled.
*/
disabled?: ?boolean,
/**
* Additional distance outside of this view in which a press is detected.
*/
hitSlop?: ?RectOrSize,
/**
* Additional distance outside of this view in which a touch is considered a
* press before `onPressOut` is triggered.
*/
pressRetentionOffset?: ?RectOrSize,
/**
* Called when this view's layout changes.
*/
onLayout?: ?(event: LayoutChangeEvent) => mixed,
/**
* Called when the hover is activated to provide visual feedback.
*/
onHoverIn?: ?(event: MouseEvent) => mixed,
/**
* Called when the hover is deactivated to undo visual feedback.
*/
onHoverOut?: ?(event: MouseEvent) => mixed,
/**
* Called when a long-tap gesture is detected.
*/
onLongPress?: ?(event: GestureResponderEvent) => mixed,
/**
* Called when a single tap gesture is detected.
*/
onPress?: ?(event: GestureResponderEvent) => mixed,
/**
* Called when a touch is engaged before `onPress`.
*/
onPressIn?: ?(event: GestureResponderEvent) => mixed,
/**
* Called when the press location moves.
*/
onPressMove?: ?(event: GestureResponderEvent) => mixed,
/**
* Called when a touch is released before `onPress`.
*/
onPressOut?: ?(event: GestureResponderEvent) => mixed,
// [macOS
/**
* Called after the element is focused.
*/
onFocus?: ?(event: FocusEvent) => void,
/**
* Called after the element loses focus.
*/
onBlur?: ?(event: BlurEvent) => void,
/**
* Called after a key down event is detected.
*/
onKeyDown?: ?(event: KeyEvent) => void,
/**
* Called after a key up event is detected.
*/
onKeyUp?: ?(event: KeyEvent) => void,
/**
* Array of keys to receive key down events for. These events have their default native behavior prevented.
*
* @platform macos
*/
keyDownEvents?: ?Array<HandledKeyEvent>,
/**
* Array of keys to receive key up events for. These events have their default native behavior prevented.
*
* @platform macos
*/
keyUpEvents?: ?Array<HandledKeyEvent>,
/**
* Specifies whether the view should receive the mouse down event when the
* containing window is in the background.
*
* @platform macos
*/
acceptsFirstMouse?: ?boolean,
/**
* Specifies whether clicking and dragging the view can move the window. This is useful
* to disable in Button like components like Pressable where mouse the user should still
* be able to click and drag off the view to cancel the click without accidentally moving the window.
*
* @platform macos
*/
mouseDownCanMoveWindow?: ?boolean,
/**
* Specifies whether system focus ring should be drawn when the view has keyboard focus.
*
* @platform macos
*/
enableFocusRing?: ?boolean,
/**
* Specifies whether the view ensures it is vibrant on top of other content.
* For more information, see the following apple documentation:
* https://developer.apple.com/documentation/appkit/nsview/1483793-allowsvibrancy
* https://developer.apple.com/documentation/appkit/nsvisualeffectview#1674177
*
* @platform macos
*/
allowsVibrancy?: ?boolean,
/**
* Specifies the Tooltip for the Pressable.
* @platform macos
*/
tooltip?: ?string,
/**
* Fired when a file is dragged into the Pressable via the mouse.
*
* @platform macos
*/
onDragEnter?: (event: DragEvent) => void,
/**
* Fired when a file is dragged out of the Pressable via the mouse.
*
* @platform macos
*/
onDragLeave?: (event: DragEvent) => void,
/**
* Fired when a file is dropped on the Pressable via the mouse.
*
* @platform macos
*/
onDrop?: (event: DragEvent) => void,
/**
* The types of dragged files that the Pressable will accept.
*
* Possible values for `draggedTypes` are:
*
* - `'fileUrl'`
*
* @platform macos
*/
draggedTypes?: ?DraggedTypesType,
// macOS]
/**
* Either view styles or a function that receives a boolean reflecting whether
* the component is currently pressed and returns view styles.
*/
style?:
| ViewStyleProp
| ((state: PressableStateCallbackType) => ViewStyleProp),
/**
* Identifier used to find this view in tests.
*/
testID?: ?string,
/**
* If true, doesn't play system sound on touch.
*/
android_disableSound?: ?boolean,
/**
* Enables the Android ripple effect and configures its color.
*/
android_ripple?: ?PressableAndroidRippleConfig,
/**
* Used only for documentation or testing (e.g. snapshot testing).
*/
testOnly_pressed?: ?boolean,
/**
* Duration to wait after press down before calling `onPressIn`.
*/
unstable_pressDelay?: ?number,
}>;
export type PressableProps = $ReadOnly<{
// Pressability may override `onMouseEnter` and `onMouseLeave` to
// implement `onHoverIn` and `onHoverOut` in a platform-agnostic way.
// Hover events should be used instead of mouse events.
...Omit<ViewProps, 'onMouseEnter' | 'onMouseLeave'>,
...PressableBaseProps,
}>;
type Instance = React.ElementRef<typeof View>;
/**
* Component used to build display components that should respond to whether the
* component is currently pressed or not.
*/
function Pressable({
ref: forwardedRef,
...props
}: {
ref?: React.RefSetter<Instance>,
...PressableProps,
}): React.Node {
const {
accessible,
accessibilityState,
'aria-live': ariaLive,
android_disableSound,
android_ripple,
'aria-busy': ariaBusy,
'aria-checked': ariaChecked,
'aria-disabled': ariaDisabled,
'aria-expanded': ariaExpanded,
'aria-label': ariaLabel,
'aria-selected': ariaSelected,
cancelable,
children,
delayHoverIn,
delayHoverOut,
delayLongPress,
disabled,
focusable,
hitSlop,
onBlur,
onFocus,
onHoverIn,
onHoverOut,
onLongPress,
onPress,
onPressIn,
onPressMove,
onPressOut,
// [macOS
onKeyDown,
onKeyUp,
keyDownEvents,
acceptsFirstMouse,
mouseDownCanMoveWindow,
enableFocusRing,
// macOS]
pressRetentionOffset,
style,
testOnly_pressed,
unstable_pressDelay,
...restProps
} = props;
const viewRef = useRef<Instance | null>(null);
const mergedRef = useMergeRefs(forwardedRef, viewRef);
const android_rippleConfig = useAndroidRippleForView(android_ripple, viewRef);
const [pressed, setPressed] = usePressState(testOnly_pressed === true);
const shouldUpdatePressed =
typeof children === 'function' || typeof style === 'function';
let _accessibilityState = {
busy: ariaBusy ?? accessibilityState?.busy,
checked: ariaChecked ?? accessibilityState?.checked,
disabled: ariaDisabled ?? accessibilityState?.disabled,
expanded: ariaExpanded ?? accessibilityState?.expanded,
selected: ariaSelected ?? accessibilityState?.selected,
};
_accessibilityState =
disabled != null ? {..._accessibilityState, disabled} : _accessibilityState;
const accessibilityValue = {
max: props['aria-valuemax'] ?? props.accessibilityValue?.max,
min: props['aria-valuemin'] ?? props.accessibilityValue?.min,
now: props['aria-valuenow'] ?? props.accessibilityValue?.now,
text: props['aria-valuetext'] ?? props.accessibilityValue?.text,
};
const accessibilityLiveRegion =
ariaLive === 'off' ? 'none' : ariaLive ?? props.accessibilityLiveRegion;
const accessibilityLabel = ariaLabel ?? props.accessibilityLabel;
const restPropsWithDefaults: React.ElementConfig<typeof View> = {
...restProps,
...android_rippleConfig?.viewProps,
accessible: accessible !== false,
accessibilityViewIsModal:
restProps['aria-modal'] ?? restProps.accessibilityViewIsModal,
accessibilityLiveRegion,
accessibilityLabel,
accessibilityState: _accessibilityState,
focusable: focusable !== false && !disabled, // macOS]
accessibilityValue,
hitSlop,
// [macOS
acceptsFirstMouse: acceptsFirstMouse !== false && !disabled,
enableFocusRing: enableFocusRing !== false && !disabled,
keyDownEvents:
keyDownEvents ??
// $FlowFixMe[unclear-type] Legacy props not in type definitions
(((props: any).validKeysDown: mixed) == null &&
// $FlowFixMe[unclear-type]
((props: any).passthroughAllKeyEvents: mixed) !== true
? [{key: ' '}, {key: 'Enter'}]
: undefined),
mouseDownCanMoveWindow: false,
// macOS]
};
const config = useMemo(
() => ({
cancelable,
disabled,
hitSlop,
pressRectOffset: pressRetentionOffset,
android_disableSound,
delayHoverIn,
delayHoverOut,
delayLongPress,
delayPressIn: unstable_pressDelay,
onBlur,
onFocus,
onHoverIn,
onHoverOut,
onLongPress,
onPress,
onPressIn(event: GestureResponderEvent): void {
if (android_rippleConfig != null) {
android_rippleConfig.onPressIn(event);
}
shouldUpdatePressed && setPressed(true);
if (onPressIn != null) {
onPressIn(event);
}
},
onPressMove(event: GestureResponderEvent): void {
android_rippleConfig?.onPressMove(event);
if (onPressMove != null) {
onPressMove(event);
}
},
onPressOut(event: GestureResponderEvent): void {
if (android_rippleConfig != null) {
android_rippleConfig.onPressOut(event);
}
shouldUpdatePressed && setPressed(false);
if (onPressOut != null) {
onPressOut(event);
}
},
// [macOS
onKeyDown,
onKeyUp,
// macOS]
}),
[
android_disableSound,
android_rippleConfig,
cancelable,
delayHoverIn,
delayHoverOut,
delayLongPress,
disabled,
hitSlop,
onBlur,
onFocus,
onHoverIn,
onHoverOut,
onLongPress,
onPress,
onPressIn,
onPressMove,
onPressOut,
// [macOS
onKeyDown,
onKeyUp,
// macOS]
pressRetentionOffset,
setPressed,
shouldUpdatePressed,
unstable_pressDelay,
],
);
const eventHandlers = usePressability(config);
return (
<View
{...restPropsWithDefaults}
{...eventHandlers}
ref={mergedRef}
style={typeof style === 'function' ? style({pressed}) : style}
collapsable={false}>
{typeof children === 'function' ? children({pressed}) : children}
{__DEV__ ? <PressabilityDebugView color="red" hitSlop={hitSlop} /> : null}
</View>
);
}
function usePressState(forcePressed: boolean): [boolean, (boolean) => void] {
const [pressed, setPressed] = useState(false);
return [pressed || forcePressed, setPressed];
}
const MemoedPressable = memo(Pressable);
MemoedPressable.displayName = 'Pressable';
export default (MemoedPressable: component(
ref?: React.RefSetter<React.ElementRef<typeof View>>,
...props: PressableProps
));