import React, { useId } from 'react'; import { useFieldContext } from './context'; import Label from '@/components/elements/Label'; import { TextInput, TextArea, NumberInput } from './controls'; import { PasswordInput } from './PasswordInput'; import { firstError } from './errors'; import { capitalize } from '@/lib/strings'; import Select, { type SelectOption } from '@/components/ui/Select'; import Switch, { type SwitchProps } from '@/components/ui/Switch'; import Checkbox from '@/components/ui/Checkbox'; type BaseProps = { label?: string; description?: string; light?: boolean; }; const HelpText = ({ id, error, description }: { id: string; error?: string; description?: string }) => { if (error) { return (

{capitalize(error)}

); } if (!description) { return null; } return (

{description}

); }; const describedBy = (...ids: (string | undefined)[]): string | undefined => ids.filter((id) => !!id).join(' ') || undefined; function useFieldState(id: string | undefined, description: string | undefined) { const field = useFieldContext(); const generatedId = useId(); const error = firstError(field.state.meta.errors); const helpId = `${generatedId}-help`; return { field, error, fieldId: id ?? generatedId, helpId, describedById: error || description ? helpId : undefined, }; } export type TextFieldProps = BaseProps & Omit, 'name' | 'value' | 'onChange' | 'defaultValue'>; export function TextField({ id, label, description, light, onBlur, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, ...props }: TextFieldProps) { const { field, error, fieldId, helpId, describedById } = useFieldState(id, description); return (
{label && ( )} field.handleChange(value)} onBlur={(event) => { field.handleBlur(); onBlur?.(event); }} aria-invalid={error ? true : ariaInvalid} aria-describedby={describedBy(ariaDescribedBy, describedById)} $hasError={!!error} $isLight={light} />
); } export type PasswordFieldProps = BaseProps & Omit, 'name' | 'value' | 'onChange' | 'defaultValue' | 'type'>; export function PasswordField({ id, label, description, light, onBlur, className, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, ...props }: PasswordFieldProps) { const { field, error, fieldId, helpId, describedById } = useFieldState(id, description); return (
{label && ( )} { field.handleBlur(); onBlur?.(event); }} aria-invalid={error ? true : ariaInvalid} aria-describedby={describedBy(ariaDescribedBy, describedById)} $hasError={!!error} $isLight={light} className={className} />
); } export type TextAreaFieldProps = BaseProps & Omit, 'name' | 'value' | 'onChange' | 'defaultValue'>; export function TextAreaField({ id, label, description, light, onBlur, 'aria-describedby': ariaDescribedBy, 'aria-invalid': ariaInvalid, ...props }: TextAreaFieldProps) { const { field, error, fieldId, helpId, describedById } = useFieldState(id, description); return (
{label && ( )}