import { useRef } from 'react'; import useStableMemo from '@cleartrip/ct-design-use-stable-memo'; import AnimatedStyle from '../AnimatedStyle/AnimatedStyle.native'; import { AnimatedStyle as INativeAnimatedStyle } from '../AnimatedStyle/type'; import type { IAnimatedStyleClass } from '../AnimatedStyle/IAnimatedStyleClass'; import { IAnimatedRef, IAnimationOptions } from '../type'; /** * @description Hook to create animated styles and controller * @param animatedStyle - The animated style to create * @param deps - The dependencies to create the styles * @returns A tuple of the styles and controller * @example * const [styles, controller] = useAnimatedStyles({ * from: { * opacity: 0, * }, * to: { * opacity: 1, * }, * }, [dependencies]); */ export const useAnimatedStyles = (animatedStyle: IAnimationOptions, deps: unknown[]) => { const elementRef = useRef(null); const styles: IAnimatedStyleClass = useStableMemo(() => { return new AnimatedStyle(animatedStyle, elementRef as React.RefObject); }, deps); const controller = { /** * @description Start the animation * @param animatedStyle - The animated style to start * @returns void * @example * controller.start?.(); * controller.start?.({ * to: { * opacity: 1, * }, * }); */ start(animatedStyle?: IAnimationOptions) { elementRef?.current?.start?.(animatedStyle); }, }; return [styles, controller] as unknown as [INativeAnimatedStyle, typeof controller]; };