[d565449] | 1 | /* eslint-disable react-hooks/exhaustive-deps */
|
---|
| 2 | import React from 'react'
|
---|
| 3 | import { Controller } from '@use-gesture/core'
|
---|
| 4 | import { GenericOptions, GestureKey, InternalHandlers, NativeHandlers } from '@use-gesture/core/types'
|
---|
| 5 | import { ReactDOMAttributes } from './types'
|
---|
| 6 |
|
---|
| 7 | type HookReturnType<Config extends GenericOptions> = Config['target'] extends object
|
---|
| 8 | ? void
|
---|
| 9 | : (...args: any[]) => ReactDOMAttributes
|
---|
| 10 |
|
---|
| 11 | /**
|
---|
| 12 | * Utility hook called by all gesture hooks and that will be responsible for
|
---|
| 13 | * the internals.
|
---|
| 14 | *
|
---|
| 15 | * @param {InternalHandlers} handlers
|
---|
| 16 | * @param {GenericOptions} config
|
---|
| 17 | * @param {GestureKey} gestureKey
|
---|
| 18 | * @param {NativeHandler} nativeHandlers
|
---|
| 19 | * @returns nothing when config.target is set, a binding function when not.
|
---|
| 20 | */
|
---|
| 21 | export function useRecognizers<Config extends GenericOptions>(
|
---|
| 22 | handlers: InternalHandlers,
|
---|
| 23 | config: Config | {} = {},
|
---|
| 24 | gestureKey?: GestureKey,
|
---|
| 25 | nativeHandlers?: NativeHandlers
|
---|
| 26 | ): HookReturnType<Config> {
|
---|
| 27 | const ctrl = React.useMemo(() => new Controller(handlers), [])
|
---|
| 28 | ctrl.applyHandlers(handlers, nativeHandlers)
|
---|
| 29 | ctrl.applyConfig(config, gestureKey)
|
---|
| 30 |
|
---|
| 31 | React.useEffect(ctrl.effect.bind(ctrl))
|
---|
| 32 |
|
---|
| 33 | React.useEffect(() => {
|
---|
| 34 | return ctrl.clean.bind(ctrl)
|
---|
| 35 | }, [])
|
---|
| 36 |
|
---|
| 37 | // When target is undefined we return the bind function of the controller which
|
---|
| 38 | // returns prop handlers.
|
---|
| 39 | // @ts-ignore
|
---|
| 40 | if (config.target === undefined) {
|
---|
| 41 | return ctrl.bind.bind(ctrl) as any
|
---|
| 42 | }
|
---|
| 43 | return undefined as any
|
---|
| 44 | }
|
---|