"use client"; import * as React from "react"; import { cn } from "./lib/utils"; export interface SelectV2Group { label: string; options: { value: string; label: string; disabled?: boolean }[]; } export interface SelectV2Props extends Omit, "onSelect"> { groups: SelectV2Group[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; placeholder?: string; label?: string; } export const SelectV2 = React.forwardRef(function SelectV2( { groups = [], value: controlledValue, defaultValue = "", onValueChange, placeholder = "Select...", label = "", className, ...props }, ref ) { const [inner, setInner] = React.useState(defaultValue); const isControlled = controlledValue !== undefined; const value = (isControlled ? controlledValue : inner) ?? ""; const [open, setOpen] = React.useState(false); const boxRef = React.useRef(null); const pick = (v: string) => { if (!isControlled) setInner(v); onValueChange?.(v); setOpen(false); }; React.useEffect(() => { if (!open) return; const onDown = (e: MouseEvent) => { if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false); }; const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); }; document.addEventListener("mousedown", onDown); document.addEventListener("keydown", onKey); return () => { document.removeEventListener("mousedown", onDown); document.removeEventListener("keydown", onKey); }; }, [open ]); const selected = groups.flatMap((g) => g.options).find((o) => o.value === value); return (
{label ? ( {label} ) : null} {open ? (
{groups.map((g) => (
{g.label}
{g.options.map((o) => (
{ if (!o.disabled) pick(o.value); }} onKeyDown={(e) => { if ((e.key === "Enter" || e.key === " ") && !o.disabled) { e.preventDefault(); pick(o.value); } }} tabIndex={o.disabled ? -1 : 0} className={cn( "rounded px-3 py-2 font-mono text-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", o.disabled ? "cursor-not-allowed opacity-40" : "cursor-pointer hover:bg-secondary", o.value === value && "bg-accent font-bold text-accent-foreground", )} > {o.label}
))}
))}
) : null}
); }); SelectV2.displayName = "SelectV2";