'use client' import { ChangeEventHandler, FC, FocusEventHandler } from 'react' import { Controller } from 'react-hook-form' import useDebounce from '../../../hooks/useDebounce' import type { DebouncedFunction, WithControllerProps } from './types' function withController( Component: FC, { shouldDebounce: factoryShouldDebounce = false, debounceTime = 500 } = {}, ) { return ({ name, control, helperText, shouldDebounce: runtimeShouldDebounce, ...props }: WithControllerProps) => { if (control) { const { onChange, onBlur, ...restOfTheProps } = props const onChangeWithFallback = onChange ?? (() => {}) const { debouncedFunction: debouncedOnChange } = useDebounce( onChangeWithFallback, { debounceTime, }, ) const shouldDebounce = runtimeShouldDebounce ?? factoryShouldDebounce return ( { const handleOnChange: ChangeEventHandler = ( event, ) => { field.onChange(event) if (onChange && shouldDebounce) { debouncedOnChange(event) } else { onChange?.(event) } } const handleOnBlur: FocusEventHandler = ( event, ) => { field.onBlur() onBlur?.(event) } return ( ) }} /> ) } return } } export default withController