1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | import {FocusableElement} from '@react-types/shared';
|
14 | import {mergeProps, useSyncRef} from '@react-aria/utils';
|
15 | import {PressProps} from './usePress';
|
16 | import {PressResponderContext} from './context';
|
17 | import React, {ReactNode, RefObject, useContext, useEffect, useRef} from 'react';
|
18 |
|
19 | interface PressResponderProps extends PressProps {
|
20 | children: ReactNode
|
21 | }
|
22 |
|
23 | export const PressResponder = React.forwardRef(({children, ...props}: PressResponderProps, ref: RefObject<FocusableElement>) => {
|
24 | let isRegistered = useRef(false);
|
25 | let prevContext = useContext(PressResponderContext);
|
26 | let context = mergeProps(prevContext || {}, {
|
27 | ...props,
|
28 | ref: ref || prevContext?.ref,
|
29 | register() {
|
30 | isRegistered.current = true;
|
31 | if (prevContext) {
|
32 | prevContext.register();
|
33 | }
|
34 | }
|
35 | });
|
36 |
|
37 | useSyncRef(prevContext, ref);
|
38 |
|
39 | useEffect(() => {
|
40 | if (!isRegistered.current) {
|
41 | console.warn(
|
42 | 'A PressResponder was rendered without a pressable child. ' +
|
43 | 'Either call the usePress hook, or wrap your DOM node with <Pressable> component.'
|
44 | );
|
45 | }
|
46 | }, []);
|
47 |
|
48 | return (
|
49 | <PressResponderContext.Provider value={context}>
|
50 | {children}
|
51 | </PressResponderContext.Provider>
|
52 | );
|
53 | });
|