import { useEffect, useRef, useState } from "react"; import { getSearchSuggestions } from "../../api/searchApi"; const SUGGEST_DELAY_MS = 150; /** Заменяет последнее (недописанное) слово строки на подсказку. */ function applySuggestion(value, word) { return value.replace(/[\p{L}\p{N}]+$/u, "") + word + " "; } export default function FeedSearchBar({ value, onChange, t }) { const [suggestions, setSuggestions] = useState([]); const [active, setActive] = useState(-1); const [focused, setFocused] = useState(false); const inputRef = useRef(null); // Подсказки нужны, только пока строка заканчивается буквой/цифрой (слово дописывается) useEffect(() => { if (!focused || !/[\p{L}\p{N}]$/u.test(value)) { setSuggestions([]); return; } const controller = new AbortController(); const timer = setTimeout(() => { getSearchSuggestions(value, controller.signal) .then(words => { setSuggestions(Array.isArray(words) ? words : []); setActive(-1); }) .catch(() => {}); // подсказки необязательны — без них поиск работает как раньше }, SUGGEST_DELAY_MS); return () => { clearTimeout(timer); controller.abort(); }; }, [value, focused]); const open = focused && suggestions.length > 0; const pick = word => { onChange(applySuggestion(value, word)); setSuggestions([]); inputRef.current?.focus(); }; const onKeyDown = e => { if (!open) return; if (e.key === "ArrowDown") { e.preventDefault(); setActive(i => (i + 1) % suggestions.length); } else if (e.key === "ArrowUp") { e.preventDefault(); setActive(i => (i <= 0 ? suggestions.length - 1 : i - 1)); } else if (e.key === "Enter" && active >= 0) { e.preventDefault(); pick(suggestions[active]); } else if (e.key === "Escape") { setSuggestions([]); } }; return (