|
| 1 | +import React, { useId } from 'react' |
| 2 | +import { Input } from '#app/components/ui/input.tsx' |
| 3 | +import { Label } from '#app/components/ui/label.tsx' |
| 4 | +import { Textarea } from '#app/components/ui/textarea.tsx' |
| 5 | + |
| 6 | +export type ListOfErrors = Array<string | null | undefined> | null | undefined |
| 7 | + |
| 8 | +export function ErrorList({ |
| 9 | + id, |
| 10 | + errors, |
| 11 | +}: { |
| 12 | + errors?: ListOfErrors |
| 13 | + id?: string |
| 14 | +}) { |
| 15 | + const errorsToRender = errors?.filter(Boolean) |
| 16 | + if (!errorsToRender?.length) return null |
| 17 | + return ( |
| 18 | + <ul id={id} className="flex flex-col gap-1"> |
| 19 | + {errorsToRender.map(e => ( |
| 20 | + <li key={e} className="text-foreground-destructive text-[10px]"> |
| 21 | + {e} |
| 22 | + </li> |
| 23 | + ))} |
| 24 | + </ul> |
| 25 | + ) |
| 26 | +} |
| 27 | + |
| 28 | +export function Field({ |
| 29 | + labelProps, |
| 30 | + inputProps, |
| 31 | + errors, |
| 32 | + className, |
| 33 | +}: { |
| 34 | + labelProps: React.LabelHTMLAttributes<HTMLLabelElement> |
| 35 | + inputProps: React.InputHTMLAttributes<HTMLInputElement> |
| 36 | + errors?: ListOfErrors |
| 37 | + className?: string |
| 38 | +}) { |
| 39 | + const fallbackId = useId() |
| 40 | + const id = inputProps.id ?? fallbackId |
| 41 | + const errorId = errors?.length ? `${id}-error` : undefined |
| 42 | + return ( |
| 43 | + <div className={className}> |
| 44 | + <Label htmlFor={id} {...labelProps} /> |
| 45 | + <Input |
| 46 | + id={id} |
| 47 | + aria-invalid={errorId ? true : undefined} |
| 48 | + aria-describedby={errorId} |
| 49 | + {...inputProps} |
| 50 | + /> |
| 51 | + <div className="min-h-[32px] px-4 pb-3 pt-1"> |
| 52 | + {errorId ? <ErrorList id={errorId} errors={errors} /> : null} |
| 53 | + </div> |
| 54 | + </div> |
| 55 | + ) |
| 56 | +} |
| 57 | + |
| 58 | +export function TextareaField({ |
| 59 | + labelProps, |
| 60 | + textareaProps, |
| 61 | + errors, |
| 62 | + className, |
| 63 | +}: { |
| 64 | + labelProps: React.LabelHTMLAttributes<HTMLLabelElement> |
| 65 | + textareaProps: React.TextareaHTMLAttributes<HTMLTextAreaElement> |
| 66 | + errors?: ListOfErrors |
| 67 | + className?: string |
| 68 | +}) { |
| 69 | + const fallbackId = useId() |
| 70 | + const id = textareaProps.id ?? textareaProps.name ?? fallbackId |
| 71 | + const errorId = errors?.length ? `${id}-error` : undefined |
| 72 | + return ( |
| 73 | + <div className={className}> |
| 74 | + <Label htmlFor={id} {...labelProps} /> |
| 75 | + <Textarea |
| 76 | + id={id} |
| 77 | + aria-invalid={errorId ? true : undefined} |
| 78 | + aria-describedby={errorId} |
| 79 | + {...textareaProps} |
| 80 | + /> |
| 81 | + <div className="min-h-[32px] px-4 pb-3 pt-1"> |
| 82 | + {errorId ? <ErrorList id={errorId} errors={errors} /> : null} |
| 83 | + </div> |
| 84 | + </div> |
| 85 | + ) |
| 86 | +} |
0 commit comments