Compare commits
26 Commits
master
...
a122d4871a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a122d4871a | ||
|
|
8208c9f4d8 | ||
|
|
db6889c9db | ||
|
|
2cc3237370 | ||
|
|
0fce7f1536 | ||
|
|
fea07d505a | ||
|
|
03a0d2ebce | ||
|
|
89fdef31cc | ||
|
|
16a55c95c0 | ||
|
|
2fd28ee776 | ||
|
|
597169407e | ||
|
|
1aeda90da1 | ||
|
|
93f00e2cb4 | ||
|
|
b924483231 | ||
|
|
55c71e664d | ||
|
|
326d00d005 | ||
|
|
17795e71ad | ||
|
|
17ad88e59f | ||
|
|
13a91b3f74 | ||
|
|
77a873a78c | ||
|
|
259bf51fdf | ||
|
|
b97387b159 | ||
|
|
9d38a77904 | ||
|
|
1d3c5bcf0f | ||
|
|
bfbe84c9aa | ||
|
|
6dc61050d9 |
4
.dockerignore
Normal file
4
.dockerignore
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
.git
|
||||||
|
node_modules
|
||||||
|
build
|
||||||
|
.idea
|
||||||
16
.env.example
Normal file
16
.env.example
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
# Скопируйте этот файл в .env и подставьте свои значения.
|
||||||
|
# .env в .gitignore не попадает — реальные ключи не должны попадать в репозиторий.
|
||||||
|
|
||||||
|
# URL бэкенда. В dev чаще всего http://localhost:8080
|
||||||
|
REACT_APP_API_URL=http://localhost:8080
|
||||||
|
|
||||||
|
# Ключ Яндекс.Геокодера (обратное геокодирование адреса в координаты).
|
||||||
|
# Получить: https://developer.tech.yandex.ru/
|
||||||
|
REACT_APP_YANDEX_GEOCODER_KEY=
|
||||||
|
|
||||||
|
# Публичный ключ Яндекс.Карт (подставляется в public/index.html при загрузке API-карт).
|
||||||
|
# Получить: https://developer.tech.yandex.ru/
|
||||||
|
REACT_APP_YANDEX_MAPS_KEY=
|
||||||
|
|
||||||
|
# Почта поддержки в модалке «Поддержка». Необязательно — есть значение по умолчанию.
|
||||||
|
REACT_APP_SUPPORT_EMAIL=
|
||||||
24
.gitea/workflows/deploy.yml
Normal file
24
.gitea/workflows/deploy.yml
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
name: deploy-frontend
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: host
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Build image
|
||||||
|
env:
|
||||||
|
GEOCODER_KEY: ${{ secrets.REACT_APP_YANDEX_GEOCODER_KEY }}
|
||||||
|
MAPS_KEY: ${{ secrets.REACT_APP_YANDEX_MAPS_KEY }}
|
||||||
|
run: |
|
||||||
|
docker build \
|
||||||
|
--build-arg REACT_APP_YANDEX_GEOCODER_KEY="$GEOCODER_KEY" \
|
||||||
|
--build-arg REACT_APP_YANDEX_MAPS_KEY="$MAPS_KEY" \
|
||||||
|
-t nakhodka-frontend:latest \
|
||||||
|
-t nakhodka-frontend:${{ github.sha }} .
|
||||||
|
- name: Restart frontend
|
||||||
|
run: docker compose -f /opt/nakhodka/docker-compose.yml up -d frontend
|
||||||
|
- name: Cleanup
|
||||||
|
run: docker image prune -f
|
||||||
9
.npmrc
Normal file
9
.npmrc
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# react-scripts@5.0.1 объявляет typescript как ОПЦИОНАЛЬНЫЙ peer с диапазоном
|
||||||
|
# "^3.2.1 || ^4", а проекту нужен TypeScript 5.x: на TS 4 не собираются
|
||||||
|
# @types/react 18.3 и zod v4 (269 ошибок в node_modules).
|
||||||
|
#
|
||||||
|
# Конфликт чисто формальный: react-scripts типы не проверяет, их вырезает babel,
|
||||||
|
# а tsc запускается отдельно через `npm run typecheck`. Поэтому разрешаем
|
||||||
|
# npm игнорировать peer-диапазоны и не заставлять каждого нового разработчика
|
||||||
|
# ставить зависимости через --force / --legacy-peer-deps вручную.
|
||||||
|
legacy-peer-deps=true
|
||||||
16
Dockerfile
Normal file
16
Dockerfile
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
FROM node:22-alpine AS build
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package*.json ./
|
||||||
|
RUN npm install --legacy-peer-deps
|
||||||
|
COPY . .
|
||||||
|
ARG REACT_APP_API_URL=https://app.nahodka-test.online
|
||||||
|
ARG REACT_APP_YANDEX_GEOCODER_KEY=
|
||||||
|
ARG REACT_APP_YANDEX_MAPS_KEY=
|
||||||
|
ENV REACT_APP_API_URL=$REACT_APP_API_URL
|
||||||
|
ENV REACT_APP_YANDEX_GEOCODER_KEY=$REACT_APP_YANDEX_GEOCODER_KEY
|
||||||
|
ENV REACT_APP_YANDEX_MAPS_KEY=$REACT_APP_YANDEX_MAPS_KEY
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
FROM nginx:alpine
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY --from=build /app/build /usr/share/nginx/html
|
||||||
@@ -170,7 +170,7 @@ src/
|
|||||||
│ ├── admin/ PostsTab, AdvertisingCreate/EditModal, CampaignCreate/EditModal, ...
|
│ ├── admin/ PostsTab, AdvertisingCreate/EditModal, CampaignCreate/EditModal, ...
|
||||||
│ ├── landing/ Hero, Navbar, StepsSection, RadarBeacon, FinalCta, Footer, Icon
|
│ ├── landing/ Hero, Navbar, StepsSection, RadarBeacon, FinalCta, Footer, Icon
|
||||||
│ ├── icons/ NavIcons + Calendar/Close/Globe/Menu/Moon/Phone/Pin/Sun/Trash
|
│ ├── icons/ NavIcons + Calendar/Close/Globe/Menu/Moon/Phone/Pin/Sun/Trash
|
||||||
│ └── … AuthModal, Toast, MapView, PostDetailModal, ImageViewer, AdCard, AdSlot, ...
|
│ └── … AuthModal, Toast, MapView, PostDetailModal, AdCard, AdSlot, ...
|
||||||
│
|
│
|
||||||
├── styles/
|
├── styles/
|
||||||
│ ├── index.css # Точка входа CSS
|
│ ├── index.css # Точка входа CSS
|
||||||
|
|||||||
14
nginx.conf
Normal file
14
nginx.conf
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location /static/ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri /index.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,15 +3,12 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@emoji-mart/data": "^1.2.1",
|
|
||||||
"@emoji-mart/react": "^1.1.1",
|
|
||||||
"@hookform/resolvers": "^5.2.2",
|
"@hookform/resolvers": "^5.2.2",
|
||||||
"@stomp/stompjs": "^7.3.0",
|
"@stomp/stompjs": "^7.3.0",
|
||||||
"@testing-library/dom": "^10.4.1",
|
"@testing-library/dom": "^10.4.1",
|
||||||
"@testing-library/jest-dom": "^6.9.1",
|
"@testing-library/jest-dom": "^6.9.1",
|
||||||
"@testing-library/react": "^16.3.2",
|
"@testing-library/react": "^16.3.2",
|
||||||
"@testing-library/user-event": "^13.5.0",
|
"@testing-library/user-event": "^13.5.0",
|
||||||
"emoji-mart": "^5.6.0",
|
|
||||||
"framer-motion": "^12.38.0",
|
"framer-motion": "^12.38.0",
|
||||||
"i18next": "^22.5.1",
|
"i18next": "^22.5.1",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
|
|||||||
@@ -1,122 +0,0 @@
|
|||||||
import { useState, useCallback, useEffect, useRef, useMemo } from "react";
|
|
||||||
import { useTranslation } from 'react-i18next';
|
|
||||||
import CloseIcon from "./icons/CloseIcon";
|
|
||||||
import Toast from "./Toast";
|
|
||||||
import { getImageUrl } from "../config/authConstants";
|
|
||||||
import { useContactSeller } from "../hooks/useContactSeller";
|
|
||||||
import { useAuthContext } from "../context/AuthContext";
|
|
||||||
|
|
||||||
export default function ImageViewer({ images, initialIndex = 0, onClose, postData }) {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const [index, setIndex] = useState(initialIndex);
|
|
||||||
const touchStart = useRef(null);
|
|
||||||
const swiped = useRef(false);
|
|
||||||
const { isAuthenticated } = useAuthContext();
|
|
||||||
const { contactSeller, error: contactError, clearError } = useContactSeller(postData);
|
|
||||||
|
|
||||||
const urls = useMemo(() => images.map(u => getImageUrl(u)), [images]);
|
|
||||||
|
|
||||||
const next = useCallback(() => {
|
|
||||||
setIndex(i => (i + 1) % urls.length);
|
|
||||||
}, [urls.length]);
|
|
||||||
|
|
||||||
const prev = useCallback(() => {
|
|
||||||
setIndex(i => (i - 1 + urls.length) % urls.length);
|
|
||||||
}, [urls.length]);
|
|
||||||
|
|
||||||
const handleImgClick = useCallback(() => {
|
|
||||||
next();
|
|
||||||
}, [next]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const handleKey = (e) => {
|
|
||||||
if (e.key === "Escape") onClose();
|
|
||||||
if (e.key === "ArrowRight") next();
|
|
||||||
if (e.key === "ArrowLeft") prev();
|
|
||||||
};
|
|
||||||
window.addEventListener("keydown", handleKey);
|
|
||||||
return () => window.removeEventListener("keydown", handleKey);
|
|
||||||
}, [onClose, next, prev]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setIndex(initialIndex);
|
|
||||||
}, [initialIndex]);
|
|
||||||
|
|
||||||
const handleTouchStart = useCallback((e) => {
|
|
||||||
touchStart.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleTouchEnd = useCallback((e) => {
|
|
||||||
if (!touchStart.current) return;
|
|
||||||
const dx = e.changedTouches[0].clientX - touchStart.current.x;
|
|
||||||
const dy = e.changedTouches[0].clientY - touchStart.current.y;
|
|
||||||
const isHorizontal = Math.abs(dx) > Math.abs(dy);
|
|
||||||
if (isHorizontal && Math.abs(dx) > 50) {
|
|
||||||
swiped.current = true;
|
|
||||||
if (dx > 0) prev();
|
|
||||||
else next();
|
|
||||||
setTimeout(() => { swiped.current = false; }, 400);
|
|
||||||
}
|
|
||||||
touchStart.current = null;
|
|
||||||
}, [prev, next]);
|
|
||||||
|
|
||||||
const handleContact = useCallback(() => {
|
|
||||||
// Закрываем вьюер перед переходом в чат
|
|
||||||
contactSeller(onClose);
|
|
||||||
}, [contactSeller, onClose]);
|
|
||||||
|
|
||||||
const showContact = isAuthenticated && postData && !postData.isOwner && postData.status !== 'CLOSED';
|
|
||||||
|
|
||||||
if (!urls.length) return null;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className="f-viewer-bg"
|
|
||||||
onTouchStart={handleTouchStart}
|
|
||||||
onTouchEnd={handleTouchEnd}
|
|
||||||
onClick={e => e.target === e.currentTarget && !swiped.current && onClose()}
|
|
||||||
>
|
|
||||||
<button type="button" className="f-viewer-close" onClick={onClose} aria-label={t('common.close')}>
|
|
||||||
<CloseIcon />
|
|
||||||
</button>
|
|
||||||
|
|
||||||
<div className="f-viewer">
|
|
||||||
<div className="f-viewer-img-wrap" onClick={handleImgClick}>
|
|
||||||
<img
|
|
||||||
src={urls[index]}
|
|
||||||
alt=""
|
|
||||||
className="f-viewer-img"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{showContact && (
|
|
||||||
<button type="button" className="f-viewer-contact" onClick={handleContact}>
|
|
||||||
{t('postCard.write')}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{urls.length > 1 && (
|
|
||||||
<div className="f-viewer-dots">
|
|
||||||
{urls.map((_, i) => (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
key={i}
|
|
||||||
className={`f-viewer-dot${i === index ? " active" : ""}`}
|
|
||||||
onClick={() => setIndex(i)}
|
|
||||||
aria-label={t('viewer.goToImage', { number: i + 1 })}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{contactError && (
|
|
||||||
<Toast
|
|
||||||
message={contactError}
|
|
||||||
type="error"
|
|
||||||
onDismiss={clearError}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
239
src/components/MapView.test.jsx
Normal file
239
src/components/MapView.test.jsx
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
/**
|
||||||
|
* Регрессия: первая загрузка маркеров должна уходить с границами карты.
|
||||||
|
*
|
||||||
|
* Раньше первый запрос висел на map.events.add('load'), которого у ymaps.Map
|
||||||
|
* в 2.1 нет — событие не наступало, fetch не уходил, а спиннер закрывал
|
||||||
|
* карту навсегда. Фейковый ymaps ниже намеренно НЕ умеет в 'load'.
|
||||||
|
*/
|
||||||
|
import { render, screen, waitFor, act } from "@testing-library/react";
|
||||||
|
import MapView from "./MapView";
|
||||||
|
// Реальный i18n, а не заглушка: MapView использует t() и без инициализации
|
||||||
|
// react-i18next сыплет предупреждение, а проверка текста ошибки теряла бы смысл.
|
||||||
|
import "../i18n";
|
||||||
|
|
||||||
|
jest.mock("../hooks/useGeolocation", () => ({
|
||||||
|
GEO_STATUS: {
|
||||||
|
IDLE: "idle",
|
||||||
|
LOADING: "loading",
|
||||||
|
SUCCESS: "success",
|
||||||
|
DENIED: "denied",
|
||||||
|
UNSUPPORTED: "unsupported",
|
||||||
|
TIMEOUT: "timeout",
|
||||||
|
},
|
||||||
|
// Геолокация в тестах не нужна и капризна (navigator.geolocation).
|
||||||
|
useGeolocation: () => ({ coords: null, status: "idle", requestLocation: jest.fn() }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const BOUNDS = [[55.7, 37.55], [55.8, 37.7]];
|
||||||
|
|
||||||
|
function installFakeYmaps({ boundsInitiallyNull = true } = {}) {
|
||||||
|
const listeners = {};
|
||||||
|
let bounds = boundsInitiallyNull ? null : BOUNDS;
|
||||||
|
|
||||||
|
const map = {
|
||||||
|
events: {
|
||||||
|
add(name, cb) {
|
||||||
|
(listeners[name] = listeners[name] || []).push(cb);
|
||||||
|
return { name, cb };
|
||||||
|
},
|
||||||
|
remove(sub) {
|
||||||
|
listeners[sub.name] = (listeners[sub.name] || []).filter((cb) => cb !== sub.cb);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
geoObjects: { add() {}, removeAll() {} },
|
||||||
|
getBounds: () => bounds,
|
||||||
|
setCenter: jest.fn(),
|
||||||
|
destroy: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
window.ymaps = {
|
||||||
|
ready: (cb) => cb(),
|
||||||
|
Map: jest.fn(() => map),
|
||||||
|
GeoObjectCollection: jest.fn(function GeoObjectCollection() {
|
||||||
|
this.add = jest.fn();
|
||||||
|
this.removeAll = jest.fn();
|
||||||
|
}),
|
||||||
|
Placemark: jest.fn(function Placemark() {
|
||||||
|
this.events = { add() {} };
|
||||||
|
this.geometry = { setCoordinates() {} };
|
||||||
|
}),
|
||||||
|
templateLayoutFactory: { createClass: jest.fn(() => function Layout() {}) },
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
map,
|
||||||
|
/** Имитирует первый расчёт вьюпорта — так ведёт себя настоящий API. */
|
||||||
|
publishBounds() {
|
||||||
|
bounds = BOUNDS;
|
||||||
|
act(() => {
|
||||||
|
(listeners.boundschange || []).forEach((cb) => cb());
|
||||||
|
});
|
||||||
|
},
|
||||||
|
panTo(next) {
|
||||||
|
bounds = next;
|
||||||
|
act(() => {
|
||||||
|
(listeners.boundschange || []).forEach((cb) => cb());
|
||||||
|
});
|
||||||
|
},
|
||||||
|
fireBoundsChangeOnly() {
|
||||||
|
act(() => {
|
||||||
|
(listeners.boundschange || []).forEach((cb) => cb());
|
||||||
|
});
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let fetchMock;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.useFakeTimers();
|
||||||
|
fetchMock = jest.fn().mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: async () => [
|
||||||
|
{ id: 1, latitude: 55.75, longitude: 37.61, type: "LOST", title: "Кошелёк" },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
global.fetch = fetchMock;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
delete window.ymaps;
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
function mapCall(index = 0) {
|
||||||
|
const url = fetchMock.mock.calls[index]?.[0] || "";
|
||||||
|
return new URL(url, "http://localhost");
|
||||||
|
}
|
||||||
|
|
||||||
|
test("первый запрос уходит с границами карты, а не пустым query", async () => {
|
||||||
|
const ymaps = installFakeYmaps();
|
||||||
|
|
||||||
|
render(<MapView focusPostId={null} focusLat={NaN} focusLng={NaN} onBack={() => {}} />);
|
||||||
|
|
||||||
|
// Границы появляются только после первого расчёта вьюпорта.
|
||||||
|
ymaps.publishBounds();
|
||||||
|
|
||||||
|
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
const url = mapCall();
|
||||||
|
expect(url.pathname).toBe("/api/v1/posts/map");
|
||||||
|
expect(url.searchParams.get("minLat")).toBe("55.7");
|
||||||
|
expect(url.searchParams.get("minLng")).toBe("37.55");
|
||||||
|
expect(url.searchParams.get("maxLat")).toBe("55.8");
|
||||||
|
expect(url.searchParams.get("maxLng")).toBe("37.7");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("все четыре граничных параметра присутствуют в каждом запросе", async () => {
|
||||||
|
const ymaps = installFakeYmaps();
|
||||||
|
|
||||||
|
render(<MapView onBack={() => {}} />);
|
||||||
|
ymaps.publishBounds();
|
||||||
|
|
||||||
|
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
|
||||||
|
|
||||||
|
for (const call of fetchMock.mock.calls) {
|
||||||
|
const url = new URL(call[0], "http://localhost");
|
||||||
|
for (const key of ["minLat", "maxLat", "minLng", "maxLng"]) {
|
||||||
|
expect(url.searchParams.get(key)).not.toBeNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("опциональные фильтры type/category уезжают в том же запросе", async () => {
|
||||||
|
const ymaps = installFakeYmaps();
|
||||||
|
|
||||||
|
render(<MapView type="LOST" category="Электроника" onBack={() => {}} />);
|
||||||
|
ymaps.publishBounds();
|
||||||
|
|
||||||
|
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
const url = mapCall();
|
||||||
|
expect(url.searchParams.get("type")).toBe("LOST");
|
||||||
|
expect(url.searchParams.get("category")).toBe("Электроника");
|
||||||
|
expect(url.searchParams.get("minLat")).toBe("55.7");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("фильтры не добавляются, когда не заданы", async () => {
|
||||||
|
const ymaps = installFakeYmaps();
|
||||||
|
|
||||||
|
render(<MapView onBack={() => {}} />);
|
||||||
|
ymaps.publishBounds();
|
||||||
|
|
||||||
|
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
const url = mapCall();
|
||||||
|
expect(url.searchParams.has("type")).toBe(false);
|
||||||
|
expect(url.searchParams.has("category")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("перемещение карты перезапрашивает маркеры один раз, несмотря на debounce", async () => {
|
||||||
|
const ymaps = installFakeYmaps();
|
||||||
|
|
||||||
|
render(<MapView onBack={() => {}} />);
|
||||||
|
ymaps.publishBounds();
|
||||||
|
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
// Серия boundschange без пауз — должна схлопнуться в один запрос.
|
||||||
|
ymaps.fireBoundsChangeOnly();
|
||||||
|
ymaps.fireBoundsChangeOnly();
|
||||||
|
ymaps.fireBoundsChangeOnly();
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
jest.advanceTimersByTime(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Новые границы = ровно один новый запрос.
|
||||||
|
ymaps.panTo([[55.9, 37.4], [56.0, 37.5]]);
|
||||||
|
await act(async () => {
|
||||||
|
jest.advanceTimersByTime(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
|
||||||
|
const url = mapCall(1);
|
||||||
|
expect(url.searchParams.get("minLat")).toBe("55.9");
|
||||||
|
expect(url.searchParams.get("maxLng")).toBe("37.5");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("одинаковые границы не порождают повторный запрос", async () => {
|
||||||
|
const ymaps = installFakeYmaps();
|
||||||
|
|
||||||
|
render(<MapView onBack={() => {}} />);
|
||||||
|
ymaps.publishBounds();
|
||||||
|
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
|
||||||
|
|
||||||
|
ymaps.fireBoundsChangeOnly();
|
||||||
|
await act(async () => {
|
||||||
|
jest.advanceTimersByTime(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("спиннер снимается и карта не остаётся закрыта оверлеем", async () => {
|
||||||
|
const ymaps = installFakeYmaps();
|
||||||
|
|
||||||
|
render(<MapView onBack={() => {}} />);
|
||||||
|
ymaps.publishBounds();
|
||||||
|
|
||||||
|
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.queryByTestId("mapview-loading")).toBeNull();
|
||||||
|
});
|
||||||
|
expect(screen.queryByText("Ошибка загрузки карты")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("даже если границы так и не пришли, карта не висит в вечной загрузке", async () => {
|
||||||
|
installFakeYmaps();
|
||||||
|
|
||||||
|
render(<MapView onBack={() => {}} />);
|
||||||
|
|
||||||
|
await waitFor(
|
||||||
|
() => {
|
||||||
|
expect(screen.queryByTestId("mapview-loading")).toBeNull();
|
||||||
|
},
|
||||||
|
{ timeout: 8000 }
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -6,7 +6,7 @@ import { useAuthContext } from "../context/AuthContext";
|
|||||||
import PostOnFeed from "../pages/PostOnFeed";
|
import PostOnFeed from "../pages/PostOnFeed";
|
||||||
import CloseIcon from "./icons/CloseIcon";
|
import CloseIcon from "./icons/CloseIcon";
|
||||||
|
|
||||||
export default function PostDetailModal({ postId, onClose, onImageClick, onLocationClick, onAuthRequired }) {
|
export default function PostDetailModal({ postId, onClose, onLocationClick, onAuthRequired }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { user } = useAuthContext();
|
const { user } = useAuthContext();
|
||||||
const [post, setPost] = useState(null);
|
const [post, setPost] = useState(null);
|
||||||
@@ -62,7 +62,6 @@ export default function PostDetailModal({ postId, onClose, onImageClick, onLocat
|
|||||||
<PostOnFeed
|
<PostOnFeed
|
||||||
ad={post}
|
ad={post}
|
||||||
isOwner={isOwner}
|
isOwner={isOwner}
|
||||||
onImageClick={onImageClick}
|
|
||||||
onLocationClick={onLocationClick}
|
onLocationClick={onLocationClick}
|
||||||
onAuthRequired={onAuthRequired}
|
onAuthRequired={onAuthRequired}
|
||||||
compact
|
compact
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ export default function Sidebar({
|
|||||||
activeNav,
|
activeNav,
|
||||||
onClose,
|
onClose,
|
||||||
onNavClick,
|
onNavClick,
|
||||||
onLogoClick,
|
|
||||||
isAuthenticated,
|
isAuthenticated,
|
||||||
onLoginClick,
|
onLoginClick,
|
||||||
onRulesClick,
|
onRulesClick,
|
||||||
@@ -80,7 +79,7 @@ export default function Sidebar({
|
|||||||
type="button"
|
type="button"
|
||||||
className="f-sb-logo-btn"
|
className="f-sb-logo-btn"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
onLogoClick?.();
|
navigate("/");
|
||||||
onClose();
|
onClose();
|
||||||
}}
|
}}
|
||||||
title={t('nav.home')}
|
title={t('nav.home')}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import PostOnFeed from "../../pages/PostOnFeed";
|
import PostOnFeed from "../../pages/PostOnFeed";
|
||||||
import CreateUpdatePost from "../../pages/CreateUpdatePost";
|
import CreateUpdatePost from "../../pages/CreateUpdatePost";
|
||||||
import ImageViewer from "../ImageViewer";
|
|
||||||
import Toast from "../Toast";
|
import Toast from "../Toast";
|
||||||
import {
|
import {
|
||||||
getAdminPosts,
|
getAdminPosts,
|
||||||
@@ -66,7 +65,6 @@ export default function PostsTab({ isAdmin, mode = "all" }) {
|
|||||||
const [statusFilter, setStatusFilter] = useState("");
|
const [statusFilter, setStatusFilter] = useState("");
|
||||||
|
|
||||||
const [editing, setEditing] = useState(null);
|
const [editing, setEditing] = useState(null);
|
||||||
const [viewer, setViewer] = useState(null);
|
|
||||||
const [busyId, setBusyId] = useState(null);
|
const [busyId, setBusyId] = useState(null);
|
||||||
const [toast, setToast] = useState(null);
|
const [toast, setToast] = useState(null);
|
||||||
|
|
||||||
@@ -148,10 +146,6 @@ export default function PostsTab({ isAdmin, mode = "all" }) {
|
|||||||
showToast(t("adminPanel.postsUpdated"));
|
showToast(t("adminPanel.postsUpdated"));
|
||||||
}, [load, page, showToast, t]);
|
}, [load, page, showToast, t]);
|
||||||
|
|
||||||
const handleImageClick = useCallback((images, index, ad) => {
|
|
||||||
if (images?.length) setViewer({ images, index, ad });
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const contentStyle = useMemo(() => ({ opacity: busyId === null ? 1 : 0.75 }), [busyId]);
|
const contentStyle = useMemo(() => ({ opacity: busyId === null ? 1 : 0.75 }), [busyId]);
|
||||||
|
|
||||||
if (!isAdmin) return null;
|
if (!isAdmin) return null;
|
||||||
@@ -234,7 +228,6 @@ export default function PostsTab({ isAdmin, mode = "all" }) {
|
|||||||
onDelete={handleDelete}
|
onDelete={handleDelete}
|
||||||
onMarkFound={(id) => setStatus(id, "CLOSED")}
|
onMarkFound={(id) => setStatus(id, "CLOSED")}
|
||||||
onReopen={(id) => setStatus(id, "ACTIVE")}
|
onReopen={(id) => setStatus(id, "ACTIVE")}
|
||||||
onImageClick={handleImageClick}
|
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -261,15 +254,6 @@ export default function PostsTab({ isAdmin, mode = "all" }) {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{viewer && (
|
|
||||||
<ImageViewer
|
|
||||||
images={viewer.images}
|
|
||||||
initialIndex={viewer.index}
|
|
||||||
postData={viewer.ad}
|
|
||||||
onClose={() => setViewer(null)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{toast && <Toast message={toast.message} type={toast.type} onDismiss={() => setToast(null)} />}
|
{toast && <Toast message={toast.message} type={toast.type} onDismiss={() => setToast(null)} />}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
export default function ChatHeader({ title, onBack, avatar, statusLabel, statusConnected }) {
|
export default function ChatHeader({ title, onBack, avatar }) {
|
||||||
return (
|
return (
|
||||||
<div className="chat-header">
|
<div className="chat-header">
|
||||||
<button className="chat-back-btn" onClick={onBack}>
|
<button className="chat-back-btn" onClick={onBack}>
|
||||||
@@ -8,13 +8,7 @@ export default function ChatHeader({ title, onBack, avatar, statusLabel, statusC
|
|||||||
<div className="chat-header-avatar">{avatar}</div>
|
<div className="chat-header-avatar">{avatar}</div>
|
||||||
)}
|
)}
|
||||||
<div className="chat-header-title">{title}</div>
|
<div className="chat-header-title">{title}</div>
|
||||||
{statusLabel !== undefined ? (
|
<div />
|
||||||
<div className={`chat-status${statusConnected ? " connected" : ""}`}>
|
|
||||||
{statusLabel}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div />
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,40 +1,12 @@
|
|||||||
import { useRef } from "react";
|
|
||||||
import Picker from "@emoji-mart/react";
|
|
||||||
import emojiData from "@emoji-mart/data";
|
|
||||||
import { useClickOutside } from "../../hooks/useClickOutside";
|
|
||||||
import { useTheme } from "../../context/ThemeContext";
|
|
||||||
|
|
||||||
export default function ChatInputBar({
|
export default function ChatInputBar({
|
||||||
input,
|
input,
|
||||||
onInputChange,
|
onInputChange,
|
||||||
onSend,
|
onSend,
|
||||||
onEmojiSelect,
|
|
||||||
showEmoji,
|
|
||||||
onToggleEmoji,
|
|
||||||
onCloseEmoji,
|
|
||||||
connected,
|
connected,
|
||||||
placeholder,
|
placeholder,
|
||||||
}) {
|
}) {
|
||||||
const emojiPickerRef = useRef(null);
|
|
||||||
useClickOutside(emojiPickerRef, onCloseEmoji, showEmoji);
|
|
||||||
const { theme } = useTheme();
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="chat-input-area">
|
<div className="chat-input-area">
|
||||||
{showEmoji && (
|
|
||||||
<div className="chat-emoji-picker" ref={emojiPickerRef}>
|
|
||||||
<Picker
|
|
||||||
data={emojiData}
|
|
||||||
onEmojiSelect={onEmojiSelect}
|
|
||||||
theme={theme}
|
|
||||||
previewPosition="none"
|
|
||||||
skinTonePosition="none"
|
|
||||||
searchPosition="sticky"
|
|
||||||
maxSearchResults={30}
|
|
||||||
perLine={8}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<form onSubmit={onSend} className="chat-input-row">
|
<form onSubmit={onSend} className="chat-input-row">
|
||||||
<input
|
<input
|
||||||
value={input}
|
value={input}
|
||||||
@@ -42,13 +14,6 @@ export default function ChatInputBar({
|
|||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
className="chat-input"
|
className="chat-input"
|
||||||
/>
|
/>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={`chat-emoji-btn${showEmoji ? " active" : ""}`}
|
|
||||||
onClick={onToggleEmoji}
|
|
||||||
>
|
|
||||||
😊
|
|
||||||
</button>
|
|
||||||
<button type="submit" className="chat-send-btn" disabled={!connected}>
|
<button type="submit" className="chat-send-btn" disabled={!connected}>
|
||||||
➤
|
➤
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ export default function FeedContent({
|
|||||||
onEdit,
|
onEdit,
|
||||||
onDelete,
|
onDelete,
|
||||||
onMarkFound,
|
onMarkFound,
|
||||||
onImageClick,
|
onReopen,
|
||||||
onLocationClick,
|
onLocationClick,
|
||||||
onAuthRequired,
|
onAuthRequired,
|
||||||
showAds = false,
|
showAds = false,
|
||||||
@@ -88,8 +88,8 @@ export default function FeedContent({
|
|||||||
onEdit={activeNav === "myads" ? onEdit : undefined}
|
onEdit={activeNav === "myads" ? onEdit : undefined}
|
||||||
onDelete={activeNav === "myads" ? onDelete : undefined}
|
onDelete={activeNav === "myads" ? onDelete : undefined}
|
||||||
onMarkFound={activeNav === "myads" ? onMarkFound : undefined}
|
onMarkFound={activeNav === "myads" ? onMarkFound : undefined}
|
||||||
|
onReopen={activeNav === "myads" ? onReopen : undefined}
|
||||||
isOwner={activeNav === "myads"}
|
isOwner={activeNav === "myads"}
|
||||||
onImageClick={onImageClick}
|
|
||||||
onLocationClick={onLocationClick}
|
onLocationClick={onLocationClick}
|
||||||
onAuthRequired={onAuthRequired}
|
onAuthRequired={onAuthRequired}
|
||||||
/>
|
/>
|
||||||
|
|||||||
8
src/components/icons/CheckIcon.jsx
Normal file
8
src/components/icons/CheckIcon.jsx
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
export default function CheckIcon ({ size = 12 }) {
|
||||||
|
return (
|
||||||
|
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
||||||
|
strokeWidth={3} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||||
|
<polyline points="20 6 9 17 4 12" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
export const API_URL = process.env.REACT_APP_API_URL || "http://localhost:8080";
|
export const API_URL = process.env.REACT_APP_API_URL || "http://localhost:8080";
|
||||||
|
|
||||||
export function getImageUrl(filename) {
|
export function getImageUrl(filename) {
|
||||||
if (!filename) return null;
|
if (!filename) return null;
|
||||||
if (filename.startsWith("http")) return filename;
|
if (filename.startsWith("http")) return filename;
|
||||||
if (filename.startsWith("/")) return `${API_URL}${filename}`;
|
if (filename.startsWith("/")) return `${API_URL}${filename}`;
|
||||||
return `${API_URL}/api/v1/files/${filename}`;
|
return `${API_URL}/api/v1/files/${filename}?presigned=true`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const SUPPORT_EMAIL = process.env.REACT_APP_SUPPORT_EMAIL || "support@nakhodka.app";
|
export const SUPPORT_EMAIL = process.env.REACT_APP_SUPPORT_EMAIL || "support@nakhodka.app";
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
export const NAV_ITEMS = [
|
export const NAV_ITEMS = [
|
||||||
{ icon: "grid", key: "home", labelKey: "nav.home" },
|
{ icon: "grid", key: "home", labelKey: "nav.home" },
|
||||||
{ icon: "chat", key: "chat", labelKey: "nav.chat" },
|
|
||||||
{ icon: "box", key: "items", labelKey: "nav.items" },
|
{ icon: "box", key: "items", labelKey: "nav.items" },
|
||||||
{ icon: "paw", key: "pets", labelKey: "nav.pets" },
|
{ icon: "paw", key: "pets", labelKey: "nav.pets" },
|
||||||
{ icon: "file", key: "myads", labelKey: "nav.myAds" },
|
{ icon: "file", key: "myads", labelKey: "nav.myAds" },
|
||||||
|
{ icon: "chat", key: "chat", labelKey: "nav.chat" },
|
||||||
{ icon: "plus", key: "create", labelKey: "nav.create" },
|
{ icon: "plus", key: "create", labelKey: "nav.create" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
7
src/config/postConstants.js
Normal file
7
src/config/postConstants.js
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
// Статусы объявления — зеркало бэкенда (enum PostStatus).
|
||||||
|
//
|
||||||
|
// Раньше строка 'CLOSED' была захардкожена в четырёх местах (карточка,
|
||||||
|
// просмотрщик, хуки, админ-панель), и любая опечатка проходила тихо:
|
||||||
|
// карточка просто не показывала статус. Держим значение в одном месте.
|
||||||
|
export const POST_STATUS_ACTIVE = "ACTIVE";
|
||||||
|
export const POST_STATUS_CLOSED = "CLOSED";
|
||||||
@@ -8,16 +8,21 @@ import { useUnread } from "../context/UnreadContext";
|
|||||||
export function useChats() {
|
export function useChats() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [chats, setChats] = useState([]);
|
const [chats, setChats] = useState([]);
|
||||||
const [loading, setLoading] = useState(false);
|
// Стартуем в состоянии загрузки: иначе самый первый рендер успевает показать
|
||||||
|
// "Нет чатов" до того, как эффект выставит loading — список "моргает".
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const { updateFromChats, clearChatUnread } = useUnread();
|
const { updateFromChats, clearChatUnread } = useUnread();
|
||||||
// fetchChats дёргается и при монтировании, и на каждое изменение totalUnread —
|
// fetchChats дёргается и при монтировании, и на каждое изменение totalUnread —
|
||||||
// без guard'а медленный предыдущий ответ воскрешал бы прочитанные счётчики.
|
// без guard'а медленный предыдущий ответ воскрешал бы прочитанные счётчики.
|
||||||
const requestIdRef = useRef(0);
|
const requestIdRef = useRef(0);
|
||||||
|
|
||||||
const fetchChats = useCallback(async () => {
|
// silent=true — фоновое обновление списка (новое сообщение по WS, удаление
|
||||||
|
// чата и т.п.): не трогаем loading, иначе текущий список на миг подменяется
|
||||||
|
// экраном загрузки и страница "моргает".
|
||||||
|
const fetchChats = useCallback(async ({ silent = false } = {}) => {
|
||||||
const requestId = ++requestIdRef.current;
|
const requestId = ++requestIdRef.current;
|
||||||
setLoading(true);
|
if (!silent) setLoading(true);
|
||||||
setError("");
|
setError("");
|
||||||
try {
|
try {
|
||||||
const res = await apiFetch(`${API_URL}/api/v1/chats`);
|
const res = await apiFetch(`${API_URL}/api/v1/chats`);
|
||||||
@@ -33,7 +38,7 @@ export function useChats() {
|
|||||||
if (requestId !== requestIdRef.current) return;
|
if (requestId !== requestIdRef.current) return;
|
||||||
setError(e.message || t('chats.fetchError'));
|
setError(e.message || t('chats.fetchError'));
|
||||||
} finally {
|
} finally {
|
||||||
if (requestId === requestIdRef.current) setLoading(false);
|
if (requestId === requestIdRef.current && !silent) setLoading(false);
|
||||||
}
|
}
|
||||||
}, [updateFromChats, t]);
|
}, [updateFromChats, t]);
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { useChats } from "./useChats";
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* useContactSeller — общая логика открытия/создания чата с автором объявления.
|
* useContactSeller — общая логика открытия/создания чата с автором объявления.
|
||||||
* Используется в PostOnFeed (карточка в ленте) и ImageViewer (просмотр фото).
|
* Используется в PostOnFeed (карточка в ленте).
|
||||||
*
|
*
|
||||||
* @param {object} post — объявление: { id, userId, title, images, emoji }
|
* @param {object} post — объявление: { id, userId, title, images, emoji }
|
||||||
* @returns {{
|
* @returns {{
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
import { useState, useCallback } from "react";
|
import { useState, useCallback } from "react";
|
||||||
import { useDeletePost } from "./useDeletePost";
|
import { useDeletePost } from "./useDeletePost";
|
||||||
import { usePostStatus } from "./usePostStatus";
|
import { usePostStatus } from "./usePostStatus";
|
||||||
|
import { rememberFoundAt, forgetFoundAt } from "../utils/foundAt";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Объединяет действия над объявлениями (удаление, отметка "найдено")
|
* Объединяет действия над объявлениями (удаление, отметка "найдено")
|
||||||
@@ -23,7 +24,7 @@ import { usePostStatus } from "./usePostStatus";
|
|||||||
*/
|
*/
|
||||||
export function useFeedActions({ refresh, loadMyPosts, onAuthRequired, isAuthenticated, t }) {
|
export function useFeedActions({ refresh, loadMyPosts, onAuthRequired, isAuthenticated, t }) {
|
||||||
const { deletePost } = useDeletePost();
|
const { deletePost } = useDeletePost();
|
||||||
const { markAsFound } = usePostStatus();
|
const { markAsFound, reopenPost } = usePostStatus();
|
||||||
|
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
|
|
||||||
@@ -54,17 +55,37 @@ export function useFeedActions({ refresh, loadMyPosts, onAuthRequired, isAuthent
|
|||||||
if (!window.confirm(t('feed.confirmMarkFound'))) return;
|
if (!window.confirm(t('feed.confirmMarkFound'))) return;
|
||||||
const result = await markAsFound(postId);
|
const result = await markAsFound(postId);
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
|
// Бэкенд не отдаёт момент перехода в CLOSED, а карточке нужна дата
|
||||||
|
// («Найдено 3 октября») — запоминаем её на устройстве.
|
||||||
|
rememberFoundAt(postId);
|
||||||
afterMutation();
|
afterMutation();
|
||||||
} else {
|
} else {
|
||||||
setError(result.error);
|
setError(result.error);
|
||||||
}
|
}
|
||||||
}, [t, markAsFound, afterMutation, isAuthenticated, onAuthRequired]);
|
}, [t, markAsFound, afterMutation, isAuthenticated, onAuthRequired]);
|
||||||
|
|
||||||
|
// Отмена отметки «найдено» (автор нажал «Вернуть в поиск»). Без confirm:
|
||||||
|
// это восстановление, а не разрушительное действие.
|
||||||
|
const handleReopen = useCallback(async (postId) => {
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
onAuthRequired?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const result = await reopenPost(postId);
|
||||||
|
if (result.success) {
|
||||||
|
forgetFoundAt(postId);
|
||||||
|
afterMutation();
|
||||||
|
} else {
|
||||||
|
setError(result.error);
|
||||||
|
}
|
||||||
|
}, [reopenPost, afterMutation, isAuthenticated, onAuthRequired]);
|
||||||
|
|
||||||
const clearError = useCallback(() => setError(""), []);
|
const clearError = useCallback(() => setError(""), []);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
handleDelete,
|
handleDelete,
|
||||||
handleMarkFound,
|
handleMarkFound,
|
||||||
|
handleReopen,
|
||||||
handleNewAd: afterMutation,
|
handleNewAd: afterMutation,
|
||||||
handleEditSave: afterMutation,
|
handleEditSave: afterMutation,
|
||||||
error,
|
error,
|
||||||
|
|||||||
@@ -30,8 +30,16 @@ export function useFeedPosts() {
|
|||||||
// (дебаунс поиска, бесконечный скролл, refresh после удаления), и без
|
// (дебаунс поиска, бесконечный скролл, refresh после удаления), и без
|
||||||
// этой проверки медленный «старый» ответ перетирал бы свежий.
|
// этой проверки медленный «старый» ответ перетирал бы свежий.
|
||||||
const requestIdRef = useRef(0);
|
const requestIdRef = useRef(0);
|
||||||
|
// Подгрузка следующей страницы возможна только поверх уже загруженной первой.
|
||||||
|
// Иначе на первом рендере (loading ещё false, лента пустая) сентинел скролла
|
||||||
|
// виден и запрашивает страницу 1 — её requestId делает ответ страницы 0
|
||||||
|
// «устаревшим», и в ленте остаются только объявления со 2-й страницы.
|
||||||
|
const firstPageLoadedRef = useRef(false);
|
||||||
|
const resetInFlightRef = useRef(false);
|
||||||
|
|
||||||
const loadFeed = useCallback(async (pageNum = 0, search = "", append = false) => {
|
const loadFeed = useCallback(async (pageNum = 0, search = "", append = false) => {
|
||||||
|
if (append && (!firstPageLoadedRef.current || resetInFlightRef.current)) return;
|
||||||
|
if (!append) resetInFlightRef.current = true;
|
||||||
const requestId = ++requestIdRef.current;
|
const requestId = ++requestIdRef.current;
|
||||||
if (pageNum === 0) {
|
if (pageNum === 0) {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -65,6 +73,7 @@ export function useFeedPosts() {
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
if (!append) firstPageLoadedRef.current = true;
|
||||||
setHasMore(!last);
|
setHasMore(!last);
|
||||||
setPage(pageNum);
|
setPage(pageNum);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -74,6 +83,7 @@ export function useFeedPosts() {
|
|||||||
// Флаг снимает только «свой» запрос: иначе подгрузка страницы N
|
// Флаг снимает только «свой» запрос: иначе подгрузка страницы N
|
||||||
// гасила бы спиннер первой страницы, и наоборот.
|
// гасила бы спиннер первой страницы, и наоборот.
|
||||||
if (requestId === requestIdRef.current) {
|
if (requestId === requestIdRef.current) {
|
||||||
|
resetInFlightRef.current = false;
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setLoadingMore(false);
|
setLoadingMore(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { useState, useCallback } from "react";
|
|||||||
* Управляет всеми модалками MainFeed через единое состояние,
|
* Управляет всеми модалками MainFeed через единое состояние,
|
||||||
* чтобы гарантировать что открыта максимум одна модалка сразу.
|
* чтобы гарантировать что открыта максимум одна модалка сразу.
|
||||||
*
|
*
|
||||||
* Типы: "create" | "edit" | "profile" | "auth" | "rules" | "viewer"
|
* Типы: "create" | "edit" | "profile" | "auth" | "rules" | "postDetail"
|
||||||
*/
|
*/
|
||||||
export function useModals() {
|
export function useModals() {
|
||||||
const [modal, setModal] = useState(null); // { type, payload }
|
const [modal, setModal] = useState(null); // { type, payload }
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { Client } from "@stomp/stompjs";
|
|||||||
import SockJS from "sockjs-client";
|
import SockJS from "sockjs-client";
|
||||||
import { API_URL } from "../config/authConstants";
|
import { API_URL } from "../config/authConstants";
|
||||||
import { getAccessToken, refreshAccessToken } from "../api/apiClient";
|
import { getAccessToken, refreshAccessToken } from "../api/apiClient";
|
||||||
|
import { timezoneConnectHeaders } from "../utils/timezone";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* useStompClient — общая инфраструктура STOMP-подключения поверх SockJS.
|
* useStompClient — общая инфраструктура STOMP-подключения поверх SockJS.
|
||||||
@@ -44,6 +45,9 @@ export function useStompClient(enabled, onConnect) {
|
|||||||
beforeConnect: () => {
|
beforeConnect: () => {
|
||||||
client.connectHeaders = {
|
client.connectHeaders = {
|
||||||
Authorization: `Bearer ${getAccessToken()}`,
|
Authorization: `Bearer ${getAccessToken()}`,
|
||||||
|
// native-заголовок timezone, чтобы время сообщений в чате
|
||||||
|
// проставлялось по зоне пользователя (если зона определилась).
|
||||||
|
...timezoneConnectHeaders(),
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
onConnect: () => {
|
onConnect: () => {
|
||||||
|
|||||||
34
src/i18n.js
Normal file
34
src/i18n.js
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import i18n from 'i18next';
|
||||||
|
import { initReactI18next } from 'react-i18next';
|
||||||
|
import translationRU from './locales/ru.json';
|
||||||
|
import translationEN from './locales/en.json';
|
||||||
|
|
||||||
|
const LANGUAGES = ['ru', 'en'];
|
||||||
|
|
||||||
|
// i18next-browser-languagedetector в проекте нет, поэтому persist делаем сами:
|
||||||
|
// иначе выбор языка жил только в памяти и сбрасывался при перезагрузке.
|
||||||
|
const stored = localStorage.getItem('i18nextLng');
|
||||||
|
const savedLang = LANGUAGES.includes(stored) ? stored : 'ru';
|
||||||
|
|
||||||
|
i18n.use(initReactI18next).init({
|
||||||
|
resources: {
|
||||||
|
ru: { translation: translationRU },
|
||||||
|
en: { translation: translationEN },
|
||||||
|
},
|
||||||
|
lng: savedLang,
|
||||||
|
fallbackLng: 'ru',
|
||||||
|
supportedLngs: LANGUAGES,
|
||||||
|
interpolation: { escapeValue: false },
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateDocumentTitle = (lng) => {
|
||||||
|
document.title = lng === 'en' ? 'Find' : 'Находка';
|
||||||
|
};
|
||||||
|
|
||||||
|
i18n.on('languageChanged', (lng) => {
|
||||||
|
localStorage.setItem('i18nextLng', lng);
|
||||||
|
updateDocumentTitle(lng);
|
||||||
|
});
|
||||||
|
updateDocumentTitle(i18n.language);
|
||||||
|
|
||||||
|
export default i18n;
|
||||||
@@ -5,6 +5,10 @@ import './i18n';
|
|||||||
import App from './App';
|
import App from './App';
|
||||||
import { UnreadProvider } from './context/UnreadContext';
|
import { UnreadProvider } from './context/UnreadContext';
|
||||||
import reportWebVitals from './reportWebVitals';
|
import reportWebVitals from './reportWebVitals';
|
||||||
|
import { installTimezoneFetch } from './utils/timezoneFetch';
|
||||||
|
|
||||||
|
// Централизованно добавляем X-Timezone во все HTTP-запросы к backend.
|
||||||
|
installTimezoneFetch();
|
||||||
|
|
||||||
const root = ReactDOM.createRoot(document.getElementById('root'));
|
const root = ReactDOM.createRoot(document.getElementById('root'));
|
||||||
root.render(
|
root.render(
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"name": "Nakhodka"
|
"name": "Nakhodka"
|
||||||
},
|
},
|
||||||
"nav": {
|
"nav": {
|
||||||
"home": "Home",
|
"home": "All ads",
|
||||||
"myAds": "My ads",
|
"myAds": "My ads",
|
||||||
"items": "Items",
|
"items": "Items",
|
||||||
"pets": "Pets",
|
"pets": "Pets",
|
||||||
@@ -142,7 +142,7 @@
|
|||||||
"loading": "Loading ads...",
|
"loading": "Loading ads...",
|
||||||
"loadError": "Failed to load feed",
|
"loadError": "Failed to load feed",
|
||||||
"emptyMyAdsTitle": "You have no ads",
|
"emptyMyAdsTitle": "You have no ads",
|
||||||
"emptyMyAdsSub": "Create your first one — click the button above",
|
"emptyMyAdsSub": "Create your first one — click the button + bellow",
|
||||||
"emptyAllTitle": "No ads yet",
|
"emptyAllTitle": "No ads yet",
|
||||||
"emptyAllSub": "Be the first — post an ad<br />about a loss or find",
|
"emptyAllSub": "Be the first — post an ad<br />about a loss or find",
|
||||||
"searchPromptTitle": "Enter search parameters",
|
"searchPromptTitle": "Enter search parameters",
|
||||||
@@ -153,6 +153,8 @@
|
|||||||
"filterLoss": "Lost",
|
"filterLoss": "Lost",
|
||||||
"filterAll": "All ads",
|
"filterAll": "All ads",
|
||||||
"filterFound": "Found",
|
"filterFound": "Found",
|
||||||
|
"filterActive": "Active",
|
||||||
|
"filterClosed": "Closed",
|
||||||
"openFilter": "Filter by ad type",
|
"openFilter": "Filter by ad type",
|
||||||
"openMenu": "Open menu",
|
"openMenu": "Open menu",
|
||||||
"filterCitiesPlaceholder": "Select city…",
|
"filterCitiesPlaceholder": "Select city…",
|
||||||
@@ -170,7 +172,10 @@
|
|||||||
"metro": "Metropolitan",
|
"metro": "Metropolitan",
|
||||||
"loss": "Lost",
|
"loss": "Lost",
|
||||||
"found": "Found",
|
"found": "Found",
|
||||||
"foundStatus": "✓ Found",
|
"foundStatus": "Found",
|
||||||
|
"petFoundStatus": "Pet found! 🎉",
|
||||||
|
"foundStatusWithDate": "{{status}} — {{date}}",
|
||||||
|
"undoFound": "Return to search",
|
||||||
"write": "Write",
|
"write": "Write",
|
||||||
"itemFound": "✓ Returned to owner",
|
"itemFound": "✓ Returned to owner",
|
||||||
"reopen": "↩ Return to feed",
|
"reopen": "↩ Return to feed",
|
||||||
@@ -180,8 +185,6 @@
|
|||||||
},
|
},
|
||||||
"chat": {
|
"chat": {
|
||||||
"title": "Chat",
|
"title": "Chat",
|
||||||
"online": "Online",
|
|
||||||
"offline": "Offline",
|
|
||||||
"noMessages": "No messages",
|
"noMessages": "No messages",
|
||||||
"messagePlaceholder": "Message...",
|
"messagePlaceholder": "Message...",
|
||||||
"chats": "Chats",
|
"chats": "Chats",
|
||||||
@@ -559,7 +562,9 @@
|
|||||||
"unmute": "Unmute sound"
|
"unmute": "Unmute sound"
|
||||||
},
|
},
|
||||||
"viewer": {
|
"viewer": {
|
||||||
"goToImage": "Go to image {{number}}"
|
"goToImage": "Go to image {{number}}",
|
||||||
|
"prevImage": "Previous photo",
|
||||||
|
"nextImage": "Next photo"
|
||||||
},
|
},
|
||||||
"chats": {
|
"chats": {
|
||||||
"fetchError": "Failed to load chats",
|
"fetchError": "Failed to load chats",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"name": "Находка"
|
"name": "Находка"
|
||||||
},
|
},
|
||||||
"nav": {
|
"nav": {
|
||||||
"home": "Главная",
|
"home": "Все объявления",
|
||||||
"myAds": "Мои объявления",
|
"myAds": "Мои объявления",
|
||||||
"items": "Вещи",
|
"items": "Вещи",
|
||||||
"pets": "Питомцы",
|
"pets": "Питомцы",
|
||||||
@@ -142,7 +142,7 @@
|
|||||||
"loading": "Загружаем объявления...",
|
"loading": "Загружаем объявления...",
|
||||||
"loadError": "Не удалось загрузить ленту",
|
"loadError": "Не удалось загрузить ленту",
|
||||||
"emptyMyAdsTitle": "У вас нет объявлений",
|
"emptyMyAdsTitle": "У вас нет объявлений",
|
||||||
"emptyMyAdsSub": "Создайте первое — нажмите кнопку выше",
|
"emptyMyAdsSub": "Создайте первое — нажмите кнопку + ниже",
|
||||||
"emptyAllTitle": "Объявлений пока нет",
|
"emptyAllTitle": "Объявлений пока нет",
|
||||||
"emptyAllSub": "Будьте первым — разместите объявление<br />о потере или находке",
|
"emptyAllSub": "Будьте первым — разместите объявление<br />о потере или находке",
|
||||||
"searchPromptTitle": "Введите параметры поиска",
|
"searchPromptTitle": "Введите параметры поиска",
|
||||||
@@ -153,6 +153,8 @@
|
|||||||
"filterLoss": "Потери",
|
"filterLoss": "Потери",
|
||||||
"filterAll": "Все объявления",
|
"filterAll": "Все объявления",
|
||||||
"filterFound": "Находки",
|
"filterFound": "Находки",
|
||||||
|
"filterActive": "Активные",
|
||||||
|
"filterClosed": "Найденные",
|
||||||
"openFilter": "Фильтр по типу объявления",
|
"openFilter": "Фильтр по типу объявления",
|
||||||
"openMenu": "Открыть меню",
|
"openMenu": "Открыть меню",
|
||||||
"filterCitiesPlaceholder": "Выберите город…",
|
"filterCitiesPlaceholder": "Выберите город…",
|
||||||
@@ -170,7 +172,10 @@
|
|||||||
"metro": "Метрополитен",
|
"metro": "Метрополитен",
|
||||||
"loss": "Потеря",
|
"loss": "Потеря",
|
||||||
"found": "Находка",
|
"found": "Находка",
|
||||||
"foundStatus": "✓ Найдено",
|
"foundStatus": "Найдено",
|
||||||
|
"petFoundStatus": "Питомец нашёлся! 🎉",
|
||||||
|
"foundStatusWithDate": "{{status}} — {{date}}",
|
||||||
|
"undoFound": "Вернуть в поиск",
|
||||||
"write": "Написать",
|
"write": "Написать",
|
||||||
"itemFound": "✓ Вернулось к владельцу",
|
"itemFound": "✓ Вернулось к владельцу",
|
||||||
"reopen": "↩ Вернуть в ленту",
|
"reopen": "↩ Вернуть в ленту",
|
||||||
@@ -180,8 +185,6 @@
|
|||||||
},
|
},
|
||||||
"chat": {
|
"chat": {
|
||||||
"title": "Чат",
|
"title": "Чат",
|
||||||
"online": "В сети",
|
|
||||||
"offline": "Отключено",
|
|
||||||
"noMessages": "Нет сообщений",
|
"noMessages": "Нет сообщений",
|
||||||
"messagePlaceholder": "Сообщение...",
|
"messagePlaceholder": "Сообщение...",
|
||||||
"chats": "Чаты по объявлениям",
|
"chats": "Чаты по объявлениям",
|
||||||
@@ -559,7 +562,9 @@
|
|||||||
"unmute": "Включить звук"
|
"unmute": "Включить звук"
|
||||||
},
|
},
|
||||||
"viewer": {
|
"viewer": {
|
||||||
"goToImage": "Перейти к изображению {{number}}"
|
"goToImage": "Перейти к изображению {{number}}",
|
||||||
|
"prevImage": "Предыдущее фото",
|
||||||
|
"nextImage": "Следующее фото"
|
||||||
},
|
},
|
||||||
"chats": {
|
"chats": {
|
||||||
"fetchError": "Не удалось загрузить чаты",
|
"fetchError": "Не удалось загрузить чаты",
|
||||||
|
|||||||
@@ -309,7 +309,6 @@ export default function AdminAdsPage() {
|
|||||||
activeNav={isPostsTab ? "admin-posts" : isPostsRejectedTab ? "admin-posts-rejected" : "admin-campaigns"}
|
activeNav={isPostsTab ? "admin-posts" : isPostsRejectedTab ? "admin-posts-rejected" : "admin-campaigns"}
|
||||||
onClose={() => setSidebarOpen(false)}
|
onClose={() => setSidebarOpen(false)}
|
||||||
onNavClick={() => navigate("/feed")}
|
onNavClick={() => navigate("/feed")}
|
||||||
onLogoClick={() => navigate("/feed")}
|
|
||||||
isAuthenticated={isAuthenticated}
|
isAuthenticated={isAuthenticated}
|
||||||
onLoginClick={() => modals.open("auth")}
|
onLoginClick={() => modals.open("auth")}
|
||||||
onRulesClick={() => modals.open("rules")}
|
onRulesClick={() => modals.open("rules")}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useState, useCallback } from "react";
|
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 { useChats } from "../hooks/useChats";
|
||||||
@@ -18,6 +18,10 @@ export default function ChatListPage() {
|
|||||||
const { unreadMap, totalUnread } = useUnread();
|
const { unreadMap, totalUnread } = useUnread();
|
||||||
const { deleteChat } = useDeleteChat();
|
const { deleteChat } = useDeleteChat();
|
||||||
const [deleteError, setDeleteError] = useState("");
|
const [deleteError, setDeleteError] = useState("");
|
||||||
|
// Пропускаем первый прогон эффекта по totalUnread: на маунте список уже
|
||||||
|
// грузится первым эффектом, и без этого guard'а через 500 мс уходил бы
|
||||||
|
// второй, повторный запрос (страница "моргала" и грузилась дважды).
|
||||||
|
const unreadWatcherReadyRef = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isAuthenticated) {
|
if (isAuthenticated) {
|
||||||
@@ -29,7 +33,11 @@ export default function ChatListPage() {
|
|||||||
// превью показывало новое сообщение и подсветку, не дожидаясь ручного обновления.
|
// превью показывало новое сообщение и подсветку, не дожидаясь ручного обновления.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isAuthenticated) return;
|
if (!isAuthenticated) return;
|
||||||
const timer = setTimeout(() => fetchChats(), 500);
|
if (!unreadWatcherReadyRef.current) {
|
||||||
|
unreadWatcherReadyRef.current = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const timer = setTimeout(() => fetchChats({ silent: true }), 500);
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
// totalUnread — числовое значение, поэтому изменение состава чатов с той же
|
// totalUnread — числовое значение, поэтому изменение состава чатов с той же
|
||||||
// суммой не создаст цикл обновлений.
|
// суммой не создаст цикл обновлений.
|
||||||
@@ -40,7 +48,7 @@ export default function ChatListPage() {
|
|||||||
if (!window.confirm(t('chat.confirmDeleteChat'))) return;
|
if (!window.confirm(t('chat.confirmDeleteChat'))) return;
|
||||||
const result = await deleteChat(chatId);
|
const result = await deleteChat(chatId);
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
fetchChats();
|
fetchChats({ silent: true });
|
||||||
} else {
|
} else {
|
||||||
setDeleteError(result.error);
|
setDeleteError(result.error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ export default function ChatPage() {
|
|||||||
const { user } = useAuthContext();
|
const { user } = useAuthContext();
|
||||||
const [messages, setMessages] = useState([]);
|
const [messages, setMessages] = useState([]);
|
||||||
const [input, setInput] = useState("");
|
const [input, setInput] = useState("");
|
||||||
const [showEmoji, setShowEmoji] = useState(false);
|
|
||||||
const [loadError, setLoadError] = useState("");
|
const [loadError, setLoadError] = useState("");
|
||||||
const [sendError, setSendError] = useState("");
|
const [sendError, setSendError] = useState("");
|
||||||
const messagesEndRef = useRef(null);
|
const messagesEndRef = useRef(null);
|
||||||
@@ -89,10 +88,6 @@ export default function ChatPage() {
|
|||||||
setInput("");
|
setInput("");
|
||||||
}, [input, sendMessage, t]);
|
}, [input, sendMessage, t]);
|
||||||
|
|
||||||
const handleEmojiSelect = useCallback((emoji) => {
|
|
||||||
setInput((prev) => prev + emoji.native);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const post = getPostForChat(chatId);
|
const post = getPostForChat(chatId);
|
||||||
const postImg = getImageUrl(post?.images?.[0]);
|
const postImg = getImageUrl(post?.images?.[0]);
|
||||||
|
|
||||||
@@ -107,8 +102,6 @@ export default function ChatPage() {
|
|||||||
) : (
|
) : (
|
||||||
post?.emoji || "📋"
|
post?.emoji || "📋"
|
||||||
)}
|
)}
|
||||||
statusLabel={connected ? t('chat.online') : t('chat.offline')}
|
|
||||||
statusConnected={connected}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="chat-messages">
|
<div className="chat-messages">
|
||||||
@@ -126,10 +119,6 @@ export default function ChatPage() {
|
|||||||
input={input}
|
input={input}
|
||||||
onInputChange={setInput}
|
onInputChange={setInput}
|
||||||
onSend={handleSend}
|
onSend={handleSend}
|
||||||
onEmojiSelect={handleEmojiSelect}
|
|
||||||
showEmoji={showEmoji}
|
|
||||||
onToggleEmoji={() => setShowEmoji((v) => !v)}
|
|
||||||
onCloseEmoji={() => setShowEmoji(false)}
|
|
||||||
connected={connected}
|
connected={connected}
|
||||||
placeholder={t('chat.messagePlaceholder')}
|
placeholder={t('chat.messagePlaceholder')}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import Sidebar from "../components/Sidebar";
|
|||||||
import BottomNav from "../components/nav/BottomNav";
|
import BottomNav from "../components/nav/BottomNav";
|
||||||
import RightSidebar from "../components/RightSidebar";
|
import RightSidebar from "../components/RightSidebar";
|
||||||
import CreateUpdatePostLegacy from "./CreateUpdatePost";
|
import CreateUpdatePostLegacy from "./CreateUpdatePost";
|
||||||
import ImageViewer from "../components/ImageViewer";
|
|
||||||
import CityFilterLegacy from "../components/CityFilter";
|
import CityFilterLegacy from "../components/CityFilter";
|
||||||
import { ProfileModal } from "../components/profile";
|
import { ProfileModal } from "../components/profile";
|
||||||
import AuthModal from "../components/AuthModal";
|
import AuthModal from "../components/AuthModal";
|
||||||
@@ -29,6 +28,7 @@ import { useModals } from "../hooks/useModals";
|
|||||||
import { useFeedActions } from "../hooks/useFeedActions";
|
import { useFeedActions } from "../hooks/useFeedActions";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { CATEGORY_ITEM, CATEGORY_OTHER, CATEGORY_PET } from "../config/feedConstants";
|
import { CATEGORY_ITEM, CATEGORY_OTHER, CATEGORY_PET } from "../config/feedConstants";
|
||||||
|
import { POST_STATUS_CLOSED } from "../config/postConstants";
|
||||||
import { useProfile } from "../hooks/useProfile";
|
import { useProfile } from "../hooks/useProfile";
|
||||||
import { useFullscreenAdTrigger } from "../hooks/useFullscreenAdTrigger";
|
import { useFullscreenAdTrigger } from "../hooks/useFullscreenAdTrigger";
|
||||||
import FullscreenAdOverlay from "../components/FullscreenAdOverlay";
|
import FullscreenAdOverlay from "../components/FullscreenAdOverlay";
|
||||||
@@ -239,10 +239,6 @@ export default function MainFeed() {
|
|||||||
activeNav === "home" && selectedCities.length === 0 && feed.hasMore && !feed.loading && !feed.loadingMore
|
activeNav === "home" && selectedCities.length === 0 && feed.hasMore && !feed.loading && !feed.loadingMore
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleImageClick = useCallback((images: string[], index: number, ad: Record<string, unknown>) => {
|
|
||||||
if (images?.length) modals.open("viewer", { images, index, ad });
|
|
||||||
}, [modals]);
|
|
||||||
|
|
||||||
const handleCreatePost = useCallback(() => {
|
const handleCreatePost = useCallback(() => {
|
||||||
if (!isAuthenticated) modals.open("auth");
|
if (!isAuthenticated) modals.open("auth");
|
||||||
else modals.open("create");
|
else modals.open("create");
|
||||||
@@ -393,6 +389,12 @@ export default function MainFeed() {
|
|||||||
if (typeFilter) {
|
if (typeFilter) {
|
||||||
result = result.filter(ad => ad.type === typeFilter);
|
result = result.filter(ad => ad.type === typeFilter);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Найденные — вниз. Сортировка стабильная, так что внутри групп порядок
|
||||||
|
// ленты (свежие сверху, бесконечный скролл) не ломается.
|
||||||
|
result = [...result].sort(
|
||||||
|
(a, b) => Number(a.status === POST_STATUS_CLOSED) - Number(b.status === POST_STATUS_CLOSED)
|
||||||
|
);
|
||||||
return result;
|
return result;
|
||||||
}, [activeNav, myPosts.myAds, cityFeed.cityAds, feed.ads, selectedCities, typeFilter]);
|
}, [activeNav, myPosts.myAds, cityFeed.cityAds, feed.ads, selectedCities, typeFilter]);
|
||||||
|
|
||||||
@@ -411,7 +413,6 @@ export default function MainFeed() {
|
|||||||
open={sidebarOpen}
|
open={sidebarOpen}
|
||||||
activeNav={activeNav}
|
activeNav={activeNav}
|
||||||
onClose={() => setSidebarOpen(false)}
|
onClose={() => setSidebarOpen(false)}
|
||||||
onLogoClick={handleHomeClick}
|
|
||||||
onNavClick={(key: string) => {
|
onNavClick={(key: string) => {
|
||||||
setActiveNav(key);
|
setActiveNav(key);
|
||||||
setSearchQuery("");
|
setSearchQuery("");
|
||||||
@@ -469,7 +470,7 @@ export default function MainFeed() {
|
|||||||
<PullToRefresh
|
<PullToRefresh
|
||||||
containerRef={feedRef}
|
containerRef={feedRef}
|
||||||
onRefresh={refreshCurrentList}
|
onRefresh={refreshCurrentList}
|
||||||
disabled={isMapView || isSearchView || (activeNav !== "home" && activeNav !== "myads")}
|
disabled={isMapView || isSearchView || !["home", "items", "pets", "myads"].includes(activeNav)}
|
||||||
/>
|
/>
|
||||||
<FeedContent
|
<FeedContent
|
||||||
loading={listLoading}
|
loading={listLoading}
|
||||||
@@ -483,7 +484,7 @@ export default function MainFeed() {
|
|||||||
onEdit={handleEdit}
|
onEdit={handleEdit}
|
||||||
onDelete={actions.handleDelete}
|
onDelete={actions.handleDelete}
|
||||||
onMarkFound={actions.handleMarkFound}
|
onMarkFound={actions.handleMarkFound}
|
||||||
onImageClick={handleImageClick}
|
onReopen={actions.handleReopen}
|
||||||
onLocationClick={handleLocationClick}
|
onLocationClick={handleLocationClick}
|
||||||
onAuthRequired={() => modals.open("auth")}
|
onAuthRequired={() => modals.open("auth")}
|
||||||
t={t}
|
t={t}
|
||||||
@@ -544,22 +545,10 @@ export default function MainFeed() {
|
|||||||
|
|
||||||
{modals.isOpen("rules") && <RulesModal onClose={modals.close} />}
|
{modals.isOpen("rules") && <RulesModal onClose={modals.close} />}
|
||||||
|
|
||||||
{modals.isOpen("viewer") && (
|
|
||||||
<ImageViewer
|
|
||||||
images={modals.modal.payload.images}
|
|
||||||
initialIndex={modals.modal.payload.index}
|
|
||||||
onClose={modals.close}
|
|
||||||
postData={modals.modal.payload.ad}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{modals.isOpen("postDetail") && (
|
{modals.isOpen("postDetail") && (
|
||||||
<PostDetailModal
|
<PostDetailModal
|
||||||
postId={modals.modal.payload.postId}
|
postId={modals.modal.payload.postId}
|
||||||
onClose={modals.close}
|
onClose={modals.close}
|
||||||
onImageClick={(images: string[], index: number, ad: Record<string, unknown>) => {
|
|
||||||
modals.open("viewer", { images, index, ad });
|
|
||||||
}}
|
|
||||||
onLocationClick={(ad: Record<string, unknown>) => {
|
onLocationClick={(ad: Record<string, unknown>) => {
|
||||||
modals.close();
|
modals.close();
|
||||||
void handleLocationClick(ad);
|
void handleLocationClick(ad);
|
||||||
|
|||||||
@@ -3,23 +3,28 @@ import PinIcon from "../components/icons/PinIcon";
|
|||||||
import CalendarIcon from "../components/icons/CalendarIcon";
|
import CalendarIcon from "../components/icons/CalendarIcon";
|
||||||
import PhoneIcon from "../components/icons/PhoneIcon";
|
import PhoneIcon from "../components/icons/PhoneIcon";
|
||||||
import TrashIcon from "../components/icons/TrashIcon";
|
import TrashIcon from "../components/icons/TrashIcon";
|
||||||
|
import CheckIcon from "../components/icons/CheckIcon";
|
||||||
import {useContactSeller} from "../hooks/useContactSeller";
|
import {useContactSeller} from "../hooks/useContactSeller";
|
||||||
import {useAuthContext} from "../context/AuthContext";
|
import {useAuthContext} from "../context/AuthContext";
|
||||||
import {getImageUrl} from "../config/authConstants";
|
import {getImageUrl} from "../config/authConstants";
|
||||||
|
import {CATEGORY_PET} from "../config/feedConstants";
|
||||||
|
import {getFoundAt, formatFoundDate} from "../utils/foundAt";
|
||||||
import DateCalendarPopup from "../components/DateCalendarPopup";
|
import DateCalendarPopup from "../components/DateCalendarPopup";
|
||||||
import RewardPopup from "../components/feed/RewardPopup";
|
import RewardPopup from "../components/feed/RewardPopup";
|
||||||
import Toast from "../components/Toast";
|
import Toast from "../components/Toast";
|
||||||
import {useTranslation} from 'react-i18next';
|
import {useTranslation} from 'react-i18next';
|
||||||
|
|
||||||
export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen, isOwner, authorLabel, allowEditClosed, onImageClick, onLocationClick, onAuthRequired, compact }) {
|
export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen, isOwner, authorLabel, allowEditClosed, onLocationClick, onAuthRequired, compact }) {
|
||||||
const { t } = useTranslation();
|
const { t, i18n } = useTranslation();
|
||||||
const [showCalendar, setShowCalendar] = useState(false);
|
const [showCalendar, setShowCalendar] = useState(false);
|
||||||
const [showReward, setShowReward] = useState(false);
|
const [showReward, setShowReward] = useState(false);
|
||||||
const [descExpanded, setDescExpanded] = useState(false);
|
const [descExpanded, setDescExpanded] = useState(false);
|
||||||
const [descTruncated, setDescTruncated] = useState(false);
|
const [descTruncated, setDescTruncated] = useState(false);
|
||||||
|
const [imgIndex, setImgIndex] = useState(0);
|
||||||
const dateAnchorRef = useRef(null);
|
const dateAnchorRef = useRef(null);
|
||||||
const rewardAnchorRef = useRef(null);
|
const rewardAnchorRef = useRef(null);
|
||||||
const descRef = useRef(null);
|
const descRef = useRef(null);
|
||||||
|
const imgTouchStartRef = useRef(null);
|
||||||
const { isAuthenticated } = useAuthContext();
|
const { isAuthenticated } = useAuthContext();
|
||||||
const { contactSeller, error: contactError, clearError } = useContactSeller(ad);
|
const { contactSeller, error: contactError, clearError } = useContactSeller(ad);
|
||||||
|
|
||||||
@@ -43,13 +48,56 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
|||||||
contactSeller();
|
contactSeller();
|
||||||
};
|
};
|
||||||
|
|
||||||
const imageUrl = getImageUrl(ad.images?.[0]);
|
const images = Array.isArray(ad.images) ? ad.images : [];
|
||||||
|
// Карусель включается для любого объявления с несколькими фото: листать
|
||||||
|
// можно и в ленте, и в детальной модалке. Полноэкранного просмотрщика нет.
|
||||||
|
const carousel = images.length > 1;
|
||||||
|
const hasImages = images.length > 0;
|
||||||
|
|
||||||
|
// Листание фото прямо в карточке: на телефоне — свайпом, на десктопе —
|
||||||
|
// стрелками и точками. Листание зациклено: с последнего кадра переходим на
|
||||||
|
// первый и наоборот.
|
||||||
|
const goToImage = (target) => {
|
||||||
|
const len = images.length;
|
||||||
|
if (!len) return;
|
||||||
|
setImgIndex(((target % len) + len) % len);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImgTouchStart = (e) => {
|
||||||
|
if (!carousel) return;
|
||||||
|
imgTouchStartRef.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImgTouchEnd = (e) => {
|
||||||
|
const start = imgTouchStartRef.current;
|
||||||
|
imgTouchStartRef.current = null;
|
||||||
|
if (!start || !carousel) return;
|
||||||
|
const dx = e.changedTouches[0].clientX - start.x;
|
||||||
|
const dy = e.changedTouches[0].clientY - start.y;
|
||||||
|
// Реагируем только на явно горизонтальный жест — вертикальный скролл ленты
|
||||||
|
// не должен переключать фото.
|
||||||
|
if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {
|
||||||
|
const len = images.length;
|
||||||
|
const step = dx < 0 ? 1 : -1;
|
||||||
|
setImgIndex(i => (i + step + len) % len);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const address = ad.address || ad.city || ad.district || ad.location;
|
const address = ad.address || ad.city || ad.district || ad.location;
|
||||||
const createdAt = ad.createdAt
|
const createdAt = ad.createdAt
|
||||||
? new Date(ad.createdAt).toLocaleDateString("ru-RU")
|
? new Date(ad.createdAt).toLocaleDateString("ru-RU")
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const isClosed = ad.status === 'CLOSED';
|
const isClosed = ad.status === 'CLOSED';
|
||||||
|
// Для питомцев «найдено» — это хорошая новость с воссоединением, поэтому
|
||||||
|
// формулировка эмоциональнее, чем сухое «Найдено».
|
||||||
|
const isPet = ad.category === CATEGORY_PET;
|
||||||
|
const foundText = isPet ? t('postCard.petFoundStatus') : t('postCard.foundStatus');
|
||||||
|
const foundDate = isClosed ? formatFoundDate(getFoundAt(ad), i18n.language) : null;
|
||||||
|
// aria-подпись собираем целиком: статус не должен читаться только цветом.
|
||||||
|
const foundAriaText = foundDate
|
||||||
|
? t('postCard.foundStatusWithDate', {status: foundText, date: foundDate})
|
||||||
|
: foundText;
|
||||||
|
|
||||||
const headAccentClass = ad.type === "found" ? " f-head-found" : " f-head-loss";
|
const headAccentClass = ad.type === "found" ? " f-head-found" : " f-head-loss";
|
||||||
|
|
||||||
@@ -60,7 +108,9 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
|||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`f-card${isClosed ? ' f-card-closed' : ''}${ad.type === "found" ? ' f-card-found' : ' f-card-loss'}`}>
|
<div className={`f-card${isClosed ? ' f-card-closed' : ''}${ad.type === "found" ? ' f-card-found' : ' f-card-loss'}`}
|
||||||
|
role="group"
|
||||||
|
aria-label={isClosed ? `${ad.title}. ${foundAriaText}` : ad.title}>
|
||||||
|
|
||||||
<div className={`f-card-head${headAccentClass}`}>
|
<div className={`f-card-head${headAccentClass}`}>
|
||||||
<div className="f-card-author">
|
<div className="f-card-author">
|
||||||
@@ -75,17 +125,75 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
|||||||
</div>
|
</div>
|
||||||
<div className="f-card-head-side">
|
<div className="f-card-head-side">
|
||||||
{typeBadge}
|
{typeBadge}
|
||||||
{isClosed && (
|
|
||||||
<span className="f-status-badge f-status-closed">{t('postCard.foundStatus')}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="f-card-img" onClick={e => { e.stopPropagation(); if (onImageClick) onImageClick(ad.images, 0, ad); }}>
|
<div
|
||||||
{imageUrl
|
className={`f-card-img${carousel ? " f-card-img-multi" : ""}${hasImages ? " f-card-img-filled" : ""}`}
|
||||||
? <img src={imageUrl} alt={ad.title} />
|
onTouchStart={handleImgTouchStart}
|
||||||
: <span className="f-card-emoji">{ad.emoji || "📋"}</span>
|
onTouchEnd={handleImgTouchEnd}
|
||||||
}
|
>
|
||||||
|
{images.length > 0 ? (
|
||||||
|
carousel ? (
|
||||||
|
<div
|
||||||
|
className="f-card-img-track"
|
||||||
|
style={{ transform: `translateX(-${imgIndex * 100}%)` }}
|
||||||
|
>
|
||||||
|
{images.map((raw, i) => (
|
||||||
|
<img
|
||||||
|
key={i}
|
||||||
|
src={getImageUrl(raw)}
|
||||||
|
alt={ad.title}
|
||||||
|
className="f-card-img-slide"
|
||||||
|
draggable={false}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<img src={getImageUrl(images[0])} alt={ad.title} />
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<span className="f-card-emoji">{ad.emoji || "📋"}</span>
|
||||||
|
)}
|
||||||
|
{/* Плашка статуса поверх фото: при быстром скролле шапка карточки
|
||||||
|
проезжает мимо, а фото с плашкой — нет. */}
|
||||||
|
{isClosed && (
|
||||||
|
<span className={`f-img-found-badge${isPet ? ' f-img-found-badge-pet' : ''}`}>
|
||||||
|
<CheckIcon size={12}/>
|
||||||
|
<span>{foundText}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{carousel && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="f-img-nav f-img-nav-prev"
|
||||||
|
aria-label={t('viewer.prevImage')}
|
||||||
|
onClick={e => { e.stopPropagation(); goToImage(imgIndex - 1); }}
|
||||||
|
>
|
||||||
|
‹
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="f-img-nav f-img-nav-next"
|
||||||
|
aria-label={t('viewer.nextImage')}
|
||||||
|
onClick={e => { e.stopPropagation(); goToImage(imgIndex + 1); }}
|
||||||
|
>
|
||||||
|
›
|
||||||
|
</button>
|
||||||
|
<div className="f-img-dots">
|
||||||
|
{images.map((_, i) => (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
key={i}
|
||||||
|
className={`f-img-dot${i === imgIndex ? " active" : ""}`}
|
||||||
|
aria-label={t('viewer.goToImage', { number: i + 1 })}
|
||||||
|
onClick={e => { e.stopPropagation(); goToImage(i); }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!compact && (
|
{!compact && (
|
||||||
@@ -210,15 +318,28 @@ export default function PostOnFeed({ ad, onEdit, onDelete, onMarkFound, onReopen
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{onReopen && isOwner && isClosed && (
|
{isClosed && (
|
||||||
<div className="f-card-found-wrap">
|
<div className="f-card-found-wrap">
|
||||||
<button type="button" className="f-card-found-btn f-card-reopen-btn"
|
{/* Кнопка «найдено» становится неактивной подтверждением: видно,
|
||||||
onClick={e => {
|
что действие уже применено, и повторно не нажать. */}
|
||||||
e.stopPropagation();
|
<button type="button" className="f-card-found-btn f-card-found-btn-done"
|
||||||
onReopen(ad.id);
|
disabled
|
||||||
}}>
|
aria-label={foundAriaText}
|
||||||
{t('postCard.reopen')}
|
title={foundAriaText}>
|
||||||
|
<CheckIcon size={14}/>
|
||||||
|
<span>{foundText}{foundDate ? ` ${foundDate}` : ''}</span>
|
||||||
</button>
|
</button>
|
||||||
|
{/* Отмена случайного нажатия — автору; в админ-панели это и есть
|
||||||
|
возврат объявления в ленту. */}
|
||||||
|
{onReopen && isOwner && (
|
||||||
|
<button type="button" className="f-card-found-undo"
|
||||||
|
onClick={e => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onReopen(ad.id);
|
||||||
|
}}>
|
||||||
|
{t('postCard.undoFound')}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
--bg-surface-solid: #ffffff;
|
--bg-surface-solid: #ffffff;
|
||||||
--bg-filter: rgba(255,255,255,.8);
|
--bg-filter: rgba(255,255,255,.8);
|
||||||
--bg-card-img: linear-gradient(135deg, #feda75 0%, #fa7e1e 35%, #d62976 65%, #962fbf 100%);
|
--bg-card-img: linear-gradient(135deg, #feda75 0%, #fa7e1e 35%, #d62976 65%, #962fbf 100%);
|
||||||
|
--card-img-fill: #ffffff;
|
||||||
--bg-input: rgba(0,0,0,.045);
|
--bg-input: rgba(0,0,0,.045);
|
||||||
--bg-overlay: rgba(0,0,0,.5);
|
--bg-overlay: rgba(0,0,0,.5);
|
||||||
--text-primary: #262626;
|
--text-primary: #262626;
|
||||||
@@ -43,6 +44,7 @@
|
|||||||
--bg-surface-solid: #000000;
|
--bg-surface-solid: #000000;
|
||||||
--bg-filter: rgba(0,0,0,.6);
|
--bg-filter: rgba(0,0,0,.6);
|
||||||
--bg-card-img: linear-gradient(135deg, #5a3d00 0%, #6b3a10 35%, #4d1f38 65%, #3a205e 100%);
|
--bg-card-img: linear-gradient(135deg, #5a3d00 0%, #6b3a10 35%, #4d1f38 65%, #3a205e 100%);
|
||||||
|
--card-img-fill: #1b1b1b;
|
||||||
--bg-input: rgba(255,255,255,.08);
|
--bg-input: rgba(255,255,255,.08);
|
||||||
--bg-overlay: rgba(0,0,0,.65);
|
--bg-overlay: rgba(0,0,0,.65);
|
||||||
--text-primary: #f5f5f5;
|
--text-primary: #f5f5f5;
|
||||||
|
|||||||
@@ -77,6 +77,81 @@
|
|||||||
border: none; outline: none;
|
border: none; outline: none;
|
||||||
}
|
}
|
||||||
.f-card-emoji { font-size: 4rem; opacity: .85; filter: drop-shadow(0 4px 12px rgba(0,0,0,.3)); }
|
.f-card-emoji { font-size: 4rem; opacity: .85; filter: drop-shadow(0 4px 12px rgba(0,0,0,.3)); }
|
||||||
|
|
||||||
|
/* ── Карусель фото в карточке ленты ──
|
||||||
|
.f-card-img остаётся «окном» (overflow:hidden, aspect-ratio 1/1), а трек
|
||||||
|
сдвигается на -100% за каждый кадр. Свайп ловим на touch-событиях в
|
||||||
|
PostOnFeed; touch-action:pan-y оставляет вертикальный скролл ленты рабочим. */
|
||||||
|
.f-card-img-multi { touch-action: pan-y; }
|
||||||
|
.f-card-img-track {
|
||||||
|
display: flex;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
transition: transform .3s ease;
|
||||||
|
will-change: transform;
|
||||||
|
}
|
||||||
|
.f-card-img-slide {
|
||||||
|
flex: 0 0 100%;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
object-position: center;
|
||||||
|
display: block;
|
||||||
|
user-select: none;
|
||||||
|
-webkit-user-drag: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Фото в фиксированном окне ──
|
||||||
|
Окно остаётся квадратным (aspect-ratio 1/1), фото вписывается целиком
|
||||||
|
(contain), а свободные полосы по краям заливаются сплошным цветом темы
|
||||||
|
(светлым в светлой теме, тёмным — в тёмной) вместо размытой подложки. */
|
||||||
|
.f-card-img-filled { background: var(--card-img-fill); }
|
||||||
|
.f-card-img img { object-fit: contain; }
|
||||||
|
.f-card-img .f-card-img-slide { object-fit: contain; }
|
||||||
|
|
||||||
|
/* Стрелки листания — показываем при наведении (десктоп). На тач-устройствах
|
||||||
|
основным остаётся свайп, поэтому здесь они не мешают. */
|
||||||
|
.f-img-nav {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
z-index: 3;
|
||||||
|
width: 34px; height: 34px;
|
||||||
|
padding: 0;
|
||||||
|
display: flex; align-items: center; justify-content: center;
|
||||||
|
border: none; border-radius: 50%;
|
||||||
|
background: rgba(0,0,0,.45);
|
||||||
|
color: #fff; font-size: 1.4rem; line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
opacity: 0; pointer-events: none;
|
||||||
|
transition: opacity .2s, background .2s;
|
||||||
|
}
|
||||||
|
.f-card-img:hover .f-img-nav { opacity: 1; pointer-events: auto; }
|
||||||
|
.f-img-nav:hover { background: rgba(0,0,0,.72); }
|
||||||
|
.f-img-nav-prev { left: 8px; }
|
||||||
|
.f-img-nav-next { right: 8px; }
|
||||||
|
|
||||||
|
/* Точки-индикаторы: видно, что фото несколько и какое сейчас открыто. */
|
||||||
|
.f-img-dots {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 10px; left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
z-index: 3;
|
||||||
|
display: flex; gap: 6px;
|
||||||
|
padding: 5px 9px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(0,0,0,.35);
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
|
-webkit-backdrop-filter: blur(4px);
|
||||||
|
}
|
||||||
|
.f-img-dot {
|
||||||
|
width: 7px; height: 7px;
|
||||||
|
padding: 0; border: none; border-radius: 50%;
|
||||||
|
background: rgba(255,255,255,.5);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background .2s, transform .2s;
|
||||||
|
}
|
||||||
|
.f-img-dot.active { background: #fff; transform: scale(1.25); }
|
||||||
.f-card-reward {
|
.f-card-reward {
|
||||||
position: absolute; top: 12px; right: 12px; z-index: 2;
|
position: absolute; top: 12px; right: 12px; z-index: 2;
|
||||||
background: rgba(0,0,0,.55); backdrop-filter: blur(6px);
|
background: rgba(0,0,0,.55); backdrop-filter: blur(6px);
|
||||||
@@ -232,16 +307,6 @@ button.f-card-reward-btn:focus-visible {
|
|||||||
.f-type-loss { background: rgba(237,73,86,.1); color: #ed4956; border: 1px solid rgba(237,73,86,.25); }
|
.f-type-loss { background: rgba(237,73,86,.1); color: #ed4956; border: 1px solid rgba(237,73,86,.25); }
|
||||||
.f-type-found { background: rgba(48,168,94,.1); color: #30a85e; border: 1px solid rgba(48,168,94,.25); }
|
.f-type-found { background: rgba(48,168,94,.1); color: #30a85e; border: 1px solid rgba(48,168,94,.25); }
|
||||||
|
|
||||||
/* Status badge for closed/found posts */
|
|
||||||
.f-status-badge {
|
|
||||||
border-radius: 999px; padding: 2px 8px;
|
|
||||||
font-size: .7rem; font-weight: 800;
|
|
||||||
display: inline-block; vertical-align: middle;
|
|
||||||
}
|
|
||||||
.f-status-closed {
|
|
||||||
background: rgba(48,168,94,.12); color: #30a85e; border: 1px solid rgba(48,168,94,.3);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ── Role badges (LOST_AND_FOUND / METRO) ── */
|
/* ── Role badges (LOST_AND_FOUND / METRO) ── */
|
||||||
.f-role-badge {
|
.f-role-badge {
|
||||||
display: inline-flex; align-items: center; gap: 4px;
|
display: inline-flex; align-items: center; gap: 4px;
|
||||||
@@ -264,6 +329,26 @@ button.f-card-reward-btn:focus-visible {
|
|||||||
font-size: 9px; font-weight: 900; line-height: 1;
|
font-size: 9px; font-weight: 900; line-height: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Плашка «Найдено» поверх фото ──
|
||||||
|
Живёт на самом изображении, а не в шапке карточки: при быстром скролле
|
||||||
|
шапка проезжает мимо, фото с плашкой остаётся в кадре. */
|
||||||
|
.f-img-found-badge {
|
||||||
|
position: absolute; top: 12px; left: 12px; z-index: 3;
|
||||||
|
display: inline-flex; align-items: center; gap: 5px;
|
||||||
|
padding: 5px 12px 5px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: linear-gradient(135deg, #35c46f, #1f9d55);
|
||||||
|
border: 1px solid rgba(255,255,255,.35);
|
||||||
|
color: #fff;
|
||||||
|
font-size: .76rem; font-weight: 800; line-height: 1.2;
|
||||||
|
white-space: nowrap;
|
||||||
|
box-shadow: 0 2px 10px rgba(0,0,0,.3);
|
||||||
|
/* Не перехватываем клик по фото (открытие карусели). */
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.f-img-found-badge svg { flex-shrink: 0; }
|
||||||
|
.f-img-found-badge-pet { background: linear-gradient(135deg, #ffb03a, #ff7a45); }
|
||||||
|
|
||||||
/* ── Footer (phone + owner actions) ── */
|
/* ── Footer (phone + owner actions) ── */
|
||||||
.f-card-foot {
|
.f-card-foot {
|
||||||
display: flex; flex-direction: row; align-items: center; justify-content: space-between;
|
display: flex; flex-direction: row; align-items: center; justify-content: space-between;
|
||||||
@@ -291,14 +376,29 @@ button.f-card-reward-btn:focus-visible {
|
|||||||
border-color: rgba(var(--teal-rgb), .5);
|
border-color: rgba(var(--teal-rgb), .5);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Closed/Found card styling */
|
/* Closed/Found card styling.
|
||||||
|
Приглушение намеренно лёгкое: объявление найдено — это хорошая новость,
|
||||||
|
поэтому НЕ гасим карточку целиком (иначе она читается как удалённая).
|
||||||
|
Работают только фото (grayscale/brightness), текст остаётся читаемым. */
|
||||||
.f-card-closed {
|
.f-card-closed {
|
||||||
opacity: .8;
|
|
||||||
border-color: rgba(48,168,94,.3);
|
border-color: rgba(48,168,94,.3);
|
||||||
}
|
}
|
||||||
.f-card-closed:hover { border-color: rgba(48,168,94,.5); }
|
/* Зелёное кольцо вместо красного/зелёного типа: статус «найдено» здесь
|
||||||
.f-card-closed .f-card-img { filter: grayscale(.5); }
|
важнее того, потеря это была или находка (иначе кольцо спорит с плашкой). */
|
||||||
.f-card-closed .f-card-caption-name { text-decoration: line-through; opacity: .7; }
|
.f-card-closed.f-card-loss,
|
||||||
|
.f-card-closed.f-card-found {
|
||||||
|
box-shadow: 0 0 0 2px rgba(48,168,94,.45);
|
||||||
|
}
|
||||||
|
.f-card-closed:hover,
|
||||||
|
.f-card-closed:hover.f-card-loss,
|
||||||
|
.f-card-closed:hover.f-card-found {
|
||||||
|
border-color: rgba(48,168,94,.5);
|
||||||
|
box-shadow: 0 0 0 2px rgba(48,168,94,.65);
|
||||||
|
}
|
||||||
|
.f-card-closed .f-card-img img,
|
||||||
|
.f-card-closed .f-card-emoji {
|
||||||
|
filter: grayscale(.6) brightness(.85);
|
||||||
|
}
|
||||||
|
|
||||||
/* Edit & Delete buttons */
|
/* Edit & Delete buttons */
|
||||||
.f-card-edit-btn,
|
.f-card-edit-btn,
|
||||||
@@ -332,13 +432,28 @@ button.f-card-reward-btn:focus-visible {
|
|||||||
.f-card-found-btn:hover {
|
.f-card-found-btn:hover {
|
||||||
background: rgba(48,168,94,.18); border-color: rgba(48,168,94,.5);
|
background: rgba(48,168,94,.18); border-color: rgba(48,168,94,.5);
|
||||||
}
|
}
|
||||||
/* Возврат закрытого объявления в ленту (только в админ-панели). */
|
/* «Найдено ✓ <дата>» — подтверждение уже применённого действия: неактивное,
|
||||||
.f-card-reopen-btn {
|
но всё ещё читаемое, без серости «заблокированной» кнопки. */
|
||||||
background: rgba(var(--teal-rgb),.1); border-color: rgba(var(--teal-rgb),.3);
|
.f-card-found-btn-done {
|
||||||
color: var(--teal);
|
background: rgba(48,168,94,.14); border-color: rgba(48,168,94,.35);
|
||||||
|
color: #30a85e; opacity: 1; cursor: default;
|
||||||
}
|
}
|
||||||
.f-card-reopen-btn:hover {
|
.f-card-found-btn-done:hover {
|
||||||
background: rgba(var(--teal-rgb),.18); border-color: rgba(var(--teal-rgb),.5);
|
background: rgba(48,168,94,.14); border-color: rgba(48,168,94,.35);
|
||||||
|
}
|
||||||
|
/* Отмена случайного нажатия «Вернулось к владельцу» — только автору. */
|
||||||
|
.f-card-found-undo {
|
||||||
|
margin-left: 10px;
|
||||||
|
background: none; border: none; padding: 2px;
|
||||||
|
color: var(--muted); font-family: var(--font);
|
||||||
|
font-size: .78rem; text-decoration: underline;
|
||||||
|
text-underline-offset: 2px;
|
||||||
|
cursor: pointer; transition: color .2s;
|
||||||
|
}
|
||||||
|
.f-card-found-undo:hover { color: var(--teal); }
|
||||||
|
.f-card-found-undo:focus-visible {
|
||||||
|
outline: 2px solid rgba(var(--teal-rgb), .6); outline-offset: 2px;
|
||||||
|
border-radius: 4px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Calendar Popup ── */
|
/* ── Calendar Popup ── */
|
||||||
|
|||||||
@@ -3,6 +3,10 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
/* Без min-width:0 flex-элемент не может ужаться ниже своего min-content
|
||||||
|
(его задаёт .chat-list с max-width:560px). На узком экране страница
|
||||||
|
становилась шире вьюпорта, и кнопка удаления уезжала за правый край. */
|
||||||
|
min-width: 0;
|
||||||
height: 100vh; height: 100dvh;
|
height: 100vh; height: 100dvh;
|
||||||
background: var(--bg-app);
|
background: var(--bg-app);
|
||||||
}
|
}
|
||||||
@@ -37,14 +41,6 @@
|
|||||||
font-weight: 800;
|
font-weight: 800;
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
}
|
}
|
||||||
.chat-status {
|
|
||||||
font-size: .72rem;
|
|
||||||
font-weight: 700;
|
|
||||||
color: var(--muted);
|
|
||||||
}
|
|
||||||
.chat-status.connected {
|
|
||||||
color: #30a85e;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-header-avatar {
|
.chat-header-avatar {
|
||||||
width: 36px;
|
width: 36px;
|
||||||
@@ -160,36 +156,9 @@
|
|||||||
.chat-send-btn:hover:not(:disabled) { background: var(--teal2); }
|
.chat-send-btn:hover:not(:disabled) { background: var(--teal2); }
|
||||||
.chat-send-btn:disabled { opacity: .4; cursor: default; }
|
.chat-send-btn:disabled { opacity: .4; cursor: default; }
|
||||||
|
|
||||||
/* ── Emoji picker ── */
|
|
||||||
.chat-input-area {
|
.chat-input-area {
|
||||||
position: relative;
|
position: relative;
|
||||||
}
|
}
|
||||||
.chat-emoji-picker {
|
|
||||||
position: absolute;
|
|
||||||
bottom: 100%;
|
|
||||||
right: 0;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
z-index: 100;
|
|
||||||
}
|
|
||||||
.chat-emoji-picker em-emoji-picker {
|
|
||||||
width: 320px;
|
|
||||||
max-height: 350px;
|
|
||||||
}
|
|
||||||
.chat-emoji-btn {
|
|
||||||
background: var(--bg-input);
|
|
||||||
border: 1px solid var(--border);
|
|
||||||
border-radius: 999px;
|
|
||||||
padding: 0 12px;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 1.2rem;
|
|
||||||
line-height: 1;
|
|
||||||
transition: background .15s, border-color .15s;
|
|
||||||
}
|
|
||||||
.chat-emoji-btn:hover,
|
|
||||||
.chat-emoji-btn.active {
|
|
||||||
background: var(--hover-bg);
|
|
||||||
border-color: rgba(var(--teal-rgb), .5);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ── Chat List ── */
|
/* ── Chat List ── */
|
||||||
.chat-list {
|
.chat-list {
|
||||||
|
|||||||
@@ -282,7 +282,7 @@
|
|||||||
.f-topbar-dropdown-menu {
|
.f-topbar-dropdown-menu {
|
||||||
position: absolute; top: 100%; left: 0; right: 0;
|
position: absolute; top: 100%; left: 0; right: 0;
|
||||||
z-index: 50;
|
z-index: 50;
|
||||||
display: flex; flex-direction: row; align-items: center; justify-content: center; gap: 6px;
|
display: flex; flex-flow: row wrap; align-items: center; justify-content: center; gap: 6px;
|
||||||
padding: 8px 12px;
|
padding: 8px 12px;
|
||||||
margin-top: 6px;
|
margin-top: 6px;
|
||||||
background: rgba(0, 0, 0, .72);
|
background: rgba(0, 0, 0, .72);
|
||||||
@@ -292,6 +292,14 @@
|
|||||||
box-shadow: 0 12px 40px rgba(0, 0, 0, .35);
|
box-shadow: 0 12px 40px rgba(0, 0, 0, .35);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Разделитель между группами фильтров (тип / состояние). */
|
||||||
|
.f-topbar-dropdown-sep {
|
||||||
|
width: 1px; align-self: stretch; margin: 2px 3px;
|
||||||
|
background: rgba(255, 255, 255, .16);
|
||||||
|
border-radius: 1px;
|
||||||
|
}
|
||||||
|
:root:not([data-theme="dark"]) .f-topbar-dropdown-sep { background: rgba(0, 0, 0, .12); }
|
||||||
|
|
||||||
:root:not([data-theme="dark"]) .f-topbar-dropdown-menu {
|
:root:not([data-theme="dark"]) .f-topbar-dropdown-menu {
|
||||||
background: rgba(255, 255, 255, .92);
|
background: rgba(255, 255, 255, .92);
|
||||||
border-color: rgba(0, 0, 0, .08);
|
border-color: rgba(0, 0, 0, .08);
|
||||||
|
|||||||
@@ -214,6 +214,25 @@ select.f-m-field::selection { background: transparent; }
|
|||||||
box-shadow: 0 8px 40px rgba(0,0,0,.5);
|
box-shadow: 0 8px 40px rgba(0,0,0,.5);
|
||||||
touch-action: pan-y;
|
touch-action: pan-y;
|
||||||
}
|
}
|
||||||
|
/* Та же лёгкая приглушка, что и в карточке: объявление найдено, но всё равно
|
||||||
|
хорошо видно, что это за вещь/питомец. */
|
||||||
|
.f-viewer-img-closed { filter: grayscale(.6) brightness(.85); }
|
||||||
|
|
||||||
|
/* Плашка «Найдено» поверх фото в просмотрщике: остаётся на каждом слайде
|
||||||
|
карусели, поэтому статус не теряется при листании. */
|
||||||
|
.f-viewer-found-badge {
|
||||||
|
position: absolute; top: 10px; left: 10px; z-index: 2;
|
||||||
|
display: inline-flex; align-items: center; gap: 6px;
|
||||||
|
padding: 7px 14px 7px 11px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: linear-gradient(135deg, #35c46f, #1f9d55);
|
||||||
|
border: 1px solid rgba(255,255,255,.35);
|
||||||
|
color: #fff;
|
||||||
|
font-size: .85rem; font-weight: 800; line-height: 1.2;
|
||||||
|
white-space: nowrap;
|
||||||
|
box-shadow: 0 2px 12px rgba(0,0,0,.35);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
.f-viewer-contact {
|
.f-viewer-contact {
|
||||||
margin-top: 16px;
|
margin-top: 16px;
|
||||||
padding: 10px 28px;
|
padding: 10px 28px;
|
||||||
@@ -564,14 +583,12 @@ select.f-m-field::selection { background: transparent; }
|
|||||||
}
|
}
|
||||||
.f-post-detail-modal .f-card-img {
|
.f-post-detail-modal .f-card-img {
|
||||||
max-height: none;
|
max-height: none;
|
||||||
overflow: visible;
|
/* Раньше было overflow: visible для полноэкранного просмотра. Теперь фото
|
||||||
|
листается прямо в карточке (карусель), поэтому кадры должны обрезаться
|
||||||
|
по «окну». */
|
||||||
|
overflow: hidden;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
.f-post-detail-modal .f-card-img img {
|
|
||||||
width: 100%;
|
|
||||||
height: auto;
|
|
||||||
object-fit: contain;
|
|
||||||
}
|
|
||||||
.f-post-detail-modal .f-card-caption {
|
.f-post-detail-modal .f-card-caption {
|
||||||
padding: 8px 14px;
|
padding: 8px 14px;
|
||||||
}
|
}
|
||||||
|
|||||||
81
src/utils/foundAt.js
Normal file
81
src/utils/foundAt.js
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
// Дата, когда объявление было отмечено как «найдено».
|
||||||
|
//
|
||||||
|
// Бэкенд статус отдаёт, но момент перехода в CLOSED в ответе /api/v1/posts
|
||||||
|
// сейчас не приходит, а в карточке он нужен («Найдено 3 октября»). Поэтому:
|
||||||
|
// 1) если поле closedAt/closedDate появится в DTO — берём его (приоритет);
|
||||||
|
// 2) иначе — дата, которую клиент запомнил в момент нажатия «Вернулось к
|
||||||
|
// владельцу» (rememberFoundAt), т.е. точная для текущего устройства;
|
||||||
|
// 3) иначе — null: показываем просто «Найдено», без выдуманной даты.
|
||||||
|
|
||||||
|
const STORAGE_KEY = "postFoundAt";
|
||||||
|
// Хранилище не должно расти бесконечно: держим последние отметки.
|
||||||
|
const MAX_ENTRIES = 100;
|
||||||
|
|
||||||
|
function readStore() {
|
||||||
|
try {
|
||||||
|
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||||
|
const parsed = raw ? JSON.parse(raw) : null;
|
||||||
|
return parsed && typeof parsed === "object" ? parsed : {};
|
||||||
|
} catch {
|
||||||
|
// Приватный режим / отключённое хранилище — работаем без даты.
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeStore(store) {
|
||||||
|
try {
|
||||||
|
const entries = Object.entries(store).slice(-MAX_ENTRIES);
|
||||||
|
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(Object.fromEntries(entries)));
|
||||||
|
} catch {
|
||||||
|
// Не смогли записать — дата просто не запомнится, это не критично.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rememberFoundAt(postId, iso = new Date().toISOString()) {
|
||||||
|
if (postId === undefined || postId === null) return;
|
||||||
|
const store = readStore();
|
||||||
|
store[postId] = iso;
|
||||||
|
writeStore(store);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function forgetFoundAt(postId) {
|
||||||
|
const store = readStore();
|
||||||
|
if (!(postId in store)) return;
|
||||||
|
delete store[postId];
|
||||||
|
writeStore(store);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getFoundAt(ad) {
|
||||||
|
if (!ad) return null;
|
||||||
|
return ad.closedAt || ad.closedDate || readStore()[ad.id] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Intl.DateTimeFormat дорого создавать, а дата рендерится в каждой закрытой
|
||||||
|
* карточке ленты — держим по одному форматтеру на локаль.
|
||||||
|
*/
|
||||||
|
const formatterCache = new Map();
|
||||||
|
|
||||||
|
function getFormatter(locale) {
|
||||||
|
const cached = formatterCache.get(locale);
|
||||||
|
if (cached) return cached;
|
||||||
|
const formatter = new Intl.DateTimeFormat(locale, { day: "numeric", month: "long" });
|
||||||
|
formatterCache.set(locale, formatter);
|
||||||
|
return formatter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* «3 октября» / «October 3» — коротко и по-человечески, без года.
|
||||||
|
* Возвращает null на невалидную дату, чтобы не показывать «Invalid Date».
|
||||||
|
*/
|
||||||
|
export function formatFoundDate(value, language) {
|
||||||
|
if (!value) return null;
|
||||||
|
const date = new Date(value);
|
||||||
|
if (Number.isNaN(date.getTime())) return null;
|
||||||
|
const locale = language === "en" ? "en-US" : "ru-RU";
|
||||||
|
try {
|
||||||
|
return getFormatter(locale).format(date);
|
||||||
|
} catch {
|
||||||
|
return date.toLocaleDateString(locale);
|
||||||
|
}
|
||||||
|
}
|
||||||
19
src/utils/timezone.js
Normal file
19
src/utils/timezone.js
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
// src/utils/timezone.js
|
||||||
|
|
||||||
|
// Зона пользователя определяется один раз при загрузке модуля и кэшируется,
|
||||||
|
// чтобы не пересчитывать её на каждый HTTP-запрос / STOMP-коннект.
|
||||||
|
function detectTimezone() {
|
||||||
|
try {
|
||||||
|
return Intl.DateTimeFormat().resolvedOptions().timeZone || null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** IANA-идентификатор зоны (например "Europe/Moscow") или null, если определить не удалось. */
|
||||||
|
export const TIMEZONE = detectTimezone();
|
||||||
|
|
||||||
|
/** native-заголовок timezone для CONNECT-фрейма STOMP (пустой объект, если зона неизвестна). */
|
||||||
|
export function timezoneConnectHeaders() {
|
||||||
|
return TIMEZONE ? { timezone: TIMEZONE } : {};
|
||||||
|
}
|
||||||
50
src/utils/timezoneFetch.js
Normal file
50
src/utils/timezoneFetch.js
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
// src/utils/timezoneFetch.js
|
||||||
|
import { API_URL } from "../config/authConstants";
|
||||||
|
import { TIMEZONE } from "./timezone";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Централизованно добавляет заголовок X-Timezone ко всем HTTP-запросам к backend.
|
||||||
|
* Вызывается один раз при старте приложения (см. src/index.js).
|
||||||
|
*
|
||||||
|
* Патчим глобальный fetch, а не каждый вызов, чтобы заголовок автоматически
|
||||||
|
* попадал в любые запросы (в т.ч. multipart/form-data и новые call-sites), и его
|
||||||
|
* нельзя было случайно забыть. Content-Type/boundary не трогаем — только заголовок.
|
||||||
|
*
|
||||||
|
* Заголовок добавляется только к запросам на origin API_URL: сторонние домены
|
||||||
|
* (например, геокодер Яндекса) не должны получать нестандартный заголовок,
|
||||||
|
* иначе браузер сделает CORS-preflight и внешний запрос может сломаться.
|
||||||
|
*/
|
||||||
|
export function installTimezoneFetch() {
|
||||||
|
if (!TIMEZONE) return;
|
||||||
|
if (typeof window === "undefined" || typeof window.fetch !== "function") return;
|
||||||
|
|
||||||
|
const originalFetch = window.fetch;
|
||||||
|
const backendOrigin = new URL(API_URL, window.location.origin).origin;
|
||||||
|
|
||||||
|
window.fetch = function timezoneFetch(input, init) {
|
||||||
|
const url =
|
||||||
|
typeof input === "string"
|
||||||
|
? input
|
||||||
|
: input instanceof URL
|
||||||
|
? input.href
|
||||||
|
: input?.url || "";
|
||||||
|
|
||||||
|
let targetOrigin = null;
|
||||||
|
try {
|
||||||
|
targetOrigin = new URL(url, window.location.origin).origin;
|
||||||
|
} catch {
|
||||||
|
targetOrigin = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetOrigin !== backendOrigin) {
|
||||||
|
return originalFetch.call(this, input, init);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceHeaders =
|
||||||
|
(init && init.headers) || (input && input.headers) || undefined;
|
||||||
|
const headers = new Headers(sourceHeaders);
|
||||||
|
if (!headers.has("X-Timezone")) headers.set("X-Timezone", TIMEZONE);
|
||||||
|
|
||||||
|
return originalFetch.call(this, input, { ...(init || {}), headers });
|
||||||
|
};
|
||||||
|
}
|
||||||
20
tsconfig.json
Normal file
20
tsconfig.json
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "es5",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"allowJs": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"strict": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx"
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user