Files
nahodka-front/src/components/feed/CitySheet.jsx
2026-10-19 00:36:41 +03:00

175 lines
7.3 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, 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, typedCity } = 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 apply = () => {
onChange(typedCity ? [...draft, typedCity] : 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") {
e.preventDefault();
apply();
}
}}
autoComplete="off"
enterKeyHint="search"
/>
</div>
<div className="f-sheet-list">
{rows.length === 0 && (
<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
);
}