UNPKG

1.85 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, useSyncRef} from '@react-aria/utils';
15import {PressProps} from './usePress';
16import {PressResponderContext} from './context';
17import React, {ReactNode, RefObject, useContext, useEffect, useRef} from 'react';
18
19interface PressResponderProps extends PressProps {
20 children: ReactNode
21}
22
23export 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});