'use client' import type { ReactElement, ReactNode } from 'react' import { cloneElement, isValidElement } from 'react' import type { Control, ControllerFieldState, ControllerRenderProps, FieldValues, Path, RegisterOptions, } from 'react-hook-form' import { Controller } from 'react-hook-form' import { Span } from 'rntwsc/components/text' import type { ViewProps } from 'rntwsc/tw/components/view' import { View } from 'rntwsc/tw/components/view' import type { StrMap } from 'rntwsc/libs/utility-types' type Rules = Omit< RegisterOptions>, 'disabled' | 'valueAsNumber' | 'valueAsDate' | 'setValueAs' > type RenderProps> = { invalid: boolean value: T[K] onChange: (value: T[K]) => void onBlur: () => void } export type FormFieldProps> = Omit< ViewProps, 'children' > & { name: K control: Control rules?: Rules label?: ReactNode | (() => ReactNode) requiredMask?: boolean valuePropName?: string onChangePropName?: string children: ReactElement | ((props: RenderProps) => ReactElement) } export const FormField = >({ id: propId, name, control, rules, label, requiredMask, valuePropName = 'value', onChangePropName = 'onChange', children, ...props }: FormFieldProps) => { const renderLabel = () => label ? ( {typeof label === 'function' ? label() : label} {requiredMask && *} ) : null const renderChildren = ( field: ControllerRenderProps>, fieldState: ControllerFieldState, ) => { if (typeof children === 'function') { return children({ invalid: !!fieldState.error, value: field.value, onChange: field.onChange, onBlur: field.onBlur, }) } if (isValidElement(children)) { return cloneElement(children, { invalid: !!fieldState.error, [valuePropName]: field.value, [onChangePropName]: (e: Parameters[0]) => { field.onChange(e) children.props?.[onChangePropName]?.(e) }, onBlur: () => { field.onBlur() children.props?.onBlur?.() }, }) } return null } const renderErr = ({ error }: ControllerFieldState) => error?.message ? ( {error.message} ) : null return ( ( {renderLabel()} {renderChildren(field, fieldState)} {renderErr(fieldState)} )} /> ) }