@hanzogui/react-native-use-pressable 2.0.0

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,590 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ *
8
+ * @format
9
+ */
10
+
11
+ const DELAY = 'DELAY'
12
+ const ERROR = 'ERROR'
13
+ const LONG_PRESS_DETECTED = 'LONG_PRESS_DETECTED'
14
+ const NOT_RESPONDER = 'NOT_RESPONDER'
15
+ const RESPONDER_ACTIVE_LONG_PRESS_START = 'RESPONDER_ACTIVE_LONG_PRESS_START'
16
+ const RESPONDER_ACTIVE_PRESS_START = 'RESPONDER_ACTIVE_PRESS_START'
17
+ const RESPONDER_INACTIVE_PRESS_START = 'RESPONDER_INACTIVE_PRESS_START'
18
+ const RESPONDER_GRANT = 'RESPONDER_GRANT'
19
+ const RESPONDER_RELEASE = 'RESPONDER_RELEASE'
20
+ const RESPONDER_TERMINATED = 'RESPONDER_TERMINATED'
21
+ const Transitions = Object.freeze({
22
+ NOT_RESPONDER: {
23
+ DELAY: ERROR,
24
+ RESPONDER_GRANT: RESPONDER_INACTIVE_PRESS_START,
25
+ RESPONDER_RELEASE: ERROR,
26
+ RESPONDER_TERMINATED: ERROR,
27
+ LONG_PRESS_DETECTED: ERROR,
28
+ },
29
+ RESPONDER_INACTIVE_PRESS_START: {
30
+ DELAY: RESPONDER_ACTIVE_PRESS_START,
31
+ RESPONDER_GRANT: ERROR,
32
+ RESPONDER_RELEASE: NOT_RESPONDER,
33
+ RESPONDER_TERMINATED: NOT_RESPONDER,
34
+ LONG_PRESS_DETECTED: ERROR,
35
+ },
36
+ RESPONDER_ACTIVE_PRESS_START: {
37
+ DELAY: ERROR,
38
+ RESPONDER_GRANT: ERROR,
39
+ RESPONDER_RELEASE: NOT_RESPONDER,
40
+ RESPONDER_TERMINATED: NOT_RESPONDER,
41
+ LONG_PRESS_DETECTED: RESPONDER_ACTIVE_LONG_PRESS_START,
42
+ },
43
+ RESPONDER_ACTIVE_LONG_PRESS_START: {
44
+ DELAY: ERROR,
45
+ RESPONDER_GRANT: ERROR,
46
+ RESPONDER_RELEASE: NOT_RESPONDER,
47
+ RESPONDER_TERMINATED: NOT_RESPONDER,
48
+ LONG_PRESS_DETECTED: RESPONDER_ACTIVE_LONG_PRESS_START,
49
+ },
50
+ ERROR: {
51
+ DELAY: NOT_RESPONDER,
52
+ RESPONDER_GRANT: RESPONDER_INACTIVE_PRESS_START,
53
+ RESPONDER_RELEASE: NOT_RESPONDER,
54
+ RESPONDER_TERMINATED: NOT_RESPONDER,
55
+ LONG_PRESS_DETECTED: NOT_RESPONDER,
56
+ },
57
+ })
58
+
59
+ const isActiveSignal = (signal) =>
60
+ signal === RESPONDER_ACTIVE_PRESS_START || signal === RESPONDER_ACTIVE_LONG_PRESS_START
61
+
62
+ const isButtonRole = (element) => element.getAttribute('role') === 'button'
63
+
64
+ const isPressStartSignal = (signal) =>
65
+ signal === RESPONDER_INACTIVE_PRESS_START ||
66
+ signal === RESPONDER_ACTIVE_PRESS_START ||
67
+ signal === RESPONDER_ACTIVE_LONG_PRESS_START
68
+
69
+ const isTerminalSignal = (signal) =>
70
+ signal === RESPONDER_TERMINATED || signal === RESPONDER_RELEASE
71
+
72
+ const isValidKeyPress = (event) => {
73
+ const key = event.key
74
+ const target = event.target
75
+ const role = target.getAttribute('role')
76
+ const isSpacebar = key === ' ' || key === 'Spacebar'
77
+ return key === 'Enter' || (isSpacebar && role === 'button')
78
+ }
79
+
80
+ const DEFAULT_LONG_PRESS_DELAY_MS = 450 // 500 - 50
81
+
82
+ const DEFAULT_PRESS_DELAY_MS = 50
83
+ /**
84
+ * =========================== PressResponder Tutorial ===========================
85
+ *
86
+ * The `PressResponder` class helps you create press interactions by analyzing the
87
+ * geometry of elements and observing when another responder (e.g. ScrollView)
88
+ * has stolen the touch lock. It offers hooks for your component to provide
89
+ * interaction feedback to the user:
90
+ *
91
+ * - When a press has activated (e.g. highlight an element)
92
+ * - When a press has deactivated (e.g. un-highlight an element)
93
+ * - When a press sould trigger an action, meaning it activated and deactivated
94
+ * while within the geometry of the element without the lock being stolen.
95
+ *
96
+ * A high quality interaction isn't as simple as you might think. There should
97
+ * be a slight delay before activation. Moving your finger beyond an element's
98
+ * bounds should trigger deactivation, but moving the same finger back within an
99
+ * element's bounds should trigger reactivation.
100
+ *
101
+ * In order to use `PressResponder`, do the following:
102
+ *
103
+ * const pressResponder = new PressResponder(config);
104
+ *
105
+ * 2. Choose the rendered component who should collect the press events. On that
106
+ * element, spread `pressability.getEventHandlers()` into its props.
107
+ *
108
+ * return (
109
+ * <View {...this.state.pressResponder.getEventHandlers()} />
110
+ * );
111
+ *
112
+ * 3. Reset `PressResponder` when your component unmounts.
113
+ *
114
+ * componentWillUnmount() {
115
+ * this.state.pressResponder.reset();
116
+ * }
117
+ *
118
+ * ==================== Implementation Details ====================
119
+ *
120
+ * `PressResponder` only assumes that there exists a `HitRect` node. The `PressRect`
121
+ * is an abstract box that is extended beyond the `HitRect`.
122
+ *
123
+ * # Geometry
124
+ *
125
+ * ┌────────────────────────┐
126
+ * │ ┌──────────────────┐ │ - Presses start anywhere within `HitRect`.
127
+ * │ │ ┌────────────┐ │ │
128
+ * │ │ │ VisualRect │ │ │
129
+ * │ │ └────────────┘ │ │ - When pressed down for sufficient amount of time
130
+ * │ │ HitRect │ │ before letting up, `VisualRect` activates.
131
+ * │ └──────────────────┘ │
132
+ * │ Out Region o │
133
+ * └────────────────────│───┘
134
+ * └────── When the press is released outside the `HitRect`,
135
+ * the responder is NOT eligible for a "press".
136
+ *
137
+ * # State Machine
138
+ *
139
+ * ┌───────────────┐ ◀──── RESPONDER_RELEASE
140
+ * │ NOT_RESPONDER │
141
+ * └───┬───────────┘ ◀──── RESPONDER_TERMINATED
142
+ * │
143
+ * │ RESPONDER_GRANT (HitRect)
144
+ * │
145
+ * ▼
146
+ * ┌─────────────────────┐ ┌───────────────────┐ ┌───────────────────┐
147
+ * │ RESPONDER_INACTIVE_ │ DELAY │ RESPONDER_ACTIVE_ │ T + DELAY │ RESPONDER_ACTIVE_ │
148
+ * │ PRESS_START ├────────▶ │ PRESS_START ├────────────▶ │ LONG_PRESS_START │
149
+ * └─────────────────────┘ └───────────────────┘ └───────────────────┘
150
+ *
151
+ * T + DELAY => LONG_PRESS_DELAY + DELAY
152
+ *
153
+ * Not drawn are the side effects of each transition. The most important side
154
+ * effect is the invocation of `onLongPress`. Only when the browser produces a
155
+ * `click` event is `onPress` invoked.
156
+ */
157
+
158
+ export class PressResponder {
159
+ _touchActivatePosition = null as any
160
+ _pressDelayTimeout = 0 as any
161
+ _selectionTerminated = false
162
+ _isPointerTouch = false
163
+ _longPressDelayTimeout = 0 as any
164
+ _longPressDispatched = false
165
+ _pressOutDelayTimeout = 0 as any
166
+ _touchState = NOT_RESPONDER
167
+ _config = null as any
168
+ _eventHandlers = null as any
169
+
170
+ constructor(config) {
171
+ this.configure(config)
172
+ }
173
+
174
+ configure(config) {
175
+ this._config = config
176
+ }
177
+ /**
178
+ * Resets any pending timers. This should be called on unmount.
179
+ */
180
+
181
+ reset() {
182
+ this._cancelLongPressDelayTimeout()
183
+
184
+ this._cancelPressDelayTimeout()
185
+
186
+ this._cancelPressOutDelayTimeout()
187
+ }
188
+ /**
189
+ * Returns a set of props to spread into the interactive element.
190
+ */
191
+
192
+ getEventHandlers() {
193
+ if (this._eventHandlers == null) {
194
+ this._eventHandlers = this._createEventHandlers()
195
+ }
196
+
197
+ return this._eventHandlers
198
+ }
199
+
200
+ _createEventHandlers() {
201
+ const start = (event, shouldDelay?: boolean) => {
202
+ event.persist()
203
+
204
+ this._cancelPressOutDelayTimeout()
205
+
206
+ this._longPressDispatched = false
207
+ this._selectionTerminated = false
208
+ this._touchState = NOT_RESPONDER
209
+ this._isPointerTouch = event.nativeEvent.type === 'touchstart'
210
+
211
+ this._receiveSignal(RESPONDER_GRANT, event)
212
+
213
+ const delayPressStart = normalizeDelay(
214
+ this._config.delayPressStart,
215
+ 0,
216
+ DEFAULT_PRESS_DELAY_MS
217
+ )
218
+
219
+ if (shouldDelay !== false && delayPressStart > 0) {
220
+ this._pressDelayTimeout = setTimeout(() => {
221
+ this._receiveSignal(DELAY, event)
222
+ }, delayPressStart)
223
+ } else {
224
+ this._receiveSignal(DELAY, event)
225
+ }
226
+
227
+ const delayLongPress = normalizeDelay(
228
+ this._config.delayLongPress,
229
+ 10,
230
+ DEFAULT_LONG_PRESS_DELAY_MS
231
+ )
232
+ this._longPressDelayTimeout = setTimeout(() => {
233
+ this._handleLongPress(event)
234
+ }, delayLongPress + delayPressStart)
235
+ }
236
+
237
+ const end = (event) => {
238
+ this._receiveSignal(RESPONDER_RELEASE, event)
239
+ }
240
+
241
+ const keyupHandler = (event) => {
242
+ const onPress = this._config.onPress
243
+ const target = event.target
244
+
245
+ if (this._touchState !== NOT_RESPONDER && isValidKeyPress(event)) {
246
+ end(event)
247
+ document.removeEventListener('keyup', keyupHandler)
248
+ const role = target.getAttribute('role')
249
+ const elementType = target.tagName.toLowerCase()
250
+ const isNativeInteractiveElement =
251
+ role === 'link' ||
252
+ elementType === 'a' ||
253
+ elementType === 'button' ||
254
+ elementType === 'input' ||
255
+ elementType === 'select' ||
256
+ elementType === 'textarea'
257
+
258
+ if (onPress != null && !isNativeInteractiveElement) {
259
+ onPress(event)
260
+ }
261
+ }
262
+ }
263
+
264
+ return {
265
+ onStartShouldSetResponder: (event) => {
266
+ const disabled = this._config.disabled
267
+
268
+ if (disabled && isButtonRole(event.currentTarget)) {
269
+ event.stopPropagation()
270
+ }
271
+
272
+ if (disabled == null) {
273
+ return true
274
+ }
275
+
276
+ return !disabled
277
+ },
278
+ onKeyDown: (event) => {
279
+ const disabled = this._config.disabled
280
+ const key = event.key
281
+ const target = event.target
282
+
283
+ if (!disabled && isValidKeyPress(event)) {
284
+ if (this._touchState === NOT_RESPONDER) {
285
+ start(event, false) // Listen to 'keyup' on document to account for situations where
286
+ // focus is moved to another element during 'keydown'.
287
+
288
+ document.addEventListener('keyup', keyupHandler)
289
+ }
290
+
291
+ const role = target.getAttribute('role')
292
+ const isSpacebarKey = key === ' ' || key === 'Spacebar'
293
+
294
+ const _isButtonRole = role === 'button' || role === 'menuitem'
295
+
296
+ if (isSpacebarKey && _isButtonRole) {
297
+ // Prevent spacebar scrolling the window
298
+ event.preventDefault()
299
+ }
300
+
301
+ event.stopPropagation()
302
+ }
303
+ },
304
+ onResponderGrant: (event) => start(event),
305
+ onResponderMove: (event) => {
306
+ if (this._config.onPressMove != null) {
307
+ this._config.onPressMove(event)
308
+ }
309
+
310
+ const touch = getTouchFromResponderEvent(event)
311
+
312
+ if (this._touchActivatePosition != null) {
313
+ const deltaX = this._touchActivatePosition.pageX - touch.pageX
314
+ const deltaY = this._touchActivatePosition.pageY - touch.pageY
315
+
316
+ if (Math.hypot(deltaX, deltaY) > 10) {
317
+ this._cancelLongPressDelayTimeout()
318
+ }
319
+ }
320
+ },
321
+ onResponderRelease: (event) => end(event),
322
+ onResponderTerminate: (event) => {
323
+ if (event.nativeEvent.type === 'selectionchange') {
324
+ this._selectionTerminated = true
325
+ }
326
+
327
+ this._receiveSignal(RESPONDER_TERMINATED, event)
328
+ },
329
+ onResponderTerminationRequest: (event) => {
330
+ const _this$_config = this._config
331
+ const cancelable = _this$_config.cancelable
332
+ const disabled = _this$_config.disabled
333
+ const onLongPress = _this$_config.onLongPress // If `onLongPress` is provided, don't terminate on `contextmenu` as default
334
+ // behavior will be prevented for non-mouse pointers.
335
+
336
+ if (
337
+ !disabled &&
338
+ onLongPress != null &&
339
+ this._isPointerTouch &&
340
+ event.nativeEvent.type === 'contextmenu'
341
+ ) {
342
+ return false
343
+ }
344
+
345
+ if (cancelable == null) {
346
+ return true
347
+ }
348
+
349
+ return cancelable
350
+ },
351
+ // NOTE: this diverges from react-native in 3 significant ways:
352
+ // * The `onPress` callback is not connected to the responder system (the native
353
+ // `click` event must be used but is dispatched in many scenarios where no pointers
354
+ // are on the screen.) Therefore, it's possible for `onPress` to be called without
355
+ // `onPress{Start,End}` being called first.
356
+ // * The `onPress` callback is only be called on the first ancestor of the native
357
+ // `click` target that is using the PressResponder.
358
+ // * The event's `nativeEvent` is a `MouseEvent` not a `TouchEvent`.
359
+ onClick: (event) => {
360
+ const _this$_config2 = this._config
361
+ const disabled = _this$_config2.disabled
362
+ const onPress = _this$_config2.onPress
363
+
364
+ if (!disabled) {
365
+ // If long press dispatched, cancel default click behavior.
366
+ // If the responder terminated because text was selected during the gesture,
367
+ // cancel the default click behavior.
368
+ event.stopPropagation()
369
+
370
+ if (this._longPressDispatched || this._selectionTerminated) {
371
+ event.preventDefault()
372
+ } else if (onPress != null && event.altKey === false) {
373
+ onPress(event)
374
+ }
375
+ } else {
376
+ if (isButtonRole(event.currentTarget)) {
377
+ event.stopPropagation()
378
+ }
379
+ }
380
+ },
381
+ // If `onLongPress` is provided and a touch pointer is being used, prevent the
382
+ // default context menu from opening.
383
+ onContextMenu: (event) => {
384
+ const _this$_config3 = this._config
385
+ const disabled = _this$_config3.disabled
386
+ const onLongPress = _this$_config3.onLongPress
387
+
388
+ if (!disabled) {
389
+ if (onLongPress != null && this._isPointerTouch && !event.defaultPrevented) {
390
+ event.preventDefault()
391
+ event.stopPropagation()
392
+ }
393
+ } else {
394
+ if (isButtonRole(event.currentTarget)) {
395
+ event.stopPropagation()
396
+ }
397
+ }
398
+ },
399
+ }
400
+ }
401
+ /**
402
+ * Receives a state machine signal, performs side effects of the transition
403
+ * and stores the new state. Validates the transition as well.
404
+ */
405
+
406
+ _receiveSignal(signal, event) {
407
+ const prevState = this._touchState
408
+ let nextState = null
409
+
410
+ if (Transitions[prevState] != null) {
411
+ nextState = Transitions[prevState][signal]
412
+ }
413
+
414
+ if (this._touchState === NOT_RESPONDER && signal === RESPONDER_RELEASE) {
415
+ return
416
+ }
417
+
418
+ if (nextState == null || nextState === ERROR) {
419
+ console.error(
420
+ `PressResponder: Invalid signal ${signal} for state ${prevState} on responder`
421
+ )
422
+ } else if (prevState !== nextState) {
423
+ this._performTransitionSideEffects(prevState, nextState, signal, event)
424
+
425
+ this._touchState = nextState
426
+ }
427
+ }
428
+ /**
429
+ * Performs a transition between touchable states and identify any activations
430
+ * or deactivations (and callback invocations).
431
+ */
432
+
433
+ _performTransitionSideEffects(prevState, nextState, signal, event) {
434
+ if (isTerminalSignal(signal)) {
435
+ // Pressable suppression of contextmenu on windows.
436
+ // On Windows, the contextmenu is displayed after pointerup.
437
+ // https://github.com/necolas/react-native-web/issues/2296
438
+ setTimeout(() => {
439
+ this._isPointerTouch = false
440
+ }, 0)
441
+ this._touchActivatePosition = null
442
+
443
+ this._cancelLongPressDelayTimeout()
444
+ }
445
+
446
+ if (isPressStartSignal(prevState) && signal === LONG_PRESS_DETECTED) {
447
+ const onLongPress = this._config.onLongPress // Long press is not supported for keyboards because 'click' can be dispatched
448
+ // immediately (and multiple times) after 'keydown'.
449
+
450
+ if (onLongPress != null && event.nativeEvent.key == null) {
451
+ onLongPress(event)
452
+ this._longPressDispatched = true
453
+ }
454
+ }
455
+
456
+ const isPrevActive = isActiveSignal(prevState)
457
+ const isNextActive = isActiveSignal(nextState)
458
+
459
+ if (!isPrevActive && isNextActive) {
460
+ this._activate(event)
461
+ } else if (isPrevActive && !isNextActive) {
462
+ this._deactivate(event)
463
+ }
464
+
465
+ if (isPressStartSignal(prevState) && signal === RESPONDER_RELEASE) {
466
+ const _this$_config4 = this._config
467
+ const _onLongPress = _this$_config4.onLongPress
468
+ const onPress = _this$_config4.onPress
469
+
470
+ if (onPress != null) {
471
+ const isPressCanceledByLongPress =
472
+ _onLongPress != null && prevState === RESPONDER_ACTIVE_LONG_PRESS_START
473
+
474
+ if (!isPressCanceledByLongPress) {
475
+ // If we never activated (due to delays), activate and deactivate now.
476
+ if (!(isNextActive || isPrevActive)) {
477
+ this._activate(event)
478
+
479
+ this._deactivate(event)
480
+ }
481
+ }
482
+ }
483
+ }
484
+
485
+ this._cancelPressDelayTimeout()
486
+ }
487
+
488
+ _activate(event) {
489
+ const _this$_config5 = this._config
490
+ const onPressChange = _this$_config5.onPressChange
491
+ const onPressStart = _this$_config5.onPressStart
492
+ const touch = getTouchFromResponderEvent(event)
493
+ this._touchActivatePosition = {
494
+ pageX: touch.pageX,
495
+ pageY: touch.pageY,
496
+ }
497
+
498
+ if (onPressStart != null) {
499
+ onPressStart(event)
500
+ }
501
+
502
+ if (onPressChange != null) {
503
+ onPressChange(true)
504
+ }
505
+ }
506
+
507
+ _deactivate(event) {
508
+ const _this$_config6 = this._config
509
+ const onPressChange = _this$_config6.onPressChange
510
+ const onPressEnd = _this$_config6.onPressEnd
511
+
512
+ function end() {
513
+ if (onPressEnd != null) {
514
+ onPressEnd(event)
515
+ }
516
+
517
+ if (onPressChange != null) {
518
+ onPressChange(false)
519
+ }
520
+ }
521
+
522
+ const delayPressEnd = normalizeDelay(this._config.delayPressEnd)
523
+
524
+ if (delayPressEnd > 0) {
525
+ this._pressOutDelayTimeout = setTimeout(() => {
526
+ end()
527
+ }, delayPressEnd)
528
+ } else {
529
+ end()
530
+ }
531
+ }
532
+
533
+ _handleLongPress(event) {
534
+ if (
535
+ this._touchState === RESPONDER_ACTIVE_PRESS_START ||
536
+ this._touchState === RESPONDER_ACTIVE_LONG_PRESS_START
537
+ ) {
538
+ this._receiveSignal(LONG_PRESS_DETECTED, event)
539
+ }
540
+ }
541
+
542
+ _cancelLongPressDelayTimeout() {
543
+ if (this._longPressDelayTimeout != null) {
544
+ clearTimeout(this._longPressDelayTimeout)
545
+ this._longPressDelayTimeout = null
546
+ }
547
+ }
548
+
549
+ _cancelPressDelayTimeout() {
550
+ if (this._pressDelayTimeout != null) {
551
+ clearTimeout(this._pressDelayTimeout)
552
+ this._pressDelayTimeout = null
553
+ }
554
+ }
555
+
556
+ _cancelPressOutDelayTimeout() {
557
+ if (this._pressOutDelayTimeout != null) {
558
+ clearTimeout(this._pressOutDelayTimeout)
559
+ this._pressOutDelayTimeout = null
560
+ }
561
+ }
562
+ }
563
+
564
+ function normalizeDelay(delay, min?: number, fallback?: any) {
565
+ if (min === void 0) {
566
+ min = 0
567
+ }
568
+
569
+ if (fallback === void 0) {
570
+ fallback = 0
571
+ }
572
+
573
+ return Math.max(min, delay !== null && delay !== void 0 ? delay : fallback)
574
+ }
575
+
576
+ function getTouchFromResponderEvent(event) {
577
+ const _event$nativeEvent = event.nativeEvent
578
+ const changedTouches = _event$nativeEvent.changedTouches
579
+ const touches = _event$nativeEvent.touches
580
+
581
+ if (touches != null && touches.length > 0) {
582
+ return touches[0]
583
+ }
584
+
585
+ if (changedTouches != null && changedTouches.length > 0) {
586
+ return changedTouches[0]
587
+ }
588
+
589
+ return event.nativeEvent
590
+ }
package/src/index.ts ADDED
@@ -0,0 +1,39 @@
1
+ import React from 'react'
2
+
3
+ /**
4
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ *
10
+ * @format
11
+ */
12
+
13
+ import { PressResponder } from './PressResponder'
14
+
15
+ // todo
16
+ export type PressResponderConfig = any
17
+
18
+ export function usePressEvents(_, config?: any) {
19
+ const pressResponderRef = React.useRef<any>(null)
20
+
21
+ if (pressResponderRef.current == null) {
22
+ pressResponderRef.current = new PressResponder(config)
23
+ }
24
+
25
+ const pressResponder = pressResponderRef.current // Re-configure to use the current node and configuration.
26
+
27
+ React.useEffect(() => {
28
+ pressResponder.configure(config)
29
+ }, [config, pressResponder]) // Reset the `pressResponder` when cleanup needs to occur. This is
30
+ // a separate effect because we do not want to rest the responder when `config` changes.
31
+
32
+ React.useEffect(() => {
33
+ return () => {
34
+ pressResponder.reset()
35
+ }
36
+ }, [pressResponder])
37
+ React.useDebugValue(config)
38
+ return pressResponder.getEventHandlers()
39
+ }