File size: 2,442 Bytes
fb8a069 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 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 `<select>` should offer, given the field and what is in it.
*
* The rule that matters here is the one that was missing. A `<select>` 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 `<select>`'s `value` should be, so the browser shows what is stored. */
export function selectValue(prop: SchemaProp, current: unknown): string {
if (current !== undefined && current !== null && current !== "") return String(current);
return prop.default !== undefined ? String(prop.default) : "";
}
|