Files
faunosteo/apps/app/src/components/editor/fields/SelectField.tsx
T

55 lines
1.3 KiB
TypeScript

import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Select from '@/components/ui/Select'
import ReadOnlyValue from './ReadOnlyValue'
export interface SelectOption {
value: string
label: string
}
export interface SelectFieldProps {
id: string
label: string
value: string
options: readonly SelectOption[]
/** A choice is a confirmation: it commits at once. */
onCommit: (value: string) => void
readOnly?: boolean
hint?: string
error?: string
}
/** A choice among fixed options; read-only, the chosen option's label as text. */
export default function SelectField({
id,
label,
value,
options,
onCommit,
readOnly,
hint,
error,
}: SelectFieldProps) {
if (readOnly) {
const chosen = options.find((option) => option.value === value)
return <ReadOnlyValue id={id} label={label} value={chosen?.label ?? ''} />
}
return (
<FormField id={id} label={label} hint={hint} error={error}>
<Select
id={id}
value={value}
onChange={(e) => onCommit(e.target.value)}
aria-invalid={Boolean(error)}
aria-describedby={fieldDescribedBy(id, hint, error)}
>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</Select>
</FormField>
)
}