Files
web/src/components/ui/form.tsx

178 lines
4.4 KiB
TypeScript
Raw Normal View History

'use client'
2025-03-14 12:40:51 +08:00
import * as LabelPrimitive from '@radix-ui/react-label'
import {Slot} from '@radix-ui/react-slot'
2025-03-14 12:40:51 +08:00
import {
Controller,
FormProvider,
ControllerProps,
SubmitHandler,
FieldValues, useFormContext, FieldPath, UseFormReturn, ControllerRenderProps,
ControllerFieldState, UseFormStateReturn, FieldError, FieldErrors, SubmitErrorHandler,
} from 'react-hook-form'
2025-03-14 12:40:51 +08:00
import {merge} from '@/lib/utils'
import {Label} from '@/components/ui/label'
2025-03-14 12:40:51 +08:00
import React, {BaseSyntheticEvent, ComponentProps, createContext, ReactNode, useContext, useId} from 'react'
2025-03-14 12:40:51 +08:00
type FormProps<T extends FieldValues> = {
form: UseFormReturn<T>
onSubmit?: SubmitHandler<T>
onError?: SubmitErrorHandler<T>
handler?: (e?: React.BaseSyntheticEvent) => Promise<void>
} & Omit<ComponentProps<'form'>, 'onSubmit' | 'onError'>
2025-03-14 12:40:51 +08:00
function Form<T extends FieldValues>(rawProps: FormProps<T>) {
const {children, onSubmit, onError, handler, ...props} = rawProps
const form = props.form
2025-03-14 12:40:51 +08:00
const handle = handler || form.handleSubmit(
onSubmit || (_ => {}),
onError,
)
2025-03-14 12:40:51 +08:00
return (
<FormProvider {...form}>
<form {...props} onSubmit={async event => {
event.preventDefault()
event.stopPropagation()
await handle(event)
}}>
{children}
</form>
</FormProvider>
2025-03-14 12:40:51 +08:00
)
}
type FormFieldProps<
V extends FieldValues = FieldValues,
N extends FieldPath<V> = FieldPath<V>,
> = {
label?: ReactNode
className?: string
children: (props: {
id: string
field: ControllerRenderProps<V, N>
fieldState: ControllerFieldState
formState: UseFormStateReturn<V>
}) => ReactNode
} & Omit<ControllerProps<V, N>, 'control' | 'render'>
type FormFieldContext = {
2025-03-14 12:40:51 +08:00
id: string
error?: FieldError
2025-03-14 12:40:51 +08:00
}
const FormFieldContext = createContext<FormFieldContext | null>(null)
2025-03-14 12:40:51 +08:00
function FormField<
V extends FieldValues = FieldValues,
N extends FieldPath<V> = FieldPath<V>,
>(props: FormFieldProps<V, N>) {
const form = useFormContext<V>()
const id = useId()
2025-03-14 12:40:51 +08:00
return (
<Controller<V, N> name={props.name} control={form.control} render={({field, fieldState, formState}) => (
<div data-slot="form-field" className={merge('grid gap-2', props.className)}>
<FormFieldContext value={{id: id, error: fieldState.error}}>
{!!props.label &&
<Label
data-slot="form-label"
data-fail={!!fieldState.error}
className={merge('data-[error=true]:text-fail')}
htmlFor={id}>
{props.label}
</Label>
}
<Slot
data-slot="form-control"
aria-invalid={!!fieldState.error}
aria-describedby={
!!fieldState.error
? `${id}-description`
: `${id}-description ${id}-message`
}>
{props.children({id, field, fieldState, formState})}
</Slot>
{!fieldState.error ? null : (
<p
data-slot="form-message"
className={merge('text-fail text-sm')}>
{fieldState.error?.message}
</p>
)}
</FormFieldContext>
</div>
)}
/>
2025-03-14 12:40:51 +08:00
)
}
const useFormField = () => {
const context = useContext(FormFieldContext)
if (!context) {
throw new Error('FormField components must be used within a FormField component')
}
return context
}
function FormLabel({className, ...props}: ComponentProps<typeof LabelPrimitive.Root>) {
const {id, error} = useFormField()
2025-03-14 12:40:51 +08:00
return (
<Label
data-slot="form-label"
data-fail={!!error}
className={merge('data-[error=true]:text-fail', className)}
htmlFor={id}
2025-03-14 12:40:51 +08:00
{...props}
/>
)
}
function FormDescription({className, ...props}: ComponentProps<'p'>) {
const {id} = useFormField()
2025-03-14 12:40:51 +08:00
return (
<p
data-slot="form-description"
id={`${id}-description`}
className={merge('text-muted-foreground text-sm', className)}
2025-03-14 12:40:51 +08:00
{...props}
/>
)
}
function FormMessage({className, ...props}: ComponentProps<'p'>) {
const {id, error} = useFormField()
const body = error ? String(error?.message ?? '') : props.children
2025-03-14 12:40:51 +08:00
if (!body) {
return null
}
return (
<p
data-slot="form-message"
id={`${id}-message`}
className={merge('text-fail text-sm', className)}
2025-03-14 12:40:51 +08:00
{...props}
>
{body}
</p>
)
}
export {
Form,
FormField,
2025-03-14 12:40:51 +08:00
FormLabel,
FormDescription,
FormMessage,
}