'use strict'; import { useEffect, useRef } from 'react'; import type { WorkletFunction } from '../commonTypes'; import { isWeb, isJest } from '../PlatformChecker'; import type { DependencyList, ReanimatedEvent } from './commonTypes'; import { areDependenciesEqual, buildDependencies } from './utils'; import { makeShareable } from '../shareables'; interface GeneralHandler< Event extends object, Context extends Record > { (event: ReanimatedEvent, context: Context): void; } type GeneralWorkletHandler< Event extends object, Context extends Record > = WorkletFunction<[event: ReanimatedEvent, context: Context]>; type GeneralHandlers< Event extends object, Context extends Record > = Record | undefined>; type GeneralWorkletHandlers< Event extends object, Context extends Record > = Record | undefined>; interface ContextWithDependencies> { context: Context; savedDependencies: DependencyList; } export interface UseHandlerContext> { context: Context; doDependenciesDiffer: boolean; useWeb: boolean; } /** * Lets you find out whether the event handler dependencies have changed. * * @param handlers - An object of event handlers. * @param dependencies - An optional array of dependencies. * @returns An object containing a boolean indicating whether the dependencies have changed, and a boolean indicating whether the code is running on the web. * @see https://docs.swmansion.com/react-native-reanimated/docs/advanced/useHandler */ // @ts-expect-error This overload is required by our API. export function useHandler< Event extends object, Context extends Record >( handlers: GeneralHandlers, dependencies?: DependencyList ): UseHandlerContext; export function useHandler< Event extends object, Context extends Record >( handlers: GeneralWorkletHandlers, dependencies?: DependencyList ): UseHandlerContext { const initRef = useRef | null>(null); if (initRef.current === null) { const context = makeShareable({} as Context); initRef.current = { context, savedDependencies: [], }; } useEffect(() => { return () => { initRef.current = null; }; }, []); const { context, savedDependencies } = initRef.current; dependencies = buildDependencies( dependencies, handlers as Record ); const doDependenciesDiffer = !areDependenciesEqual( dependencies, savedDependencies ); initRef.current.savedDependencies = dependencies; const useWeb = isWeb() || isJest(); return { context, doDependenciesDiffer, useWeb }; }