Files
nahodka-front/src/components/feed/FeedSearchBar.jsx
2026-10-18 23:49:56 +03:00

118 lines
4.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 (
<div className="f-search-bar">
<svg className="f-search-icon" viewBox="0 0 24 24" fill="none"
stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.35-4.35" />
</svg>
<input
ref={inputRef}
className="f-search-input"
type="text"
placeholder={t('feed.searchPlaceholder')}
value={value}
onChange={e => onChange(e.target.value)}
onKeyDown={onKeyDown}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
role="combobox"
aria-expanded={open}
aria-controls="f-search-suggest"
aria-autocomplete="list"
aria-activedescendant={open && active >= 0 ? `f-search-suggest-${active}` : undefined}
autoComplete="off"
/>
{value && (
<button className="f-search-clear" onClick={() => onChange("")}>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="18" height="18">
<path d="M18 6 6 18M6 6l12 12" />
</svg>
</button>
)}
{open && (
<ul className="f-search-suggest" id="f-search-suggest" role="listbox">
{suggestions.map((word, i) => (
<li
key={word}
id={`f-search-suggest-${i}`}
role="option"
aria-selected={i === active}
className={`f-search-suggest-item${i === active ? " is-active" : ""}`}
// mousedown, а не click: иначе blur инпута закроет список раньше выбора
onMouseDown={e => {
e.preventDefault();
pick(word);
}}
onMouseEnter={() => setActive(i)}
>
{word}
</li>
))}
</ul>
)}
</div>
);
}