94 lines
2.2 KiB
TypeScript
Raw Normal View History

import { Field, Label, Input as HeadlessInput } from '@headlessui/react'
import { useState, type ComponentProps, type ReactNode } from 'react'
import {
get,
type FieldError,
type FieldValues,
type Path,
type RegisterOptions,
} from 'react-hook-form'
import { useRemixFormContext } from 'remix-hook-form'
import { twMerge } from 'tailwind-merge'
import { EyeIcon } from '~/components/icons/eye'
import { Button } from './button'
type TInputProperties<T extends FieldValues> = Omit<
ComponentProps<'input'>,
'size'
> & {
id: string
label?: ReactNode
name: Path<T>
rules?: RegisterOptions
2025-03-05 23:39:09 +08:00
containerClassName?: string
labelClassName?: string
}
export const Input = <TFormValues extends Record<string, unknown>>(
properties: TInputProperties<TFormValues>,
) => {
const {
id,
label,
name,
rules,
type = 'text',
placeholder,
disabled,
className,
2025-03-05 23:39:09 +08:00
containerClassName,
labelClassName,
...restProperties
} = properties
const [inputType, setInputType] = useState(type)
const {
register,
formState: { errors },
} = useRemixFormContext()
const error: FieldError = get(errors, name)
return (
<Field
2025-03-05 23:39:09 +08:00
className={twMerge('relative', containerClassName)}
disabled={disabled}
id={id}
>
<Label className={twMerge('mb-1 block text-gray-700', labelClassName)}>
{label} {error && <span className="text-red-500">{error.message}</span>}
</Label>
<HeadlessInput
type={inputType}
className={twMerge(
'h-[42px] w-full rounded-md border border-[#DFDFDF] p-2',
className,
)}
placeholder={inputType === 'password' ? '******' : placeholder}
{...register(name, rules)}
{...restProperties}
/>
{type === 'password' && (
<Button
type="button"
variant="icon"
size="fit"
className="absolute right-3 h-[42px]"
onClick={() =>
setInputType(inputType === 'password' ? 'text' : 'password')
}
>
<EyeIcon
className={twMerge(
'h-4 w-4',
inputType === 'password' ? 'text-gray-500/50' : 'text-gray-500',
)}
/>
</Button>
)}
</Field>
)
}