diff --git a/src/components/feed/FeedSearchBar.jsx b/src/components/feed/FeedSearchBar.jsx
index d0a7f77..64827d2 100644
--- a/src/components/feed/FeedSearchBar.jsx
+++ b/src/components/feed/FeedSearchBar.jsx
@@ -1,4 +1,64 @@
+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 (
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 && (
)}
+ {open && (
+
+ {suggestions.map((word, i) => (
+ - {
+ e.preventDefault();
+ pick(word);
+ }}
+ onMouseEnter={() => setActive(i)}
+ >
+ {word}
+
+ ))}
+
+ )}
);
-}
\ No newline at end of file
+}
diff --git a/src/hooks/useCityFeed.jsx b/src/hooks/useCityFeed.jsx
deleted file mode 100644
index 9217c08..0000000
--- a/src/hooks/useCityFeed.jsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useState, useEffect, useCallback } from "react";
-import { useSearchPosts } from "./useSearchPosts";
-
-/**
- * Поиск объявлений по нескольким выбранным городам, с объединением
- * результатов без дублей. Автоматически перезапускается при смене
- * selectedCities.
- */
-export function useCityFeed(selectedCities) {
- const { loading: cityLoading, searchPosts } = useSearchPosts();
- const [cityAds, setCityAds] = useState([]);
-
- const searchCities = useCallback((citiesToSearch) => {
- if (!citiesToSearch.length) return Promise.resolve([]);
- return Promise.all(citiesToSearch.map(c => searchPosts(c))).then(results => {
- const seen = new Set();
- const merged = [];
- results.flat().forEach(ad => {
- if (!seen.has(ad.id)) {
- seen.add(ad.id);
- merged.push(ad);
- }
- });
- return merged;
- });
- }, [searchPosts]);
-
- useEffect(() => {
- if (selectedCities.length === 0) {
- setCityAds([]);
- return;
- }
- let cancelled = false;
- searchCities(selectedCities).then(result => {
- if (!cancelled) setCityAds(result);
- });
- return () => { cancelled = true; };
- }, [selectedCities, searchCities]);
-
- return { cityAds, cityLoading, searchCities };
-}
\ No newline at end of file
diff --git a/src/hooks/useFeedPosts.jsx b/src/hooks/useFeedPosts.jsx
index 6e33e71..d8e8e40 100644
--- a/src/hooks/useFeedPosts.jsx
+++ b/src/hooks/useFeedPosts.jsx
@@ -16,8 +16,22 @@ function extractPage(data) {
return { items, last };
}
+/**
+ * Собирает query-параметры фильтров ленты для GET /api/v1/posts.
+ * @param {{ type?: string|null, categories?: string[], cities?: string[] }} filters
+ */
+function appendFilters(params, filters) {
+ if (!filters) return;
+ if (filters.type) params.set("type", filters.type);
+ (filters.categories || []).forEach(c => params.append("category", c));
+ (filters.cities || []).forEach(c => params.append("city", c));
+}
+
/**
* Управляет основной лентой объявлений: загрузка, пагинация, поиск.
+ * Поиск и фильтры (тип, категории, города) выполняет сервер — так бесконечная
+ * прокрутка подгружает именно подходящие объявления, а не фильтрует страницы
+ * «общей» ленты на клиенте.
*/
export function useFeedPosts() {
const [ads, setAds] = useState([]);
@@ -36,9 +50,13 @@ export function useFeedPosts() {
// «устаревшим», и в ленте остаются только объявления со 2-й страницы.
const firstPageLoadedRef = useRef(false);
const resetInFlightRef = useRef(false);
+ // Фильтры последней загрузки первой страницы: следующие страницы бесконечной
+ // прокрутки обязаны запрашиваться с теми же фильтрами.
+ const filtersRef = useRef(null);
- const loadFeed = useCallback(async (pageNum = 0, search = "", append = false) => {
+ const loadFeed = useCallback(async (pageNum = 0, search = "", append = false, filters) => {
if (append && (!firstPageLoadedRef.current || resetInFlightRef.current)) return;
+ if (!append) filtersRef.current = filters || null;
if (!append) resetInFlightRef.current = true;
const requestId = ++requestIdRef.current;
if (pageNum === 0) {
@@ -50,6 +68,7 @@ export function useFeedPosts() {
try {
const params = new URLSearchParams({ page: pageNum, size: PAGE_SIZE });
if (search) params.set("search", search);
+ appendFilters(params, append ? filtersRef.current : filters);
const res = await fetch(`${API_URL}/api/v1/posts?${params}`);
if (!res.ok) throw new Error(`Error ${res.status}`);
diff --git a/src/hooks/useSearchPosts.js b/src/hooks/useSearchPosts.js
deleted file mode 100644
index 0894cfe..0000000
--- a/src/hooks/useSearchPosts.js
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useState, useCallback } from "react";
-import { API_URL } from "../config/authConstants";
-
-/**
- * useSearchPosts — поиск объявлений по городу.
- * Ходит на GET /api/v1/posts/search?city=..., возвращает список без пагинации.
- *
- * @returns {Object} { posts, loading, error, searchPosts }
- */
-export function useSearchPosts() {
- const [posts, setPosts] = useState([]);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState("");
-
- const searchPosts = useCallback(async (city) => {
- setLoading(true);
- setError("");
- try {
- const params = new URLSearchParams();
- if (city) params.set("city", city);
-
- const res = await fetch(`${API_URL}/api/v1/posts/search?${params}`);
- if (!res.ok) throw new Error(`Error ${res.status}`);
- const data = await res.json();
-
- const list = Array.isArray(data) ? data : [];
- const normalized = list.map(ad => ({
- ...ad,
- type: ad.type ? ad.type.toLowerCase() : "loss"
- }));
- setPosts(normalized);
- return normalized;
- } catch (err) {
- setError(err.message || "Failed to search posts");
- setPosts([]);
- return [];
- } finally {
- setLoading(false);
- }
- }, []);
-
- return { posts, loading, error, searchPosts };
-}
diff --git a/src/pages/MainFeed.tsx b/src/pages/MainFeed.tsx
index a7a761b..c89e489 100644
--- a/src/pages/MainFeed.tsx
+++ b/src/pages/MainFeed.tsx
@@ -22,7 +22,6 @@ import { useAuthContext } from "../context/AuthContext";
import { useCities } from "../hooks/useCities";
import { useFeedPosts } from "../hooks/useFeedPosts";
import { useMyPosts } from "../hooks/useMyPosts";
-import { useCityFeed } from "../hooks/useCityFeed";
import { useInfiniteScroll } from "../hooks/useInfiniteScroll";
import { useModals } from "../hooks/useModals";
import { useFeedActions } from "../hooks/useFeedActions";
@@ -104,6 +103,17 @@ export default function MainFeed() {
const hasSearchParams = searchQuery.trim().length > 0 || selectedCities.length > 0;
const searchPrompt = isSearchView && !hasSearchParams;
+ // Фильтры, которые применяет сервер: вкладка (вещи/питомцы), «потеря/находка»
+ // и выбранные города. Ключ — чтобы эффекты перезапускались по значению, а не по ссылке.
+ const feedFilters = useMemo(() => ({
+ type: typeFilter,
+ categories: activeNav === "items" ? [CATEGORY_ITEM, CATEGORY_OTHER]
+ : activeNav === "pets" ? [CATEGORY_PET]
+ : [],
+ cities: selectedCities,
+ }), [typeFilter, activeNav, selectedCities]);
+ const feedFiltersKey = JSON.stringify(feedFilters);
+
// Реклама показывается на главной ленте (без фильтров/городов). Эта же
// переменная включает обычные AdSlot-карточки в ленте и полноэкранную рекламу.
const showAds = activeNav === "home" && selectedCities.length === 0 && !searchQuery.trim();
@@ -115,7 +125,6 @@ export default function MainFeed() {
const feed = useFeedPosts();
const myPosts = useMyPosts(user?.id);
- const cityFeed = useCityFeed(selectedCities);
const profileData = useMemo(() => {
if (!user) return {} as Record
;
@@ -137,11 +146,8 @@ export default function MainFeed() {
if (activeNav === "myads") {
return Promise.resolve(myPosts.loadMyPosts());
}
- if (selectedCities.length > 0) {
- return cityFeed.searchCities(selectedCities);
- }
- return feed.loadFeed();
- }, [activeNav, myPosts, selectedCities, cityFeed, feed]);
+ return feed.loadFeed(0, searchQuery, false, feedFilters);
+ }, [activeNav, myPosts, feed, searchQuery, feedFilters]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actions = useFeedActions({
@@ -207,24 +213,27 @@ export default function MainFeed() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [modals.isOpen("profile"), isAuthenticated, user?.id]);
- // Загрузка основной ленты (не в режиме поиска)
+ // Загрузка основной ленты (не в режиме поиска). Перезагружаем при смене
+ // вкладки (вещи/питомцы) и фильтра «потеря/находка» — их применяет сервер.
useEffect(() => {
+ if (activeNav === "myads" || activeNav === "map") return;
if (!isSearchView && selectedCities.length === 0 && !searchQuery.trim()) {
- feed.loadFeed(0, "", false);
+ feed.loadFeed(0, "", false, feedFilters);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isSearchView]);
+ }, [isSearchView, feedFiltersKey]);
- // Дебаунс поиска: только когда в search view и есть параметры
+ // Дебаунс поиска: только когда в search view и есть параметры.
+ // Текст и выбранные города уходят на сервер одним запросом.
useEffect(() => {
if (!isSearchView) return;
if (!hasSearchParams) return;
const timer = setTimeout(() => {
- feed.loadFeed(0, searchQuery, false);
+ feed.loadFeed(0, searchQuery.trim(), false, feedFilters);
}, 400);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [searchQuery, selectedCities, isSearchView]);
+ }, [searchQuery, feedFiltersKey, isSearchView]);
// Когда переключаемся на «Мои объявления» — подгружаем с бэкенда
useEffect(() => {
@@ -234,9 +243,10 @@ export default function MainFeed() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeNav, isAuthenticated, user?.id]);
+ const infiniteFeed = ["home", "items", "pets"].includes(activeNav) && !searchPrompt;
const sentinelRef = useInfiniteScroll(
- () => feed.loadFeed(feed.page + 1, searchQuery, true),
- activeNav === "home" && selectedCities.length === 0 && feed.hasMore && !feed.loading && !feed.loadingMore
+ () => feed.loadFeed(feed.page + 1, searchQuery.trim(), true),
+ infiniteFeed && feed.hasMore && !feed.loading && !feed.loadingMore
);
const handleCreatePost = useCallback(() => {
@@ -300,7 +310,7 @@ export default function MainFeed() {
if (el) el.scrollTop = feedStateRef.current.scrollTop;
restoreScrollRef.current = false;
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [isMapView, feed.ads, cityFeed.cityAds, feed.loading, cityFeed.cityLoading]);
+ }, [isMapView, feed.ads, feed.loading]);
// Приводит значение к числу координат или null.
//
@@ -371,8 +381,6 @@ export default function MainFeed() {
let result: AnyAds;
if (activeNav === "myads") {
result = myPosts.myAds;
- } else if (selectedCities.length > 0) {
- result = cityFeed.cityAds;
} else {
result = feed.ads;
}
@@ -396,7 +404,7 @@ export default function MainFeed() {
(a, b) => Number(a.status === POST_STATUS_CLOSED) - Number(b.status === POST_STATUS_CLOSED)
);
return result;
- }, [activeNav, myPosts.myAds, cityFeed.cityAds, feed.ads, selectedCities, typeFilter]);
+ }, [activeNav, myPosts.myAds, feed.ads, typeFilter]);
const listLoading = activeNav === "myads"
? myPosts.loading
@@ -474,7 +482,6 @@ export default function MainFeed() {
/>
0}
error={listError}
filteredAds={filteredAds}
@@ -489,7 +496,7 @@ export default function MainFeed() {
onAuthRequired={() => modals.open("auth")}
t={t}
/>
- {activeNav === "home" && selectedCities.length === 0 && !feed.loading && (
+ {infiniteFeed && !feed.loading && (
)}
{feed.loadingMore && (
diff --git a/src/styles/layout.css b/src/styles/layout.css
index 0b7f4b7..c7a51f0 100644
--- a/src/styles/layout.css
+++ b/src/styles/layout.css
@@ -189,6 +189,7 @@
/* ── Search Bar ── */
.f-search-bar {
+ position: relative;
display: flex; align-items: center; gap: 10px;
padding: 10px 16px;
background: var(--bg-surface);
@@ -226,6 +227,25 @@
}
.f-search-clear:hover { color: var(--text-primary); background: var(--hover-bg); }
+/* Подсказки при вводе — под полем поиска, поверх ленты */
+.f-search-suggest {
+ position: absolute; z-index: 30;
+ top: calc(100% - 4px); left: 44px; right: 16px;
+ margin: 0; padding: 6px 0; list-style: none;
+ background: var(--bg-card-popup);
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ box-shadow: 0 6px 20px rgba(0,0,0,.12);
+ max-height: 320px; overflow-y: auto;
+}
+.f-search-suggest-item {
+ padding: 8px 18px;
+ font-family: var(--font); font-size: 0.9rem;
+ color: var(--text-primary);
+ cursor: pointer;
+}
+.f-search-suggest-item.is-active { background: var(--hover-bg); }
+
/* ── Filter Bar ── */
.f-filter-bar {
display: flex; gap: 8px;