UNPKG

2.23 kBTypeScriptView Raw
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
13import {FocusableElement} from '@react-types/shared';
14import {mergeProps, useObjectRef, useSyncRef} from '@react-aria/utils';
15import {PressProps} from './usePress';
16import {PressResponderContext} from './context';
17import React, {ForwardedRef, ReactNode, useContext, useEffect, useMemo, useRef} from 'react';
18
19interface PressResponderProps extends PressProps {
20 children: ReactNode
21}
22
23export const PressResponder = React.forwardRef(({children, ...props}: PressResponderProps, ref: ForwardedRef<FocusableElement>) => {
24 let isRegistered = useRef(false);
25 let prevContext = useContext(PressResponderContext);
26 ref = useObjectRef(ref || prevContext?.ref);
27 let context = mergeProps(prevContext || {}, {
28 ...props,
29 ref,
30 register() {
31 isRegistered.current = true;
32 if (prevContext) {
33 prevContext.register();
34 }
35 }
36 });
37
38 useSyncRef(prevContext, ref);
39
40 useEffect(() => {
41 if (!isRegistered.current) {
42 console.warn(
43 'A PressResponder was rendered without a pressable child. ' +
44 'Either call the usePress hook, or wrap your DOM node with <Pressable> component.'
45 );
46 isRegistered.current = true; // only warn once in strict mode.
47 }
48 }, []);
49
50 return (
51 <PressResponderContext.Provider value={context}>
52 {children}
53 </PressResponderContext.Provider>
54 );
55});
56
57export function ClearPressResponder({children}: {children: ReactNode}) {
58 let context = useMemo(() => ({register: () => {}}), []);
59 return (
60 <PressResponderContext.Provider value={context}>
61 {children}
62 </PressResponderContext.Provider>
63 );
64}