diff --git a/src/components/CityFilter.jsx b/src/components/CityFilter.jsx index ee5e631..844eb83 100644 --- a/src/components/CityFilter.jsx +++ b/src/components/CityFilter.jsx @@ -1,5 +1,6 @@ -import { useState, useRef, useEffect, useMemo } from "react"; +import { useState, useRef, useEffect } from "react"; import { useTranslation } from "react-i18next"; +import { useCityOptions } from "../hooks/useCityOptions"; /** * CityFilter — мультиселект городов с поиском и свободным вводом. @@ -27,18 +28,7 @@ export default function CityFilter({ cities, value, onChange }) { return () => document.removeEventListener("mousedown", onDocMouseDown); }, [open]); - const normalizedQuery = query.trim().toLowerCase(); - - // Города, совпадающие с введённым текстом (выбранные помечаются галочкой) - const options = useMemo(() => { - const q = normalizedQuery; - return cities.filter(c => c && (!q || c.toLowerCase().includes(q))); - }, [cities, normalizedQuery]); - - // Свободный ввод доступен, если введён текст, которого нет ни в списке, ни в выбранных - const canAddCustom = normalizedQuery.length > 0 && - !value.some(c => c.toLowerCase() === normalizedQuery) && - !cities.some(c => c.toLowerCase() === normalizedQuery); + const { options, canAddCustom } = useCityOptions(cities, value, query); const toggle = (city) => { if (value.includes(city)) { diff --git a/src/components/feed/CityQuickFilter.jsx b/src/components/feed/CityQuickFilter.jsx new file mode 100644 index 0000000..62e0e25 --- /dev/null +++ b/src/components/feed/CityQuickFilter.jsx @@ -0,0 +1,59 @@ +import { useCallback, useState } from "react"; +import { useTranslation } from "react-i18next"; +import CitySheet from "./CitySheet"; + +/** + * CityQuickFilter — мобильный фильтр городов: круглая кнопка со счётчиком + * рядом с поиском + строка чипов выбранных городов + нижняя шторка выбора. + * + * Возвращает фрагмент: кнопка и строка чипов — соседние элементы флекс-панели + * .f-search-panel (чипы переносятся на свою строку через flex-basis: 100%). + * Видимость (только телефон) управляется CSS. + */ +export default function CityQuickFilter({ cities, value, onChange }) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const close = useCallback(() => setOpen(false), []); + + return ( + <> + + + {value.length > 0 && ( +
+ {value.map(city => ( + + {city} + + + ))} +
+ )} + + + + ); +} diff --git a/src/components/feed/CitySheet.jsx b/src/components/feed/CitySheet.jsx new file mode 100644 index 0000000..a171c8c --- /dev/null +++ b/src/components/feed/CitySheet.jsx @@ -0,0 +1,187 @@ +import { useEffect, useState } from "react"; +import { createPortal } from "react-dom"; +import { motion, AnimatePresence, useDragControls } from "framer-motion"; +import { useTranslation } from "react-i18next"; +import { useCityOptions } from "../../hooks/useCityOptions"; + +// Сколько нужно протянуть шторку вниз (px) или с какой скоростью, чтобы она закрылась +const DRAG_CLOSE_OFFSET = 100; +const DRAG_CLOSE_VELOCITY = 500; + +/** + * CitySheet — мобильная нижняя шторка выбора городов. + * + * Работает с черновиком: выбор применяется только по «Показать», + * закрытие свайпом/тапом по фону изменения отбрасывает. + * + * @param {boolean} open + * @param {() => void} onClose + * @param {string[]} cities — доступные города (из /posts/cities) + * @param {string[]} value — применённые города + * @param {(next: string[]) => void} onChange — применить выбор + */ +export default function CitySheet({ open, onClose, cities, value, onChange }) { + const { t } = useTranslation(); + const [draft, setDraft] = useState(value); + const [query, setQuery] = useState(""); + // Тянуть шторку можно только за ручку/заголовок — иначе drag мешает скроллу списка + const dragControls = useDragControls(); + + // При каждом открытии черновик начинается с применённого выбора + useEffect(() => { + if (open) { + setDraft(value); + setQuery(""); + } + }, [open]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + if (!open) return; + const onKeyDown = (e) => e.key === "Escape" && onClose(); + document.addEventListener("keydown", onKeyDown); + return () => document.removeEventListener("keydown", onKeyDown); + }, [open, onClose]); + + const { options, canAddCustom } = useCityOptions(cities, draft, query); + + // Города, добавленные свободным вводом, в общем списке отсутствуют — показываем их сверху + const q = query.trim().toLowerCase(); + const customSelected = draft.filter(c => + !cities.includes(c) && (!q || c.toLowerCase().includes(q))); + const rows = [...customSelected, ...options]; + + const toggle = (city) => { + setDraft(d => d.includes(city) ? d.filter(c => c !== city) : [...d, city]); + }; + + const addCustom = () => { + const city = query.trim(); + if (city && !draft.includes(city)) setDraft(d => [...d, city]); + setQuery(""); + }; + + const apply = () => { + onChange(draft); + onClose(); + }; + + return createPortal( + + {open && ( + <> + + { + if (info.offset.y > DRAG_CLOSE_OFFSET || info.velocity.y > DRAG_CLOSE_VELOCITY) { + onClose(); + } + }} + > +
dragControls.start(e)}> + + +
+ + + + + setQuery(e.target.value)} + onKeyDown={e => { + if (e.key === "Enter" && canAddCustom) { + e.preventDefault(); + addCustom(); + } + }} + autoComplete="off" + enterKeyHint="done" + /> +
+ +
+ {canAddCustom && ( + + )} + + {rows.length === 0 && !canAddCustom && ( +
{t("feed.filterCitiesEmpty")}
+ )} + + {rows.map(city => { + const selected = draft.includes(city); + return ( + + ); + })} +
+ +
+ + +
+ + + )} + , + document.body + ); +} + diff --git a/src/hooks/useCityOptions.js b/src/hooks/useCityOptions.js new file mode 100644 index 0000000..181f8b4 --- /dev/null +++ b/src/hooks/useCityOptions.js @@ -0,0 +1,26 @@ +import { useMemo } from "react"; + +/** + * Общая логика выбора городов для CityFilter (десктоп) и CitySheet (мобильная шторка). + * + * @param {string[]} cities — доступные города (из /posts/cities) + * @param {string[]} value — выбранные города + * @param {string} query — введённый текст поиска + * @returns {{ options: string[], canAddCustom: boolean }} + * options — города, совпадающие с текстом (выбранные помечаются в UI галочкой); + * canAddCustom — введён текст, которого нет ни в списке, ни среди выбранных + */ +export function useCityOptions(cities, value, query) { + const normalizedQuery = query.trim().toLowerCase(); + + const options = useMemo(() => { + const q = normalizedQuery; + return cities.filter(c => c && (!q || c.toLowerCase().includes(q))); + }, [cities, normalizedQuery]); + + const canAddCustom = normalizedQuery.length > 0 && + !value.some(c => c.toLowerCase() === normalizedQuery) && + !cities.some(c => c.toLowerCase() === normalizedQuery); + + return { options, canAddCustom }; +} diff --git a/src/hooks/useHideOnScroll.js b/src/hooks/useHideOnScroll.js new file mode 100644 index 0000000..a761ee5 --- /dev/null +++ b/src/hooks/useHideOnScroll.js @@ -0,0 +1,63 @@ +import { useEffect, useRef, useState } from "react"; + +// Сколько нужно непрерывно проскроллить в одну сторону, чтобы переключиться +const THRESHOLD_PX = 24; +// У самого верха списка шапка показывается всегда +const TOP_ZONE_PX = 60; +// Пока шапка сворачивается/разворачивается, высота скролл-контейнера меняется +// и браузер может сам поправить scrollTop — эти события игнорируем, иначе дрожание +const LOCK_MS = 350; + +/** + * Хук «прятать шапку при скролле вниз, показывать при скролле вверх». + * + * @param {React.RefObject} scrollRef — скролл-контейнер + * @param {boolean} enabled — когда false, шапка всегда видна + * @returns {boolean} hidden + */ +export function useHideOnScroll(scrollRef, enabled) { + const [hidden, setHidden] = useState(false); + const hiddenRef = useRef(false); + + useEffect(() => { + const el = scrollRef.current; + if (!enabled || !el) { + hiddenRef.current = false; + setHidden(false); + return; + } + + let lastY = el.scrollTop; + let acc = 0; + let lockUntil = 0; + + const set = (next) => { + if (hiddenRef.current === next) return; + hiddenRef.current = next; + setHidden(next); + acc = 0; + lockUntil = Date.now() + LOCK_MS; + }; + + const onScroll = () => { + const y = el.scrollTop; + const delta = y - lastY; + lastY = y; + if (Date.now() < lockUntil) return; + + if (y < TOP_ZONE_PX) { + set(false); + return; + } + // Копим путь только в одном направлении: смена направления сбрасывает счётчик + acc = Math.sign(delta) === Math.sign(acc) ? acc + delta : delta; + if (acc > THRESHOLD_PX) set(true); + else if (acc < -THRESHOLD_PX) set(false); + }; + + el.addEventListener("scroll", onScroll, { passive: true }); + return () => el.removeEventListener("scroll", onScroll); + }, [scrollRef, enabled]); + + return hidden; +} diff --git a/src/locales/en.json b/src/locales/en.json index a5a6abe..0b978bf 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -167,6 +167,11 @@ "filterCitiesAdd": "Add \"{{city}}\"", "filterCitiesRemove": "Remove city", "filterCitiesClear": "Reset cities", + "filterCitiesTitle": "Cities", + "filterCitiesSearch": "Find a city", + "filterCitiesApply": "Show", + "filterCitiesReset": "Reset", + "filterCitiesOpen": "Choose cities", "emptyCityTitle": "No ads in this city", "emptyCitySub": "Try another city", "confirmDelete": "Are you sure you want to delete this ad?", diff --git a/src/locales/ru.json b/src/locales/ru.json index 594bce3..7de6aae 100644 --- a/src/locales/ru.json +++ b/src/locales/ru.json @@ -167,6 +167,11 @@ "filterCitiesAdd": "Добавить «{{city}}»", "filterCitiesRemove": "Убрать город", "filterCitiesClear": "Сбросить города", + "filterCitiesTitle": "Города", + "filterCitiesSearch": "Найти город", + "filterCitiesApply": "Показать", + "filterCitiesReset": "Сбросить", + "filterCitiesOpen": "Выбрать города", "emptyCityTitle": "В этом городе объявлений нет", "emptyCitySub": "Попробуйте выбрать другой город", "confirmDelete": "Вы уверены, что хотите удалить это объявление?", diff --git a/src/pages/MainFeed.tsx b/src/pages/MainFeed.tsx index c89e489..552e845 100644 --- a/src/pages/MainFeed.tsx +++ b/src/pages/MainFeed.tsx @@ -13,6 +13,7 @@ import AuthModal from "../components/AuthModal"; import RulesModal from "./RulesModal"; import FeedTopBar from "../components/feed/FeedTopBar"; import FeedSearchBar from "../components/feed/FeedSearchBar"; +import CityQuickFilterLegacy from "../components/feed/CityQuickFilter"; import FeedContent from "../components/feed/FeedContent"; import PullToRefresh from "../components/feed/PullToRefresh"; @@ -23,6 +24,8 @@ import { useCities } from "../hooks/useCities"; import { useFeedPosts } from "../hooks/useFeedPosts"; import { useMyPosts } from "../hooks/useMyPosts"; import { useInfiniteScroll } from "../hooks/useInfiniteScroll"; +import { useHideOnScroll } from "../hooks/useHideOnScroll"; +import { useIsDesktop } from "../hooks/useIsDesktop"; import { useModals } from "../hooks/useModals"; import { useFeedActions } from "../hooks/useFeedActions"; import { useTranslation } from "react-i18next"; @@ -37,6 +40,7 @@ import type { ComponentType } from "react"; // Legacy .jsx-модули: TS инферирует их типы из JS неточно (бывают «странные» // сигнатуры). Приводим к типовому виду вручную — никакой логики не меняет. const CityFilter = CityFilterLegacy as unknown as ComponentType; +const CityQuickFilter = CityQuickFilterLegacy as unknown as ComponentType; const CreateUpdatePost = CreateUpdatePostLegacy as unknown as ComponentType; // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -181,6 +185,11 @@ export default function MainFeed() { const fadeHeight = measuredFade; + // На мобильном поиске шапка (логотип + поле + город) прячется при скролле вниз, + // чтобы результаты занимали весь экран; на десктопе панель всегда на месте. + const isDesktop = useIsDesktop() as boolean; + const searchHeadHidden = useHideOnScroll(feedRef, isSearchView && !isMapView && !isDesktop); + // Открываем модалку аутентификации если пришли с лендинга useEffect(() => { if (location.state?.openAuth) { @@ -437,21 +446,30 @@ export default function MainFeed() { />
- {isSearchView && ( - setSidebarOpen(v => !v)} - typeFilter={typeFilter} - onTypeFilterChange={setTypeFilter} - /> - )} -
- + {/* Шапка поиска: на мобильном сворачивается при скролле вниз (grid 1fr → 0fr) */} +
+
+ {isSearchView && ( + setSidebarOpen(v => !v)} + typeFilter={typeFilter} + onTypeFilterChange={setTypeFilter} + /> + )} +
+ - {activeNav === "home" && ( -
- + {activeNav === "home" && ( + <> + {/* Десктоп/планшет — инлайн-мультиселект, телефон — кнопка + шторка (переключение в CSS) */} +
+ +
+ + + )}
- )} +
diff --git a/src/styles/layout.css b/src/styles/layout.css index c7a51f0..ca1e908 100644 --- a/src/styles/layout.css +++ b/src/styles/layout.css @@ -188,12 +188,21 @@ .f-topbar-login-icon { font-size: 1.1rem; line-height: 1; } /* ── Search Bar ── */ +/* Поле-капсула с лупой внутри — в одном стиле с .f-city-ms-control */ .f-search-bar { position: relative; - display: flex; align-items: center; gap: 10px; - padding: 10px 16px; - background: var(--bg-surface); - border-bottom: 1px solid var(--border); + flex: 2; min-width: 0; + display: flex; align-items: center; gap: 8px; + padding: 0 14px; + min-height: 42px; + background: var(--bg-input); + border: 1px solid var(--border); + border-radius: 999px; + transition: border-color .2s, box-shadow .2s; +} +.f-search-bar:focus-within { + border-color: rgba(var(--teal-rgb), .5); + box-shadow: 0 0 0 3px rgba(var(--teal-rgb), .12); } .f-search-icon { @@ -203,21 +212,14 @@ .f-search-input { flex: 1; min-width: 0; - background: var(--bg-input); - border: 1px solid transparent; - border-radius: 999px; - padding: 10px 18px; + background: transparent; + border: none; + padding: 10px 0; font-family: var(--font); font-size: 0.9rem; color: var(--text-primary); outline: none; - transition: border-color .2s, box-shadow .2s, background .2s; } .f-search-input::placeholder { color: var(--muted); } -.f-search-input:focus { - border-color: var(--border); - background: var(--bg-surface); - box-shadow: 0 1px 6px rgba(0,0,0,.06); -} .f-search-clear { background: none; border: none; cursor: pointer; @@ -230,7 +232,7 @@ /* Подсказки при вводе — под полем поиска, поверх ленты */ .f-search-suggest { position: absolute; z-index: 30; - top: calc(100% - 4px); left: 44px; right: 16px; + top: calc(100% + 6px); left: 0; right: 0; margin: 0; padding: 6px 0; list-style: none; background: var(--bg-card-popup); border: 1px solid var(--border); @@ -362,15 +364,13 @@ /* ── City Multiselect ── */ .f-city-filter-wrap { position: relative; z-index: 20; + flex: 1; min-width: 220px; display: flex; align-items: center; - padding: 10px 16px; - border-bottom: 1px solid var(--border); - background: var(--bg-surface); } .f-city-multiselect { position: relative; flex: 1; - width: 100%; max-width: 440px; margin: 0 auto; + width: 100%; } .f-city-ms-control { @@ -572,7 +572,168 @@ /* Search panel — видна только во вкладке «Поиск» (на десктопе всегда) */ .f-search-panel { display: none; } -.f-app.f-search-view .f-search-panel { display: block; } +.f-app.f-search-view .f-search-panel { display: flex; } + +/* Поиск и город — одной строкой в общей полосе */ +.f-search-panel { + position: relative; z-index: 20; + gap: 8px; align-items: flex-start; + padding: 10px 16px; + background: var(--bg-surface); + border-bottom: 1px solid var(--border); +} + +/* Обёртка шапки поиска: сворачивается по высоте через grid-template-rows + (1fr → 0fr) — плавно и без замеров высоты. overflow: hidden только в + свёрнутом виде, иначе обрезались бы подсказки и дропдауны. */ +.f-search-head { + position: relative; z-index: 20; + display: grid; grid-template-rows: 1fr; + transition: grid-template-rows .25s ease; +} +.f-search-head.is-hidden { grid-template-rows: 0fr; } +.f-search-head-inner { min-height: 0; } +.f-search-head.is-hidden .f-search-head-inner { overflow: hidden; } + +/* ── Мобильный фильтр городов: кнопка + чипы (показываются только на телефоне) ── */ +.f-city-btn, +.f-city-chips { display: none; } + +.f-city-btn { + position: relative; flex-shrink: 0; + width: 42px; height: 42px; + align-items: center; justify-content: center; + border-radius: 50%; + background: var(--bg-input); + border: 1px solid var(--border); + color: var(--muted); + cursor: pointer; + transition: border-color .2s, color .2s; +} +.f-city-btn.active { + color: var(--teal); + border-color: rgba(var(--teal-rgb), .5); +} +.f-city-btn-badge { + position: absolute; top: -4px; right: -4px; + min-width: 18px; height: 18px; padding: 0 5px; + border-radius: 999px; + background: var(--teal); color: #fff; + font-size: 0.7rem; font-weight: 600; line-height: 18px; + text-align: center; +} + +.f-city-chips { + flex-basis: 100%; + gap: 6px; + overflow-x: auto; + scrollbar-width: none; + margin: 0 -12px; padding: 0 12px; +} +.f-city-chips::-webkit-scrollbar { display: none; } +.f-city-chip { + display: inline-flex; align-items: center; gap: 2px; + flex-shrink: 0; + padding: 4px 4px 4px 12px; + border-radius: 999px; + background: rgba(var(--teal-rgb), .12); + color: var(--teal); + font-size: 0.82rem; white-space: nowrap; +} +.f-city-chip-remove { + display: flex; align-items: center; justify-content: center; + width: 22px; height: 22px; + background: none; border: none; border-radius: 50%; + color: inherit; cursor: pointer; +} + +/* ── Нижняя шторка выбора городов ── */ +.f-sheet-backdrop { + position: fixed; inset: 0; z-index: 90; + background: var(--bg-overlay); +} +.f-sheet { + position: fixed; left: 0; right: 0; bottom: 0; z-index: 91; + display: flex; flex-direction: column; + max-height: 85vh; max-height: 85dvh; + /* Фиксированный минимум: при фильтрации короткий список не «схлопывает» шторку */ + min-height: 60vh; min-height: 60dvh; + background: var(--bg-surface-solid); + border-radius: 20px 20px 0 0; + box-shadow: 0 -8px 32px rgba(0, 0, 0, .18); + padding-bottom: env(safe-area-inset-bottom); +} +.f-sheet-grab { padding: 8px 20px 4px; touch-action: none; cursor: grab; } +.f-sheet-handle { + width: 36px; height: 4px; margin: 0 auto 12px; + border-radius: 2px; background: var(--border); +} +.f-sheet-header { display: flex; align-items: center; gap: 8px; } +.f-sheet-title { + margin: 0; font-family: var(--font); + font-size: 1.1rem; font-weight: 600; color: var(--text-primary); +} +.f-sheet-count { + min-width: 22px; height: 22px; padding: 0 7px; + border-radius: 999px; background: var(--teal); color: #fff; + font-size: 0.75rem; font-weight: 600; line-height: 22px; text-align: center; +} +.f-sheet-search { + display: flex; align-items: center; gap: 8px; + margin: 8px 20px; + padding: 0 14px; min-height: 44px; + background: var(--bg-input); + border: 1px solid var(--border); + border-radius: 999px; +} +.f-sheet-search:focus-within { border-color: rgba(var(--teal-rgb), .5); } +.f-sheet-search-input { + flex: 1; min-width: 0; + background: transparent; border: none; outline: none; + font-family: var(--font); + font-size: 16px; /* не меньше 16px — иначе iOS Safari зумит страницу при фокусе */ + color: var(--text-primary); +} +.f-sheet-search-input::placeholder { color: var(--muted); } +.f-sheet-list { + flex: 1; min-height: 0; + overflow-y: auto; overscroll-behavior: contain; + padding: 0 20px; +} +.f-sheet-row { + display: flex; align-items: center; gap: 12px; + width: 100%; min-height: 48px; + background: none; border: none; + border-bottom: 1px solid var(--border); + font-family: var(--font); font-size: 1rem; color: var(--text-primary); + text-align: left; cursor: pointer; +} +.f-sheet-row:last-child { border-bottom: none; } +.f-sheet-check { + display: flex; align-items: center; justify-content: center; + flex-shrink: 0; width: 22px; height: 22px; + border-radius: 6px; border: 1.5px solid var(--border); + color: #fff; font-size: 0.9rem; + transition: background .15s, border-color .15s; +} +.f-sheet-row.selected .f-sheet-check { background: var(--teal); border-color: var(--teal); } +.f-sheet-row-add { color: var(--teal); } +.f-sheet-row-add .f-sheet-check { border-color: var(--teal); color: var(--teal); } +.f-sheet-row-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.f-sheet-empty { padding: 24px 0; text-align: center; color: var(--muted); font-size: 0.9rem; } +.f-sheet-actions { + display: flex; gap: 10px; + padding: 12px 20px 16px; + border-top: 1px solid var(--border); +} +.f-sheet-btn { + flex: 1; height: 46px; + border-radius: 999px; + background: none; border: 1px solid var(--border); + font-family: var(--font); font-size: 0.95rem; font-weight: 500; + color: var(--text-primary); cursor: pointer; +} +.f-sheet-btn-primary { flex: 2; background: var(--teal); border-color: var(--teal); color: #fff; } /* Map view */ .f-mapview { @@ -756,7 +917,7 @@ display: none; } .f-search-panel { - display: block; + display: flex; } .f-bottom-nav { display: none; @@ -800,9 +961,12 @@ font-size: 0.82rem; } - .f-city-filter-wrap { padding: 8px 12px; } + .f-search-panel { padding: 8px 12px; } + .f-search-bar { min-height: 38px; padding: 0 12px; } + /* 16px — минимум, при котором iOS Safari не зумит страницу при фокусе на поле */ + .f-search-input { font-size: 16px; padding: 8px 0; } .f-city-ms-control { padding: 5px 12px; min-height: 38px; } - .f-city-ms-input { font-size: 0.85rem; } + .f-city-ms-input { font-size: 16px; } .f-city-ms-tag { font-size: 0.75rem; padding: 2px 8px; } .f-topbar-dropdown-menu { @@ -813,6 +977,13 @@ } @media (max-width: 600px) { + /* Телефон: поиск + круглая кнопка города в одну строку, чипы — строкой ниже */ + .f-search-panel { flex-wrap: wrap; align-items: center; row-gap: 8px; } + .f-search-bar { flex: 1; min-height: 42px; } + .f-city-filter-wrap { display: none; } + .f-city-btn, + .f-city-chips { display: flex; } + .f-post-btn { padding: 7px 10px; font-size: 0.7rem;