import type { BaseFormBuilderProps, GenericFormElementProps, } from "@components/Form/DynamicForm.tsx"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@components/UI/Select.tsx"; import { cn } from "@core/utils/cn.ts"; import { type FieldValues, useController } from "react-hook-form"; export interface SelectFieldProps extends BaseFormBuilderProps { type: "select"; selectChange?: (e: string, name: string) => void; validate?: (newValue: string) => Promise; defaultValue?: string; properties: BaseFormBuilderProps["properties"] & { defaultValue?: T; enumValue: { [s: string]: string | number; }; formatEnumName?: boolean; }; } const formatEnumDisplay = (name: string): string => { return name .replace(/_/g, " ") .toLowerCase() .split(" ") .map((s) => s.charAt(0).toUpperCase() + s.substring(1)) .join(" "); }; export function SelectInput({ control, disabled, field, isDirty, invalid, }: GenericFormElementProps>) { const { field: { value, onChange, ref, onBlur, ...rest }, } = useController({ name: field.name, control, }); const { enumValue, formatEnumName, defaultValue, className, ...remainingProperties } = field.properties; const valueToKeyMap: Record = {}; const optionsEnumValues: [string, number][] = []; if (enumValue) { Object.entries(enumValue).forEach(([key, val]) => { if (typeof val === "number") { valueToKeyMap[val.toString()] = key; optionsEnumValues.push([key, val]); } }); } const handleValueChange = async (newValue: string) => { const selectedKey = valueToKeyMap[newValue]; if (field.validate) { const isValid = await field.validate(selectedKey); if (!isValid) { return; } } if (field.selectChange) { field.selectChange(newValue, selectedKey); } onChange(Number.parseInt(newValue)); }; return ( ); }