Uecko_ERP/packages/rdx-ui/src/components/form/SelectField.tsx
2026-03-18 17:38:40 +01:00

111 lines
2.8 KiB
TypeScript

import {
Field,
FieldDescription,
FieldError,
FieldLabel,
FormControl,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@repo/shadcn-ui/components";
import { cn } from "@repo/shadcn-ui/lib/utils";
import {
type Control,
Controller,
type FieldPath,
type FieldValues,
useController,
useFormState,
} from "react-hook-form";
import { useTranslation } from "../../locales/i18n.ts";
type SelectFieldProps<TFormValues extends FieldValues> = {
control: Control<TFormValues>;
name: FieldPath<TFormValues>;
label?: string;
description?: string;
disabled?: boolean;
required?: boolean;
readOnly?: boolean;
placeholder?: string;
items: Array<{ value: string; label: string }>;
orientation?: "vertical" | "horizontal" | "responsive";
className?: string;
inputClassName?: string;
};
export function SelectField<TFormValues extends FieldValues>({
control,
name,
items,
label,
placeholder,
description,
disabled = false,
required = false,
readOnly = false,
orientation = "vertical",
className,
inputClassName,
}: SelectFieldProps<TFormValues>) {
const { t } = useTranslation();
const { isSubmitting } = useFormState({ control, name });
const { field, fieldState } = useController({ control, name });
const isDisabled = disabled || readOnly;
return (
<Controller
control={control}
name={name}
render={({ field, fieldState }) => {
return (
<Field
className={cn("gap-1", className)}
data-invalid={fieldState.invalid}
orientation={orientation}
>
{label && <FieldLabel htmlFor={name}>{label}</FieldLabel>}
<Select defaultValue={field.value} disabled={isDisabled} onValueChange={field.onChange}>
<FormControl>
<SelectTrigger
className={cn(
"w-full h-8",
"font-medium bg-muted/50 hover:bg-inherit hover:border-ring hover:ring-ring/50 hover:ring-[2px]",
inputClassName
)}
>
<SelectValue
className={"placeholder:font-normal placeholder:italic"}
placeholder={placeholder}
/>
</SelectTrigger>
</FormControl>
<SelectContent>
{items.map((item) => (
<SelectItem key={`key-${item.value}`} value={item.value}>
{item.label}
</SelectItem>
))}
</SelectContent>
</Select>
<FieldDescription>{description || "\u00A0"}</FieldDescription>
<FieldError errors={[fieldState.error]} />
</Field>
);
}}
/>
);
}