186 lines
6.5 KiB
TypeScript
186 lines
6.5 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useRef, useEffect } from "react";
|
|
import { createPortal } from "react-dom";
|
|
import { ChevronDown } from "lucide-react";
|
|
|
|
|
|
type DropdownItem = { id: string, value: string };
|
|
|
|
interface Props {
|
|
placeholder?:string
|
|
items: DropdownItem[];
|
|
value?: DropdownItem | null; // id
|
|
onChange?: (item: DropdownItem) => void;
|
|
}
|
|
|
|
export default function SelectAndSearch2({ placeholder,items, value, onChange }: Props) {
|
|
const [open, setOpen] = useState(false);
|
|
const [selected, setSelected] = useState<DropdownItem>(value ?? {id:"",value:""});
|
|
const [query, setQuery] = useState("");
|
|
const [highlightIndex, setHighlightIndex] = useState(0);
|
|
const [filtered, setFiltered] = useState<DropdownItem[]>(items);
|
|
|
|
const buttonRef = useRef<HTMLButtonElement>(null);
|
|
const searchRef = useRef<HTMLInputElement>(null);
|
|
const itemRefs = useRef<HTMLButtonElement[]>([]);
|
|
|
|
const [position, setPosition] = useState({ top: 0, left: 0, width: 0 });
|
|
|
|
useEffect(() => {
|
|
setFiltered(items);
|
|
}, [items]);
|
|
|
|
// Gefilterte Liste
|
|
useEffect(() => {
|
|
const filtered = items.filter((cat) =>
|
|
cat.value.toLowerCase().includes(query.toLowerCase()))
|
|
setFiltered(() => filtered)
|
|
}, [query])
|
|
|
|
// Dropdown-Position aktualisieren
|
|
const updatePosition = () => {
|
|
if (!buttonRef.current) return;
|
|
const rect = buttonRef.current.getBoundingClientRect();
|
|
setPosition({
|
|
top: rect.bottom + window.scrollY,
|
|
left: rect.left + window.scrollX,
|
|
width: rect.width,
|
|
});
|
|
};
|
|
|
|
// Öffnen → positionieren & Fokus setzen
|
|
useEffect(() => {
|
|
if (open) {
|
|
updatePosition();
|
|
setTimeout(() => searchRef.current?.focus(), 0);
|
|
window.addEventListener("resize", updatePosition);
|
|
window.addEventListener("scroll", updatePosition);
|
|
}
|
|
return () => {
|
|
window.removeEventListener("resize", updatePosition);
|
|
window.removeEventListener("scroll", updatePosition);
|
|
};
|
|
}, [open]);
|
|
|
|
// Dropdown schließen bei Klick außerhalb
|
|
useEffect(() => {
|
|
const handleClick = (e: MouseEvent) => {
|
|
if (buttonRef.current && !buttonRef.current.contains(e.target as Node)) {
|
|
setOpen(false);
|
|
}
|
|
};
|
|
document.addEventListener("click", handleClick);
|
|
return () => document.removeEventListener("click", handleClick);
|
|
}, []);
|
|
|
|
// Tastatursteuerung
|
|
const handleKey = (e: React.KeyboardEvent) => {
|
|
if (!open) return;
|
|
|
|
switch (e.key) {
|
|
case "ArrowDown":
|
|
e.preventDefault();
|
|
setHighlightIndex((i) => Math.min(i + 1, filtered.length - 1));
|
|
break;
|
|
|
|
case "ArrowUp":
|
|
e.preventDefault();
|
|
setHighlightIndex((i) => Math.max(i - 1, 0));
|
|
break;
|
|
|
|
case "Enter":
|
|
e.preventDefault();
|
|
if (filtered[highlightIndex]) {
|
|
choose(filtered[highlightIndex]);
|
|
}
|
|
break;
|
|
|
|
case "Escape":
|
|
setOpen(false);
|
|
break;
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
const el = itemRefs.current[highlightIndex];
|
|
if (el) {
|
|
el.scrollIntoView({ block: "nearest" });
|
|
}
|
|
}, [highlightIndex]);
|
|
|
|
const choose = (cat: DropdownItem) => {
|
|
console.log('Change',cat)
|
|
setSelected(cat);
|
|
setOpen(false);
|
|
if(onChange) onChange(cat);
|
|
setTimeout(() => {
|
|
buttonRef.current?.focus();
|
|
}, 0);
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<button
|
|
ref={buttonRef}
|
|
onClick={() => setOpen((o) => !o)}
|
|
onKeyDown={handleKey}
|
|
className="flex justify-between items-center px-4 py-2 border border-gray-300 rounded-xl w-64 bg-white"
|
|
>
|
|
<span>{selected.value || placeholder ||"auswählen…"}</span>
|
|
<ChevronDown className="w-4 h-4" />
|
|
</button>
|
|
|
|
{open &&
|
|
createPortal(
|
|
<div
|
|
className="absolute bg-white border border-gray-200 rounded-xl shadow-lg z-50"
|
|
style={{
|
|
top: position.top,
|
|
left: position.left,
|
|
width: position.width,
|
|
}}
|
|
>
|
|
{/* Suchfeld */}
|
|
<div className="p-2 border-b border-gray-100">
|
|
<input
|
|
ref={searchRef}
|
|
value={query}
|
|
onChange={(e) => {
|
|
setQuery(e.target.value);
|
|
setHighlightIndex(0);
|
|
}}
|
|
onKeyDown={handleKey}
|
|
className="w-full px-2 py-1 border border-gray-300 rounded-md"
|
|
placeholder="Suchen..."
|
|
/>
|
|
</div>
|
|
|
|
{/* Liste */}
|
|
<div className="max-h-60 overflow-auto">
|
|
{filtered.map((cat, index) => (
|
|
<button
|
|
key={cat.id}
|
|
ref={(el) => { itemRefs.current[index] = el!; }}
|
|
onClick={() => choose(cat)}
|
|
className={`w-full text-left px-4 py-2
|
|
${index === highlightIndex
|
|
? "bg-gray-200"
|
|
: "hover:bg-gray-100"
|
|
}
|
|
`}
|
|
>
|
|
{cat.value}
|
|
</button>
|
|
))}
|
|
|
|
{filtered.length === 0 && (
|
|
<div className="px-4 py-3 text-gray-500">Keine Treffer…</div>
|
|
)}
|
|
</div>
|
|
</div>,
|
|
document.body
|
|
)}
|
|
</>
|
|
);
|
|
} |