Merge pull request #112 from SlimusMinus/desktop-redesign
All checks were successful
deploy-frontend / deploy (push) Successful in 2m2s

fixed desktop version
This commit is contained in:
SlimusMinus
2026-10-23 00:05:40 +03:00
committed by GitHub
19 changed files with 2446 additions and 132 deletions

View File

@@ -1,6 +1,6 @@
// src/App.jsx // src/App.jsx
import { useEffect, useRef } from 'react'; import { useEffect, useRef } from 'react';
import { BrowserRouter, Routes, Route, useLocation, Navigate } from 'react-router-dom'; import { BrowserRouter, Routes, Route, useLocation, Navigate, useParams } from 'react-router-dom';
import { AuthProvider } from './context/AuthContext'; import { AuthProvider } from './context/AuthContext';
import { ThemeProvider } from './context/ThemeContext'; import { ThemeProvider } from './context/ThemeContext';
import { useAuthContext } from './context/AuthContext'; import { useAuthContext } from './context/AuthContext';
@@ -12,7 +12,11 @@ import ChatPage from './pages/ChatPage';
import ChatListPage from './pages/ChatListPage'; import ChatListPage from './pages/ChatListPage';
import ReviewsPage from './pages/ReviewsPage'; import ReviewsPage from './pages/ReviewsPage';
import AdminAdsPage from './pages/AdminAdsPage'; import AdminAdsPage from './pages/AdminAdsPage';
import DesktopChats from './components/desktop/DesktopChats';
import { useIsDesktop } from './hooks/useIsDesktop';
import './styles/chat.css'; import './styles/chat.css';
// Десктопный слой (>= 900px) — последним, чтобы переопределять базовые стили.
import './styles/desktop.css';
function ScrollToTop() { function ScrollToTop() {
const { pathname } = useLocation(); const { pathname } = useLocation();
@@ -48,6 +52,17 @@ function AdminRoute({ children }) {
return children; return children;
} }
// Чаты: на десктопе — один двухпанельный мессенджер для всех трёх адресов
// (список не перемонтируется при переключении чатов), на мобильном —
// прежние отдельные страницы списка и переписки.
function ChatsRoute() {
const isDesktop = useIsDesktop();
const { chatId } = useParams();
const { pathname } = useLocation();
if (isDesktop) return <DesktopChats />;
return chatId || pathname === '/chats/new' ? <ChatPage /> : <ChatListPage />;
}
function App() { function App() {
return ( return (
<ThemeProvider> <ThemeProvider>
@@ -59,9 +74,9 @@ function App() {
<Route path="/" element={<LandingPage />} /> <Route path="/" element={<LandingPage />} />
<Route path="/feed" element={<MainFeed />} /> <Route path="/feed" element={<MainFeed />} />
<Route path="/reviews" element={<ReviewsPage />} /> <Route path="/reviews" element={<ReviewsPage />} />
<Route path="/chats" element={<ChatListPage />} /> <Route path="/chats" element={<ChatsRoute />} />
<Route path="/chats/new" element={<ChatPage />} /> <Route path="/chats/new" element={<ChatsRoute />} />
<Route path="/chats/:chatId" element={<ChatPage />} /> <Route path="/chats/:chatId" element={<ChatsRoute />} />
<Route path="/admin/ads" element={<AdminRoute><AdminAdsPage /></AdminRoute>} /> <Route path="/admin/ads" element={<AdminRoute><AdminAdsPage /></AdminRoute>} />
<Route path="*" element={<LandingPage />} /> <Route path="*" element={<LandingPage />} />
</Routes> </Routes>

View File

@@ -11,13 +11,13 @@ const MARKER_COLORS = {
FOUND: "#34c759", FOUND: "#34c759",
}; };
function createMarkerLayout(color, imageUrl) { function createMarkerLayout(color, imageUrl, pinId) {
const bgStyle = imageUrl const bgStyle = imageUrl
? `background-image:url('${escapeCssUrl(imageUrl)}');background-size:cover;background-position:center;` ? `background-image:url('${escapeCssUrl(imageUrl)}');background-size:cover;background-position:center;`
: ""; : "";
return window.ymaps.templateLayoutFactory.createClass( return window.ymaps.templateLayoutFactory.createClass(
`<div style=" `<div class="f-map-pin" data-pin-id="${escapeHtml(pinId ?? "")}" style="
width:40px;height:40px; width:40px;height:40px;
border-radius:50%; border-radius:50%;
border:3px solid ${color}; border:3px solid ${color};
@@ -86,7 +86,7 @@ function createPostPlacemark(m) {
const color = MARKER_COLORS[m.type] || MARKER_COLORS.LOST; const color = MARKER_COLORS[m.type] || MARKER_COLORS.LOST;
const typeLabel = m.type === "FOUND" ? "Находка" : "Потеря"; const typeLabel = m.type === "FOUND" ? "Находка" : "Потеря";
const imgSrc = m.imageUrl ? getImageUrl(m.imageUrl) : null; const imgSrc = m.imageUrl ? getImageUrl(m.imageUrl) : null;
const iconLayout = createMarkerLayout(color, imgSrc); const iconLayout = createMarkerLayout(color, imgSrc, m.id != null ? String(m.id) : "");
return new window.ymaps.Placemark( return new window.ymaps.Placemark(
[m.latitude, m.longitude], [m.latitude, m.longitude],
@@ -111,6 +111,15 @@ function createPostPlacemark(m) {
); );
} }
/**
* @param {{
* focusPostId?: any, focusLat?: number, focusLng?: number,
* type?: string | null, category?: string | null,
* onPostClick?: (id: any) => void, onBack?: () => void,
* onMarkersChange?: (markers: any[]) => void, onMarkerHover?: (id: string | null) => void,
* highlightId?: string | null, focusTarget?: { lat: number, lng: number, zoom?: number } | null,
* }} props
*/
export default function MapView({ export default function MapView({
focusPostId, focusPostId,
focusLat, focusLat,
@@ -119,6 +128,14 @@ export default function MapView({
category = null, category = null,
onPostClick, onPostClick,
onBack, onBack,
// Необязательные пропсы десктопной карты (на мобильном не передаются):
// onMarkersChange — список меток в видимой области после каждой загрузки,
// onMarkerHover — наведение на метку (id | null), highlightId — подсветка
// метки, focusTarget — {lat, lng, zoom?} плавный перелёт к точке.
onMarkersChange,
onMarkerHover,
highlightId = null,
focusTarget = null,
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
// tRef нужен, чтобы читать перевод из эффектов, не добавляя t в их deps: // tRef нужен, чтобы читать перевод из эффектов, не добавляя t в их deps:
@@ -137,6 +154,11 @@ export default function MapView({
const onPostClickRef = useRef(onPostClick); const onPostClickRef = useRef(onPostClick);
onPostClickRef.current = onPostClick; onPostClickRef.current = onPostClick;
const onMarkersChangeRef = useRef(onMarkersChange);
onMarkersChangeRef.current = onMarkersChange;
const onMarkerHoverRef = useRef(onMarkerHover);
onMarkerHoverRef.current = onMarkerHover;
const placemarksRef = useRef(new Map());
// Фильтры читаются через ref: их смена не должна пересоздавать карту, // Фильтры читаются через ref: их смена не должна пересоздавать карту,
// они просто уезжают вместе с границами в том же самом запросе. // они просто уезжают вместе с границами в том же самом запросе.
@@ -161,6 +183,7 @@ export default function MapView({
if (!collection) return placemarksById; if (!collection) return placemarksById;
collection.removeAll(); collection.removeAll();
placemarksRef.current = new Map();
markers.forEach((m) => { markers.forEach((m) => {
if (m.latitude == null || m.longitude == null) return; if (m.latitude == null || m.longitude == null) return;
@@ -171,14 +194,18 @@ export default function MapView({
if (m.id != null) { if (m.id != null) {
const postId = String(m.id); const postId = String(m.id);
placemarksById.set(postId, [m.latitude, m.longitude]); placemarksById.set(postId, [m.latitude, m.longitude]);
placemarksRef.current.set(postId, placemark);
placemark.events.add("click", () => { placemark.events.add("click", () => {
if (onPostClickRef.current) { if (onPostClickRef.current) {
onPostClickRef.current(postId); onPostClickRef.current(postId);
} }
}); });
placemark.events.add("mouseenter", () => onMarkerHoverRef.current?.(postId));
placemark.events.add("mouseleave", () => onMarkerHoverRef.current?.(null));
} }
}); });
onMarkersChangeRef.current?.(markers.filter((m) => m.latitude != null && m.longitude != null));
return placemarksById; return placemarksById;
}; };
renderMarkersRef.current = renderMarkers; renderMarkersRef.current = renderMarkers;
@@ -362,8 +389,11 @@ export default function MapView({
// Смена фильтров type/category: догружаем маркеры для текущих границ, // Смена фильтров type/category: догружаем маркеры для текущих границ,
// карту при этом не пересоздаём. // карту при этом не пересоздаём.
const prevFiltersRef = useRef({ type, category });
useEffect(() => { useEffect(() => {
if (type == null && category == null) return; const prev = prevFiltersRef.current;
prevFiltersRef.current = { type, category };
if (prev.type === type && prev.category === category) return;
const map = ymapRef.current; const map = ymapRef.current;
if (!map) return; if (!map) return;
const bounds = map.getBounds(); const bounds = map.getBounds();
@@ -380,6 +410,31 @@ export default function MapView({
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, [type, category]); }, [type, category]);
// Подсветка метки (наведение на карточку в списке десктопной карты):
// класс на DOM-узле лейаута + zIndex, чтобы метка была поверх соседних.
useEffect(() => {
if (highlightId == null) return undefined;
const id = String(highlightId);
const placemark = placemarksRef.current.get(id);
placemark?.options.set("zIndex", 1000);
const node = mapRef.current?.querySelector(`[data-pin-id="${CSS.escape(id)}"]`);
node?.classList.add("is-hl");
return () => {
placemark?.options.unset("zIndex");
node?.classList.remove("is-hl");
};
}, [highlightId]);
// Программный перелёт к точке (клик по карточке в списке десктопной карты).
useEffect(() => {
if (!focusTarget) return;
const map = ymapRef.current;
if (!map) return;
const { lat, lng, zoom } = focusTarget;
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return;
map.setCenter([lat, lng], Math.max(map.getZoom(), zoom ?? FOCUS_ZOOM - 1), { duration: 300 });
}, [focusTarget]);
// Геолокация: если юзер разрешил и карта уже создана — центр на его месте. // Геолокация: если юзер разрешил и карта уже создана — центр на его месте.
// Не трогаем, если карта была открыта с фокусом на конкретном объявлении. // Не трогаем, если карта была открыта с фокусом на конкретном объявлении.
const hasFocus = focusPostId != null || (Number.isFinite(focusLat) && Number.isFinite(focusLng)); const hasFocus = focusPostId != null || (Number.isFinite(focusLat) && Number.isFinite(focusLng));

View File

@@ -1,90 +1,160 @@
import { useState } from "react"; import { useMemo, useState } from "react";
import { useTranslation } from 'react-i18next'; import { useTranslation } from "react-i18next";
import ProfileAvatar from "./profile/ProfileAvatar"; import ProfileAvatar from "./profile/ProfileAvatar";
import SupportModal from "./SupportModal";
import { DesktopIcons } from "./desktop/DesktopIcons";
import { getImageUrl } from "../config/authConstants";
import { POST_STATUS_CLOSED } from "../config/postConstants";
import { formatRelativeTime } from "../utils/relativeTime";
function FollowButton() { const FRESH_LIMIT = 5;
const [following, setFollowing] = useState(false);
const { t } = useTranslation();
return (
<button className="f-right-action-btn" onClick={() => setFollowing(f => !f)}>
{following ? t('rightSidebar.following') : t('rightSidebar.subscribe')}
</button>
);
}
export default function RightSidebar({ ads, profileData, isAuthenticated, onProfileClick, onLoginClick, onNavClick }) { /**
const { t } = useTranslation(); * RightSidebar — правая колонка десктопной ленты (>= 1280px, ниже скрыта CSS):
* карточка профиля, CTA размещения, переход на карту и свежие объявления.
* На мобильной раскладке не отображается.
*
* @param {{
* ads: any[], profileData: any, isAuthenticated: boolean,
* onProfileClick: () => void, onLoginClick: () => void, onNavClick?: (key: string) => void,
* onCreatePost?: () => void, onMapClick?: () => void, onPostClick?: (id: any) => void,
* onRulesClick?: () => void, onReviewsClick?: () => void,
* }} props
*/
export default function RightSidebar({
ads,
profileData,
isAuthenticated,
onProfileClick,
onLoginClick,
onNavClick,
onCreatePost,
onMapClick,
onPostClick,
onRulesClick,
onReviewsClick,
}) {
const { t, i18n } = useTranslation();
const [supportOpen, setSupportOpen] = useState(false);
const suggestions = [...(ads || [])] // Свежие активные объявления: по дате создания, найденные не показываем.
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)) const fresh = useMemo(() => (
.slice(0, 4); [...(ads || [])]
.filter((ad) => ad.status !== POST_STATUS_CLOSED)
.sort((a, b) => new Date(b.createdAt || 0) - new Date(a.createdAt || 0))
.slice(0, FRESH_LIMIT)
), [ads]);
const profileName = isAuthenticated const profileName = isAuthenticated
? `${profileData?.firstName || ""} ${profileData?.lastName || ""}`.trim() || profileData?.login ? `${profileData?.firstName || ""} ${profileData?.lastName || ""}`.trim() || profileData?.login
: null; : null;
return ( return (
<div className="f-right"> <aside className="f-right fd-right">
<div className="f-right-profile"> {/* Профиль / гость */}
<section className="fd-card fd-profile-card">
{isAuthenticated ? ( {isAuthenticated ? (
<> <button type="button" className="fd-profile-row" onClick={onProfileClick}>
<ProfileAvatar avatar={profileData?.avatar} name={profileName} /> <ProfileAvatar avatar={profileData?.avatar} name={profileName} />
<div className="f-right-profile-info"> <span className="fd-profile-info">
<div className="f-right-profile-name">{profileName}</div> <span className="fd-profile-name">{profileName}</span>
<div className="f-right-profile-sub">{profileData?.login}</div> <span className="fd-profile-sub">@{profileData?.login}</span>
</div> </span>
<button className="f-right-action-btn" onClick={onProfileClick}> <DesktopIcons.ChevronRight size={18} />
{t('rightSidebar.yourProfile')} </button>
</button>
</>
) : ( ) : (
<> <div className="fd-guest">
<div className="f-ig-ring"> <div className="fd-guest-icon"><DesktopIcons.User size={22} /></div>
<div className="f-ig-avatar">👤</div> <div className="fd-guest-text">
<div className="fd-guest-title">{t("desktop.guestTitle")}</div>
<div className="fd-guest-sub">{t("desktop.guestText")}</div>
</div> </div>
<div className="f-right-profile-info"> <button type="button" className="fd-btn fd-btn-primary fd-btn-block" onClick={onLoginClick}>
<div className="f-right-profile-name">{t('rightSidebar.guest')}</div> {t("feed.login")}
<div className="f-right-profile-sub">{t('rightSidebar.guestSub')}</div>
</div>
<button className="f-right-action-btn" onClick={onLoginClick}>
{t('feed.login')}
</button> </button>
</> </div>
)} )}
</div> </section>
<div className="f-right-header"> {/* CTA размещения */}
<span className="f-right-label">{t('rightSidebar.suggestions')}</span> <section className="fd-card fd-cta-card">
<button className="f-right-link" onClick={() => onNavClick?.("home")}> <div className="fd-cta-glow" aria-hidden="true" />
{t('rightSidebar.all')} <div className="fd-cta-icon"><DesktopIcons.Sparkles size={20} /></div>
<div className="fd-cta-title">{t("desktop.ctaTitle")}</div>
<div className="fd-cta-text">{t("desktop.ctaText")}</div>
<button type="button" className="fd-btn fd-btn-brand fd-btn-block fd-cta-btn" onClick={onCreatePost}>
<DesktopIcons.Plus size={18} />
<span className="fd-cta-btn-label">{t("desktop.createPost")}</span>
</button> </button>
</div> </section>
{suggestions.length === 0 && ( {/* Карта */}
<div className="f-right-suggest-sub">{t('rightSidebar.empty')}</div> <button type="button" className="fd-card fd-map-card" onClick={onMapClick}>
)} <span className="fd-map-art" aria-hidden="true">
<span className="fd-map-road fd-map-road-1" />
<span className="fd-map-road fd-map-road-2" />
<span className="fd-map-road fd-map-road-3" />
<span className="fd-map-pin fd-map-pin-loss" style={{ left: "22%", top: "38%" }} />
<span className="fd-map-pin fd-map-pin-found" style={{ left: "58%", top: "24%" }} />
<span className="fd-map-pin fd-map-pin-loss" style={{ left: "72%", top: "62%" }} />
<span className="fd-map-pin fd-map-pin-found" style={{ left: "36%", top: "70%" }} />
</span>
<span className="fd-map-body">
<span className="fd-map-title">{t("desktop.mapCardTitle")}</span>
<span className="fd-map-text">{t("desktop.mapCardText")}</span>
<span className="fd-map-link">
{t("desktop.mapCardBtn")}
<DesktopIcons.ArrowRight size={16} />
</span>
</span>
</button>
{suggestions.map(ad => ( {/* Свежие объявления */}
<div className="f-right-suggest" key={ad.id}> <section className="fd-card fd-fresh">
<div className="f-ig-ring f-ig-ring-sm"> <div className="fd-card-head">
<div className="f-ig-avatar">{ad.emoji || "📋"}</div> <span className="fd-card-title">{t("desktop.fresh")}</span>
</div> <button type="button" className="fd-link-btn" onClick={() => onNavClick?.("home")}>
<div className="f-right-suggest-info"> {t("desktop.seeAll")}
<div className="f-right-suggest-name">{ad.title}</div> </button>
<div className="f-right-suggest-sub"> </div>
{ad.city || (ad.type === "loss" ? t('postCard.loss') : t('postCard.found'))} {fresh.length === 0 ? (
</div> <div className="fd-fresh-empty">{t("desktop.freshEmpty")}</div>
</div> ) : (
<FollowButton /> <ul className="fd-fresh-list">
</div> {fresh.map((ad) => {
))} const img = Array.isArray(ad.images) && ad.images[0] ? getImageUrl(ad.images[0]) : null;
const when = formatRelativeTime(ad.createdAt, i18n.language);
return (
<li key={ad.id}>
<button type="button" className="fd-fresh-item" onClick={() => onPostClick?.(ad.id)}>
<span className="fd-fresh-thumb">
{img ? <img src={img} alt="" loading="lazy" decoding="async" /> : <span>{ad.emoji || "📋"}</span>}
<span className={`fd-fresh-type fd-fresh-type-${ad.type === "found" ? "found" : "loss"}`} />
</span>
<span className="fd-fresh-info">
<span className="fd-fresh-title">{ad.title}</span>
<span className="fd-fresh-sub">
{ad.type === "found" ? t("postCard.found") : t("postCard.loss")}
{ad.city && <> · {ad.city}</>}
{when && <> · {when}</>}
</span>
</span>
</button>
</li>
);
})}
</ul>
)}
</section>
<div className="f-right-foot"> <footer className="fd-right-foot">
<span>© {new Date().getFullYear()} {t('app.name')}</span> <button type="button" onClick={onRulesClick}>{t("rightSidebar.footRules")}</button>
<span>{t('rightSidebar.footRules')}</span> <button type="button" onClick={onReviewsClick}>{t("nav.reviews")}</button>
<span>{t('rightSidebar.footPrivacy')}</span> <button type="button" onClick={() => setSupportOpen(true)}>{t("rightSidebar.footSupport")}</button>
<span>{t('rightSidebar.footSupport')}</span> <span>© {new Date().getFullYear()} {t("app.name")}</span>
</div> </footer>
</div>
{supportOpen && <SupportModal onClose={() => setSupportOpen(false)} />}
</aside>
); );
} }

View File

@@ -15,7 +15,16 @@ import SupportModal from "./SupportModal";
import UploadAdModal from "./UploadAdModal"; import UploadAdModal from "./UploadAdModal";
import ProfileAvatar from "./profile/ProfileAvatar"; import ProfileAvatar from "./profile/ProfileAvatar";
import NahodkaLogo from "./MainNahodkaLogo"; import NahodkaLogo from "./MainNahodkaLogo";
import DesktopSidebar from "./desktop/DesktopSidebar";
/**
* @param {{
* open: boolean, activeNav: string, onClose: () => void, onNavClick: (key: string) => void,
* isAuthenticated: boolean, onLoginClick: () => void, onRulesClick?: () => void,
* onReviewsClick?: () => void, onCreatePost?: () => void, onProfileClick?: () => void,
* onMapClick?: () => void, profileData: any,
* }} props
*/
export default function Sidebar({ export default function Sidebar({
open, open,
activeNav, activeNav,
@@ -27,6 +36,7 @@ export default function Sidebar({
onReviewsClick, onReviewsClick,
onCreatePost, onCreatePost,
onProfileClick, onProfileClick,
onMapClick,
profileData, profileData,
}) { }) {
const navigate = useNavigate(); const navigate = useNavigate();
@@ -42,6 +52,25 @@ export default function Sidebar({
const [uploadAdOpen, setUploadAdOpen] = useState(false); const [uploadAdOpen, setUploadAdOpen] = useState(false);
const HelpIcon = NavIcons.help; const HelpIcon = NavIcons.help;
// Десктоп (>= 900px) — отдельная навигация с картой, CTA и свёрткой в рейку.
// Мобильный drawer ниже остаётся без изменений.
if (isDesktop) {
return (
<DesktopSidebar
activeNav={activeNav}
onNavClick={onNavClick}
isAuthenticated={isAuthenticated}
onLoginClick={onLoginClick}
onRulesClick={onRulesClick}
onReviewsClick={onReviewsClick || (() => navigate("/reviews"))}
onCreatePost={onCreatePost}
onProfileClick={onProfileClick}
onMapClick={onMapClick}
profileData={profileData}
/>
);
}
const handleNavItem = (itemKey) => { const handleNavItem = (itemKey) => {
if (!isAuthenticated && itemKey === "myads") { if (!isAuthenticated && itemKey === "myads") {
onLoginClick(); onLoginClick();

View File

@@ -0,0 +1,191 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import Sidebar from "../Sidebar";
import ChatListItem from "../chat/ChatListItem";
import Toast from "../Toast";
import AuthModal from "../AuthModal";
import { ProfileModal } from "../profile";
import RulesModal from "../../pages/RulesModal";
import ChatPage from "../../pages/ChatPage";
import { DesktopIcons } from "./DesktopIcons";
import { useChatList } from "../../hooks/useChatList";
import { useProfileData } from "../../hooks/useProfileData";
import { useAuthContext } from "../../context/AuthContext";
import { getPostForChat } from "../../stores/chatPostStore";
import { getChatDisplayInfo } from "../../utils/chatDisplay";
/**
* DesktopChats — двухпанельный мессенджер десктопа: список чатов слева,
* открытая переписка справа. Один компонент обслуживает /chats, /chats/new
* и /chats/:chatId, поэтому список не перезагружается при переключении чатов.
*/
export default function DesktopChats() {
const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const { chatId } = useParams();
const isDraft = location.pathname === "/chats/new";
const { user } = useAuthContext();
const profileData = useProfileData(user);
const {
chats, loading, fetchChats, unreadMap, isAuthenticated,
handleDeleteChat, deleteError, clearDeleteError,
} = useChatList();
const [query, setQuery] = useState("");
const [modal, setModal] = useState(null);
// Новое сообщение в открытом чате → обновляем превью в списке
// (с небольшой задержкой, чтобы сервер успел сохранить сообщение).
const refreshTimerRef = useRef(null);
const refreshList = useCallback(() => {
clearTimeout(refreshTimerRef.current);
refreshTimerRef.current = setTimeout(() => fetchChats({ silent: true }), 700);
}, [fetchChats]);
useEffect(() => () => clearTimeout(refreshTimerRef.current), []);
const items = useMemo(() => {
const q = query.trim().toLowerCase();
return chats
.map((chat) => {
const post = getPostForChat(chat.id);
const info = getChatDisplayInfo(chat, post, unreadMap, t);
return { chat, post, info };
})
.filter(({ info }) => !q
|| String(info.title || "").toLowerCase().includes(q)
|| String(info.preview || "").toLowerCase().includes(q));
}, [chats, unreadMap, query, t]);
const onDelete = async (id) => {
const deleted = await handleDeleteChat(id);
if (deleted && String(id) === String(chatId)) navigate("/chats", { replace: true });
};
const goFeed = (state) => navigate("/feed", state ? { state } : undefined);
return (
<div className="f-app fd-chats-app">
<Sidebar
open={false}
activeNav="chat"
onClose={() => {}}
onNavClick={(key) => goFeed({ desktopNav: key })}
isAuthenticated={isAuthenticated}
onLoginClick={() => setModal("auth")}
onRulesClick={() => setModal("rules")}
onReviewsClick={() => navigate("/reviews")}
onCreatePost={() => (isAuthenticated ? goFeed({ desktopAction: "create" }) : setModal("auth"))}
onProfileClick={() => setModal("profile")}
onMapClick={() => navigate("/feed?view=map")}
profileData={profileData}
/>
<div className="fd-chats">
<section className="fd-chats-list" aria-label={t("chat.chats")}>
<div className="fd-chats-list-head">
<h1 className="fd-chats-title">
{t("chat.chats")}
{chats.length > 0 && <span className="fd-chats-count">{chats.length}</span>}
</h1>
{isAuthenticated && chats.length > 0 && (
<label className="fd-chats-search">
<DesktopIcons.Search size={17} />
<input
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t("desktop.chats.search")}
aria-label={t("desktop.chats.search")}
/>
</label>
)}
</div>
<div className="fd-chats-scroll">
{!isAuthenticated ? (
<div className="fd-empty fd-empty-sm">
<div className="fd-empty-sub">{t("chat.loginToSee")}</div>
</div>
) : loading ? (
Array.from({ length: 7 }, (_, i) => (
<div key={i} className="fd-chat-skeleton" aria-hidden="true">
<span className="fd-skeleton fd-chat-skeleton-avatar" />
<span className="fd-chat-skeleton-lines">
<span className="fd-skeleton fd-skeleton-line" />
<span className="fd-skeleton fd-skeleton-line fd-skeleton-line-short" />
</span>
</div>
))
) : chats.length === 0 && !isDraft ? (
<div className="fd-empty fd-empty-sm">
<div className="fd-empty-icon"><DesktopIcons.Message size={24} /></div>
<div className="fd-empty-title">{t("chat.noChats")}</div>
</div>
) : items.length === 0 && !isDraft ? (
<div className="fd-empty fd-empty-sm">
<div className="fd-empty-sub">{t("desktop.chats.nothingFound")}</div>
</div>
) : (
<>
{isDraft && (
<div className="fd-chat-row is-active">
<div className="chat-list-item fd-chat-draft">
<div className="chat-list-avatar"><DesktopIcons.Plus size={18} /></div>
<div className="chat-list-info">
<div className="chat-list-name">{location.state?.post?.title || t("desktop.chats.newChat")}</div>
<div className="chat-list-preview">{t("desktop.chats.newChat")}</div>
</div>
</div>
</div>
)}
{items.map(({ chat, post }) => (
<div
key={chat.id}
className={`fd-chat-row${String(chat.id) === String(chatId) ? " is-active" : ""}`}
>
<ChatListItem
chat={chat}
post={post}
unreadMap={unreadMap}
t={t}
onOpen={(id) => navigate(`/chats/${id}`)}
onDelete={onDelete}
/>
</div>
))}
</>
)}
</div>
</section>
<section className="fd-chats-main">
{!isAuthenticated ? (
<div className="fd-chats-placeholder">
<div className="fd-chats-placeholder-icon"><DesktopIcons.Message size={30} /></div>
<div className="fd-empty-title">{t("chat.loginToSee")}</div>
<button type="button" className="fd-btn fd-btn-primary" onClick={() => setModal("auth")}>
{t("feed.login")}
</button>
</div>
) : chatId || isDraft ? (
<ChatPage key={chatId || "new"} embedded onActivity={refreshList} />
) : (
<div className="fd-chats-placeholder">
<div className="fd-chats-placeholder-icon"><DesktopIcons.Message size={30} /></div>
<div className="fd-empty-title">{t("desktop.chats.selectTitle")}</div>
<div className="fd-empty-sub">{t("desktop.chats.selectSub")}</div>
</div>
)}
</section>
</div>
{deleteError && <Toast message={deleteError} type="error" onDismiss={clearDeleteError} />}
{modal === "auth" && <AuthModal onClose={() => setModal(null)} />}
{modal === "rules" && <RulesModal onClose={() => setModal(null)} />}
{modal === "profile" && isAuthenticated && (
<ProfileModal onClose={() => setModal(null)} initialData={profileData} />
)}
</div>
);
}

View File

@@ -0,0 +1,131 @@
import { useTranslation } from "react-i18next";
import FeedSearchBar from "../feed/FeedSearchBar";
import CityFilter from "../CityFilter";
import { DesktopIcons } from "./DesktopIcons";
const TITLE_KEYS = {
home: "nav.home",
items: "nav.items",
pets: "nav.pets",
myads: "nav.myAds",
};
/**
* Сегментированный переключатель «Все / Потери / Находки».
* Индикатор активного сегмента — отдельный слой, который едет под кнопками.
*/
export function TypeSegment({ value, onChange, size = "md" }) {
const { t } = useTranslation();
const options = [
{ key: null, label: t("desktop.typeAll") },
{ key: "loss", label: t("feed.filterLoss"), tone: "loss" },
{ key: "found", label: t("feed.filterFound"), tone: "found" },
];
const activeIndex = Math.max(0, options.findIndex((o) => o.key === value));
return (
<div
className={`fd-segment fd-segment-${size}`}
role="radiogroup"
aria-label={String(t("feed.openFilter"))}
style={{ "--fd-seg-index": activeIndex, "--fd-seg-count": options.length }}
>
<span className="fd-segment-thumb" aria-hidden="true" />
{options.map((opt) => (
<button
key={opt.key ?? "all"}
type="button"
role="radio"
aria-checked={value === opt.key}
className={`fd-segment-btn${value === opt.key ? " is-active" : ""}`}
onClick={() => onChange(opt.key)}
>
{opt.tone && <span className={`fd-dot fd-dot-${opt.tone}`} aria-hidden="true" />}
{opt.label}
</button>
))}
</div>
);
}
/**
* DesktopFeedHeader — шапка ленты на десктопе: заголовок раздела, счётчик,
* фильтр «потеря/находка», поиск с подсказками и мультивыбор городов.
* На мобильном не рендерится (там FeedTopBar + шапка поиска).
*/
export default function DesktopFeedHeader({
activeNav,
typeFilter,
onTypeFilterChange,
searchQuery,
onSearchChange,
cities,
selectedCities,
onCitiesChange,
count,
loading,
onMapClick,
}) {
const { t } = useTranslation();
const searching = searchQuery.trim().length > 0 || selectedCities.length > 0;
const titleKey = TITLE_KEYS[activeNav] || "nav.home";
const showSearch = activeNav !== "myads";
const hasFilters = searching || typeFilter != null;
const reset = () => {
onSearchChange("");
onCitiesChange([]);
onTypeFilterChange(null);
};
return (
<header className="fd-feed-header">
<div className="fd-feed-header-inner">
<div className="fd-feed-title-row">
<div className="fd-feed-title-block">
<h1 className="fd-feed-title">
{searching ? t("desktop.searchResults") : t(titleKey)}
</h1>
<p className="fd-feed-sub">
{t(`desktop.feedSub.${TITLE_KEYS[activeNav] ? activeNav : "home"}`)}
{!loading && count > 0 && (
<>
<span className="fd-sep" aria-hidden="true">·</span>
<span className="fd-feed-count">{t("desktop.shown", { count })}</span>
</>
)}
</p>
</div>
<div className="fd-feed-title-actions">
{hasFilters && (
<button type="button" className="fd-link-btn" onClick={reset}>
<DesktopIcons.Close size={16} />
{t("desktop.resetFilters")}
</button>
)}
{onMapClick && (
<button type="button" className="fd-ghost-btn" onClick={onMapClick}>
<DesktopIcons.Map size={18} />
{t("nav.map")}
</button>
)}
</div>
</div>
<div className="fd-feed-controls">
<TypeSegment value={typeFilter} onChange={onTypeFilterChange} />
{showSearch && (
<div className="fd-feed-search">
<FeedSearchBar value={searchQuery} onChange={onSearchChange} t={t} />
</div>
)}
{activeNav === "home" && (
<div className="fd-feed-city">
<CityFilter cities={cities} value={selectedCities} onChange={onCitiesChange} />
</div>
)}
</div>
</div>
</header>
);
}

View File

@@ -0,0 +1,82 @@
// Линейные иконки десктопной раскладки (единый стиль: 24×24, stroke 2).
const base = {
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
strokeWidth: 2,
strokeLinecap: "round",
strokeLinejoin: "round",
"aria-hidden": true,
};
const Svg = ({ size = 20, children, ...rest }) => (
<svg width={size} height={size} {...base} {...rest}>{children}</svg>
);
export const DesktopIcons = {
Map: (p) => (
<Svg {...p}>
<path d="M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z" />
<path d="M15 5.764v15" />
<path d="M9 3.236v15" />
</Svg>
),
Plus: (p) => (
<Svg strokeWidth={2.4} {...p}>
<path d="M12 5v14" />
<path d="M5 12h14" />
</Svg>
),
User: (p) => (
<Svg {...p}>
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</Svg>
),
Pin: (p) => (
<Svg {...p}>
<path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0" />
<circle cx="12" cy="10" r="3" />
</Svg>
),
ArrowRight: (p) => (
<Svg {...p}>
<path d="M5 12h14" />
<path d="m12 5 7 7-7 7" />
</Svg>
),
ChevronRight: (p) => (
<Svg {...p}>
<path d="m9 18 6-6-6-6" />
</Svg>
),
Search: (p) => (
<Svg {...p}>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</Svg>
),
Message: (p) => (
<Svg {...p}>
<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z" />
</Svg>
),
Close: (p) => (
<Svg {...p}>
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</Svg>
),
Sparkles: (p) => (
<Svg {...p}>
<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z" />
</Svg>
),
Image: (p) => (
<Svg {...p}>
<rect width="18" height="18" x="3" y="3" rx="2" />
<circle cx="9" cy="9" r="2" />
<path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
</Svg>
),
};

View File

@@ -0,0 +1,163 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import MapView from "../MapView";
import { TypeSegment } from "./DesktopFeedHeader";
import { DesktopIcons } from "./DesktopIcons";
import { getImageUrl } from "../../config/authConstants";
import { CATEGORIES } from "../../config/feedConstants";
// Список рендерим ограниченным: в крупном масштабе в область могут попасть
// сотни меток, а пользователю всё равно нужен ближайший десяток.
const LIST_LIMIT = 150;
/**
* DesktopMapView — карта объявлений для десктопа: слева панель с фильтрами
* и списком объявлений из видимой области, справа карта.
* Наведение на карточку подсвечивает метку и наоборот; клик по карточке
* открывает объявление, кнопка с пином — плавно перелетает к метке.
*/
export default function DesktopMapView({ focusPostId, focusLat, focusLng, onPostClick }) {
const { t } = useTranslation();
const [type, setType] = useState(null);
const [category, setCategory] = useState(null);
const [markers, setMarkers] = useState(null);
const [hoverId, setHoverId] = useState(null);
const [focusTarget, setFocusTarget] = useState(null);
const listRef = useRef(null);
const handleMarkers = useCallback((list) => setMarkers(list), []);
// Наведение на метку карты: подсвечиваем карточку и докручиваем к ней список.
const handleMarkerHover = useCallback((id) => {
setHoverId(id);
if (id == null) return;
const node = listRef.current?.querySelector(`[data-item-id="${CSS.escape(String(id))}"]`);
node?.scrollIntoView({ block: "nearest", behavior: "smooth" });
}, []);
// Открытие с фокусом на объявлении — сразу подсвечиваем его в списке.
useEffect(() => {
if (focusPostId != null) setHoverId(String(focusPostId));
}, [focusPostId]);
const visible = markers ? markers.slice(0, LIST_LIMIT) : [];
return (
<div className="fd-map">
<aside className="fd-map-panel">
<div className="fd-map-panel-head">
<h1 className="fd-map-title-h">{t("desktop.map.title")}</h1>
<TypeSegment value={type} onChange={setType} size="sm" />
<div className="fd-chips" role="radiogroup" aria-label={t("post.category")}>
<button
type="button"
role="radio"
aria-checked={category == null}
className={`fd-chip${category == null ? " is-active" : ""}`}
onClick={() => setCategory(null)}
>
{t("desktop.map.catAll")}
</button>
{CATEGORIES.map((c) => (
<button
key={c.value}
type="button"
role="radio"
aria-checked={category === c.value}
className={`fd-chip${category === c.value ? " is-active" : ""}`}
onClick={() => setCategory(c.value)}
>
{t(c.labelKey)}
</button>
))}
</div>
<div className="fd-map-count">
{markers == null
? t("desktop.map.loading")
: t("desktop.map.inArea", { count: markers.length })}
</div>
</div>
<div className="fd-map-list" ref={listRef}>
{markers == null && (
Array.from({ length: 6 }, (_, i) => (
<div key={i} className="fd-map-item fd-skeleton-item" aria-hidden="true">
<span className="fd-map-item-thumb fd-skeleton" />
<span className="fd-map-item-body">
<span className="fd-skeleton fd-skeleton-line" />
<span className="fd-skeleton fd-skeleton-line fd-skeleton-line-short" />
</span>
</div>
))
)}
{markers != null && markers.length === 0 && (
<div className="fd-empty fd-empty-sm">
<div className="fd-empty-icon"><DesktopIcons.Pin size={26} /></div>
<div className="fd-empty-title">{t("desktop.map.emptyArea")}</div>
<div className="fd-empty-sub">{t("desktop.map.emptyAreaSub")}</div>
</div>
)}
{visible.map((m) => {
const id = String(m.id);
const img = m.imageUrl ? getImageUrl(m.imageUrl) : null;
const isFound = m.type === "FOUND";
return (
<div
key={id}
data-item-id={id}
className={`fd-map-item${hoverId === id ? " is-hl" : ""}`}
onMouseEnter={() => setHoverId(id)}
onMouseLeave={() => setHoverId(null)}
>
<button
type="button"
className="fd-map-item-main"
onClick={() => onPostClick(id)}
title={t("desktop.map.open")}
>
<span className="fd-map-item-thumb">
{img
? <img src={img} alt="" loading="lazy" decoding="async" />
: <DesktopIcons.Image size={20} />}
</span>
<span className="fd-map-item-body">
<span className="fd-map-item-title">{m.title}</span>
<span className={`fd-badge ${isFound ? "fd-badge-found" : "fd-badge-loss"}`}>
{isFound ? t("postCard.found") : t("postCard.loss")}
</span>
</span>
</button>
<button
type="button"
className="fd-icon-btn fd-map-item-locate"
onClick={() => setFocusTarget({ lat: m.latitude, lng: m.longitude })}
title={t("desktop.map.showOnMap")}
aria-label={t("desktop.map.showOnMap")}
>
<DesktopIcons.Pin size={18} />
</button>
</div>
);
})}
</div>
</aside>
<div className="fd-map-canvas">
<MapView
focusPostId={focusPostId}
focusLat={focusLat}
focusLng={focusLng}
type={type}
category={category}
onPostClick={onPostClick}
onMarkersChange={handleMarkers}
onMarkerHover={handleMarkerHover}
highlightId={hoverId}
focusTarget={focusTarget}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,240 @@
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { NavIcons } from "../icons/NavIcons";
import SunIcon from "../icons/SunIcon";
import MoonIcon from "../icons/MoonIcon";
import GlobeIcon from "../icons/GlobeIcon";
import NahodkaLogo from "../MainNahodkaLogo";
import ProfileAvatar from "../profile/ProfileAvatar";
import SupportModal from "../SupportModal";
import UploadAdModal from "../UploadAdModal";
import { useTheme } from "../../context/ThemeContext";
import { useUnread } from "../../context/UnreadContext";
import { useAuthContext } from "../../context/AuthContext";
import { useLanguageToggle } from "../../hooks/useLanguageToggle";
import { DesktopIcons } from "./DesktopIcons";
// Порядок пунктов основной навигации десктопа. «Карта» есть только здесь:
// на мобильном она живёт в нижней панели (BottomNav).
const MAIN_NAV = [
{ key: "home", labelKey: "nav.home", icon: () => NavIcons.grid() },
{ key: "items", labelKey: "nav.items", icon: () => NavIcons.box() },
{ key: "pets", labelKey: "nav.pets", icon: () => NavIcons.paw() },
{ key: "map", labelKey: "nav.map", icon: () => <DesktopIcons.Map /> },
{ key: "myads", labelKey: "nav.myAds", icon: () => NavIcons.file() },
{ key: "chat", labelKey: "nav.chat", icon: () => NavIcons.chat() },
];
const ADMIN_NAV = [
{ key: "admin-campaigns", labelKey: "adminPanel.campaignsNav", icon: () => NavIcons.grid(), to: "/admin/ads" },
{ key: "admin-posts", labelKey: "adminPanel.postsNav", icon: () => NavIcons.rules(), to: "/admin/ads?tab=posts" },
{ key: "admin-posts-rejected", labelKey: "adminPanel.postsRejectedNav", icon: () => NavIcons.rules(), to: "/admin/ads?tab=rejected" },
];
/**
* DesktopSidebar — левая навигация десктопной раскладки (>= 900px).
*
* На 900–1199px автоматически сворачивается в узкую «рейку» с иконками
* (подписи скрываются CSS-ом, остаются title-подсказки), на >= 1200px —
* полная панель с подписями. Мобильный drawer — отдельный компонент Sidebar.
*/
export default function DesktopSidebar({
activeNav,
onNavClick,
isAuthenticated,
onLoginClick,
onRulesClick,
onReviewsClick,
onCreatePost,
onProfileClick,
onMapClick,
profileData,
}) {
const navigate = useNavigate();
const { t } = useTranslation();
const { isAdmin } = useAuthContext();
const { theme, toggle: toggleTheme } = useTheme();
const { totalUnread } = useUnread();
const { language, toggleLanguage } = useLanguageToggle();
const [supportOpen, setSupportOpen] = useState(false);
const [uploadAdOpen, setUploadAdOpen] = useState(false);
const profileName = `${profileData?.firstName || ""} ${profileData?.lastName || ""}`.trim();
const handleMain = (key) => {
if (key === "chat") {
if (!isAuthenticated) onLoginClick();
else navigate("/chats");
return;
}
if (key === "myads" && !isAuthenticated) {
onLoginClick();
return;
}
if (key === "map") {
if (onMapClick) onMapClick();
else navigate("/feed?view=map");
return;
}
onNavClick(key);
};
const handleProfile = () => {
if (!isAuthenticated) onLoginClick();
else onProfileClick?.();
};
return (
<>
<aside className="fd-sidebar" aria-label={t("feed.openMenu")}>
<div className="fd-sb-head">
<button
type="button"
className="fd-sb-logo"
onClick={() => navigate("/")}
title={t("app.name")}
aria-label={t("app.name")}
>
<NahodkaLogo className="fd-sb-logo-full" />
<img src="/favicon.svg" alt="" className="fd-sb-logo-mark" />
</button>
</div>
<button
type="button"
className="fd-sb-cta"
onClick={onCreatePost}
title={t("desktop.createPost")}
>
<DesktopIcons.Plus />
<span className="fd-sb-label">{t("desktop.createPost")}</span>
</button>
<nav className="fd-sb-nav">
{MAIN_NAV.map(({ key, labelKey, icon }) => (
<button
type="button"
key={key}
className={`fd-sb-item${activeNav === key ? " is-active" : ""}`}
onClick={() => handleMain(key)}
title={t(labelKey)}
aria-current={activeNav === key ? "page" : undefined}
>
<span className="fd-sb-icon">
{icon()}
{key === "chat" && totalUnread > 0 && <span className="fd-sb-dot" />}
</span>
<span className="fd-sb-label">{t(labelKey)}</span>
{key === "chat" && totalUnread > 0 && (
<span className="fd-sb-badge">{totalUnread > 99 ? "99+" : totalUnread}</span>
)}
</button>
))}
{isAdmin && (
<>
<div className="fd-sb-section">{t("desktop.adminSection")}</div>
<button
type="button"
className="fd-sb-item"
onClick={() => setUploadAdOpen(true)}
title={t("admin.uploadAd")}
>
<span className="fd-sb-icon">{NavIcons.megaphone()}</span>
<span className="fd-sb-label">{t("admin.uploadAd")}</span>
</button>
{ADMIN_NAV.map(({ key, labelKey, icon, to }) => (
<button
type="button"
key={key}
className={`fd-sb-item${activeNav === key ? " is-active" : ""}`}
onClick={() => navigate(to)}
title={t(labelKey)}
>
<span className="fd-sb-icon">{icon()}</span>
<span className="fd-sb-label">{t(labelKey)}</span>
</button>
))}
</>
)}
</nav>
<div className="fd-sb-bottom">
<button
type="button"
className={`fd-sb-item fd-sb-item-sm${activeNav === "reviews" ? " is-active" : ""}`}
onClick={onReviewsClick}
title={t("nav.reviews")}
>
<span className="fd-sb-icon">{NavIcons.star()}</span>
<span className="fd-sb-label">{t("nav.reviews")}</span>
</button>
<button
type="button"
className="fd-sb-item fd-sb-item-sm"
onClick={onRulesClick}
title={t("nav.rules")}
>
<span className="fd-sb-icon">{NavIcons.rules()}</span>
<span className="fd-sb-label">{t("nav.rules")}</span>
</button>
<button
type="button"
className="fd-sb-item fd-sb-item-sm"
onClick={() => setSupportOpen(true)}
title={t("nav.support")}
>
<span className="fd-sb-icon">{NavIcons.help()}</span>
<span className="fd-sb-label">{t("nav.support")}</span>
</button>
<div className="fd-sb-prefs">
<button
type="button"
className="fd-sb-pref"
onClick={toggleTheme}
title={theme === "dark" ? t("sidebar.lightTheme") : t("sidebar.darkTheme")}
aria-label={theme === "dark" ? t("sidebar.lightTheme") : t("sidebar.darkTheme")}
>
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
</button>
<button
type="button"
className="fd-sb-pref fd-sb-pref-lang"
onClick={toggleLanguage}
title={language === "ru" ? "English" : "Русский"}
aria-label={language === "ru" ? "English" : "Русский"}
>
<GlobeIcon />
<span>{language === "ru" ? "RU" : "EN"}</span>
</button>
</div>
<button
type="button"
className="fd-sb-profile"
onClick={handleProfile}
title={isAuthenticated ? t("desktop.myProfile") : t("feed.login")}
>
{isAuthenticated ? (
<ProfileAvatar avatar={profileData?.avatar} name={profileName} />
) : (
<span className="fd-sb-profile-guest"><DesktopIcons.User /></span>
)}
<span className="fd-sb-profile-info fd-sb-label">
<span className="fd-sb-profile-name">
{isAuthenticated ? profileName || profileData?.login : t("feed.login")}
</span>
<span className="fd-sb-profile-sub">
{isAuthenticated ? `@${profileData?.login || t("profile.default")}` : t("desktop.guestText")}
</span>
</span>
</button>
</div>
</aside>
{supportOpen && <SupportModal onClose={() => setSupportOpen(false)} />}
{uploadAdOpen && <UploadAdModal onClose={() => setUploadAdOpen(false)} />}
</>
);
}

67
src/hooks/useChatList.js Normal file
View File

@@ -0,0 +1,67 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useChats } from "./useChats";
import { useDeleteChat } from "./useDeleteChat";
import { useAuthContext } from "../context/AuthContext";
import { useUnread } from "../context/UnreadContext";
/**
* Список чатов текущего пользователя: загрузка, фоновое обновление при новых
* непрочитанных (WS) и удаление с подтверждением. Общая логика мобильной
* страницы списка (ChatListPage) и десктопного двухпанельного мессенджера.
*/
export function useChatList() {
const { t } = useTranslation();
const { chats, loading, fetchChats } = useChats();
const { isAuthenticated } = useAuthContext();
const { unreadMap, totalUnread } = useUnread();
const { deleteChat } = useDeleteChat();
const [deleteError, setDeleteError] = useState("");
// Пропускаем первый прогон эффекта по totalUnread: на маунте список уже
// грузится первым эффектом, и без этого guard'а через 500 мс уходил бы
// второй, повторный запрос (страница "моргала" и грузилась дважды).
const unreadWatcherReadyRef = useRef(false);
useEffect(() => {
if (isAuthenticated) {
fetchChats();
}
}, [isAuthenticated, fetchChats]);
// При поступлении непрочитанного сообщения (WS) обновляем список, чтобы
// превью показывало новое сообщение и подсветку, не дожидаясь ручного обновления.
useEffect(() => {
if (!isAuthenticated) return;
if (!unreadWatcherReadyRef.current) {
unreadWatcherReadyRef.current = true;
return;
}
const timer = setTimeout(() => fetchChats({ silent: true }), 500);
return () => clearTimeout(timer);
// totalUnread — числовое значение, поэтому изменение состава чатов с той же
// суммой не создаст цикл обновлений.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [totalUnread, isAuthenticated, fetchChats]);
const handleDeleteChat = useCallback(async (chatId) => {
if (!window.confirm(t('chat.confirmDeleteChat'))) return false;
const result = await deleteChat(chatId);
if (result.success) {
fetchChats({ silent: true });
return true;
}
setDeleteError(result.error);
return false;
}, [t, deleteChat, fetchChats]);
return {
chats,
loading,
fetchChats,
unreadMap,
isAuthenticated,
handleDeleteChat,
deleteError,
clearDeleteError: () => setDeleteError(""),
};
}

View File

@@ -0,0 +1,22 @@
import { useMemo } from "react";
import { getImageUrl } from "../config/authConstants";
/**
* Данные профиля для навигации/аватаров из пользователя AuthContext
* (та же нормализация, что в ленте и на странице отзывов).
*/
export function useProfileData(user) {
return useMemo(() => {
if (!user) return {};
const nameParts = (user.name || "").trim().split(/\s+/);
return {
login: user.login || "",
firstName: user.firstName || nameParts[0] || "",
lastName: user.lastName || nameParts.slice(1).join(" ") || "",
email: user.email || "",
phone: user.phone || "",
avatar: getImageUrl(user.avatar),
id: user.id,
};
}, [user]);
}

View File

@@ -617,5 +617,51 @@
"openLink": "Open ad in a new tab", "openLink": "Open ad in a new tab",
"closeIn": "Close in {{seconds}}s", "closeIn": "Close in {{seconds}}s",
"close": "Close ad" "close": "Close ad"
},
"desktop": {
"createPost": "Post a listing",
"typeAll": "All",
"feedSub": {
"home": "Lost and found items and pets",
"items": "Documents, keys, electronics, bags and more",
"pets": "Lost and found animals",
"myads": "Your listings: edit, close or bring them back to the feed"
},
"shown": "Showing {{count}}",
"searchResults": "Search results",
"resetFilters": "Reset filters",
"ctaTitle": "Lost or found something?",
"ctaText": "Post a listing in a minute — people nearby will see it.",
"mapCardTitle": "Listings on the map",
"mapCardText": "See where things were lost and found nearby",
"mapCardBtn": "Open map",
"fresh": "Fresh listings",
"seeAll": "All",
"freshEmpty": "No new listings yet",
"guestTitle": "Welcome",
"guestText": "Sign in to post listings and message authors",
"myProfile": "My profile",
"settings": "Settings",
"collapse": "Collapse menu",
"expand": "Expand menu",
"map": {
"title": "Listings map",
"inArea": "In this area: {{count}}",
"emptyArea": "No listings here yet",
"emptyAreaSub": "Zoom out or move to another area",
"catAll": "All categories",
"loading": "Loading listings…",
"showOnMap": "Show on map",
"open": "Open"
},
"chats": {
"selectTitle": "Select a chat",
"selectSub": "Open a conversation on the left to keep talking with the listing author",
"search": "Search chats",
"nothingFound": "Nothing found",
"newChat": "New chat"
},
"adminSection": "Administration",
"reviewsSub": "What people think about Nakhodka — and a place for your opinion"
} }
} }

View File

@@ -617,5 +617,51 @@
"openLink": "Открыть рекламу в новой вкладке", "openLink": "Открыть рекламу в новой вкладке",
"closeIn": "Закрыть через {{seconds}}с", "closeIn": "Закрыть через {{seconds}}с",
"close": "Закрыть рекламу" "close": "Закрыть рекламу"
},
"desktop": {
"createPost": "Разместить объявление",
"typeAll": "Все",
"feedSub": {
"home": "Потерянные и найденные вещи и питомцы",
"items": "Документы, ключи, электроника, сумки и другое",
"pets": "Потерявшиеся и найденные животные",
"myads": "Ваши объявления: редактируйте, закрывайте, возвращайте в ленту"
},
"shown": "Показано {{count}}",
"searchResults": "Результаты поиска",
"resetFilters": "Сбросить фильтры",
"ctaTitle": "Потеряли или нашли?",
"ctaText": "Разместите объявление за минуту — его увидят люди рядом с вами.",
"mapCardTitle": "Объявления на карте",
"mapCardText": "Смотрите, где теряли и находили вещи поблизости",
"mapCardBtn": "Открыть карту",
"fresh": "Свежие объявления",
"seeAll": "Все",
"freshEmpty": "Пока нет новых объявлений",
"guestTitle": "Добро пожаловать",
"guestText": "Войдите, чтобы размещать объявления и писать авторам",
"myProfile": "Мой профиль",
"settings": "Настройки",
"collapse": "Свернуть меню",
"expand": "Развернуть меню",
"map": {
"title": "Карта объявлений",
"inArea": "В этой области: {{count}}",
"emptyArea": "Здесь пока нет объявлений",
"emptyAreaSub": "Отдалите карту или переместитесь в другой район",
"catAll": "Все категории",
"loading": "Загружаем объявления…",
"showOnMap": "Показать на карте",
"open": "Открыть"
},
"chats": {
"selectTitle": "Выберите чат",
"selectSub": "Откройте переписку слева, чтобы продолжить общение с автором объявления",
"search": "Поиск по чатам",
"nothingFound": "Ничего не найдено",
"newChat": "Новый чат"
},
"adminSection": "Администрирование",
"reviewsSub": "Что пользователи думают о Находке — и место для вашего мнения"
} }
} }

View File

@@ -1,11 +1,7 @@
import { useEffect, useState, useCallback, useRef } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useChats } from "../hooks/useChats";
import { useAuthContext } from "../context/AuthContext";
import { useUnread } from "../context/UnreadContext";
import { getPostForChat } from "../stores/chatPostStore"; import { getPostForChat } from "../stores/chatPostStore";
import { useDeleteChat } from "../hooks/useDeleteChat"; import { useChatList } from "../hooks/useChatList";
import ChatHeader from "../components/chat/ChatHeader"; import ChatHeader from "../components/chat/ChatHeader";
import ChatListItem from "../components/chat/ChatListItem"; import ChatListItem from "../components/chat/ChatListItem";
import Toast from "../components/Toast"; import Toast from "../components/Toast";
@@ -13,46 +9,10 @@ import Toast from "../components/Toast";
export default function ChatListPage() { export default function ChatListPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
const { chats, loading, fetchChats } = useChats(); const {
const { isAuthenticated } = useAuthContext(); chats, loading, unreadMap, isAuthenticated,
const { unreadMap, totalUnread } = useUnread(); handleDeleteChat, deleteError, clearDeleteError,
const { deleteChat } = useDeleteChat(); } = useChatList();
const [deleteError, setDeleteError] = useState("");
// Пропускаем первый прогон эффекта по totalUnread: на маунте список уже
// грузится первым эффектом, и без этого guard'а через 500 мс уходил бы
// второй, повторный запрос (страница "моргала" и грузилась дважды).
const unreadWatcherReadyRef = useRef(false);
useEffect(() => {
if (isAuthenticated) {
fetchChats();
}
}, [isAuthenticated, fetchChats]);
// При поступлении непрочитанного сообщения (WS) обновляем список, чтобы
// превью показывало новое сообщение и подсветку, не дожидаясь ручного обновления.
useEffect(() => {
if (!isAuthenticated) return;
if (!unreadWatcherReadyRef.current) {
unreadWatcherReadyRef.current = true;
return;
}
const timer = setTimeout(() => fetchChats({ silent: true }), 500);
return () => clearTimeout(timer);
// totalUnread — числовое значение, поэтому изменение состава чатов с той же
// суммой не создаст цикл обновлений.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [totalUnread, isAuthenticated, fetchChats]);
const handleDeleteChat = useCallback(async (chatId) => {
if (!window.confirm(t('chat.confirmDeleteChat'))) return;
const result = await deleteChat(chatId);
if (result.success) {
fetchChats({ silent: true });
} else {
setDeleteError(result.error);
}
}, [t, deleteChat, fetchChats]);
const goBack = () => navigate("/feed"); const goBack = () => navigate("/feed");
const openChat = (chatId) => navigate(`/chats/${chatId}`); const openChat = (chatId) => navigate(`/chats/${chatId}`);
@@ -100,7 +60,7 @@ export default function ChatListPage() {
<Toast <Toast
message={deleteError} message={deleteError}
type="error" type="error"
onDismiss={() => setDeleteError("")} onDismiss={clearDeleteError}
/> />
)} )}
</div> </div>

View File

@@ -15,7 +15,14 @@ import MessageBubble from "../components/chat/MessageBubble";
import ChatInputBar from "../components/chat/ChatInputBar"; import ChatInputBar from "../components/chat/ChatInputBar";
import Toast from "../components/Toast"; import Toast from "../components/Toast";
export default function ChatPage() { /**
* Открытый чат. На мобильном — отдельная страница; на десктопе встраивается
* правой панелью мессенджера (embedded): без собственной обёртки .f-app,
* а onActivity сообщает списку чатов, что превью пора обновить.
*
* @param {{ embedded?: boolean, onActivity?: () => void }} [props]
*/
export default function ChatPage({ embedded = false, onActivity } = {}) {
const { t } = useTranslation(); const { t } = useTranslation();
const { chatId } = useParams(); const { chatId } = useParams();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -122,6 +129,7 @@ export default function ChatPage() {
startChat(draft.otherUserId, draft.postId, trimmed, draft.post) startChat(draft.otherUserId, draft.postId, trimmed, draft.post)
.then((chat) => { .then((chat) => {
setInput(""); setInput("");
onActivity?.();
navigate(`/chats/${chat.id}`, { replace: true }); navigate(`/chats/${chat.id}`, { replace: true });
}) })
// 429 — лимит начала чатов; 400 — чат с собой, чужое объявление и т.п. // 429 — лимит начала чатов; 400 — чат с собой, чужое объявление и т.п.
@@ -136,14 +144,15 @@ export default function ChatPage() {
return; return;
} }
setInput(""); setInput("");
}, [input, sendMessage, t, draft, startingChat, startChat, navigate]); onActivity?.();
}, [input, sendMessage, t, draft, startingChat, startChat, navigate, onActivity]);
const post = draft ? draft.post : getPostForChat(chatId); const post = draft ? draft.post : getPostForChat(chatId);
const postImg = getImageUrl(post?.images?.[0]); const postImg = getImageUrl(post?.images?.[0]);
return ( const content = (
<div className="f-app"> <>
<div className="chat-page chat-page--open" ref={pageRef}> <div className={`chat-page chat-page--open${embedded ? " chat-page--embedded" : ""}`} ref={pageRef}>
<ChatHeader <ChatHeader
title={post?.title || t('chat.title')} title={post?.title || t('chat.title')}
onBack={() => navigate("/chats")} onBack={() => navigate("/chats")}
@@ -181,6 +190,8 @@ export default function ChatPage() {
onDismiss={() => setSendError("")} onDismiss={() => setSendError("")}
/> />
)} )}
</div> </>
); );
return embedded ? content : <div className="f-app">{content}</div>;
} }

View File

@@ -18,6 +18,8 @@ import CityQuickFilterLegacy from "../components/feed/CityQuickFilter";
import FeedContent from "../components/feed/FeedContent"; import FeedContent from "../components/feed/FeedContent";
import PullToRefresh from "../components/feed/PullToRefresh"; import PullToRefresh from "../components/feed/PullToRefresh";
import MapView from "../components/MapView"; import MapView from "../components/MapView";
import DesktopFeedHeaderLegacy from "../components/desktop/DesktopFeedHeader";
import DesktopMapViewLegacy from "../components/desktop/DesktopMapView";
import PostDetailModal from "../components/PostDetailModal"; import PostDetailModal from "../components/PostDetailModal";
import { useAuthContext } from "../context/AuthContext"; import { useAuthContext } from "../context/AuthContext";
import { useCities } from "../hooks/useCities"; import { useCities } from "../hooks/useCities";
@@ -42,6 +44,8 @@ import type { ComponentType } from "react";
const CityFilter = CityFilterLegacy as unknown as ComponentType<any>; const CityFilter = CityFilterLegacy as unknown as ComponentType<any>;
const CityQuickFilter = CityQuickFilterLegacy as unknown as ComponentType<any>; const CityQuickFilter = CityQuickFilterLegacy as unknown as ComponentType<any>;
const CreateUpdatePost = CreateUpdatePostLegacy as unknown as ComponentType<any>; const CreateUpdatePost = CreateUpdatePostLegacy as unknown as ComponentType<any>;
const DesktopFeedHeader = DesktopFeedHeaderLegacy as unknown as ComponentType<any>;
const DesktopMapView = DesktopMapViewLegacy as unknown as ComponentType<any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
type AnyAds = any[]; type AnyAds = any[];
@@ -198,6 +202,21 @@ export default function MainFeed() {
} }
}, [location.state]); // eslint-disable-line react-hooks/exhaustive-deps }, [location.state]); // eslint-disable-line react-hooks/exhaustive-deps
// Десктопная навигация с других страниц (чаты, отзывы): раздел ленты
// или сразу форма создания объявления.
useEffect(() => {
const state = location.state as { desktopNav?: string; desktopAction?: string } | null;
if (!state?.desktopNav && !state?.desktopAction) return;
if (state.desktopNav && ["home", "items", "pets", "myads"].includes(state.desktopNav)) {
setActiveNav(state.desktopNav);
}
if (state.desktopAction === "create") {
if (isAuthenticated) modals.open("create");
else modals.open("auth");
}
navigate(`${location.pathname}${location.search}`, { replace: true, state: null });
}, [location.state]); // eslint-disable-line react-hooks/exhaustive-deps
// При загрузке приложения подтягиваем свежие данные профиля (аватар и т.д.) // При загрузке приложения подтягиваем свежие данные профиля (аватар и т.д.)
// с бэка, чтобы нижняя навигация и профиль отражали изменения с других // с бэка, чтобы нижняя навигация и профиль отражали изменения с других
// устройств, а не устаревший кэш контекста. Дергаем один раз на пользователя. // устройств, а не устаревший кэш контекста. Дергаем один раз на пользователя.
@@ -226,6 +245,9 @@ export default function MainFeed() {
// вкладки (вещи/питомцы) и фильтра «потеря/находка» — их применяет сервер. // вкладки (вещи/питомцы) и фильтра «потеря/находка» — их применяет сервер.
useEffect(() => { useEffect(() => {
if (activeNav === "myads" || activeNav === "map") return; if (activeNav === "myads" || activeNav === "map") return;
// На десктопе поиск и фильтры живут прямо в ленте — загрузкой занимается
// отдельный эффект ниже (desktopLoadKeyRef), здесь запрос не дублируем.
if (isDesktop && !isSearchView) return;
if (!isSearchView && selectedCities.length === 0 && !searchQuery.trim()) { if (!isSearchView && selectedCities.length === 0 && !searchQuery.trim()) {
feed.loadFeed(0, "", false, feedFilters); feed.loadFeed(0, "", false, feedFilters);
} }
@@ -244,6 +266,28 @@ export default function MainFeed() {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchQuery, feedFiltersKey, isSearchView]); }, [searchQuery, feedFiltersKey, isSearchView]);
// Десктоп: поиск и города всегда в шапке ленты (без отдельной вкладки
// «Поиск»), поэтому текст/города/фильтры применяются сразу, текст — с
// дебаунсом. Ключ последней загрузки не даёт перезапрашивать ленту при
// возврате с карты, если фильтры не менялись.
const desktopLoadKeyRef = useRef<string | null>(null);
useEffect(() => {
if (!isDesktop || isSearchView) {
desktopLoadKeyRef.current = null;
return;
}
if (activeNav === "myads" || activeNav === "map") return;
const q = searchQuery.trim();
const key = `${q}|${feedFiltersKey}`;
if (key === desktopLoadKeyRef.current) return;
const timer = setTimeout(() => {
desktopLoadKeyRef.current = key;
feed.loadFeed(0, q, false, feedFilters);
}, q ? 400 : 0);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isDesktop, isSearchView, searchQuery, feedFiltersKey, activeNav]);
// Когда переключаемся на «Мои объявления» — подгружаем с бэкенда // Когда переключаемся на «Мои объявления» — подгружаем с бэкенда
useEffect(() => { useEffect(() => {
if (activeNav === "myads" && isAuthenticated && user?.id) { if (activeNav === "myads" && isAuthenticated && user?.id) {
@@ -442,11 +486,27 @@ export default function MainFeed() {
onReviewsClick={() => navigate("/reviews")} onReviewsClick={() => navigate("/reviews")}
onCreatePost={handleCreatePost} onCreatePost={handleCreatePost}
onProfileClick={() => modals.open("profile")} onProfileClick={() => modals.open("profile")}
onMapClick={handleMapClick}
profileData={profileData} profileData={profileData}
/> />
<div className="f-main f-main-feed"> <div className="f-main f-main-feed">
{/* Шапка поиска: на мобильном сворачивается при скролле вниз (grid 1fr → 0fr) */} {isDesktop ? (!isMapView && (
<DesktopFeedHeader
activeNav={activeNav}
typeFilter={typeFilter}
onTypeFilterChange={setTypeFilter}
searchQuery={searchQuery}
onSearchChange={setSearchQuery}
cities={cities}
selectedCities={selectedCities}
onCitiesChange={setSelectedCities}
count={filteredAds.length}
loading={listLoading}
onMapClick={handleMapClick}
/>
)) : (
/* Шапка поиска: на мобильном сворачивается при скролле вниз (grid 1fr → 0fr) */
<div className={`f-search-head${searchHeadHidden ? " is-hidden" : ""}`}> <div className={`f-search-head${searchHeadHidden ? " is-hidden" : ""}`}>
<div className="f-search-head-inner"> <div className="f-search-head-inner">
{isSearchView && ( {isSearchView && (
@@ -471,9 +531,17 @@ export default function MainFeed() {
</div> </div>
</div> </div>
</div> </div>
)}
<div className="f-wrap"> <div className="f-wrap">
{isMapView ? ( {isMapView && isDesktop ? (
<DesktopMapView
focusPostId={focusPostId}
focusLat={focusLat}
focusLng={focusLng}
onPostClick={handleMapPostClick}
/>
) : isMapView ? (
<MapView <MapView
focusPostId={focusPostId} focusPostId={focusPostId}
focusLat={focusLat} focusLat={focusLat}
@@ -498,6 +566,26 @@ export default function MainFeed() {
onRefresh={refreshCurrentList} onRefresh={refreshCurrentList}
disabled={isMapView || isSearchView || !["home", "items", "pets", "myads"].includes(activeNav)} disabled={isMapView || isSearchView || !["home", "items", "pets", "myads"].includes(activeNav)}
/> />
{isDesktop ? (
<div className="fd-grid">
<FeedContent
loading={listLoading}
citySearchActive={selectedCities.length > 0}
error={listError}
filteredAds={filteredAds}
activeNav={activeNav}
searchPrompt={searchPrompt}
showAds={showAds}
onEdit={handleEdit}
onDelete={actions.handleDelete}
onMarkFound={actions.handleMarkFound}
onReopen={actions.handleReopen}
onLocationClick={handleLocationClick}
onAuthRequired={() => modals.open("auth")}
t={t}
/>
</div>
) : (
<FeedContent <FeedContent
loading={listLoading} loading={listLoading}
citySearchActive={selectedCities.length > 0} citySearchActive={selectedCities.length > 0}
@@ -514,6 +602,7 @@ export default function MainFeed() {
onAuthRequired={() => modals.open("auth")} onAuthRequired={() => modals.open("auth")}
t={t} t={t}
/> />
)}
{infiniteFeed && !feed.loading && ( {infiniteFeed && !feed.loading && (
<div ref={sentinelRef} style={{ height: "1px" }} /> <div ref={sentinelRef} style={{ height: "1px" }} />
)} )}
@@ -544,6 +633,11 @@ export default function MainFeed() {
setSelectedCities([]); setSelectedCities([]);
if (isMapView || isSearchView) navigate("/feed"); if (isMapView || isSearchView) navigate("/feed");
}} }}
onCreatePost={handleCreatePost}
onMapClick={handleMapClick}
onPostClick={(postId: number) => modals.open("postDetail", { postId })}
onRulesClick={() => modals.open("rules")}
onReviewsClick={() => navigate("/reviews")}
/> />
</> </>
)} )}

View File

@@ -15,12 +15,14 @@ import { useReviews } from "../hooks/useReviews";
import "../styles/reviews.css"; import "../styles/reviews.css";
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useProfile } from "../hooks/useProfile"; import { useProfile } from "../hooks/useProfile";
import { useIsDesktop } from "../hooks/useIsDesktop";
export default function ReviewsPage() { export default function ReviewsPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
const { user, isAuthenticated, updateUser } = useAuthContext(); const { user, isAuthenticated, updateUser } = useAuthContext();
const { fetchProfile } = useProfile(); const { fetchProfile } = useProfile();
const isDesktop = useIsDesktop();
const [sidebarOpen, setSidebarOpen] = useState(false); const [sidebarOpen, setSidebarOpen] = useState(false);
const [profileModalOpen, setProfileModalOpen] = useState(false); const [profileModalOpen, setProfileModalOpen] = useState(false);
@@ -88,16 +90,25 @@ export default function ReviewsPage() {
open={sidebarOpen} open={sidebarOpen}
activeNav="reviews" activeNav="reviews"
onClose={() => setSidebarOpen(false)} onClose={() => setSidebarOpen(false)}
onNavClick={(key) => navigate("/feed")} onNavClick={(key) => navigate("/feed", isDesktop ? { state: { desktopNav: key } } : undefined)}
isAuthenticated={isAuthenticated} isAuthenticated={isAuthenticated}
onLoginClick={() => setAuthModalOpen(true)} onLoginClick={() => setAuthModalOpen(true)}
onRulesClick={() => setRulesModalOpen(true)} onRulesClick={() => setRulesModalOpen(true)}
onCreatePost={() => navigate("/feed")} onCreatePost={() => navigate("/feed", isDesktop ? { state: { desktopAction: "create" } } : undefined)}
onMapClick={() => navigate("/feed?view=map")}
onProfileClick={() => setProfileModalOpen(true)} onProfileClick={() => setProfileModalOpen(true)}
profileData={profileData} profileData={profileData}
/> />
<div className="f-main"> <div className="f-main">
{isDesktop ? (
<header className="fd-feed-header fd-page-header">
<div className="fd-feed-header-inner">
<h1 className="fd-feed-title">{t('reviews.title')}</h1>
<p className="fd-feed-sub">{t('desktop.reviewsSub')}</p>
</div>
</header>
) : (
<AppTopBar <AppTopBar
onMenuClick={() => setSidebarOpen((v) => !v)} onMenuClick={() => setSidebarOpen((v) => !v)}
isAuthenticated={isAuthenticated} isAuthenticated={isAuthenticated}
@@ -108,6 +119,7 @@ export default function ReviewsPage() {
centerContent={<h1 className="rv-page-title">{t('reviews.title')}</h1>} centerContent={<h1 className="rv-page-title">{t('reviews.title')}</h1>}
hideWordmark hideWordmark
/> />
)}
<div className="rv-scroll" ref={scrollRef}> <div className="rv-scroll" ref={scrollRef}>
<PullToRefresh containerRef={scrollRef} onRefresh={refreshReviews} disabled={loading} /> <PullToRefresh containerRef={scrollRef} onRefresh={refreshReviews} disabled={loading} />

1053
src/styles/desktop.css Normal file

File diff suppressed because it is too large Load Diff

27
src/utils/relativeTime.js Normal file
View File

@@ -0,0 +1,27 @@
const UNITS = [
["year", 365 * 24 * 3600],
["month", 30 * 24 * 3600],
["week", 7 * 24 * 3600],
["day", 24 * 3600],
["hour", 3600],
["minute", 60],
];
/**
* «5 минут назад», «вчера», «2 недели назад» — по языку интерфейса.
* Возвращает null для пустой/некорректной даты.
*/
export function formatRelativeTime(value, language = "ru", now = Date.now()) {
if (!value) return null;
const time = new Date(value).getTime();
if (!Number.isFinite(time)) return null;
const diffSec = Math.round((time - now) / 1000);
const abs = Math.abs(diffSec);
const rtf = new Intl.RelativeTimeFormat(language, { numeric: "auto" });
for (const [unit, sec] of UNITS) {
if (abs >= sec) return rtf.format(Math.round(diffSec / sec), unit);
}
return rtf.format(0, "minute");
}