fix bug and errors
This commit is contained in:
38
src/App.css
38
src/App.css
@@ -1,38 +0,0 @@
|
||||
.App {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.App-logo {
|
||||
height: 40vmin;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.App-logo {
|
||||
animation: App-logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.App-header {
|
||||
background-color: #282c34;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: calc(10px + 2vmin);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.App-link {
|
||||
color: #61dafb;
|
||||
}
|
||||
|
||||
@keyframes App-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@@ -63,30 +63,3 @@ export function putWithProgress(url, file, onProgress) {
|
||||
xhr.send(file);
|
||||
});
|
||||
}
|
||||
|
||||
export async function uploadAdVideo(advertisingId, file, onProgress) {
|
||||
const presignRes = await apiFetch(
|
||||
`${API_URL}/api/v1/admin/ads/${advertisingId}/video/presign-upload`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ contentType: file.type }),
|
||||
}
|
||||
);
|
||||
if (!presignRes.ok) throw new Error(`Presign failed (${presignRes.status})`);
|
||||
const { uploadUrl, sourceKey } = await presignRes.json();
|
||||
|
||||
await putWithProgress(uploadUrl, file, onProgress);
|
||||
|
||||
const confirmRes = await apiFetch(
|
||||
`${API_URL}/api/v1/admin/ads/${advertisingId}/video/confirm-upload`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sourceKey }),
|
||||
}
|
||||
);
|
||||
if (!confirmRes.ok) throw new Error(`Confirm failed (${confirmRes.status})`);
|
||||
|
||||
return { sourceKey };
|
||||
}
|
||||
@@ -106,7 +106,7 @@ function LoginFormInline({ saveAuth, onClose, onSwitch }) {
|
||||
|
||||
<p style={{textAlign: "center", marginTop: 14, color: "var(--muted)", fontSize: ".85rem"}}>
|
||||
{t('auth.noAccount')}{" "}
|
||||
<button onClick={onSwitch}
|
||||
<button type="button" onClick={onSwitch}
|
||||
style={{background: "none", border: "none", color: "var(--teal)", cursor: "pointer", fontWeight: 700, fontSize: ".85rem", fontFamily: "var(--font)",}}
|
||||
>
|
||||
{t('auth.register')}
|
||||
@@ -224,7 +224,7 @@ function RegisterFormInline({ saveAuth, onClose, onSwitch }) {
|
||||
|
||||
<p style={{textAlign: "center", marginTop: 14, color: "var(--muted)", fontSize: ".85rem"}}>
|
||||
{t('auth.hasAccount')}{" "}
|
||||
<button onClick={onSwitch}
|
||||
<button type="button" onClick={onSwitch}
|
||||
style={{background: "none", border: "none", color: "var(--teal)", cursor: "pointer", fontWeight: 700, fontSize: ".85rem", fontFamily: "var(--font)",}}>
|
||||
{t('auth.loginLink')}
|
||||
</button>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { API_URL, getImageUrl } from "../config/authConstants";
|
||||
import { useGeolocation, GEO_STATUS } from "../hooks/useGeolocation";
|
||||
import { whenYmapsReady } from "../utils/ymapsApi";
|
||||
|
||||
const MARKER_COLORS = {
|
||||
LOST: "#ff3b30",
|
||||
@@ -118,6 +119,10 @@ export default function MapView({
|
||||
onBack,
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// tRef нужен, чтобы читать перевод из эффектов, не добавляя t в их deps:
|
||||
// иначе смена языка пересоздавала бы карту и все маркеры с нуля.
|
||||
const tRef = useRef(t);
|
||||
tRef.current = t;
|
||||
const mapRef = useRef(null);
|
||||
const ymapRef = useRef(null);
|
||||
const userMarkerRef = useRef(null);
|
||||
@@ -319,9 +324,20 @@ export default function MapView({
|
||||
}
|
||||
};
|
||||
|
||||
if (window.ymaps?.ready) {
|
||||
window.ymaps.ready(init);
|
||||
}
|
||||
whenYmapsReady()
|
||||
.then((ymaps) => {
|
||||
if (destroyed) return;
|
||||
ymaps.ready(init);
|
||||
})
|
||||
.catch((e) => {
|
||||
// API карт не подгрузился (заблокирован/офлайн/медленный CDN).
|
||||
// Без этой ветки пользователь смотрел бы в вечный спиннер без ошибки.
|
||||
if (!destroyed) {
|
||||
setError(tRef.current("post.mapLoadFailed"));
|
||||
setLoading(false);
|
||||
}
|
||||
console.warn("Yandex Maps API failed to load:", e);
|
||||
});
|
||||
|
||||
return () => {
|
||||
destroyed = true;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// src/components/Toast.jsx
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
/**
|
||||
* Toast — всплывающее сообщение об ошибке/успехе, автоматически скрывается.
|
||||
@@ -10,10 +10,16 @@ import { useEffect } from "react";
|
||||
* @param {number} [duration=4000] — время жизни в мс
|
||||
*/
|
||||
export default function Toast({ message, type = "error", onDismiss, duration = 4000 }) {
|
||||
// onDismiss почти всегда — свежий инлайн-стрелки. Если держать его в
|
||||
// зависимостях useEffect, любой ре-рендер родителя (сообщения чата, поллинг
|
||||
// рекламы) перезапускал бы отсчёт и тост висел бы бесконечно.
|
||||
const dismissRef = useRef(onDismiss);
|
||||
dismissRef.current = onDismiss;
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(onDismiss, duration);
|
||||
const timer = setTimeout(() => dismissRef.current?.(), duration);
|
||||
return () => clearTimeout(timer);
|
||||
}, [onDismiss, duration]);
|
||||
}, [duration]);
|
||||
|
||||
if (!message) return null;
|
||||
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
/**
|
||||
* Отдельный блюр-слой поверх ленты, независим от FeedTopBar.
|
||||
* Прижат к верху общего контейнера, высота подстраивается под
|
||||
* реальную высоту topBar (включая safe-area на iOS).
|
||||
*/
|
||||
export default function FeedBlurMask({ topBarRef }) {
|
||||
const [height, setHeight] = useState(56);
|
||||
|
||||
useEffect(() => {
|
||||
const el = topBarRef?.current;
|
||||
if (!el) return;
|
||||
const update = () => setHeight(el.getBoundingClientRect().height || 56);
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, [topBarRef]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="f-feed-blur-mask"
|
||||
style={{ height }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -35,6 +35,9 @@ export default function PullToRefresh({ containerRef, onRefresh, disabled = fals
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
el.classList.toggle("f-ptr-active", visible);
|
||||
// Размонтирование с visible=true иначе навсегда оставило бы маску
|
||||
// затухания и блокировку pointer-events на контейнере ленты.
|
||||
return () => el.classList.remove("f-ptr-active");
|
||||
}, [visible, containerRef]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
export default function TypeFilterBar({ value, onChange, t }) {
|
||||
const options = [
|
||||
{ key: "loss", label: t('feed.filterLoss') },
|
||||
{ key: null, label: t('feed.filterAll') },
|
||||
{ key: "found", label: t('feed.filterFound') },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="f-filter-bar">
|
||||
{options.map(opt => (
|
||||
<button
|
||||
key={opt.key ?? "all"}
|
||||
className={`f-filter-btn${value === opt.key ? " active" : ""}`}
|
||||
onClick={() => onChange(opt.key)}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
export default function HeartIcon({filled}) {
|
||||
return (
|
||||
<svg width={14} height={14} viewBox="0 0 24 24"
|
||||
fill={filled ? "#ff6b6b" : "none"} stroke="#ff6b6b" strokeWidth={2}
|
||||
strokeLinecap="round">
|
||||
<path
|
||||
d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import magnifier from "../../assets/magnifier.png";
|
||||
|
||||
export default function LogoIcon() {
|
||||
return (
|
||||
<img
|
||||
src={magnifier}
|
||||
alt="logo"
|
||||
width={20}
|
||||
height={20}
|
||||
style={{ objectFit: "contain" }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
export default function MapIcon() {
|
||||
return (
|
||||
<svg width={14} height={14} viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" strokeWidth={2} strokeLinecap="round">
|
||||
<polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/>
|
||||
<line x1="8" y1="2" x2="8" y2="18"/>
|
||||
<line x1="16" y1="6" x2="16" y2="22"/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -12,10 +12,24 @@ export const NAV_BOTTOM = [
|
||||
{ icon: "rules", key: "rules", labelKey: "nav.rules" },
|
||||
];
|
||||
|
||||
export const CATEGORY_KEYS = [
|
||||
"categories.item", "categories.pet", "categories.other",
|
||||
/**
|
||||
* Категории объявления.
|
||||
*
|
||||
* value — то, что уходит на бэкенд и хранится в БД (в т.ч. у уже созданных
|
||||
* объявлений), поэтому это стабильные значения, а НЕ переводы. Раньше сюда
|
||||
* клали i18n-ключи и отправляли t(key), из-за чего одно и то же объявление
|
||||
* получало разный category в зависимости от языка интерфейса.
|
||||
*/
|
||||
export const CATEGORIES = [
|
||||
{ value: "Вещь", labelKey: "categories.item" },
|
||||
{ value: "Питомец", labelKey: "categories.pet" },
|
||||
{ value: "Другое", labelKey: "categories.other" },
|
||||
];
|
||||
|
||||
export const CATEGORY_ITEM = "Вещь";
|
||||
export const CATEGORY_PET = "Питомец";
|
||||
export const CATEGORY_OTHER = "Другое";
|
||||
|
||||
export const EMPTY_FORM = {
|
||||
type: "loss",
|
||||
title: "",
|
||||
@@ -29,5 +43,3 @@ export const EMPTY_FORM = {
|
||||
reward: false,
|
||||
rewardText: ""
|
||||
};
|
||||
|
||||
export const MAX_PHOTO_SIZE_MB = 5;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { useState, useCallback, useRef } from "react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API_URL } from "../config/authConstants";
|
||||
import { apiFetch } from "../api/apiClient";
|
||||
@@ -11,8 +11,12 @@ export function useChats() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const { updateFromChats, clearChatUnread } = useUnread();
|
||||
// fetchChats дёргается и при монтировании, и на каждое изменение totalUnread —
|
||||
// без guard'а медленный предыдущий ответ воскрешал бы прочитанные счётчики.
|
||||
const requestIdRef = useRef(0);
|
||||
|
||||
const fetchChats = useCallback(async () => {
|
||||
const requestId = ++requestIdRef.current;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
@@ -20,14 +24,16 @@ export function useChats() {
|
||||
if (!res.ok) throw new Error(t('chats.fetchError'));
|
||||
|
||||
const data = await res.json();
|
||||
if (requestId !== requestIdRef.current) return; // устаревший ответ
|
||||
const list = Array.isArray(data) ? data : (data.items ?? data.content ?? []);
|
||||
cachePostsFromChats(list);
|
||||
setChats(list);
|
||||
updateFromChats(list);
|
||||
} catch (e) {
|
||||
if (requestId !== requestIdRef.current) return;
|
||||
setError(e.message || t('chats.fetchError'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (requestId === requestIdRef.current) setLoading(false);
|
||||
}
|
||||
}, [updateFromChats, t]);
|
||||
|
||||
@@ -46,6 +52,9 @@ export function useChats() {
|
||||
|
||||
const fetchMessages = useCallback(async (chatId) => {
|
||||
const res = await apiFetch(`${API_URL}/api/v1/chats/${chatId}/messages`);
|
||||
// Без этой проверки 5xx с JSON-телом ошибки превращался в пустой список,
|
||||
// и только что отправленное сообщение выглядело как потерянное.
|
||||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||||
const data = await res.json();
|
||||
return Array.isArray(data) ? data : (data.items ?? data.content ?? []);
|
||||
}, []);
|
||||
|
||||
@@ -33,14 +33,14 @@ export function useDeleteChat() {
|
||||
if (!res.ok) {
|
||||
let body;
|
||||
try { body = await res.json(); } catch { body = null; }
|
||||
throw new Error(body?.message || t('chat.deleteErrorWithStatus', { status: res.status }));
|
||||
throw new Error(body?.message || t('chats.deleteErrorWithStatus', { status: res.status }));
|
||||
}
|
||||
|
||||
clearChatUnread(chatId);
|
||||
removePostForChat(chatId);
|
||||
return { success: true, error: null };
|
||||
} catch (err) {
|
||||
const message = err.message || t('chat.deleteError');
|
||||
const message = err.message || t('chats.deleteError');
|
||||
setError(message);
|
||||
return { success: false, error: message };
|
||||
} finally {
|
||||
|
||||
@@ -33,6 +33,10 @@ export function useFeedActions({ refresh, loadMyPosts, onAuthRequired, isAuthent
|
||||
}, [refresh, loadMyPosts]);
|
||||
|
||||
const handleDelete = useCallback(async (postId) => {
|
||||
if (!isAuthenticated) {
|
||||
onAuthRequired?.();
|
||||
return;
|
||||
}
|
||||
if (!window.confirm(t('feed.confirmDelete'))) return;
|
||||
const result = await deletePost(postId);
|
||||
if (result.success) {
|
||||
@@ -40,9 +44,13 @@ export function useFeedActions({ refresh, loadMyPosts, onAuthRequired, isAuthent
|
||||
} else {
|
||||
setError(result.error);
|
||||
}
|
||||
}, [t, deletePost, afterMutation]);
|
||||
}, [t, deletePost, afterMutation, isAuthenticated, onAuthRequired]);
|
||||
|
||||
const handleMarkFound = useCallback(async (postId) => {
|
||||
if (!isAuthenticated) {
|
||||
onAuthRequired?.();
|
||||
return;
|
||||
}
|
||||
if (!window.confirm(t('feed.confirmMarkFound'))) return;
|
||||
const result = await markAsFound(postId);
|
||||
if (result.success) {
|
||||
@@ -50,7 +58,7 @@ export function useFeedActions({ refresh, loadMyPosts, onAuthRequired, isAuthent
|
||||
} else {
|
||||
setError(result.error);
|
||||
}
|
||||
}, [t, markAsFound, afterMutation]);
|
||||
}, [t, markAsFound, afterMutation, isAuthenticated, onAuthRequired]);
|
||||
|
||||
const clearError = useCallback(() => setError(""), []);
|
||||
|
||||
|
||||
@@ -1,8 +1,21 @@
|
||||
import { useState, useCallback } from "react";
|
||||
import { useState, useCallback, useRef } from "react";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
/**
|
||||
* Достаёт элементы страницы независимо от формы ответа бэкенда
|
||||
* (Spring Page {content,last}, {items,last} или голый массив).
|
||||
*/
|
||||
function extractPage(data) {
|
||||
if (Array.isArray(data)) {
|
||||
return { items: data, last: data.length < PAGE_SIZE };
|
||||
}
|
||||
const items = data?.content ?? data?.items ?? [];
|
||||
const last = typeof data?.last === "boolean" ? data.last : items.length < PAGE_SIZE;
|
||||
return { items, last };
|
||||
}
|
||||
|
||||
/**
|
||||
* Управляет основной лентой объявлений: загрузка, пагинация, поиск.
|
||||
*/
|
||||
@@ -13,8 +26,13 @@ export function useFeedPosts() {
|
||||
const [page, setPage] = useState(0);
|
||||
const [hasMore, setHasMore] = useState(true);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
// Номер последнего начатого запроса: ответы приходят не по порядку
|
||||
// (дебаунс поиска, бесконечный скролл, refresh после удаления), и без
|
||||
// этой проверки медленный «старый» ответ перетирал бы свежий.
|
||||
const requestIdRef = useRef(0);
|
||||
|
||||
const loadFeed = useCallback(async (pageNum = 0, search = "", append = false) => {
|
||||
const requestId = ++requestIdRef.current;
|
||||
if (pageNum === 0) {
|
||||
setLoading(true);
|
||||
} else {
|
||||
@@ -28,21 +46,37 @@ export function useFeedPosts() {
|
||||
const res = await fetch(`${API_URL}/api/v1/posts?${params}`);
|
||||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||||
const data = await res.json();
|
||||
if (requestId !== requestIdRef.current) return; // устаревший ответ
|
||||
|
||||
const content = data.content ?? [];
|
||||
const normalizedAds = content.map(ad => ({
|
||||
const { items, last } = extractPage(data);
|
||||
const normalizedAds = items.map(ad => ({
|
||||
...ad,
|
||||
type: ad.type ? ad.type.toLowerCase() : "loss",
|
||||
}));
|
||||
|
||||
setAds(prev => (append ? [...prev, ...normalizedAds] : normalizedAds));
|
||||
setHasMore(!data.last);
|
||||
setAds(prev => {
|
||||
const merged = append ? [...prev, ...normalizedAds] : normalizedAds;
|
||||
// Пересекающиеся страницы (сдвиг при вставке новых объявлений) не должны
|
||||
// давать дубликаты — React потеряет state у карточек с одинаковым key.
|
||||
const seen = new Set();
|
||||
return merged.filter(ad => {
|
||||
if (seen.has(ad.id)) return false;
|
||||
seen.add(ad.id);
|
||||
return true;
|
||||
});
|
||||
});
|
||||
setHasMore(!last);
|
||||
setPage(pageNum);
|
||||
} catch (err) {
|
||||
if (requestId !== requestIdRef.current) return;
|
||||
setError(err.message || "Failed to load ads");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setLoadingMore(false);
|
||||
// Флаг снимает только «свой» запрос: иначе подгрузка страницы N
|
||||
// гасила бы спиннер первой страницы, и наоборот.
|
||||
if (requestId === requestIdRef.current) {
|
||||
setLoading(false);
|
||||
setLoadingMore(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRef, useCallback } from "react";
|
||||
import { useRef, useCallback, useEffect } from "react";
|
||||
|
||||
/**
|
||||
* Универсальный хук для бесконечного скролла через IntersectionObserver.
|
||||
@@ -9,19 +9,32 @@ import { useRef, useCallback } from "react";
|
||||
*/
|
||||
export function useInfiniteScroll(onIntersect, enabled) {
|
||||
const observerRef = useRef(null);
|
||||
// Колбэк храним в ref: если держать его в зависимостях useCallback, то новый
|
||||
// инлайн-колбэк на каждом рендере родителя пересоздавал бы IntersectionObserver,
|
||||
// а новый observer сразу отдаёт первоначальное срабатывание — подгрузка
|
||||
// страницы превращалась бы в цикл запросов.
|
||||
const onIntersectRef = useRef(onIntersect);
|
||||
onIntersectRef.current = onIntersect;
|
||||
const enabledRef = useRef(enabled);
|
||||
enabledRef.current = enabled;
|
||||
|
||||
const sentinelRef = useCallback(node => {
|
||||
if (!enabled) return;
|
||||
if (observerRef.current) observerRef.current.disconnect();
|
||||
const sentinelRef = useCallback((node) => {
|
||||
observerRef.current?.disconnect();
|
||||
observerRef.current = null;
|
||||
|
||||
observerRef.current = new IntersectionObserver(entries => {
|
||||
if (entries[0].isIntersecting && enabled) {
|
||||
onIntersect();
|
||||
if (!node || !enabledRef.current) return;
|
||||
|
||||
observerRef.current = new IntersectionObserver((entries) => {
|
||||
if (entries[0].isIntersecting && enabledRef.current) {
|
||||
onIntersectRef.current();
|
||||
}
|
||||
}, { rootMargin: "200px" });
|
||||
|
||||
if (node) observerRef.current.observe(node);
|
||||
}, [enabled, onIntersect]);
|
||||
observerRef.current.observe(node);
|
||||
}, []);
|
||||
|
||||
// Без этого observer остаётся подписан на уже отсоединённый узел.
|
||||
useEffect(() => () => observerRef.current?.disconnect(), []);
|
||||
|
||||
return sentinelRef;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,8 @@ import { useTranslation } from 'react-i18next';
|
||||
/**
|
||||
* useLanguageToggle — переключение между ru/en.
|
||||
*
|
||||
* i18next сам сохраняет выбранный язык в localStorage
|
||||
* через LanguageDetector (ключ 'i18nextLng'),
|
||||
* если detection.caches включает localStorage.
|
||||
* Persist делает сам i18n (см. src/i18n.js, подписка на languageChanged),
|
||||
* здесь только инициируем смену.
|
||||
*/
|
||||
export function useLanguageToggle() {
|
||||
const { i18n } = useTranslation();
|
||||
|
||||
@@ -6,7 +6,7 @@ import { apiFetch } from '../api/apiClient';
|
||||
|
||||
/**
|
||||
* Хук для изменения статуса поста (ACTIVE/CLOSED).
|
||||
* Используется для отметки "Вещь найдена" и (в будущем) для reopen.
|
||||
* Используется для отметки "найдено" и (в будущем) для reopen.
|
||||
*/
|
||||
export function usePostStatus() {
|
||||
const { t } = useTranslation();
|
||||
@@ -40,7 +40,7 @@ export function usePostStatus() {
|
||||
}, [t]);
|
||||
|
||||
/**
|
||||
* Изменяет статус поста на CLOSED (вещь найдена).
|
||||
* Изменяет статус поста на CLOSED («найдено»).
|
||||
* @param {number} postId - ID поста
|
||||
* @returns {Promise<{success: boolean, error: string|null}>}
|
||||
*/
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useState, useCallback, useMemo } from "react";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
import { apiFetch } from "../api/apiClient";
|
||||
|
||||
/**
|
||||
* Загрузка/отправка отзывов + производные данные (средний рейтинг,
|
||||
* распределение по звёздам).
|
||||
*
|
||||
* token здесь намеренно не принимается: apiFetch берёт актуальный access-токен
|
||||
* из хранилища сам и рефрешит его при 401.
|
||||
*/
|
||||
export function useReviews({ token, isAuthenticated, onAuthRequired, authorFallbackName }) {
|
||||
export function useReviews({ isAuthenticated, onAuthRequired, authorFallbackName }) {
|
||||
const [reviews, setReviews] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
@@ -37,12 +41,12 @@ export function useReviews({ token, isAuthenticated, onAuthRequired, authorFallb
|
||||
setSubmitting(true);
|
||||
setSubmitError("");
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/v1/reviews`, {
|
||||
// apiFetch, а не голый fetch: он сам подставляет актуальный access-токен
|
||||
// и обновляет его при 401. С пропом token из контекста запрос падал бы
|
||||
// на просроченном токене (контекст обновляется только при логине).
|
||||
const res = await apiFetch(`${API_URL}/api/v1/reviews`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ rating, text }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Error ${res.status}`);
|
||||
@@ -66,23 +70,28 @@ export function useReviews({ token, isAuthenticated, onAuthRequired, authorFallb
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}, [isAuthenticated, onAuthRequired, token, loadReviews, authorFallbackName]);
|
||||
}, [isAuthenticated, onAuthRequired, loadReviews, authorFallbackName]);
|
||||
|
||||
const avgRating = reviews.length
|
||||
? (reviews.reduce((s, r) => s + r.rating, 0) / reviews.length).toFixed(1)
|
||||
// Несохранённые отзывы показываются пользователю, но не должны попадать
|
||||
// в публичную статистику площадки — иначе avgRating и распределение
|
||||
// навсегда искажаются отзывами, которых нет на сервере.
|
||||
const savedReviews = useMemo(() => reviews.filter((r) => !r.pending), [reviews]);
|
||||
|
||||
const avgRating = savedReviews.length
|
||||
? (savedReviews.reduce((s, r) => s + r.rating, 0) / savedReviews.length).toFixed(1)
|
||||
: null;
|
||||
|
||||
const distribution = useMemo(() => {
|
||||
const counts = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
|
||||
reviews.forEach((r) => {
|
||||
savedReviews.forEach((r) => {
|
||||
if (counts[r.rating] !== undefined) counts[r.rating] += 1;
|
||||
});
|
||||
return [5, 4, 3, 2, 1].map((star) => ({
|
||||
star,
|
||||
count: counts[star],
|
||||
pct: reviews.length ? Math.round((counts[star] / reviews.length) * 100) : 0,
|
||||
pct: savedReviews.length ? Math.round((counts[star] / savedReviews.length) * 100) : 0,
|
||||
}));
|
||||
}, [reviews]);
|
||||
}, [savedReviews]);
|
||||
|
||||
return {
|
||||
reviews, loading, error, submitting, submitError,
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { RefObject } from "react";
|
||||
|
||||
export type ScrollDirection = "up" | "down";
|
||||
|
||||
/**
|
||||
* useScrollDirection — отслеживает направление скролла контейнера `containerRef`
|
||||
* и сообщает, когда тулбар должен быть скрыт.
|
||||
*
|
||||
* Логика (как в Telegram Web):
|
||||
* - при скролле вниз тулбар прячется (hidden = true);
|
||||
* - при скролле вверх (или подъезде в самое начало списка) — показывается;
|
||||
* - есть порог `showThreshold` у вершины, чтобы тулбар появлялся не раньше,
|
||||
* чем контент вернулся достаточно близко к началу.
|
||||
*
|
||||
* requestAnimationFrame + ref'ы: обработчик скролла НЕ триггерит ре-рендер
|
||||
* на каждое событие — состояние меняется только когда скрытость реально
|
||||
* пересекает границу, всё остальное живёт в ref'ах.
|
||||
*/
|
||||
export default function useScrollDirection<T extends HTMLElement>(
|
||||
containerRef: RefObject<T | null>,
|
||||
{ hideThreshold = 12, showThreshold = 88 }: { hideThreshold?: number; showThreshold?: number } = {},
|
||||
): boolean {
|
||||
const [hidden, setHidden] = useState(false);
|
||||
|
||||
const hiddenRef = useRef(false);
|
||||
const lastYRef = useRef(0);
|
||||
const rafRef = useRef<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
|
||||
lastYRef.current = el.scrollTop;
|
||||
|
||||
const onScroll = () => {
|
||||
if (rafRef.current != null) return;
|
||||
rafRef.current = requestAnimationFrame(() => {
|
||||
rafRef.current = null;
|
||||
const y = el.scrollTop;
|
||||
|
||||
const maxScroll = el.scrollHeight - el.clientHeight;
|
||||
const isAtTop = y <= showThreshold;
|
||||
const isAtBottom = maxScroll > 0 && y >= maxScroll - showThreshold;
|
||||
// Без сенсорных/фрикционных возражений: крошечные рывки не считаем за жест
|
||||
const dy = Math.abs(y - lastYRef.current);
|
||||
|
||||
let next = hiddenRef.current;
|
||||
if (isAtTop || isAtBottom) {
|
||||
next = false;
|
||||
} else if (dy >= hideThreshold) {
|
||||
next = y > lastYRef.current;
|
||||
}
|
||||
lastYRef.current = y;
|
||||
|
||||
if (next !== hiddenRef.current) {
|
||||
hiddenRef.current = next;
|
||||
setHidden(next);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
el.addEventListener("scroll", onScroll, { passive: true });
|
||||
return () => {
|
||||
el.removeEventListener("scroll", onScroll);
|
||||
if (rafRef.current != null) cancelAnimationFrame(rafRef.current);
|
||||
};
|
||||
}, [containerRef, hideThreshold, showThreshold]);
|
||||
|
||||
return hidden;
|
||||
}
|
||||
@@ -11,6 +11,11 @@ import { getAccessToken, refreshAccessToken } from "../api/apiClient";
|
||||
* и переподключение. Конкретные топики и обработку сообщений задаёт вызывающий
|
||||
* хук через onConnect.
|
||||
*
|
||||
* Соединение пересоздаётся не только при смене enabled, но и при смене
|
||||
* onConnect: подписка живёт внутри клиента, поэтому новый onConnect (например,
|
||||
* новый chatId → новый топик) обязан переподписать заново, иначе клиент останется
|
||||
* подписан на предыдущий топик, а отправлять будет в новый.
|
||||
*
|
||||
* @param {boolean} enabled — активировать соединение (например, есть ли userId/chatId)
|
||||
* @param {(client: Client) => void} onConnect — вызывается при успешном коннекте,
|
||||
* внутри обычно делают client.subscribe(...)
|
||||
@@ -28,7 +33,10 @@ export function useStompClient(enabled, onConnect) {
|
||||
}, [onConnect]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
if (!enabled) {
|
||||
setConnected(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const client = new Client({
|
||||
webSocketFactory: () => new SockJS(`${API_URL}/ws`),
|
||||
@@ -43,7 +51,11 @@ export function useStompClient(enabled, onConnect) {
|
||||
onConnectRef.current?.(client);
|
||||
},
|
||||
onDisconnect: () => setConnected(false),
|
||||
// stompjs не вызывает onDisconnect при обрыве сокета — без этого флага
|
||||
// UI продолжал бы считать нас "онлайн", пока идёт реконнект.
|
||||
onWebSocketClose: () => setConnected(false),
|
||||
onStompError: async (frame) => {
|
||||
setConnected(false);
|
||||
if (frame.headers?.message?.includes("Unauthorized")) {
|
||||
try {
|
||||
await refreshAccessToken();
|
||||
@@ -54,11 +66,18 @@ export function useStompClient(enabled, onConnect) {
|
||||
},
|
||||
});
|
||||
|
||||
client.activate();
|
||||
clientRef.current = client;
|
||||
// activate() сам не awaited — без catch любое исключение из beforeConnect
|
||||
// всплывало бы как необработанный rejected promise.
|
||||
Promise.resolve(client.activate()).catch((e) => {
|
||||
console.warn("[stomp] activate failed", e);
|
||||
});
|
||||
|
||||
return () => client.deactivate();
|
||||
}, [enabled]);
|
||||
return () => {
|
||||
setConnected(false);
|
||||
client.deactivate();
|
||||
};
|
||||
}, [enabled, onConnect]);
|
||||
|
||||
return { clientRef, connected };
|
||||
}
|
||||
|
||||
@@ -18,7 +18,12 @@ export function useTranscodingStatusPolling(advertisingId, enabled, path = "ads"
|
||||
const attemptsRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !advertisingId) return;
|
||||
if (!enabled || !advertisingId) {
|
||||
// Статус предыдущей сущности нельзя переносить на следующую: иначе
|
||||
// новый элемент сразу получит терминальный статус и polling сразу выключится.
|
||||
setStatus('PROCESSING');
|
||||
return;
|
||||
}
|
||||
|
||||
attemptsRef.current = 0;
|
||||
let cancelled = false;
|
||||
@@ -37,7 +42,7 @@ export function useTranscodingStatusPolling(advertisingId, enabled, path = "ads"
|
||||
const data = await res.json();
|
||||
if (cancelled) return;
|
||||
|
||||
setStatus(data.transcodingStatus);
|
||||
setStatus(data.transcodingStatus ?? 'PROCESSING');
|
||||
|
||||
attemptsRef.current += 1;
|
||||
const isTerminal = TERMINAL_STATUSES.includes(data.transcodingStatus);
|
||||
@@ -49,7 +54,15 @@ export function useTranscodingStatusPolling(advertisingId, enabled, path = "ads"
|
||||
setStatus('TIMEOUT');
|
||||
}
|
||||
} catch (err) {
|
||||
if (cancelled) return;
|
||||
console.warn('Status poll failed, retrying', err);
|
||||
// Ошибки тоже тратят попытки, иначе MAX_POLL_ATTEMPTS недостижим
|
||||
// и запрос к несуществующему эндпоинту будет повторяться вечно.
|
||||
attemptsRef.current += 1;
|
||||
if (attemptsRef.current >= MAX_POLL_ATTEMPTS) {
|
||||
setStatus('TIMEOUT');
|
||||
return;
|
||||
}
|
||||
timeoutId = setTimeout(poll, POLL_INTERVAL_MS);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useStompClient } from './useStompClient'; // ваш существующий хук из чата
|
||||
|
||||
/**
|
||||
* STOMP/WebSocket-подписка на статус транскодинга медиа.
|
||||
* @param {number|string} advertisingId — id сущности
|
||||
* @param {boolean} enabled — включать подписку
|
||||
* @param {string} [path="ads"] — сегмент пути (например, "ads" или "fullscreen-ads")
|
||||
* @returns {string} транскодинг-статус
|
||||
*/
|
||||
export function useTranscodingStatusSocket(advertisingId, enabled, path = "ads") {
|
||||
const [status, setStatus] = useState('PROCESSING');
|
||||
const stompClient = useStompClient();
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !advertisingId || !stompClient?.connected) return;
|
||||
|
||||
const subscription = stompClient.subscribe(
|
||||
`/topic/${path}/${advertisingId}/status`,
|
||||
(message) => {
|
||||
const payload = JSON.parse(message.body);
|
||||
setStatus(payload.transcodingStatus);
|
||||
}
|
||||
);
|
||||
|
||||
return () => subscription.unsubscribe();
|
||||
}, [advertisingId, enabled, path, stompClient]);
|
||||
|
||||
return status;
|
||||
}
|
||||
@@ -1,10 +1,17 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { whenYmapsReady } from "../utils/ymapsApi";
|
||||
|
||||
const YANDEX_GEOCODER_API_KEY = process.env.REACT_APP_YANDEX_GEOCODER_KEY;
|
||||
|
||||
const DEFAULT_CENTER = [55.751574, 37.573856];
|
||||
|
||||
export function useYandexMap(enabled, initialCoords = null, initialAddress = "") {
|
||||
const { t } = useTranslation();
|
||||
// tRef читается из эффекта инициализации карты. Добавлять t в его deps нельзя:
|
||||
// смена языка тогда пересоздавала бы карту и теряла бы выбранную метку.
|
||||
const tRef = useRef(t);
|
||||
tRef.current = t;
|
||||
const mapRef = useRef(null);
|
||||
const ymapRef = useRef(null);
|
||||
const placemarkRef = useRef(null);
|
||||
@@ -16,6 +23,8 @@ export function useYandexMap(enabled, initialCoords = null, initialAddress = "")
|
||||
const [address, setAddress] = useState(initialAddress ?? "");
|
||||
const addressRef = useRef(initialAddress ?? "");
|
||||
const [loading, setLoading] = useState(false);
|
||||
// Ошибка загрузки API карт: без неё пользователь смотрел бы в вечный спиннер.
|
||||
const [loadError, setLoadError] = useState("");
|
||||
// Всегда хранит последние координаты, чтобы при повторной инициализации
|
||||
// карты (например, при повторном открытии модалки) маркер появлялся там,
|
||||
// где пользователь его оставил, а не сбрасывался на initialCoords.
|
||||
@@ -127,13 +136,30 @@ export function useYandexMap(enabled, initialCoords = null, initialAddress = "")
|
||||
useEffect(() => {
|
||||
if (!enabled || !mapRef.current) return;
|
||||
if (initializedRef.current) return; // уже инициализировали
|
||||
initializedRef.current = true;
|
||||
|
||||
if (window.ymaps?.ready) {
|
||||
window.ymaps.ready(init);
|
||||
}
|
||||
let cancelled = false;
|
||||
|
||||
// Сбрасываем прошлую ошибку на новой попытке, иначе после успешной
|
||||
// загрузки карты старая плашка об ошибке осталась бы на экране.
|
||||
setLoadError("");
|
||||
|
||||
whenYmapsReady()
|
||||
.then((ymaps) => {
|
||||
if (cancelled) return;
|
||||
initializedRef.current = true;
|
||||
ymaps.ready(init);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (cancelled) return;
|
||||
// API карт так и не подгрузился: сбрасываем флаг, чтобы следующая
|
||||
// попытка открытия карты её повторила, и гасим бесконечный спиннер.
|
||||
initializedRef.current = false;
|
||||
setLoadError(tRef.current("post.mapLoadFailed"));
|
||||
console.warn("Yandex Maps API failed to load:", e);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
ymapRef.current?.destroy();
|
||||
ymapRef.current = null;
|
||||
placemarkRef.current = null;
|
||||
@@ -146,5 +172,5 @@ export function useYandexMap(enabled, initialCoords = null, initialAddress = "")
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [enabled, init]);
|
||||
|
||||
return { mapRef, coords, address, addressRef, loading, moveTo };
|
||||
return { mapRef, coords, address, addressRef, loading, loadError, moveTo };
|
||||
}
|
||||
|
||||
@@ -80,7 +80,8 @@
|
||||
"registrationError": "Registration error",
|
||||
"nameLabel": "Name",
|
||||
"loginMinChars": "Minimum 3 characters",
|
||||
"accountCreatedLoginManually": "Account created. Log in manually."
|
||||
"accountCreatedLoginManually": "Account created. Log in manually.",
|
||||
"autoLoginFailed": "Account created, but automatic sign-in failed — please log in manually."
|
||||
},
|
||||
"post": {
|
||||
"editTitle": "Edit ad",
|
||||
@@ -110,6 +111,7 @@
|
||||
"geoDenied": "Location access denied",
|
||||
"geoUnsupported": "Geolocation is not available in this browser",
|
||||
"geoTimeout": "Unable to determine your location",
|
||||
"mapLoadFailed": "Could not load the map. Check your connection or ad blocker and try again.",
|
||||
"addressLabel": "Address",
|
||||
"addressPlaceholder": "E.g. 123 Main St, New York",
|
||||
"phoneLabel": "Phone number",
|
||||
@@ -130,6 +132,8 @@
|
||||
"deleteError": "Failed to delete the ad",
|
||||
"deleteErrorWithStatus": "Failed to delete ad (error {{status}})",
|
||||
"statusUpdateError": "Failed to change the ad status.",
|
||||
"serverError": "The server returned an error ({{status}})",
|
||||
"unknownError": "Unknown error",
|
||||
"nextStep": "Next",
|
||||
"backStep": "Back"
|
||||
},
|
||||
@@ -205,7 +209,9 @@
|
||||
"loading": "Loading reviews...",
|
||||
"emptyTitle": "No reviews yet",
|
||||
"emptySub": "Be the first — leave a review about the platform",
|
||||
"you": "You"
|
||||
"you": "You",
|
||||
"notSaved": "not saved",
|
||||
"submitError": "Failed to submit your review"
|
||||
},
|
||||
"rightSidebar": {
|
||||
"advertisement": "Advertisement",
|
||||
|
||||
@@ -80,7 +80,8 @@
|
||||
"registrationError": "Ошибка регистрации",
|
||||
"nameLabel": "Имя",
|
||||
"loginMinChars": "Минимум 3 символа",
|
||||
"accountCreatedLoginManually": "Аккаунт создан. Войдите вручную"
|
||||
"accountCreatedLoginManually": "Аккаунт создан. Войдите вручную",
|
||||
"autoLoginFailed": "Аккаунт создан, но войти автоматически не удалось — войдите вручную"
|
||||
},
|
||||
"post": {
|
||||
"editTitle": "Редактировать объявление",
|
||||
@@ -110,6 +111,7 @@
|
||||
"geoDenied": "Доступ к геолокации запрещён",
|
||||
"geoUnsupported": "Геолокация недоступна в этом браузере",
|
||||
"geoTimeout": "Не удалось определить местоположение",
|
||||
"mapLoadFailed": "Не удалось загрузить карту. Проверьте интернет или блокировщик рекламы и попробуйте снова.",
|
||||
"addressLabel": "Адрес",
|
||||
"addressPlaceholder": "Например: Москва, ул. Ленина, 5",
|
||||
"phoneLabel": "Номер телефона",
|
||||
@@ -130,6 +132,8 @@
|
||||
"deleteError": "Не удалось удалить объявление",
|
||||
"deleteErrorWithStatus": "Не удалось удалить объявление (ошибка {{status}})",
|
||||
"statusUpdateError": "Не удалось изменить статус объявления",
|
||||
"serverError": "Сервер вернул ошибку {{status}}",
|
||||
"unknownError": "Неизвестная ошибка",
|
||||
"nextStep": "Далее",
|
||||
"backStep": "Назад"
|
||||
|
||||
@@ -206,7 +210,9 @@
|
||||
"loading": "Загружаем отзывы...",
|
||||
"emptyTitle": "Отзывов пока нет",
|
||||
"emptySub": "Станьте первым — оставьте отзыв о площадке",
|
||||
"you": "Вы"
|
||||
"you": "Вы",
|
||||
"notSaved": "не сохранён",
|
||||
"submitError": "Не удалось отправить отзыв"
|
||||
},
|
||||
"rightSidebar": {
|
||||
"advertisement": "Реклама",
|
||||
|
||||
@@ -64,7 +64,7 @@ export default function ChatPage() {
|
||||
return sortMessages([...list, ...extra]);
|
||||
});
|
||||
})
|
||||
.catch(() => setLoadError(t('chat.loadError')));
|
||||
.catch(() => setLoadError(t('chats.loadError')));
|
||||
|
||||
markAsRead(chatId);
|
||||
clearChatUnread(chatId);
|
||||
@@ -83,7 +83,7 @@ export default function ChatPage() {
|
||||
|
||||
const sent = sendMessage(trimmed);
|
||||
if (!sent) {
|
||||
setSendError(t('chat.sendError'));
|
||||
setSendError(t('chats.sendError'));
|
||||
return;
|
||||
}
|
||||
setInput("");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import CloseIcon from "../components/icons/CloseIcon";
|
||||
import RulesModal from "./RulesModal";
|
||||
import { EMPTY_FORM, CATEGORY_KEYS } from "../config/feedConstants";
|
||||
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePostMutation } from "../hooks/usePostMutation";
|
||||
import { useImageUpload, ACCEPT, MAX_SIZE_MB } from "../hooks/useImageUpload";
|
||||
@@ -67,7 +67,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
? { latitude: initialData.latitude, longitude: initialData.longitude }
|
||||
: null;
|
||||
|
||||
const { mapRef, coords, address, addressRef, loading: mapLoading, moveTo } = useYandexMap(
|
||||
const { mapRef, coords, address, addressRef, loading: mapLoading, loadError: mapLoadError, moveTo } = useYandexMap(
|
||||
mapModalOpen,
|
||||
initialCoords,
|
||||
isEdit ? (initialData.location || "") : ""
|
||||
@@ -301,7 +301,9 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
onChange={e => set("category", e.target.value)}
|
||||
>
|
||||
<option value="">{t('categories.select')}</option>
|
||||
{CATEGORY_KEYS.map(k => <option key={k} value={t(k)}>{t(k)}</option>)}
|
||||
{CATEGORIES.map(c => (
|
||||
<option key={c.value} value={c.value}>{t(c.labelKey)}</option>
|
||||
))}
|
||||
</select>
|
||||
{errors.category && <p className="f-err-msg">{errors.category}</p>}
|
||||
</div>
|
||||
@@ -317,6 +319,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
{form.address ? `📍 ${form.address}` : t('post.mapPickLabel')}
|
||||
</button>
|
||||
{!coords && <p className="f-hint">{t('post.mapHint')}</p>}
|
||||
{mapLoadError && <p className="f-err-msg">{mapLoadError}</p>}
|
||||
{errors.map && <p className="f-err-msg">{errors.map}</p>}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -27,9 +27,11 @@ import { useInfiniteScroll } from "../hooks/useInfiniteScroll";
|
||||
import { useModals } from "../hooks/useModals";
|
||||
import { useFeedActions } from "../hooks/useFeedActions";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CATEGORY_ITEM, CATEGORY_OTHER, CATEGORY_PET } from "../config/feedConstants";
|
||||
import { useProfile } from "../hooks/useProfile";
|
||||
import { useFullscreenAdTrigger } from "../hooks/useFullscreenAdTrigger";
|
||||
import FullscreenAdOverlay from "../components/FullscreenAdOverlay";
|
||||
import Toast from "../components/Toast";
|
||||
import type { ComponentType } from "react";
|
||||
|
||||
// Legacy .jsx-модули: TS инферирует их типы из JS неточно (бывают «странные»
|
||||
@@ -328,10 +330,13 @@ export default function MainFeed() {
|
||||
result = feed.ads;
|
||||
}
|
||||
|
||||
// Сравниваем с теми же значениями, что уходят на бэкенд (CATEGORIES),
|
||||
// а не с русскими литералами: интерфейс-то может быть на английском.
|
||||
if (activeNav === "items") {
|
||||
result = result.filter(ad => ["Вещь", "Другое"].includes(ad.category));
|
||||
result = result.filter((ad: AnyAds[number]) =>
|
||||
[CATEGORY_ITEM, CATEGORY_OTHER].includes(ad.category));
|
||||
} else if (activeNav === "pets") {
|
||||
result = result.filter(ad => ad.category === "Питомец");
|
||||
result = result.filter((ad: AnyAds[number]) => ad.category === CATEGORY_PET);
|
||||
}
|
||||
|
||||
if (typeFilter) {
|
||||
@@ -514,6 +519,14 @@ export default function MainFeed() {
|
||||
|
||||
{fullscreenAd && <FullscreenAdOverlay ad={fullscreenAd} onClose={closeFullscreenAd} />}
|
||||
|
||||
{/* Ошибки удаления/отметки «найдено»: без этого тоста неудачный запрос
|
||||
выглядел бы как «ничего не произошло». */}
|
||||
<Toast
|
||||
message={actions.error}
|
||||
type="error"
|
||||
onDismiss={actions.clearError}
|
||||
/>
|
||||
|
||||
<BottomNav
|
||||
activeTab={isMapView ? "map" : isSearchView ? "search" : "home"}
|
||||
hasFilters={hasActiveFilters}
|
||||
|
||||
@@ -44,7 +44,7 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
||||
};
|
||||
|
||||
const imageUrl = getImageUrl(ad.images?.[0]);
|
||||
const address = ad.city;
|
||||
const address = ad.address || ad.city || ad.district || ad.location;
|
||||
const createdAt = ad.createdAt
|
||||
? new Date(ad.createdAt).toLocaleDateString("ru-RU")
|
||||
: null;
|
||||
|
||||
@@ -18,7 +18,7 @@ import { useProfile } from "../hooks/useProfile";
|
||||
export default function ReviewsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { user, token, isAuthenticated, updateUser } = useAuthContext();
|
||||
const { user, isAuthenticated, updateUser } = useAuthContext();
|
||||
const { fetchProfile } = useProfile();
|
||||
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
@@ -45,7 +45,6 @@ export default function ReviewsPage() {
|
||||
reviews, loading, error, submitting, submitError,
|
||||
loadReviews, submitReview, avgRating, distribution,
|
||||
} = useReviews({
|
||||
token,
|
||||
isAuthenticated,
|
||||
onAuthRequired: () => setAuthModalOpen(true),
|
||||
authorFallbackName: profileData.firstName || t('reviews.you'),
|
||||
|
||||
@@ -2,6 +2,13 @@ const STORAGE_KEY = "nakhodka:chatPosts";
|
||||
|
||||
const postByChatId = new Map();
|
||||
|
||||
/**
|
||||
* Map не приводит ключи к строке, а chat.id из JSON приходит числом, тогда как
|
||||
* из useParams() — всегда строкой. Без нормализации запись просто не
|
||||
* находилась (а после перезагрузки страницы в кеше жили оба варианта ключа).
|
||||
*/
|
||||
const key = (chatId) => String(chatId);
|
||||
|
||||
/** Восстанавливает кеш постов из localStorage (выживает при перезагрузке страницы). */
|
||||
function loadFromStorage() {
|
||||
try {
|
||||
@@ -32,18 +39,18 @@ function persist() {
|
||||
loadFromStorage();
|
||||
|
||||
export function setPostForChat(chatId, post) {
|
||||
postByChatId.set(chatId, post);
|
||||
postByChatId.set(key(chatId), post);
|
||||
persist();
|
||||
}
|
||||
|
||||
export function getPostForChat(chatId) {
|
||||
return postByChatId.get(chatId);
|
||||
return postByChatId.get(key(chatId));
|
||||
}
|
||||
|
||||
export function cachePostsFromChats(chats) {
|
||||
for (const chat of chats) {
|
||||
if (chat.post) {
|
||||
postByChatId.set(chat.id, chat.post);
|
||||
postByChatId.set(key(chat.id), chat.post);
|
||||
}
|
||||
}
|
||||
if (chats.length) persist();
|
||||
@@ -51,16 +58,6 @@ export function cachePostsFromChats(chats) {
|
||||
|
||||
/** Удаляет запись при удалении конкретного чата. */
|
||||
export function removePostForChat(chatId) {
|
||||
postByChatId.delete(chatId);
|
||||
postByChatId.delete(key(chatId));
|
||||
persist();
|
||||
}
|
||||
|
||||
/** Полностью очищает кеш — вызывать при logout(), чтобы не хранить данные предыдущей сессии. */
|
||||
export function clearPostCache() {
|
||||
postByChatId.clear();
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,308 +0,0 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Onest:wght@400;500;600;700;800;900&display=swap');
|
||||
|
||||
/* ─── Page ──────────────────────────────────────────────────────────────────── */
|
||||
.auth-page {
|
||||
font-family: 'Onest', sans-serif;
|
||||
min-height: 100vh;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: radial-gradient(ellipse at 30% 40%, #1a2340 0%, #0d1018 60%);
|
||||
overflow: hidden; position: relative;
|
||||
}
|
||||
|
||||
.bg-glow {
|
||||
position: fixed; top: 40%; right: 0;
|
||||
width: 500px; height: 400px;
|
||||
background: radial-gradient(ellipse, #0f2a22 0%, transparent 70%);
|
||||
pointer-events: none; opacity: 0.7;
|
||||
}
|
||||
|
||||
/* ─── Floating icons ────────────────────────────────────────────────────────── */
|
||||
.fi {
|
||||
position: fixed;
|
||||
opacity: 0.13;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
animation: float 7s ease-in-out infinite;
|
||||
}
|
||||
@keyframes float {
|
||||
0%, 100% { transform: translateY(0) rotate(-6deg); }
|
||||
50% { transform: translateY(-18px) rotate(6deg); }
|
||||
}
|
||||
|
||||
/* ─── Card ──────────────────────────────────────────────────────────────────── */
|
||||
.auth-card {
|
||||
position: relative; z-index: 10; width: 375px;
|
||||
background: linear-gradient(155deg, #1d2436 0%, #131720 100%);
|
||||
border: 1px solid rgba(255,255,255,0.08);
|
||||
border-radius: 30px; padding: 36px 38px 30px;
|
||||
box-shadow: 0 40px 100px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.03);
|
||||
/* height transition — карточка плавно меняет размер при смене формы */
|
||||
transition: height 0.35s ease;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Появление карточки / контента */
|
||||
.card-in {
|
||||
animation: cardIn .45s cubic-bezier(.34,1.56,.64,1) both;
|
||||
}
|
||||
@keyframes cardIn {
|
||||
from { opacity: 0; transform: scale(.92) translateY(30px); }
|
||||
to { opacity: 1; transform: scale(1) translateY(0); }
|
||||
}
|
||||
|
||||
/* Уход карточки при переключении */
|
||||
.card-out {
|
||||
animation: cardOut .3s cubic-bezier(.4,0,.6,1) both;
|
||||
}
|
||||
@keyframes cardOut {
|
||||
from { opacity: 1; transform: scale(1) translateY(0); }
|
||||
to { opacity: 0; transform: scale(.94) translateY(-20px); }
|
||||
}
|
||||
|
||||
/* Контент формы — появляется снизу при смене */
|
||||
.form-body {
|
||||
animation: formIn .4s cubic-bezier(.34,1.56,.64,1) both;
|
||||
}
|
||||
@keyframes formIn {
|
||||
from { opacity: 0; transform: translateY(22px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
/* Переход между шагами регистрации */
|
||||
@keyframes stepIn {
|
||||
from { opacity: 0; transform: translateX(18px) scale(.98); }
|
||||
to { opacity: 1; transform: translateX(0) scale(1); }
|
||||
}
|
||||
|
||||
/* ─── Logo ──────────────────────────────────────────────────────────────────── */
|
||||
.logo-wrap { text-align: center; margin-bottom: 2px; }
|
||||
|
||||
@keyframes logoPulse {
|
||||
0%, 100% { filter: drop-shadow(0 0 18px rgba(45,224,200,.45)); }
|
||||
50% { filter: drop-shadow(0 0 38px rgba(45,224,200,.8)); }
|
||||
}
|
||||
/* Apply this class to your MagnifierLogo svg if needed */
|
||||
.logo-pulse { animation: logoPulse 3s ease-in-out infinite; }
|
||||
|
||||
/* ─── Typography ────────────────────────────────────────────────────────────── */
|
||||
.auth-title {
|
||||
text-align: center; color: #fff;
|
||||
font-size: 2rem; font-weight: 900;
|
||||
letter-spacing: -0.5px; margin: 12px 0 0;
|
||||
}
|
||||
.form-subtitle {
|
||||
text-align: center; color: rgba(255,255,255,0.35);
|
||||
font-size: 0.83rem; margin: 4px 0 20px;
|
||||
}
|
||||
|
||||
/* ─── Step dots ─────────────────────────────────────────────────────────────── */
|
||||
.step-dots {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
gap: 6px; margin-bottom: 18px;
|
||||
}
|
||||
.dot {
|
||||
width: 8px; height: 8px; border-radius: 50%;
|
||||
background: rgba(255,255,255,0.15);
|
||||
transition: all 0.35s cubic-bezier(.34,1.56,.64,1);
|
||||
}
|
||||
.dot-active {
|
||||
width: 26px; border-radius: 4px;
|
||||
background: #2de0c8;
|
||||
}
|
||||
.dot-done {
|
||||
background: rgba(45,224,200,0.4);
|
||||
}
|
||||
|
||||
/* ─── Fields ────────────────────────────────────────────────────────────────── */
|
||||
.field-wrap { margin-bottom: 12px; }
|
||||
|
||||
.field-label {
|
||||
display: block; color: rgba(255,255,255,0.45);
|
||||
font-size: 0.73rem; font-weight: 700;
|
||||
letter-spacing: 0.6px; margin-bottom: 5px;
|
||||
text-transform: uppercase; font-family: 'Onest', sans-serif;
|
||||
}
|
||||
|
||||
.field {
|
||||
width: 100%; box-sizing: border-box;
|
||||
background: rgba(255,255,255,0.055);
|
||||
border: 1.5px solid rgba(255,255,255,0.09);
|
||||
border-radius: 14px; padding: 13px 18px;
|
||||
color: #fff; font-family: 'Onest', sans-serif;
|
||||
font-size: 0.93rem; outline: none;
|
||||
transition: border-color .2s, background .2s, box-shadow .2s;
|
||||
}
|
||||
.field:focus {
|
||||
border-color: #2de0c8;
|
||||
background: rgba(45,224,200,.07);
|
||||
box-shadow: 0 0 0 3px rgba(45,224,200,.12);
|
||||
}
|
||||
.field::placeholder { color: rgba(255,255,255,.32); }
|
||||
|
||||
.field-err { border-color: rgba(255,107,107,0.55) !important; box-shadow: 0 0 0 3px rgba(255,107,107,0.09) !important; }
|
||||
.field-ok { border-color: rgba(45,224,200,0.45) !important; }
|
||||
|
||||
.eye-btn {
|
||||
position: absolute; right: 13px; top: 50%;
|
||||
transform: translateY(-50%);
|
||||
background: none; border: none; cursor: pointer;
|
||||
color: rgba(255,255,255,0.35); font-size: 1.05rem; line-height: 1;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.input-wrap {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.input-wrap .eye-btn {
|
||||
position: absolute;
|
||||
right: 13px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
.input-wrap .field {
|
||||
padding-right: 44px;
|
||||
}
|
||||
|
||||
/* ─── Password strength ──────────────────────────────────────────────────────── */
|
||||
.strength-bar { display: flex; gap: 4px; margin-top: 7px; }
|
||||
.seg {
|
||||
flex: 1; height: 3px; border-radius: 2px;
|
||||
background: rgba(255,255,255,0.1);
|
||||
transition: background 0.3s;
|
||||
}
|
||||
.sw { background: #ff6b6b; }
|
||||
.sm { background: #ffd166; }
|
||||
.ss { background: #2de0c8; }
|
||||
.strength-label { font-size: 0.72rem; text-align: right; margin-top: 3px; }
|
||||
|
||||
/* ─── Messages ──────────────────────────────────────────────────────────────── */
|
||||
.err-msg {
|
||||
color: #ff6b6b; font-size: 0.8rem;
|
||||
margin-top: 5px; padding-left: 2px;
|
||||
font-family: 'Onest', sans-serif;
|
||||
}
|
||||
|
||||
/* ─── Confirm box ───────────────────────────────────────────────────────────── */
|
||||
.confirm-box {
|
||||
background: rgba(255,255,255,0.04);
|
||||
border: 1px solid rgba(255,255,255,0.08);
|
||||
border-radius: 18px; padding: 16px 20px; margin-bottom: 14px;
|
||||
}
|
||||
.confirm-row { display: flex; justify-content: space-between; align-items: center; }
|
||||
.confirm-label { color: rgba(255,255,255,0.4); font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.5px; }
|
||||
.confirm-val { color: #fff; font-weight: 700; }
|
||||
.confirm-val.accent { color: #2de0c8; }
|
||||
.confirm-divider { height: 1px; background: rgba(255,255,255,0.06); margin: 10px 0; }
|
||||
|
||||
/* ─── Buttons ───────────────────────────────────────────────────────────────── */
|
||||
.btn-primary {
|
||||
width: 100%;
|
||||
background: linear-gradient(90deg, #1fc9b0, #2de0c8, #1fc9b0);
|
||||
background-size: 200% 100%;
|
||||
border: none; border-radius: 14px; padding: 15px;
|
||||
color: #082320; font-family: 'Onest', sans-serif;
|
||||
font-size: 1.05rem; font-weight: 900; cursor: pointer;
|
||||
margin-top: 6px;
|
||||
box-shadow: 0 6px 24px rgba(45,224,200,0.32);
|
||||
animation: shimmer 3s linear infinite;
|
||||
transition: opacity .15s, transform .15s;
|
||||
}
|
||||
.btn-primary:hover:not(:disabled) { opacity: .88; transform: translateY(-2px); }
|
||||
.btn-primary:active:not(:disabled) { transform: translateY(0); }
|
||||
.btn-primary:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
.ghost-btn {
|
||||
display: block; width: 100%; text-align: center;
|
||||
color: #2de0c8; font-size: 0.87rem; margin-top: 13px;
|
||||
background: none; border: none; cursor: pointer;
|
||||
font-family: 'Onest', sans-serif;
|
||||
transition: opacity .15s;
|
||||
}
|
||||
.ghost-btn:hover { opacity: 0.75; }
|
||||
|
||||
.back-btn {
|
||||
display: block; width: 100%; text-align: center;
|
||||
color: rgba(255,255,255,0.35); font-size: 0.85rem; margin-top: 11px;
|
||||
background: none; border: none; cursor: pointer;
|
||||
font-family: 'Onest', sans-serif;
|
||||
transition: color .15s;
|
||||
}
|
||||
.back-btn:hover { color: rgba(255,255,255,0.6); }
|
||||
|
||||
/* ─── Switch row ────────────────────────────────────────────────────────────── */
|
||||
.switch-row {
|
||||
text-align: center; color: rgba(255,255,255,0.4);
|
||||
font-size: 0.87rem; margin-top: 13px;
|
||||
}
|
||||
.link-btn {
|
||||
color: #2de0c8; background: none; border: none;
|
||||
cursor: pointer; font-family: 'Onest', sans-serif;
|
||||
font-size: inherit; font-weight: 700; padding: 0;
|
||||
transition: opacity .15s;
|
||||
}
|
||||
.link-btn:hover { opacity: 0.75; text-decoration: underline; }
|
||||
|
||||
/* ─── Dots btn ──────────────────────────────────────────────────────────────── */
|
||||
.dots-btn {
|
||||
position: absolute; top: 18px; right: 20px;
|
||||
background: none; border: none;
|
||||
color: rgba(255,255,255,0.25); font-size: 1.3rem;
|
||||
cursor: pointer; letter-spacing: 3px;
|
||||
}
|
||||
|
||||
/* ─── Success ───────────────────────────────────────────────────────────────── */
|
||||
.success-wrap { text-align: center; padding: 16px 0 8px; }
|
||||
.success-icon {
|
||||
font-size: 3.8rem; display: block; margin-bottom: 14px;
|
||||
animation: pop .55s cubic-bezier(.34,1.56,.64,1) both;
|
||||
}
|
||||
@keyframes pop {
|
||||
from { transform: scale(0) rotate(-20deg); opacity: 0; }
|
||||
to { transform: scale(1) rotate(0deg); opacity: 1; }
|
||||
}
|
||||
.success-title { color: #2de0c8; font-size: 1.45rem; font-weight: 900; margin-bottom: 6px; }
|
||||
.success-sub { color: rgba(255,255,255,0.4); font-size: 0.88rem; line-height: 1.5; }
|
||||
|
||||
.success-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.success-icon {
|
||||
background-color: #2de0c8;
|
||||
-webkit-mask: url("../assets/success.png") no-repeat center;
|
||||
mask: url("../assets/success.png") no-repeat center;
|
||||
}
|
||||
|
||||
.logoSvg {
|
||||
width: 130px;
|
||||
height: 130px;
|
||||
animation: logoPulse 3s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.auth-modal {
|
||||
width: 420px;
|
||||
}
|
||||
|
||||
.auth-form-error {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.auth-submit-btn {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.auth-row {
|
||||
text-align: center;
|
||||
margin-top: 14px;
|
||||
color: rgba(255,255,255,.45);
|
||||
font-size: .85rem
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=Onest:wght@400;500;600;700;800;900&display=swap');
|
||||
|
||||
.fi {
|
||||
position: fixed;
|
||||
opacity: 0.15;
|
||||
filter: grayscale(1) brightness(2);
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
animation: float 7s ease-in-out infinite;
|
||||
}
|
||||
@keyframes float {
|
||||
0%, 100% { transform: translateY(0) rotate(-6deg); }
|
||||
50% { transform: translateY(-18px) rotate(6deg); }
|
||||
}
|
||||
|
||||
.card-in {
|
||||
animation: cardIn .7s cubic-bezier(.34,1.56,.64,1) both;
|
||||
}
|
||||
@keyframes cardIn {
|
||||
from { opacity: 0; transform: scale(.86) translateY(40px); }
|
||||
to { opacity: 1; transform: scale(1) translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes logoPulse {
|
||||
0%, 100% { filter: drop-shadow(0 0 18px rgba(var(--teal-rgb), .45)); }
|
||||
50% { filter: drop-shadow(0 0 38px rgba(var(--teal-rgb), .8)); }
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
.li:focus {
|
||||
border-color: var(--teal) !important;
|
||||
background: rgba(var(--teal-rgb), .07) !important;
|
||||
box-shadow: 0 0 0 3px rgba(var(--teal-rgb), .12) !important;
|
||||
}
|
||||
.li::placeholder { color: rgba(255,255,255,.32); }
|
||||
|
||||
.btn-l:hover { opacity: .88; transform: translateY(-2px); transition: all .15s; }
|
||||
.btn-l:active { transform: translateY(0); }
|
||||
|
||||
.soc:hover {
|
||||
background: rgba(255,255,255,.1) !important;
|
||||
border-color: rgba(255,255,255,.22) !important;
|
||||
transform: translateY(-1px);
|
||||
transition: all .2s;
|
||||
}
|
||||
|
||||
.div-line::before, .div-line::after {
|
||||
content: ''; flex: 1;
|
||||
height: 1px; background: rgba(255,255,255,.08);
|
||||
}
|
||||
@@ -12,10 +12,23 @@ function generateAdSessionId() {
|
||||
}
|
||||
|
||||
export function getAdSessionId() {
|
||||
let sessionId = localStorage.getItem(AD_SESSION_KEY);
|
||||
if (!sessionId) {
|
||||
sessionId = generateAdSessionId();
|
||||
// localStorage бросает в приватном режиме Safari и при отключённом
|
||||
// хранилище. Здесь это ломало не только трекинг, но и сам клик по рекламе
|
||||
// (id читается до window.open), поэтому падение деградируем до временного id.
|
||||
let persisted = null;
|
||||
try {
|
||||
persisted = localStorage.getItem(AD_SESSION_KEY);
|
||||
} catch {
|
||||
persisted = null;
|
||||
}
|
||||
|
||||
if (persisted) return persisted;
|
||||
|
||||
const sessionId = generateAdSessionId();
|
||||
try {
|
||||
localStorage.setItem(AD_SESSION_KEY, sessionId);
|
||||
} catch {
|
||||
// хранилище недоступно — отдаём id без persist
|
||||
}
|
||||
return sessionId;
|
||||
}
|
||||
@@ -14,7 +14,10 @@ export function formatPhone(val) {
|
||||
: digits;
|
||||
let result = "+7";
|
||||
if (local.length > 0) result += " (" + local.slice(0, 3);
|
||||
// Скобку закрываем сразу же: иначе при 1–2 цифрах поле показывало
|
||||
// «+7 (9» / «+7 (91» и каретка прыгала при каждом нажатии.
|
||||
if (local.length >= 3) result += ") " + local.slice(3, 6);
|
||||
else if (local.length > 0) result += ")";
|
||||
if (local.length >= 6) result += "-" + local.slice(6, 8);
|
||||
if (local.length >= 8) result += "-" + local.slice(8, 10);
|
||||
return result;
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export function isMobileDevice() {
|
||||
return /Mobi|Android|iPhone/i.test(navigator.userAgent);
|
||||
}
|
||||
@@ -2,14 +2,20 @@ import i18n from '../i18n';
|
||||
|
||||
export function validatePostForm(form) {
|
||||
const errors = {};
|
||||
if (!form.title.trim()) errors.title = i18n.t('validation.titleRequired');
|
||||
if (!form.description.trim()) errors.description = i18n.t('validation.descriptionRequired');
|
||||
if (!form.category) errors.category = i18n.t('validation.categoryRequired');
|
||||
// Поля нормализуем через ??: форма могла прийти без ключа (например, из
|
||||
// нового вызывающего кода), и .trim() на undefined уронил бы форму
|
||||
// с TypeError вместо нормального сообщения валидации.
|
||||
const title = (form.title ?? "").trim();
|
||||
const description = (form.description ?? "").trim();
|
||||
|
||||
if (!title) errors.title = i18n.t('validation.titleRequired');
|
||||
if (!description) errors.description = i18n.t('validation.descriptionRequired');
|
||||
if (!form.category) errors.category = i18n.t('validation.categoryRequired');
|
||||
|
||||
// Телефон обязателен для объявления (в отличие от профиля) — проверяем
|
||||
// количество цифр, а не просто пустоту, т.к. form.phone форматируется
|
||||
// через formatPhone и всегда содержит минимум "+7".
|
||||
if (form.phone.replace(/\D/g, "").length < 11) {
|
||||
if ((form.phone ?? "").replace(/\D/g, "").length < 11) {
|
||||
errors.phone = i18n.t('validation.phoneRequired');
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user