fixed city search

This commit is contained in:
SlimusMinus
2026-10-19 00:18:49 +03:00
parent 0c9af11063
commit 28fedb4308
9 changed files with 573 additions and 49 deletions

View File

@@ -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(
<AnimatePresence>
{open && (
<>
<motion.div
key="backdrop"
className="f-sheet-backdrop"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
onClick={onClose}
/>
<motion.div
key="sheet"
className="f-sheet"
role="dialog"
aria-modal="true"
aria-label={String(t("feed.filterCitiesTitle"))}
initial={{ y: "100%" }}
animate={{ y: 0 }}
exit={{ y: "100%" }}
transition={{ type: "spring", damping: 32, stiffness: 320 }}
drag="y"
dragConstraints={{ top: 0, bottom: 0 }}
dragElastic={{ top: 0, bottom: 0.6 }}
dragListener={false}
dragControls={dragControls}
onDragEnd={(_, info) => {
if (info.offset.y > DRAG_CLOSE_OFFSET || info.velocity.y > DRAG_CLOSE_VELOCITY) {
onClose();
}
}}
>
<div className="f-sheet-grab" onPointerDown={e => dragControls.start(e)}>
<div className="f-sheet-handle" aria-hidden="true" />
<div className="f-sheet-header">
<h3 className="f-sheet-title">{t("feed.filterCitiesTitle")}</h3>
{draft.length > 0 && (
<span className="f-sheet-count">{draft.length}</span>
)}
</div>
</div>
<div className="f-sheet-search">
<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
className="f-sheet-search-input"
type="text"
value={query}
placeholder={t("feed.filterCitiesSearch")}
onChange={e => setQuery(e.target.value)}
onKeyDown={e => {
if (e.key === "Enter" && canAddCustom) {
e.preventDefault();
addCustom();
}
}}
autoComplete="off"
enterKeyHint="done"
/>
</div>
<div className="f-sheet-list">
{canAddCustom && (
<button type="button" className="f-sheet-row f-sheet-row-add" onClick={addCustom}>
<span className="f-sheet-check">+</span>
<span className="f-sheet-row-label">
{t("feed.filterCitiesAdd", { city: query.trim() })}
</span>
</button>
)}
{rows.length === 0 && !canAddCustom && (
<div className="f-sheet-empty">{t("feed.filterCitiesEmpty")}</div>
)}
{rows.map(city => {
const selected = draft.includes(city);
return (
<button key={city} type="button"
className={`f-sheet-row${selected ? " selected" : ""}`}
aria-pressed={selected}
onClick={() => toggle(city)}>
<span className="f-sheet-check">
{selected && (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"
strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"
width="12" height="12">
<path d="M20 6 9 17l-5-5" />
</svg>
)}
</span>
<span className="f-sheet-row-label">{city}</span>
</button>
);
})}
</div>
<div className="f-sheet-actions">
<button type="button" className="f-sheet-btn"
onClick={() => setDraft([])}>
{t("feed.filterCitiesReset")}
</button>
<button type="button" className="f-sheet-btn f-sheet-btn-primary" onClick={apply}>
{t("feed.filterCitiesApply")}
</button>
</div>
</motion.div>
</>
)}
</AnimatePresence>,
document.body
);
}