import type { SchemaProp } from "../../lib/types"; export interface SelectOption { /** The value sent to the server. The empty string means nothing chosen. */ value: string; label: string; /** A placeholder cannot be chosen again once a real option has been. */ disabled?: boolean; } /** * What a `` whose * `value` matches none of its options displays its first option anyway, while * the form state stays empty - so a required field with no default showed the * first choice as though it were chosen, and choosing it fired no `change` * event, because it was already what the browser had selected. The field then * refused to submit, saying it was required, pointing at a control that was * visibly filled in. * * So an unset required field gets a placeholder row: the displayed state and * the stored state agree, and the first real choice is a real change. It is * disabled, so it cannot be picked back once something has been. * * An optional field keeps its "none" row instead, and a field with a default * gets neither - it is never unset, and offering "none" would invent a third * choice that does not exist. */ export function selectOptions( prop: SchemaProp, opts: { required: boolean; current: unknown; noneLabel: string; chooseLabel: string }, ): SelectOption[] { const { required, current, noneLabel, chooseLabel } = opts; const values = (prop.enum ?? []).map(String); const labels = prop.enumLabelsAr ?? {}; const rows: SelectOption[] = values.map((value) => ({ value, label: labels[value] ?? value, })); const hasDefault = prop.default !== undefined; const chosen = current === undefined || current === null ? "" : String(current); const unset = chosen === "" || !values.includes(chosen); if (!hasDefault && !required) { return [{ value: "", label: noneLabel }, ...rows]; } if (!hasDefault && required && unset) { return [{ value: "", label: chooseLabel, disabled: true }, ...rows]; } return rows; } /** What the `