102 lines
3.3 KiB
TypeScript
102 lines
3.3 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useState } from "react";
|
|
import { Check, ChevronsUpDown } from "lucide-react";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
|
import { cn } from "@/lib/utils";
|
|
|
|
interface SearchableSelectProps {
|
|
value: string;
|
|
options: string[];
|
|
placeholder: string;
|
|
searchPlaceholder?: string;
|
|
emptyText?: string;
|
|
onValueChange: (value: string) => void;
|
|
}
|
|
|
|
export function SearchableSelect({
|
|
value,
|
|
options,
|
|
placeholder,
|
|
searchPlaceholder = "输入关键字搜索",
|
|
emptyText = "暂无可选项",
|
|
onValueChange,
|
|
}: SearchableSelectProps) {
|
|
const [open, setOpen] = useState(false);
|
|
const [query, setQuery] = useState("");
|
|
|
|
useEffect(() => {
|
|
if (!open) {
|
|
setQuery("");
|
|
}
|
|
}, [open]);
|
|
|
|
const filteredOptions = useMemo(() => {
|
|
const normalizedQuery = query.trim().toLowerCase();
|
|
if (!normalizedQuery) return options;
|
|
return options.filter((item) => item.toLowerCase().includes(normalizedQuery));
|
|
}, [options, query]);
|
|
|
|
return (
|
|
<Popover onOpenChange={setOpen} open={open}>
|
|
<PopoverTrigger asChild>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
className="h-10 w-full justify-between px-3 text-left font-normal"
|
|
>
|
|
<span className={cn("truncate", value ? "text-foreground" : "text-muted-foreground")}>
|
|
{value || placeholder}
|
|
</span>
|
|
<ChevronsUpDown className="h-4 w-4 text-muted-foreground" />
|
|
</Button>
|
|
</PopoverTrigger>
|
|
<PopoverContent align="start" className="w-[var(--radix-popover-trigger-width)] p-3">
|
|
<div className="space-y-3">
|
|
<Input
|
|
autoFocus
|
|
value={query}
|
|
onChange={(event) => setQuery(event.target.value)}
|
|
placeholder={searchPlaceholder}
|
|
/>
|
|
<ScrollArea className="max-h-64">
|
|
<div className="space-y-1">
|
|
{filteredOptions.length > 0 ? (
|
|
filteredOptions.map((item) => {
|
|
const selected = item === value;
|
|
return (
|
|
<button
|
|
key={item}
|
|
type="button"
|
|
onClick={() => {
|
|
onValueChange(item);
|
|
setOpen(false);
|
|
}}
|
|
className={cn(
|
|
"flex w-full items-center justify-between rounded-md px-3 py-2 text-left text-sm transition-colors",
|
|
selected
|
|
? "bg-primary/10 text-primary"
|
|
: "hover:bg-muted"
|
|
)}
|
|
>
|
|
<span className="truncate">{item}</span>
|
|
{selected ? <Check className="h-4 w-4" /> : null}
|
|
</button>
|
|
);
|
|
})
|
|
) : (
|
|
<div className="px-3 py-6 text-center text-sm text-muted-foreground">
|
|
{emptyText}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</ScrollArea>
|
|
</div>
|
|
</PopoverContent>
|
|
</Popover>
|
|
);
|
|
}
|