UNPKG

2.51 kBPlain TextView Raw
1'use strict';
2import { useRef } from 'react';
3import { WorkletEventHandler } from '../WorkletEventHandler';
4import type { IWorkletEventHandler, ReanimatedEvent } from './commonTypes';
5
6/**
7 * Worklet to provide as an argument to `useEvent` hook.
8 */
9export type EventHandler<
10 Event extends object,
11 Context extends Record<string, unknown> = never
12> = (event: ReanimatedEvent<Event>, context?: Context) => void;
13
14export type EventHandlerProcessed<
15 Event extends object,
16 Context extends Record<string, unknown> = never
17> = (event: Event, context?: Context) => void;
18
19export type EventHandlerInternal<Event extends object> = {
20 workletEventHandler: IWorkletEventHandler<Event>;
21};
22
23/**
24 * Lets you run a function whenever a specified native event occurs.
25 *
26 * @param handler - A function that receives an event object with event data - {@link EventHandler}.
27 * @param eventNames - An array of event names the `handler` callback will react to.
28 * @param rebuild - Whether the event handler should be rebuilt. Defaults to `false`.
29 * @returns A function that will be called when the event occurs - {@link EventHandlerProcessed}.
30 * @see https://docs.swmansion.com/react-native-reanimated/docs/advanced/useEvent
31 */
32// @ts-expect-error This overload is required by our API.
33// We don't know which properites of a component that is made into
34// an AnimatedComponent are event handlers and we don't want to force the user to define it.
35// Therefore we disguise `useEvent` return type as a simple function and we handle
36// it being a React Ref in `createAnimatedComponent`.
37export function useEvent<
38 Event extends object,
39 Context extends Record<string, unknown> = never
40>(
41 handler: EventHandler<Event, Context>,
42 eventNames?: string[],
43 rebuild?: boolean
44): EventHandlerProcessed<Event, Context>;
45
46export function useEvent<Event extends object, Context = never>(
47 handler: (event: ReanimatedEvent<Event>, context?: Context) => void,
48 eventNames: string[] = [],
49 rebuild = false
50): EventHandlerInternal<Event> {
51 const initRef = useRef<EventHandlerInternal<Event>>(null!);
52 if (initRef.current === null) {
53 const workletEventHandler = new WorkletEventHandler<Event>(
54 handler,
55 eventNames
56 );
57 initRef.current = { workletEventHandler };
58 } else if (rebuild) {
59 const workletEventHandler = initRef.current.workletEventHandler;
60 workletEventHandler.updateEventHandler(handler, eventNames);
61 initRef.current = { workletEventHandler };
62 }
63
64 return initRef.current;
65}