ldc-groupe/resources/ts/back/Components/Inputs/ModelSelect.tsx
2025-10-17 14:52:51 +02:00

83 lines
2.7 KiB
TypeScript

// * Packages
import { usePage } from "@inertiajs/react";
import { useState } from "react";
// * Components shadcn
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
// * Other
import InputError from "@/back/Components/InputError";
import { AppEnv, Model, TranslationField } from "@/back/types/global";
import { cn } from "@/lib/utils";
type SimpleSelectProps = {
name: string;
label: string;
placeholder?: string;
options: Array<Model>;
field: string;
required?: boolean;
disabled?: boolean;
selected?: string;
// eslint-disable-next-line no-unused-vars
setData: (name: string, value: string) => void;
};
export default function SimpleSelect({
name,
label,
placeholder = "ex: Administrateur",
options = [],
field = "label",
selected = "",
required = true,
disabled = false,
setData,
}: SimpleSelectProps) {
const { locale } = usePage().props.appEnv as AppEnv;
const { errors } = usePage().props;
const [selectedValue, setSelected] = useState(selected);
const updateData = (name: string, value: string) => {
setSelected(value);
setData(name, value);
}
return (
<div className="flex flex-col w-full justify-start items-start gap-1.5">
<Label htmlFor={name}>{label + (required ? " *" : "")}</Label>
<Select
name={name}
required={required}
disabled={disabled}
value={selectedValue}
onValueChange={(value) => updateData(name, value)}
>
<SelectTrigger
className={cn(
"w-full",
{ "text-muted-foreground": !selectedValue },
{ "border-destructive/50": errors[name] },
)}
>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
{Object.values(options).map((option) => (
<SelectItem key={option.id} value={String(option.id)}>
{String(
typeof option[field as keyof typeof option] === "object"
? (option[field as keyof typeof option] as unknown as TranslationField)[locale]
: option[field as keyof typeof option]
)}
</SelectItem>
))}
</SelectContent>
</Select>
<InputError message={errors[name]} />
</div>
);
}