|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its 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 | + * @flow |
| 8 | + */ |
| 9 | + |
| 10 | +import type {EventPriority} from 'shared/ReactTypes'; |
| 11 | +import type { |
| 12 | + ReactDOMListenerEvent, |
| 13 | + ReactDOMListenerMap, |
| 14 | +} from 'shared/ReactDOMTypes'; |
| 15 | + |
| 16 | +import ReactSharedInternals from 'shared/ReactSharedInternals'; |
| 17 | +import invariant from 'shared/invariant'; |
| 18 | + |
| 19 | +import {getEventPriorityForListenerSystem} from '../events/DOMEventProperties'; |
| 20 | + |
| 21 | +type EventOptions = {| |
| 22 | + capture?: boolean, |
| 23 | + passive?: boolean, |
| 24 | + priority?: EventPriority, |
| 25 | +|}; |
| 26 | + |
| 27 | +const {ReactCurrentDispatcher} = ReactSharedInternals; |
| 28 | + |
| 29 | +function resolveDispatcher() { |
| 30 | + const dispatcher = ReactCurrentDispatcher.current; |
| 31 | + invariant( |
| 32 | + dispatcher !== null, |
| 33 | + 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + |
| 34 | + ' one of the following reasons:\n' + |
| 35 | + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + |
| 36 | + '2. You might be breaking the Rules of Hooks\n' + |
| 37 | + '3. You might have more than one copy of React in the same app\n' + |
| 38 | + 'See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.', |
| 39 | + ); |
| 40 | + return dispatcher; |
| 41 | +} |
| 42 | + |
| 43 | +export function useEvent( |
| 44 | + type: string, |
| 45 | + options?: EventOptions, |
| 46 | +): ReactDOMListenerMap { |
| 47 | + const dispatcher = resolveDispatcher(); |
| 48 | + let capture = false; |
| 49 | + let passive = false; |
| 50 | + let priority = getEventPriorityForListenerSystem((type: any)); |
| 51 | + |
| 52 | + if (options != null) { |
| 53 | + const optionsCapture = options.capture; |
| 54 | + const optionsPassive = options.passive; |
| 55 | + const optionsPriority = options.priority; |
| 56 | + |
| 57 | + if (typeof optionsCapture === 'boolean') { |
| 58 | + capture = optionsCapture; |
| 59 | + } |
| 60 | + if (typeof optionsPassive === 'boolean') { |
| 61 | + passive = optionsPassive; |
| 62 | + } |
| 63 | + if (typeof optionsPriority === 'number') { |
| 64 | + priority = optionsPriority; |
| 65 | + } |
| 66 | + } |
| 67 | + const event: ReactDOMListenerEvent = { |
| 68 | + capture, |
| 69 | + passive, |
| 70 | + priority, |
| 71 | + type, |
| 72 | + }; |
| 73 | + return dispatcher.useEvent(event); |
| 74 | +} |
0 commit comments