"use client"; import React, { useState, useRef, useEffect } from "react"; interface Option { id: string, value: string } interface Props { options: Option[] onSelect: (value: Option) => void } export default function SelectTest({ options = [], onSelect }: Props) { const [open, setOpen] = useState(false); const [highlight, setHighlight] = useState(0); const [value, setValue] = useState(""); const wrapperRef = useRef(null); // Klick außerhalb schließen useEffect(() => { function handleClickOutside(e: any) { if (wrapperRef.current && !wrapperRef.current.contains(e.target)) { setOpen(false); } } document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, []); const filtered = options.filter((opt) => opt.value.toLowerCase().includes(value.toLowerCase()) ); function handleKeyDown(e: React.KeyboardEvent) { if (!open) setOpen(true); if (e.key === "ArrowDown") { e.preventDefault(); setHighlight((h) => Math.min(h + 1, filtered.length - 1)); } if (e.key === "ArrowUp") { e.preventDefault(); setHighlight((h) => Math.max(h - 1, 0)); } if (e.key === "Enter") { e.preventDefault(); selectOption(filtered[highlight]); } if (e.key === "Escape") { setOpen(false); } if (e.key === "Tab") { setOpen(false); } } function selectOption(opt: Option) { if (!opt) return; setValue(opt.value); setOpen(false); onSelect?.(opt); } return (
{ setValue(e.target.value); setOpen(true); }} onFocus={() => setOpen(true)} onBlur={(e) => { if (!wrapperRef.current?.contains(e.relatedTarget)) { setOpen(false); } }} onKeyDown={handleKeyDown} style={{ width: "100%", padding: "8px", border: "1px solid #ccc", borderRadius: 4, }} placeholder="Wähle Option..." /> {open && filtered.length > 0 && ( )}
); }